]> git.sur5r.net Git - openldap/blob - servers/slapd/back-meta/bind.c
ITS#5854
[openldap] / servers / slapd / back-meta / bind.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1999-2008 The OpenLDAP Foundation.
5  * Portions Copyright 2001-2003 Pierangelo Masarati.
6  * Portions Copyright 1999-2003 Howard Chu.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted only as authorized by the OpenLDAP
11  * Public License.
12  *
13  * A copy of this license is available in the file LICENSE in the
14  * top-level directory of the distribution or, alternatively, at
15  * <http://www.OpenLDAP.org/license.html>.
16  */
17 /* ACKNOWLEDGEMENTS:
18  * This work was initially developed by the Howard Chu for inclusion
19  * in OpenLDAP Software and subsequently enhanced by Pierangelo
20  * Masarati.
21  */
22
23 #include "portable.h"
24
25 #include <stdio.h>
26
27 #include <ac/errno.h>
28 #include <ac/socket.h>
29 #include <ac/string.h>
30
31
32 #define AVL_INTERNAL
33 #include "slap.h"
34 #include "../back-ldap/back-ldap.h"
35 #include "back-meta.h"
36 #undef ldap_debug       /* silence a warning in ldap-int.h */
37 #include "../../../libraries/libldap/ldap-int.h"
38
39 #include "lutil_ldap.h"
40
41 static int
42 meta_back_proxy_authz_bind(
43         metaconn_t              *mc,
44         int                     candidate,
45         Operation               *op,
46         SlapReply               *rs,
47         ldap_back_send_t        sendok );
48
49 static int
50 meta_back_single_bind(
51         Operation               *op,
52         SlapReply               *rs,
53         metaconn_t              *mc,
54         int                     candidate );
55
56 int
57 meta_back_bind( Operation *op, SlapReply *rs )
58 {
59         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
60         metaconn_t      *mc = NULL;
61
62         int             rc = LDAP_OTHER,
63                         i,
64                         gotit = 0,
65                         isroot = 0;
66
67         SlapReply       *candidates;
68
69         rs->sr_err = LDAP_SUCCESS;
70
71         Debug( LDAP_DEBUG_ARGS, "%s meta_back_bind: dn=\"%s\".\n",
72                 op->o_log_prefix, op->o_req_dn.bv_val, 0 );
73
74         /* the test on the bind method should be superfluous */
75         switch ( be_rootdn_bind( op, rs ) ) {
76         case LDAP_SUCCESS:
77                 if ( META_BACK_DEFER_ROOTDN_BIND( mi ) ) {
78                         /* frontend will return success */
79                         return rs->sr_err;
80                 }
81
82                 isroot = 1;
83                 /* fallthru */
84
85         case SLAP_CB_CONTINUE:
86                 break;
87
88         default:
89                 /* be_rootdn_bind() sent result */
90                 return rs->sr_err;
91         }
92
93         /* we need meta_back_getconn() not send result even on error,
94          * because we want to intercept the error and make it
95          * invalidCredentials */
96         mc = meta_back_getconn( op, rs, NULL, LDAP_BACK_BIND_DONTSEND );
97         if ( !mc ) {
98                 if ( LogTest( LDAP_DEBUG_ANY ) ) {
99                         char    buf[ SLAP_TEXT_BUFLEN ];
100
101                         snprintf( buf, sizeof( buf ),
102                                 "meta_back_bind: no target "
103                                 "for dn \"%s\" (%d%s%s).",
104                                 op->o_req_dn.bv_val, rs->sr_err,
105                                 rs->sr_text ? ". " : "",
106                                 rs->sr_text ? rs->sr_text : "" );
107                         Debug( LDAP_DEBUG_ANY,
108                                 "%s %s\n",
109                                 op->o_log_prefix, buf, 0 );
110                 }
111
112                 /* FIXME: there might be cases where we don't want
113                  * to map the error onto invalidCredentials */
114                 switch ( rs->sr_err ) {
115                 case LDAP_NO_SUCH_OBJECT:
116                 case LDAP_UNWILLING_TO_PERFORM:
117                         rs->sr_err = LDAP_INVALID_CREDENTIALS;
118                         rs->sr_text = NULL;
119                         break;
120                 }
121                 send_ldap_result( op, rs );
122                 return rs->sr_err;
123         }
124
125         candidates = meta_back_candidates_get( op );
126
127         /*
128          * Each target is scanned ...
129          */
130         mc->mc_authz_target = META_BOUND_NONE;
131         for ( i = 0; i < mi->mi_ntargets; i++ ) {
132                 metatarget_t    *mt = mi->mi_targets[ i ];
133                 int             lerr;
134
135                 /*
136                  * Skip non-candidates
137                  */
138                 if ( !META_IS_CANDIDATE( &candidates[ i ] ) ) {
139                         continue;
140                 }
141
142                 if ( gotit == 0 ) {
143                         /* set rc to LDAP_SUCCESS only if at least
144                          * one candidate has been tried */
145                         rc = LDAP_SUCCESS;
146                         gotit = 1;
147
148                 } else if ( !isroot ) {
149                         /*
150                          * A bind operation is expected to have
151                          * ONE CANDIDATE ONLY!
152                          */
153                         Debug( LDAP_DEBUG_ANY,
154                                 "### %s meta_back_bind: more than one"
155                                 " candidate selected...\n",
156                                 op->o_log_prefix, 0, 0 );
157                 }
158
159                 if ( isroot ) {
160                         if ( mt->mt_idassert_authmethod == LDAP_AUTH_NONE
161                                 || BER_BVISNULL( &mt->mt_idassert_authcDN ) )
162                         {
163                                 metasingleconn_t        *msc = &mc->mc_conns[ i ];
164
165                                 /* skip the target if no pseudorootdn is provided */
166                                 if ( !BER_BVISNULL( &msc->msc_bound_ndn ) ) {
167                                         ch_free( msc->msc_bound_ndn.bv_val );
168                                         BER_BVZERO( &msc->msc_bound_ndn );
169                                 }
170
171                                 if ( !BER_BVISNULL( &msc->msc_cred ) ) {
172                                         /* destroy sensitive data */
173                                         memset( msc->msc_cred.bv_val, 0,
174                                                 msc->msc_cred.bv_len );
175                                         ch_free( msc->msc_cred.bv_val );
176                                         BER_BVZERO( &msc->msc_cred );
177                                 }
178
179                                 continue;
180                         }
181
182                         
183                         (void)meta_back_proxy_authz_bind( mc, i, op, rs, LDAP_BACK_DONTSEND );
184                         lerr = rs->sr_err;
185
186                 } else {
187                         lerr = meta_back_single_bind( op, rs, mc, i );
188                 }
189
190                 if ( lerr != LDAP_SUCCESS ) {
191                         rc = rs->sr_err = lerr;
192
193                         /* FIXME: in some cases (e.g. unavailable)
194                          * do not assume it's not candidate; rather
195                          * mark this as an error to be eventually
196                          * reported to client */
197                         META_CANDIDATE_CLEAR( &candidates[ i ] );
198                         break;
199                 }
200         }
201
202         /* must re-insert if local DN changed as result of bind */
203         if ( rc == LDAP_SUCCESS ) {
204                 if ( isroot ) {
205                         mc->mc_authz_target = META_BOUND_ALL;
206                 }
207
208                 if ( !LDAP_BACK_PCONN_ISPRIV( mc )
209                         && !dn_match( &op->o_req_ndn, &mc->mc_local_ndn ) )
210                 {
211                         int             lerr;
212
213                         /* wait for all other ops to release the connection */
214                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
215                         assert( mc->mc_refcnt == 1 );
216 #if META_BACK_PRINT_CONNTREE > 0
217                         meta_back_print_conntree( mi, ">>> meta_back_bind" );
218 #endif /* META_BACK_PRINT_CONNTREE */
219
220                         /* delete all cached connections with the current connection */
221                         if ( LDAP_BACK_SINGLECONN( mi ) ) {
222                                 metaconn_t      *tmpmc;
223
224                                 while ( ( tmpmc = avl_delete( &mi->mi_conninfo.lai_tree, (caddr_t)mc, meta_back_conn_cmp ) ) != NULL )
225                                 {
226                                         Debug( LDAP_DEBUG_TRACE,
227                                                 "=>meta_back_bind: destroying conn %ld (refcnt=%u)\n",
228                                                 LDAP_BACK_PCONN_ID( mc ), mc->mc_refcnt, 0 );
229
230                                         if ( tmpmc->mc_refcnt != 0 ) {
231                                                 /* taint it */
232                                                 LDAP_BACK_CONN_TAINTED_SET( tmpmc );
233
234                                         } else {
235                                                 /*
236                                                  * Needs a test because the handler may be corrupted,
237                                                  * and calling ldap_unbind on a corrupted header results
238                                                  * in a segmentation fault
239                                                  */
240                                                 meta_back_conn_free( tmpmc );
241                                         }
242                                 }
243                         }
244
245                         ber_bvreplace( &mc->mc_local_ndn, &op->o_req_ndn );
246                         lerr = avl_insert( &mi->mi_conninfo.lai_tree, (caddr_t)mc,
247                                 meta_back_conndn_cmp, meta_back_conndn_dup );
248 #if META_BACK_PRINT_CONNTREE > 0
249                         meta_back_print_conntree( mi, "<<< meta_back_bind" );
250 #endif /* META_BACK_PRINT_CONNTREE */
251                         if ( lerr == 0 ) {
252 #if 0
253                                 /* NOTE: a connection cannot be privileged
254                                  * and be in the avl tree at the same time
255                                  */
256                                 if ( isroot ) {
257                                         LDAP_BACK_CONN_ISPRIV_SET( mc );
258                                         LDAP_BACK_PCONN_SET( mc, op );
259                                 }
260 #endif
261                                 LDAP_BACK_CONN_CACHED_SET( mc );
262
263                         } else {
264                                 LDAP_BACK_CONN_CACHED_CLEAR( mc );
265                         }
266                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
267                 }
268         }
269
270         if ( mc != NULL ) {
271                 meta_back_release_conn( mi, mc );
272         }
273
274         /*
275          * rc is LDAP_SUCCESS if at least one bind succeeded,
276          * err is the last error that occurred during a bind;
277          * if at least (and at most?) one bind succeeds, fine.
278          */
279         if ( rc != LDAP_SUCCESS ) {
280                 
281                 /*
282                  * deal with bind failure ...
283                  */
284
285                 /*
286                  * no target was found within the naming context, 
287                  * so bind must fail with invalid credentials
288                  */
289                 if ( rs->sr_err == LDAP_SUCCESS && gotit == 0 ) {
290                         rs->sr_err = LDAP_INVALID_CREDENTIALS;
291                 } else {
292                         rs->sr_err = slap_map_api2result( rs );
293                 }
294                 send_ldap_result( op, rs );
295                 return rs->sr_err;
296
297         }
298
299         return LDAP_SUCCESS;
300 }
301
302 static int
303 meta_back_bind_op_result(
304         Operation               *op,
305         SlapReply               *rs,
306         metaconn_t              *mc,
307         int                     candidate,
308         int                     msgid,
309         ldap_back_send_t        sendok )
310 {
311         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
312         metatarget_t            *mt = mi->mi_targets[ candidate ];
313         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
314         LDAPMessage             *res;
315         struct timeval          tv;
316         int                     rc;
317         int                     nretries = mt->mt_nretries;
318         char                    buf[ SLAP_TEXT_BUFLEN ];
319
320         Debug( LDAP_DEBUG_TRACE,
321                 ">>> %s meta_back_bind_op_result[%d]\n",
322                 op->o_log_prefix, candidate, 0 );
323
324         /* make sure this is clean */
325         assert( rs->sr_ctrls == NULL );
326
327         if ( rs->sr_err == LDAP_SUCCESS ) {
328                 time_t          stoptime = (time_t)(-1),
329                                 timeout;
330                 int             timeout_err = op->o_protocol >= LDAP_VERSION3 ?
331                                 LDAP_ADMINLIMIT_EXCEEDED : LDAP_OTHER;
332                 const char      *timeout_text = "Operation timed out";
333                 slap_op_t       opidx = slap_req2op( op->o_tag );
334
335                 /* since timeout is not specified, compute and use
336                  * the one specific to the ongoing operation */
337                 if ( opidx == LDAP_REQ_SEARCH ) {
338                         if ( op->ors_tlimit <= 0 ) {
339                                 timeout = 0;
340
341                         } else {
342                                 timeout = op->ors_tlimit;
343                                 timeout_err = LDAP_TIMELIMIT_EXCEEDED;
344                                 timeout_text = NULL;
345                         }
346
347                 } else {
348                         timeout = mt->mt_timeout[ opidx ];
349                 }
350
351                 /* better than nothing :) */
352                 if ( timeout == 0 ) {
353                         if ( mi->mi_idle_timeout ) {
354                                 timeout = mi->mi_idle_timeout;
355
356                         } else if ( mi->mi_conn_ttl ) {
357                                 timeout = mi->mi_conn_ttl;
358                         }
359                 }
360
361                 if ( timeout ) {
362                         stoptime = op->o_time + timeout;
363                 }
364
365                 LDAP_BACK_TV_SET( &tv );
366
367                 /*
368                  * handle response!!!
369                  */
370 retry:;
371                 rc = ldap_result( msc->msc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
372                 switch ( rc ) {
373                 case 0:
374                         if ( nretries != META_RETRY_NEVER 
375                                 || ( timeout && slap_get_time() <= stoptime ) )
376                         {
377                                 ldap_pvt_thread_yield();
378                                 if ( nretries > 0 ) {
379                                         nretries--;
380                                 }
381                                 tv = mt->mt_bind_timeout;
382                                 goto retry;
383                         }
384
385                         /* don't let anyone else use this handler,
386                          * because there's a pending bind that will not
387                          * be acknowledged */
388                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
389                         assert( LDAP_BACK_CONN_BINDING( msc ) );
390
391 #ifdef DEBUG_205
392                         Debug( LDAP_DEBUG_ANY, "### %s meta_back_bind_op_result ldap_unbind_ext[%d] ld=%p\n",
393                                 op->o_log_prefix, candidate, (void *)msc->msc_ld );
394 #endif /* DEBUG_205 */
395
396                         meta_clear_one_candidate( op, mc, candidate );
397                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
398
399                         rs->sr_err = timeout_err;
400                         rs->sr_text = timeout_text;
401                         break;
402
403                 case -1:
404                         ldap_get_option( msc->msc_ld, LDAP_OPT_ERROR_NUMBER,
405                                 &rs->sr_err );
406
407                         snprintf( buf, sizeof( buf ),
408                                 "err=%d (%s) nretries=%d",
409                                 rs->sr_err, ldap_err2string( rs->sr_err ), nretries );
410                         Debug( LDAP_DEBUG_ANY,
411                                 "### %s meta_back_bind_op_result[%d]: %s.\n",
412                                 op->o_log_prefix, candidate, buf );
413                         break;
414
415                 default:
416                         /* only touch when activity actually took place... */
417                         if ( mi->mi_idle_timeout != 0 && msc->msc_time < op->o_time ) {
418                                 msc->msc_time = op->o_time;
419                         }
420
421                         /* FIXME: matched? referrals? response controls? */
422                         rc = ldap_parse_result( msc->msc_ld, res, &rs->sr_err,
423                                         NULL, NULL, NULL, NULL, 1 );
424                         if ( rc != LDAP_SUCCESS ) {
425                                 rs->sr_err = rc;
426                         }
427                         break;
428                 }
429         }
430
431         rs->sr_err = slap_map_api2result( rs );
432
433         Debug( LDAP_DEBUG_TRACE,
434                 "<<< %s meta_back_bind_op_result[%d] err=%d\n",
435                 op->o_log_prefix, candidate, rs->sr_err );
436
437         return rs->sr_err;
438 }
439
440 /*
441  * meta_back_single_bind
442  *
443  * attempts to perform a bind with creds
444  */
445 static int
446 meta_back_single_bind(
447         Operation               *op,
448         SlapReply               *rs,
449         metaconn_t              *mc,
450         int                     candidate )
451 {
452         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
453         metatarget_t            *mt = mi->mi_targets[ candidate ];
454         struct berval           mdn = BER_BVNULL;
455         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
456         int                     msgid;
457         dncookie                dc;
458         struct berval           save_o_dn;
459         int                     save_o_do_not_cache;
460         LDAPControl             **ctrls = NULL;
461         
462         if ( !BER_BVISNULL( &msc->msc_bound_ndn ) ) {
463                 ch_free( msc->msc_bound_ndn.bv_val );
464                 BER_BVZERO( &msc->msc_bound_ndn );
465         }
466
467         if ( !BER_BVISNULL( &msc->msc_cred ) ) {
468                 /* destroy sensitive data */
469                 memset( msc->msc_cred.bv_val, 0, msc->msc_cred.bv_len );
470                 ch_free( msc->msc_cred.bv_val );
471                 BER_BVZERO( &msc->msc_cred );
472         }
473
474         /*
475          * Rewrite the bind dn if needed
476          */
477         dc.target = mt;
478         dc.conn = op->o_conn;
479         dc.rs = rs;
480         dc.ctx = "bindDN";
481
482         if ( ldap_back_dn_massage( &dc, &op->o_req_dn, &mdn ) ) {
483                 rs->sr_text = "DN rewrite error";
484                 rs->sr_err = LDAP_OTHER;
485                 return rs->sr_err;
486         }
487
488         /* don't add proxyAuthz; set the bindDN */
489         save_o_dn = op->o_dn;
490         save_o_do_not_cache = op->o_do_not_cache;
491         op->o_do_not_cache = 1;
492         op->o_dn = op->o_req_dn;
493
494         ctrls = op->o_ctrls;
495         rs->sr_err = meta_back_controls_add( op, rs, mc, candidate, &ctrls );
496         op->o_dn = save_o_dn;
497         op->o_do_not_cache = save_o_do_not_cache;
498         if ( rs->sr_err != LDAP_SUCCESS ) {
499                 goto return_results;
500         }
501
502         /* FIXME: this fixes the bind problem right now; we need
503          * to use the asynchronous version to get the "matched"
504          * and more in case of failure ... */
505         /* FIXME: should we check if at least some of the op->o_ctrls
506          * can/should be passed? */
507         for (;;) {
508                 rs->sr_err = ldap_sasl_bind( msc->msc_ld, mdn.bv_val,
509                         LDAP_SASL_SIMPLE, &op->orb_cred,
510                         ctrls, NULL, &msgid );
511                 if ( rs->sr_err != LDAP_X_CONNECTING ) {
512                         break;
513                 }
514                 ldap_pvt_thread_yield();
515         }
516
517         mi->mi_ldap_extra->controls_free( op, rs, &ctrls );
518
519         meta_back_bind_op_result( op, rs, mc, candidate, msgid, LDAP_BACK_DONTSEND );
520         if ( rs->sr_err != LDAP_SUCCESS ) {
521                 goto return_results;
522         }
523
524         /* If defined, proxyAuthz will be used also when
525          * back-ldap is the authorizing backend; for this
526          * purpose, a successful bind is followed by a
527          * bind with the configured identity assertion */
528         /* NOTE: use with care */
529         if ( mt->mt_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) {
530                 meta_back_proxy_authz_bind( mc, candidate, op, rs, LDAP_BACK_SENDERR );
531                 if ( !LDAP_BACK_CONN_ISBOUND( msc ) ) {
532                         goto return_results;
533                 }
534                 goto cache_refresh;
535         }
536
537         ber_bvreplace( &msc->msc_bound_ndn, &op->o_req_ndn );
538         LDAP_BACK_CONN_ISBOUND_SET( msc );
539         mc->mc_authz_target = candidate;
540
541         if ( LDAP_BACK_SAVECRED( mi ) ) {
542                 if ( !BER_BVISNULL( &msc->msc_cred ) ) {
543                         memset( msc->msc_cred.bv_val, 0,
544                                 msc->msc_cred.bv_len );
545                 }
546                 ber_bvreplace( &msc->msc_cred, &op->orb_cred );
547                 ldap_set_rebind_proc( msc->msc_ld, mt->mt_rebind_f, msc );
548         }
549
550 cache_refresh:;
551         if ( mi->mi_cache.ttl != META_DNCACHE_DISABLED
552                         && !BER_BVISEMPTY( &op->o_req_ndn ) )
553         {
554                 ( void )meta_dncache_update_entry( &mi->mi_cache,
555                                 &op->o_req_ndn, candidate );
556         }
557
558 return_results:;
559         if ( mdn.bv_val != op->o_req_dn.bv_val ) {
560                 free( mdn.bv_val );
561         }
562
563         if ( META_BACK_TGT_QUARANTINE( mt ) ) {
564                 meta_back_quarantine( op, rs, candidate );
565         }
566
567         return rs->sr_err;
568 }
569
570 /*
571  * meta_back_single_dobind
572  */
573 int
574 meta_back_single_dobind(
575         Operation               *op,
576         SlapReply               *rs,
577         metaconn_t              **mcp,
578         int                     candidate,
579         ldap_back_send_t        sendok,
580         int                     nretries,
581         int                     dolock )
582 {
583         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
584         metatarget_t            *mt = mi->mi_targets[ candidate ];
585         metaconn_t              *mc = *mcp;
586         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
587         static struct berval    cred = BER_BVC( "" );
588         int                     msgid;
589
590         assert( !LDAP_BACK_CONN_ISBOUND( msc ) );
591
592         /* NOTE: this obsoletes pseudorootdn */
593         if ( op->o_conn != NULL &&
594                 !op->o_do_not_cache &&
595                 ( BER_BVISNULL( &msc->msc_bound_ndn ) ||
596                         BER_BVISEMPTY( &msc->msc_bound_ndn ) ||
597                         ( LDAP_BACK_CONN_ISPRIV( mc ) && dn_match( &msc->msc_bound_ndn, &mt->mt_idassert_authcDN ) ) ||
598                         ( mt->mt_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) ) )
599         {
600                 (void)meta_back_proxy_authz_bind( mc, candidate, op, rs, sendok );
601
602         } else {
603
604                 /* FIXME: should we check if at least some of the op->o_ctrls
605                  * can/should be passed? */
606                 for (;;) {
607                         rs->sr_err = ldap_sasl_bind( msc->msc_ld,
608                                 "", LDAP_SASL_SIMPLE, &cred,
609                                 NULL, NULL, &msgid );
610                         if ( rs->sr_err != LDAP_X_CONNECTING ) {
611                                 break;
612                         }
613                         ldap_pvt_thread_yield();
614                 }
615
616                 rs->sr_err = meta_back_bind_op_result( op, rs, mc, candidate, msgid, sendok );
617         }
618
619         if ( rs->sr_err != LDAP_SUCCESS ) {
620                 if ( dolock ) {
621                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
622                 }
623                 LDAP_BACK_CONN_BINDING_CLEAR( msc );
624                 if ( META_BACK_ONERR_STOP( mi ) ) {
625                         LDAP_BACK_CONN_TAINTED_SET( mc );
626                         meta_back_release_conn_lock( mi, mc, 0 );
627                         *mcp = NULL;
628                 }
629                 if ( dolock ) {
630                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
631                 }
632         }
633
634         if ( META_BACK_TGT_QUARANTINE( mt ) ) {
635                 meta_back_quarantine( op, rs, candidate );
636         }
637
638         return rs->sr_err;
639 }
640
641 /*
642  * meta_back_dobind
643  */
644 int
645 meta_back_dobind(
646         Operation               *op,
647         SlapReply               *rs,
648         metaconn_t              *mc,
649         ldap_back_send_t        sendok )
650 {
651         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
652
653         int                     bound = 0,
654                                 i,
655                                 isroot = 0;
656
657         SlapReply               *candidates;
658
659         if ( be_isroot( op ) ) {
660                 isroot = 1;
661         }
662
663         Debug( LDAP_DEBUG_TRACE,
664                 "%s meta_back_dobind: conn=%ld%s\n",
665                 op->o_log_prefix,
666                 LDAP_BACK_PCONN_ID( mc ),
667                 isroot ? " (isroot)" : "" );
668
669         /*
670          * all the targets are bound as pseudoroot
671          */
672         if ( mc->mc_authz_target == META_BOUND_ALL ) {
673                 bound = 1;
674                 goto done;
675         }
676
677         candidates = meta_back_candidates_get( op );
678
679         for ( i = 0; i < mi->mi_ntargets; i++ ) {
680                 metatarget_t            *mt = mi->mi_targets[ i ];
681                 metasingleconn_t        *msc = &mc->mc_conns[ i ];
682                 int                     rc;
683
684                 /*
685                  * Not a candidate
686                  */
687                 if ( !META_IS_CANDIDATE( &candidates[ i ] ) ) {
688                         continue;
689                 }
690
691                 assert( msc->msc_ld != NULL );
692
693                 /*
694                  * If the target is already bound it is skipped
695                  */
696
697 retry_binding:;
698                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
699                 if ( LDAP_BACK_CONN_ISBOUND( msc )
700                         || ( LDAP_BACK_CONN_ISANON( msc )
701                                 && mt->mt_idassert_authmethod == LDAP_AUTH_NONE ) )
702                 {
703                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
704                         ++bound;
705                         continue;
706
707                 } else if ( META_BACK_CONN_CREATING( msc ) || LDAP_BACK_CONN_BINDING( msc ) )
708                 {
709                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
710                         ldap_pvt_thread_yield();
711                         goto retry_binding;
712
713                 }
714
715                 LDAP_BACK_CONN_BINDING_SET( msc );
716                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
717
718                 rc = meta_back_single_dobind( op, rs, &mc, i,
719                         LDAP_BACK_DONTSEND, mt->mt_nretries, 1 );
720                 /*
721                  * NOTE: meta_back_single_dobind() already retries;
722                  * in case of failure, it resets mc...
723                  */
724                 if ( rc != LDAP_SUCCESS ) {
725                         char            buf[ SLAP_TEXT_BUFLEN ];
726
727                         if ( mc == NULL ) {
728                                 /* meta_back_single_dobind() already sent 
729                                  * response and released connection */
730                                 goto send_err;
731                         }
732
733
734                         if ( rc == LDAP_UNAVAILABLE ) {
735                                 /* FIXME: meta_back_retry() already re-calls
736                                  * meta_back_single_dobind() */
737                                 if ( meta_back_retry( op, rs, &mc, i, sendok ) ) {
738                                         goto retry_ok;
739                                 }
740
741                                 if ( mc != NULL ) {
742                                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
743                                         LDAP_BACK_CONN_BINDING_CLEAR( msc );
744                                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
745                                         meta_back_release_conn( mi, mc );
746                                 }
747
748                                 return 0;
749                         }
750
751                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
752                         LDAP_BACK_CONN_BINDING_CLEAR( msc );
753                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
754
755                         snprintf( buf, sizeof( buf ),
756                                 "meta_back_dobind[%d]: (%s) err=%d (%s).",
757                                 i, isroot ? op->o_bd->be_rootdn.bv_val : "anonymous",
758                                 rc, ldap_err2string( rc ) );
759                         Debug( LDAP_DEBUG_ANY,
760                                 "%s %s\n",
761                                 op->o_log_prefix, buf, 0 );
762
763                         /*
764                          * null cred bind should always succeed
765                          * as anonymous, so a failure means
766                          * the target is no longer candidate possibly
767                          * due to technical reasons (remote host down?)
768                          * so better clear the handle
769                          */
770                         /* leave the target candidate, but record the error for later use */
771                         candidates[ i ].sr_err = rc;
772                         if ( META_BACK_ONERR_STOP( mi ) ) {
773                                 bound = 0;
774                                 goto done;
775                         }
776
777                         continue;
778                 } /* else */
779
780 retry_ok:;
781                 Debug( LDAP_DEBUG_TRACE,
782                         "%s meta_back_dobind[%d]: "
783                         "(%s)\n",
784                         op->o_log_prefix, i,
785                         isroot ? op->o_bd->be_rootdn.bv_val : "anonymous" );
786
787                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
788                 LDAP_BACK_CONN_BINDING_CLEAR( msc );
789                 if ( isroot ) {
790                         LDAP_BACK_CONN_ISBOUND_SET( msc );
791                 } else {
792                         LDAP_BACK_CONN_ISANON_SET( msc );
793                 }
794                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
795                 ++bound;
796         }
797
798 done:;
799         Debug( LDAP_DEBUG_TRACE,
800                 "%s meta_back_dobind: conn=%ld bound=%d\n",
801                 op->o_log_prefix, LDAP_BACK_PCONN_ID( mc ), bound );
802
803         if ( bound == 0 ) {
804                 meta_back_release_conn( mi, mc );
805
806 send_err:;
807                 if ( sendok & LDAP_BACK_SENDERR ) {
808                         if ( rs->sr_err == LDAP_SUCCESS ) {
809                                 rs->sr_err = LDAP_BUSY;
810                         }
811                         send_ldap_result( op, rs );
812                 }
813
814                 return 0;
815         }
816
817         return ( bound > 0 );
818 }
819
820 /*
821  * meta_back_default_rebind
822  *
823  * This is a callback used for chasing referrals using the same
824  * credentials as the original user on this session.
825  */
826 int 
827 meta_back_default_rebind(
828         LDAP                    *ld,
829         LDAP_CONST char         *url,
830         ber_tag_t               request,
831         ber_int_t               msgid,
832         void                    *params )
833 {
834         metasingleconn_t        *msc = ( metasingleconn_t * )params;
835
836         return ldap_sasl_bind_s( ld, msc->msc_bound_ndn.bv_val,
837                         LDAP_SASL_SIMPLE, &msc->msc_cred,
838                         NULL, NULL, NULL );
839 }
840
841 /*
842  * meta_back_default_urllist
843  *
844  * This is a callback used for mucking with the urllist
845  */
846 int 
847 meta_back_default_urllist(
848         LDAP            *ld,
849         LDAPURLDesc     **urllist,
850         LDAPURLDesc     **url,
851         void            *params )
852 {
853         metatarget_t    *mt = (metatarget_t *)params;
854         LDAPURLDesc     **urltail;
855
856         if ( urllist == url ) {
857                 return LDAP_SUCCESS;
858         }
859
860         for ( urltail = &(*url)->lud_next; *urltail; urltail = &(*urltail)->lud_next )
861                 /* count */ ;
862
863         *urltail = *urllist;
864         *urllist = *url;
865         *url = NULL;
866
867         ldap_pvt_thread_mutex_lock( &mt->mt_uri_mutex );
868         if ( mt->mt_uri ) {
869                 ch_free( mt->mt_uri );
870         }
871
872         ldap_get_option( ld, LDAP_OPT_URI, (void *)&mt->mt_uri );
873         ldap_pvt_thread_mutex_unlock( &mt->mt_uri_mutex );
874
875         return LDAP_SUCCESS;
876 }
877
878 int
879 meta_back_cancel(
880         metaconn_t              *mc,
881         Operation               *op,
882         SlapReply               *rs,
883         ber_int_t               msgid,
884         int                     candidate,
885         ldap_back_send_t        sendok )
886 {
887         metainfo_t              *mi = (metainfo_t *)op->o_bd->be_private;
888
889         metatarget_t            *mt = mi->mi_targets[ candidate ];
890         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
891
892         int                     rc = LDAP_OTHER;
893
894         Debug( LDAP_DEBUG_TRACE, ">>> %s meta_back_cancel[%d] msgid=%d\n",
895                 op->o_log_prefix, candidate, msgid );
896
897         /* default behavior */
898         if ( META_BACK_TGT_ABANDON( mt ) ) {
899                 rc = ldap_abandon_ext( msc->msc_ld, msgid, NULL, NULL );
900
901         } else if ( META_BACK_TGT_IGNORE( mt ) ) {
902                 rc = ldap_pvt_discard( msc->msc_ld, msgid );
903
904         } else if ( META_BACK_TGT_CANCEL( mt ) ) {
905                 rc = ldap_cancel_s( msc->msc_ld, msgid, NULL, NULL );
906
907         } else {
908                 assert( 0 );
909         }
910
911         Debug( LDAP_DEBUG_TRACE, "<<< %s meta_back_cancel[%d] err=%d\n",
912                 op->o_log_prefix, candidate, rc );
913
914         return rc;
915 }
916
917
918
919 /*
920  * FIXME: error return must be handled in a cleaner way ...
921  */
922 int
923 meta_back_op_result(
924         metaconn_t              *mc,
925         Operation               *op,
926         SlapReply               *rs,
927         int                     candidate,
928         ber_int_t               msgid,
929         time_t                  timeout,
930         ldap_back_send_t        sendok )
931 {
932         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
933
934         const char      *save_text = rs->sr_text,
935                         *save_matched = rs->sr_matched;
936         BerVarray       save_ref = rs->sr_ref;
937         LDAPControl     **save_ctrls = rs->sr_ctrls;
938         void            *matched_ctx = NULL;
939
940         char            *matched = NULL;
941         char            *text = NULL;
942         char            **refs = NULL;
943         LDAPControl     **ctrls = NULL;
944
945         assert( mc != NULL );
946
947         rs->sr_text = NULL;
948         rs->sr_matched = NULL;
949         rs->sr_ref = NULL;
950         rs->sr_ctrls = NULL;
951
952         if ( candidate != META_TARGET_NONE ) {
953                 metatarget_t            *mt = mi->mi_targets[ candidate ];
954                 metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
955
956                 if ( LDAP_ERR_OK( rs->sr_err ) ) {
957                         int             rc;
958                         struct timeval  tv;
959                         LDAPMessage     *res = NULL;
960                         time_t          stoptime = (time_t)(-1);
961                         int             timeout_err = op->o_protocol >= LDAP_VERSION3 ?
962                                                 LDAP_ADMINLIMIT_EXCEEDED : LDAP_OTHER;
963                         const char      *timeout_text = "Operation timed out";
964
965                         /* if timeout is not specified, compute and use
966                          * the one specific to the ongoing operation */
967                         if ( timeout == (time_t)(-1) ) {
968                                 slap_op_t       opidx = slap_req2op( op->o_tag );
969
970                                 if ( opidx == SLAP_OP_SEARCH ) {
971                                         if ( op->ors_tlimit <= 0 ) {
972                                                 timeout = 0;
973
974                                         } else {
975                                                 timeout = op->ors_tlimit;
976                                                 timeout_err = LDAP_TIMELIMIT_EXCEEDED;
977                                                 timeout_text = NULL;
978                                         }
979
980                                 } else {
981                                         timeout = mt->mt_timeout[ opidx ];
982                                 }
983                         }
984
985                         /* better than nothing :) */
986                         if ( timeout == 0 ) {
987                                 if ( mi->mi_idle_timeout ) {
988                                         timeout = mi->mi_idle_timeout;
989
990                                 } else if ( mi->mi_conn_ttl ) {
991                                         timeout = mi->mi_conn_ttl;
992                                 }
993                         }
994
995                         if ( timeout ) {
996                                 stoptime = op->o_time + timeout;
997                         }
998
999                         LDAP_BACK_TV_SET( &tv );
1000
1001 retry:;
1002                         rc = ldap_result( msc->msc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
1003                         switch ( rc ) {
1004                         case 0:
1005                                 if ( timeout && slap_get_time() > stoptime ) {
1006                                         (void)meta_back_cancel( mc, op, rs, msgid, candidate, sendok );
1007                                         rs->sr_err = timeout_err;
1008                                         rs->sr_text = timeout_text;
1009                                         break;
1010                                 }
1011
1012                                 LDAP_BACK_TV_SET( &tv );
1013                                 ldap_pvt_thread_yield();
1014                                 goto retry;
1015
1016                         case -1:
1017                                 ldap_get_option( msc->msc_ld, LDAP_OPT_RESULT_CODE,
1018                                                 &rs->sr_err );
1019                                 break;
1020
1021
1022                         /* otherwise get the result; if it is not
1023                          * LDAP_SUCCESS, record it in the reply
1024                          * structure (this includes 
1025                          * LDAP_COMPARE_{TRUE|FALSE}) */
1026                         default:
1027                                 /* only touch when activity actually took place... */
1028                                 if ( mi->mi_idle_timeout != 0 && msc->msc_time < op->o_time ) {
1029                                         msc->msc_time = op->o_time;
1030                                 }
1031
1032                                 rc = ldap_parse_result( msc->msc_ld, res, &rs->sr_err,
1033                                                 &matched, &text, &refs, &ctrls, 1 );
1034                                 res = NULL;
1035                                 rs->sr_text = text;
1036                                 if ( rc != LDAP_SUCCESS ) {
1037                                         rs->sr_err = rc;
1038                                 }
1039
1040                                 /* RFC 4511: referrals can only appear
1041                                  * if result code is LDAP_REFERRAL */
1042                                 if ( refs != NULL
1043                                         && refs[ 0 ] != NULL
1044                                         && refs[ 0 ][ 0 ] != '\0' )
1045                                 {
1046                                         if ( rs->sr_err != LDAP_REFERRAL ) {
1047                                                 Debug( LDAP_DEBUG_ANY,
1048                                                         "%s meta_back_op_result[%d]: "
1049                                                         "got referrals with err=%d\n",
1050                                                         op->o_log_prefix,
1051                                                         candidate, rs->sr_err );
1052
1053                                         } else {
1054                                                 int     i;
1055         
1056                                                 for ( i = 0; refs[ i ] != NULL; i++ )
1057                                                         /* count */ ;
1058                                                 rs->sr_ref = op->o_tmpalloc( sizeof( struct berval ) * ( i + 1 ),
1059                                                         op->o_tmpmemctx );
1060                                                 for ( i = 0; refs[ i ] != NULL; i++ ) {
1061                                                         ber_str2bv( refs[ i ], 0, 0, &rs->sr_ref[ i ] );
1062                                                 }
1063                                                 BER_BVZERO( &rs->sr_ref[ i ] );
1064                                         }
1065
1066                                 } else if ( rs->sr_err == LDAP_REFERRAL ) {
1067                                         Debug( LDAP_DEBUG_ANY,
1068                                                 "%s meta_back_op_result[%d]: "
1069                                                 "got err=%d with null "
1070                                                 "or empty referrals\n",
1071                                                 op->o_log_prefix,
1072                                                 candidate, rs->sr_err );
1073
1074                                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
1075                                 }
1076
1077                                 if ( ctrls != NULL ) {
1078                                         rs->sr_ctrls = ctrls;
1079                                 }
1080                         }
1081
1082                         assert( res == NULL );
1083                 }
1084
1085                 /* if the error in the reply structure is not
1086                  * LDAP_SUCCESS, try to map it from client 
1087                  * to server error */
1088                 if ( !LDAP_ERR_OK( rs->sr_err ) ) {
1089                         rs->sr_err = slap_map_api2result( rs );
1090
1091                         /* internal ops ( op->o_conn == NULL ) 
1092                          * must not reply to client */
1093                         if ( op->o_conn && !op->o_do_not_cache && matched ) {
1094
1095                                 /* record the (massaged) matched
1096                                  * DN into the reply structure */
1097                                 rs->sr_matched = matched;
1098                         }
1099                 }
1100
1101                 if ( META_BACK_TGT_QUARANTINE( mt ) ) {
1102                         meta_back_quarantine( op, rs, candidate );
1103                 }
1104
1105         } else {
1106                 int     i,
1107                         err = rs->sr_err;
1108
1109                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
1110                         metasingleconn_t        *msc = &mc->mc_conns[ i ];
1111                         char                    *xtext = NULL;
1112                         char                    *xmatched = NULL;
1113
1114                         rs->sr_err = LDAP_SUCCESS;
1115
1116                         ldap_get_option( msc->msc_ld, LDAP_OPT_RESULT_CODE, &rs->sr_err );
1117                         if ( rs->sr_err != LDAP_SUCCESS ) {
1118                                 /*
1119                                  * better check the type of error. In some cases
1120                                  * (search ?) it might be better to return a
1121                                  * success if at least one of the targets gave
1122                                  * positive result ...
1123                                  */
1124                                 ldap_get_option( msc->msc_ld,
1125                                                 LDAP_OPT_DIAGNOSTIC_MESSAGE, &xtext );
1126                                 if ( xtext != NULL && xtext [ 0 ] == '\0' ) {
1127                                         ldap_memfree( xtext );
1128                                         xtext = NULL;
1129                                 }
1130
1131                                 ldap_get_option( msc->msc_ld,
1132                                                 LDAP_OPT_MATCHED_DN, &xmatched );
1133                                 if ( xmatched != NULL && xmatched[ 0 ] == '\0' ) {
1134                                         ldap_memfree( xmatched );
1135                                         xmatched = NULL;
1136                                 }
1137
1138                                 rs->sr_err = slap_map_api2result( rs );
1139         
1140                                 if ( LogTest( LDAP_DEBUG_ANY ) ) {
1141                                         char    buf[ SLAP_TEXT_BUFLEN ];
1142
1143                                         snprintf( buf, sizeof( buf ),
1144                                                 "meta_back_op_result[%d] "
1145                                                 "err=%d text=\"%s\" matched=\"%s\"", 
1146                                                 i, rs->sr_err,
1147                                                 ( xtext ? xtext : "" ),
1148                                                 ( xmatched ? xmatched : "" ) );
1149                                         Debug( LDAP_DEBUG_ANY, "%s %s.\n",
1150                                                 op->o_log_prefix, buf, 0 );
1151                                 }
1152
1153                                 /*
1154                                  * FIXME: need to rewrite "match" (need rwinfo)
1155                                  */
1156                                 switch ( rs->sr_err ) {
1157                                 default:
1158                                         err = rs->sr_err;
1159                                         if ( xtext != NULL ) {
1160                                                 if ( text ) {
1161                                                         ldap_memfree( text );
1162                                                 }
1163                                                 text = xtext;
1164                                                 xtext = NULL;
1165                                         }
1166                                         if ( xmatched != NULL ) {
1167                                                 if ( matched ) {
1168                                                         ldap_memfree( matched );
1169                                                 }
1170                                                 matched = xmatched;
1171                                                 xmatched = NULL;
1172                                         }
1173                                         break;
1174                                 }
1175
1176                                 if ( xtext ) {
1177                                         ldap_memfree( xtext );
1178                                 }
1179         
1180                                 if ( xmatched ) {
1181                                         ldap_memfree( xmatched );
1182                                 }
1183                         }
1184
1185                         if ( META_BACK_TGT_QUARANTINE( mi->mi_targets[ i ] ) ) {
1186                                 meta_back_quarantine( op, rs, i );
1187                         }
1188                 }
1189
1190                 if ( err != LDAP_SUCCESS ) {
1191                         rs->sr_err = err;
1192                 }
1193         }
1194
1195         if ( matched != NULL ) {
1196                 struct berval   dn, pdn;
1197
1198                 ber_str2bv( matched, 0, 0, &dn );
1199                 if ( dnPretty( NULL, &dn, &pdn, op->o_tmpmemctx ) == LDAP_SUCCESS ) {
1200                         ldap_memfree( matched );
1201                         matched_ctx = op->o_tmpmemctx;
1202                         matched = pdn.bv_val;
1203                 }
1204                 rs->sr_matched = matched;
1205         }
1206
1207         if ( rs->sr_err == LDAP_UNAVAILABLE ) {
1208                 if ( !( sendok & LDAP_BACK_RETRYING ) ) {
1209                         if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
1210                                 if ( rs->sr_text == NULL ) rs->sr_text = "Proxy operation retry failed";
1211                                 send_ldap_result( op, rs );
1212                         }
1213                 }
1214
1215         } else if ( op->o_conn &&
1216                 ( ( ( sendok & LDAP_BACK_SENDOK ) && LDAP_ERR_OK( rs->sr_err ) )
1217                         || ( ( sendok & LDAP_BACK_SENDERR ) && !LDAP_ERR_OK( rs->sr_err ) ) ) )
1218         {
1219                 send_ldap_result( op, rs );
1220         }
1221         if ( matched ) {
1222                 op->o_tmpfree( (char *)rs->sr_matched, matched_ctx );
1223         }
1224         if ( text ) {
1225                 ldap_memfree( text );
1226         }
1227         if ( rs->sr_ref ) {
1228                 op->o_tmpfree( rs->sr_ref, op->o_tmpmemctx );
1229                 rs->sr_ref = NULL;
1230         }
1231         if ( refs ) {
1232                 ber_memvfree( (void **)refs );
1233         }
1234         if ( ctrls ) {
1235                 assert( rs->sr_ctrls != NULL );
1236                 ldap_controls_free( ctrls );
1237         }
1238
1239         rs->sr_text = save_text;
1240         rs->sr_matched = save_matched;
1241         rs->sr_ref = save_ref;
1242         rs->sr_ctrls = save_ctrls;
1243
1244         return( LDAP_ERR_OK( rs->sr_err ) ? LDAP_SUCCESS : rs->sr_err );
1245 }
1246
1247 /*
1248  * meta_back_proxy_authz_cred()
1249  *
1250  * prepares credentials & method for meta_back_proxy_authz_bind();
1251  * or, if method is SASL, performs the SASL bind directly.
1252  */
1253 int
1254 meta_back_proxy_authz_cred(
1255         metaconn_t              *mc,
1256         int                     candidate,
1257         Operation               *op,
1258         SlapReply               *rs,
1259         ldap_back_send_t        sendok,
1260         struct berval           *binddn,
1261         struct berval           *bindcred,
1262         int                     *method )
1263 {
1264         metainfo_t              *mi = (metainfo_t *)op->o_bd->be_private;
1265         metatarget_t            *mt = mi->mi_targets[ candidate ];
1266         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
1267         struct berval           ndn;
1268         int                     dobind = 0;
1269
1270         /* don't proxyAuthz if protocol is not LDAPv3 */
1271         switch ( mt->mt_version ) {
1272         case LDAP_VERSION3:
1273                 break;
1274
1275         case 0:
1276                 if ( op->o_protocol == 0 || op->o_protocol == LDAP_VERSION3 ) {
1277                         break;
1278                 }
1279                 /* fall thru */
1280
1281         default:
1282                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1283                 if ( sendok & LDAP_BACK_SENDERR ) {
1284                         send_ldap_result( op, rs );
1285                 }
1286                 LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1287                 goto done;
1288         }
1289
1290         if ( op->o_tag == LDAP_REQ_BIND ) {
1291                 ndn = op->o_req_ndn;
1292
1293         } else if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1294                 ndn = op->o_conn->c_ndn;
1295
1296         } else {
1297                 ndn = op->o_ndn;
1298         }
1299
1300         /*
1301          * FIXME: we need to let clients use proxyAuthz
1302          * otherwise we cannot do symmetric pools of servers;
1303          * we have to live with the fact that a user can
1304          * authorize itself as any ID that is allowed
1305          * by the authzTo directive of the "proxyauthzdn".
1306          */
1307         /*
1308          * NOTE: current Proxy Authorization specification
1309          * and implementation do not allow proxy authorization
1310          * control to be provided with Bind requests
1311          */
1312         /*
1313          * if no bind took place yet, but the connection is bound
1314          * and the "proxyauthzdn" is set, then bind as 
1315          * "proxyauthzdn" and explicitly add the proxyAuthz 
1316          * control to every operation with the dn bound 
1317          * to the connection as control value.
1318          */
1319
1320         /* bind as proxyauthzdn only if no idassert mode
1321          * is requested, or if the client's identity
1322          * is authorized */
1323         switch ( mt->mt_idassert_mode ) {
1324         case LDAP_BACK_IDASSERT_LEGACY:
1325                 if ( !BER_BVISNULL( &ndn ) && !BER_BVISEMPTY( &ndn ) ) {
1326                         if ( !BER_BVISNULL( &mt->mt_idassert_authcDN ) && !BER_BVISEMPTY( &mt->mt_idassert_authcDN ) )
1327                         {
1328                                 *binddn = mt->mt_idassert_authcDN;
1329                                 *bindcred = mt->mt_idassert_passwd;
1330                                 dobind = 1;
1331                         }
1332                 }
1333                 break;
1334
1335         default:
1336                 /* NOTE: rootdn can always idassert */
1337                 if ( BER_BVISNULL( &ndn )
1338                         && mt->mt_idassert_authz == NULL
1339                         && !( mt->mt_idassert_flags & LDAP_BACK_AUTH_AUTHZ_ALL ) )
1340                 {
1341                         if ( mt->mt_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1342                                 rs->sr_err = LDAP_INAPPROPRIATE_AUTH;
1343                                 if ( sendok & LDAP_BACK_SENDERR ) {
1344                                         send_ldap_result( op, rs );
1345                                 }
1346                                 LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1347                                 goto done;
1348
1349                         }
1350
1351                         rs->sr_err = LDAP_SUCCESS;
1352                         *binddn = slap_empty_bv;
1353                         *bindcred = slap_empty_bv;
1354                         break;
1355
1356                 } else if ( mt->mt_idassert_authz && !be_isroot( op ) ) {
1357                         struct berval authcDN;
1358
1359                         if ( BER_BVISNULL( &ndn ) ) {
1360                                 authcDN = slap_empty_bv;
1361
1362                         } else {
1363                                 authcDN = ndn;
1364                         }       
1365                         rs->sr_err = slap_sasl_matches( op, mt->mt_idassert_authz,
1366                                         &authcDN, &authcDN );
1367                         if ( rs->sr_err != LDAP_SUCCESS ) {
1368                                 if ( mt->mt_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1369                                         if ( sendok & LDAP_BACK_SENDERR ) {
1370                                                 send_ldap_result( op, rs );
1371                                         }
1372                                         LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1373                                         goto done;
1374                                 }
1375
1376                                 rs->sr_err = LDAP_SUCCESS;
1377                                 *binddn = slap_empty_bv;
1378                                 *bindcred = slap_empty_bv;
1379                                 break;
1380                         }
1381                 }
1382
1383                 *binddn = mt->mt_idassert_authcDN;
1384                 *bindcred = mt->mt_idassert_passwd;
1385                 dobind = 1;
1386                 break;
1387         }
1388
1389         if ( dobind && mt->mt_idassert_authmethod == LDAP_AUTH_SASL ) {
1390 #ifdef HAVE_CYRUS_SASL
1391                 void            *defaults = NULL;
1392                 struct berval   authzID = BER_BVNULL;
1393                 int             freeauthz = 0;
1394
1395                 /* if SASL supports native authz, prepare for it */
1396                 if ( ( !op->o_do_not_cache || !op->o_is_auth_check ) &&
1397                                 ( mt->mt_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
1398                 {
1399                         switch ( mt->mt_idassert_mode ) {
1400                         case LDAP_BACK_IDASSERT_OTHERID:
1401                         case LDAP_BACK_IDASSERT_OTHERDN:
1402                                 authzID = mt->mt_idassert_authzID;
1403                                 break;
1404
1405                         case LDAP_BACK_IDASSERT_ANONYMOUS:
1406                                 BER_BVSTR( &authzID, "dn:" );
1407                                 break;
1408
1409                         case LDAP_BACK_IDASSERT_SELF:
1410                                 if ( BER_BVISNULL( &ndn ) ) {
1411                                         /* connection is not authc'd, so don't idassert */
1412                                         BER_BVSTR( &authzID, "dn:" );
1413                                         break;
1414                                 }
1415                                 authzID.bv_len = STRLENOF( "dn:" ) + ndn.bv_len;
1416                                 authzID.bv_val = slap_sl_malloc( authzID.bv_len + 1, op->o_tmpmemctx );
1417                                 AC_MEMCPY( authzID.bv_val, "dn:", STRLENOF( "dn:" ) );
1418                                 AC_MEMCPY( authzID.bv_val + STRLENOF( "dn:" ),
1419                                                 ndn.bv_val, ndn.bv_len + 1 );
1420                                 freeauthz = 1;
1421                                 break;
1422
1423                         default:
1424                                 break;
1425                         }
1426                 }
1427
1428                 if ( mt->mt_idassert_secprops != NULL ) {
1429                         rs->sr_err = ldap_set_option( msc->msc_ld,
1430                                 LDAP_OPT_X_SASL_SECPROPS,
1431                                 (void *)mt->mt_idassert_secprops );
1432
1433                         if ( rs->sr_err != LDAP_OPT_SUCCESS ) {
1434                                 rs->sr_err = LDAP_OTHER;
1435                                 if ( sendok & LDAP_BACK_SENDERR ) {
1436                                         send_ldap_result( op, rs );
1437                                 }
1438                                 LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1439                                 goto done;
1440                         }
1441                 }
1442
1443                 defaults = lutil_sasl_defaults( msc->msc_ld,
1444                                 mt->mt_idassert_sasl_mech.bv_val,
1445                                 mt->mt_idassert_sasl_realm.bv_val,
1446                                 mt->mt_idassert_authcID.bv_val,
1447                                 mt->mt_idassert_passwd.bv_val,
1448                                 authzID.bv_val );
1449                 if ( defaults == NULL ) {
1450                         rs->sr_err = LDAP_OTHER;
1451                         LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1452                         if ( sendok & LDAP_BACK_SENDERR ) {
1453                                 send_ldap_result( op, rs );
1454                         }
1455                         goto done;
1456                 }
1457
1458                 rs->sr_err = ldap_sasl_interactive_bind_s( msc->msc_ld, binddn->bv_val,
1459                                 mt->mt_idassert_sasl_mech.bv_val, NULL, NULL,
1460                                 LDAP_SASL_QUIET, lutil_sasl_interact,
1461                                 defaults );
1462
1463                 rs->sr_err = slap_map_api2result( rs );
1464                 if ( rs->sr_err != LDAP_SUCCESS ) {
1465                         LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1466                         if ( sendok & LDAP_BACK_SENDERR ) {
1467                                 send_ldap_result( op, rs );
1468                         }
1469
1470                 } else {
1471                         LDAP_BACK_CONN_ISBOUND_SET( msc );
1472                 }
1473
1474                 lutil_sasl_freedefs( defaults );
1475                 if ( freeauthz ) {
1476                         slap_sl_free( authzID.bv_val, op->o_tmpmemctx );
1477                 }
1478
1479                 goto done;
1480 #endif /* HAVE_CYRUS_SASL */
1481         }
1482
1483         *method = mt->mt_idassert_authmethod;
1484         switch ( mt->mt_idassert_authmethod ) {
1485         case LDAP_AUTH_NONE:
1486                 BER_BVSTR( binddn, "" );
1487                 BER_BVSTR( bindcred, "" );
1488                 /* fallthru */
1489
1490         case LDAP_AUTH_SIMPLE:
1491                 break;
1492
1493         default:
1494                 /* unsupported! */
1495                 LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1496                 rs->sr_err = LDAP_AUTH_METHOD_NOT_SUPPORTED;
1497                 if ( sendok & LDAP_BACK_SENDERR ) {
1498                         send_ldap_result( op, rs );
1499                 }
1500                 break;
1501         }
1502
1503 done:;
1504         return rs->sr_err;
1505 }
1506
1507 static int
1508 meta_back_proxy_authz_bind( metaconn_t *mc, int candidate, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1509 {
1510         metainfo_t              *mi = (metainfo_t *)op->o_bd->be_private;
1511         metatarget_t            *mt = mi->mi_targets[ candidate ];
1512         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
1513         struct berval           binddn = BER_BVC( "" ),
1514                                 cred = BER_BVC( "" );
1515         int                     method = LDAP_AUTH_NONE,
1516                                 rc;
1517
1518         rc = meta_back_proxy_authz_cred( mc, candidate, op, rs, sendok, &binddn, &cred, &method );
1519         if ( rc == LDAP_SUCCESS && !LDAP_BACK_CONN_ISBOUND( msc ) ) {
1520                 int     msgid;
1521
1522                 switch ( method ) {
1523                 case LDAP_AUTH_NONE:
1524                 case LDAP_AUTH_SIMPLE:
1525                         for (;;) {
1526                                 rs->sr_err = ldap_sasl_bind( msc->msc_ld,
1527                                         binddn.bv_val, LDAP_SASL_SIMPLE,
1528                                         &cred, NULL, NULL, &msgid );
1529                                 if ( rs->sr_err != LDAP_X_CONNECTING ) {
1530                                         break;
1531                                 }
1532                                 ldap_pvt_thread_yield();
1533                         }
1534                         rc = meta_back_bind_op_result( op, rs, mc, candidate, msgid, sendok );
1535                         if ( rc == LDAP_SUCCESS ) {
1536                                 /* set rebind stuff in case of successful proxyAuthz bind,
1537                                  * so that referral chasing is attempted using the right
1538                                  * identity */
1539                                 LDAP_BACK_CONN_ISBOUND_SET( msc );
1540                                 ber_bvreplace( &msc->msc_bound_ndn, &binddn );
1541
1542                                 if ( LDAP_BACK_SAVECRED( mi ) ) {
1543                                         if ( !BER_BVISNULL( &msc->msc_cred ) ) {
1544                                                 memset( msc->msc_cred.bv_val, 0,
1545                                                         msc->msc_cred.bv_len );
1546                                         }
1547                                         ber_bvreplace( &msc->msc_cred, &cred );
1548                                         ldap_set_rebind_proc( msc->msc_ld, mt->mt_rebind_f, msc );
1549                                 }
1550                         }
1551                         break;
1552
1553                 default:
1554                         assert( 0 );
1555                         break;
1556                 }
1557         }
1558
1559         return LDAP_BACK_CONN_ISBOUND( msc );
1560 }
1561
1562 /*
1563  * Add controls;
1564  *
1565  * if any needs to be added, it is prepended to existing ones,
1566  * in a newly allocated array.  The companion function
1567  * mi->mi_ldap_extra->controls_free() must be used to restore the original
1568  * status of op->o_ctrls.
1569  */
1570 int
1571 meta_back_controls_add(
1572                 Operation       *op,
1573                 SlapReply       *rs,
1574                 metaconn_t      *mc,
1575                 int             candidate,
1576                 LDAPControl     ***pctrls )
1577 {
1578         metainfo_t              *mi = (metainfo_t *)op->o_bd->be_private;
1579         metatarget_t            *mt = mi->mi_targets[ candidate ];
1580         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
1581
1582         LDAPControl             **ctrls = NULL;
1583         /* set to the maximum number of controls this backend can add */
1584         LDAPControl             c[ 2 ] = {{ 0 }};
1585         int                     n = 0, i, j1 = 0, j2 = 0;
1586
1587         *pctrls = NULL;
1588
1589         rs->sr_err = LDAP_SUCCESS;
1590
1591         /* don't add controls if protocol is not LDAPv3 */
1592         switch ( mt->mt_version ) {
1593         case LDAP_VERSION3:
1594                 break;
1595
1596         case 0:
1597                 if ( op->o_protocol == 0 || op->o_protocol == LDAP_VERSION3 ) {
1598                         break;
1599                 }
1600                 /* fall thru */
1601
1602         default:
1603                 goto done;
1604         }
1605
1606         /* put controls that go __before__ existing ones here */
1607
1608         /* proxyAuthz for identity assertion */
1609         switch ( mi->mi_ldap_extra->proxy_authz_ctrl( op, rs, &msc->msc_bound_ndn,
1610                 mt->mt_version, &mt->mt_idassert, &c[ j1 ] ) )
1611         {
1612         case SLAP_CB_CONTINUE:
1613                 break;
1614
1615         case LDAP_SUCCESS:
1616                 j1++;
1617                 break;
1618
1619         default:
1620                 goto done;
1621         }
1622
1623         /* put controls that go __after__ existing ones here */
1624
1625 #ifdef SLAP_CONTROL_X_SESSION_TRACKING
1626         /* session tracking */
1627         if ( META_BACK_TGT_ST_REQUEST( mt ) ) {
1628                 switch ( slap_ctrl_session_tracking_request_add( op, rs, &c[ j1 + j2 ] ) ) {
1629                 case SLAP_CB_CONTINUE:
1630                         break;
1631
1632                 case LDAP_SUCCESS:
1633                         j2++;
1634                         break;
1635
1636                 default:
1637                         goto done;
1638                 }
1639         }
1640 #endif /* SLAP_CONTROL_X_SESSION_TRACKING */
1641
1642         if ( rs->sr_err == SLAP_CB_CONTINUE ) {
1643                 rs->sr_err = LDAP_SUCCESS;
1644         }
1645
1646         /* if nothing to do, just bail out */
1647         if ( j1 == 0 && j2 == 0 ) {
1648                 goto done;
1649         }
1650
1651         assert( j1 + j2 <= (int) (sizeof( c )/sizeof( c[0] )) );
1652
1653         if ( op->o_ctrls ) {
1654                 for ( n = 0; op->o_ctrls[ n ]; n++ )
1655                         /* just count ctrls */ ;
1656         }
1657
1658         ctrls = op->o_tmpalloc( (n + j1 + j2 + 1) * sizeof( LDAPControl * ) + ( j1 + j2 ) * sizeof( LDAPControl ),
1659                         op->o_tmpmemctx );
1660         if ( j1 ) {
1661                 ctrls[ 0 ] = (LDAPControl *)&ctrls[ n + j1 + j2 + 1 ];
1662                 *ctrls[ 0 ] = c[ 0 ];
1663                 for ( i = 1; i < j1; i++ ) {
1664                         ctrls[ i ] = &ctrls[ 0 ][ i ];
1665                         *ctrls[ i ] = c[ i ];
1666                 }
1667         }
1668
1669         i = 0;
1670         if ( op->o_ctrls ) {
1671                 for ( i = 0; op->o_ctrls[ i ]; i++ ) {
1672                         ctrls[ i + j1 ] = op->o_ctrls[ i ];
1673                 }
1674         }
1675
1676         n += j1;
1677         if ( j2 ) {
1678                 ctrls[ n ] = (LDAPControl *)&ctrls[ n + j2 + 1 ] + j1;
1679                 *ctrls[ n ] = c[ j1 ];
1680                 for ( i = 1; i < j2; i++ ) {
1681                         ctrls[ n + i ] = &ctrls[ n ][ i ];
1682                         *ctrls[ n + i ] = c[ i ];
1683                 }
1684         }
1685
1686         ctrls[ n + j2 ] = NULL;
1687
1688 done:;
1689         if ( ctrls == NULL ) {
1690                 ctrls = op->o_ctrls;
1691         }
1692
1693         *pctrls = ctrls;
1694         
1695         return rs->sr_err;
1696 }
1697