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