]> git.sur5r.net Git - openldap/blob - servers/slapd/back-meta/bind.c
streamline group attr specification/diagnostics
[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-2007 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 = meta_back_candidates_get( op );
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         if ( op->orb_method == LDAP_AUTH_SIMPLE
76                 && be_isroot_dn( op->o_bd, &op->o_req_ndn ) )
77         {
78                 if ( !be_isroot_pw( op ) ) {
79                         rs->sr_err = LDAP_INVALID_CREDENTIALS;
80                         rs->sr_text = NULL;
81                         send_ldap_result( op, rs );
82                         return rs->sr_err;
83                 }
84
85                 if ( META_BACK_DEFER_ROOTDN_BIND( mi ) ) {
86                         rs->sr_err = LDAP_SUCCESS;
87                         rs->sr_text = NULL;
88                         /* frontend will return success */
89                         return rs->sr_err;
90                 }
91
92                 isroot = 1;
93         }
94
95         /* we need meta_back_getconn() not send result even on error,
96          * because we want to intercept the error and make it
97          * invalidCredentials */
98         mc = meta_back_getconn( op, rs, NULL, LDAP_BACK_BIND_DONTSEND );
99         if ( !mc ) {
100                 if ( LogTest( LDAP_DEBUG_ANY ) ) {
101                         char    buf[ SLAP_TEXT_BUFLEN ];
102
103                         snprintf( buf, sizeof( buf ),
104                                 "meta_back_bind: no target "
105                                 "for dn \"%s\" (%d%s%s).",
106                                 op->o_req_dn.bv_val, rs->sr_err,
107                                 rs->sr_text ? ". " : "",
108                                 rs->sr_text ? rs->sr_text : "" );
109                         Debug( LDAP_DEBUG_ANY,
110                                 "%s %s\n",
111                                 op->o_log_prefix, buf, 0 );
112                 }
113
114                 /* FIXME: there might be cases where we don't want
115                  * to map the error onto invalidCredentials */
116                 switch ( rs->sr_err ) {
117                 case LDAP_NO_SUCH_OBJECT:
118                 case LDAP_UNWILLING_TO_PERFORM:
119                         rs->sr_err = LDAP_INVALID_CREDENTIALS;
120                         rs->sr_text = NULL;
121                         break;
122                 }
123                 send_ldap_result( op, rs );
124                 return rs->sr_err;
125         }
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 == 0 ) {
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                         /* FIXME: in some cases (e.g. unavailable)
193                          * do not assume it's not candidate; rather
194                          * mark this as an error to be eventually
195                          * reported to client */
196                         META_CANDIDATE_CLEAR( &candidates[ i ] );
197                         break;
198                 }
199         }
200
201         /* must re-insert if local DN changed as result of bind */
202         if ( rc == LDAP_SUCCESS ) {
203                 if ( isroot ) {
204                         mc->mc_authz_target = META_BOUND_ALL;
205                         ber_dupbv( &op->orb_edn, be_root_dn( op->o_bd ) );
206                 }
207
208                 if ( !dn_match( &op->o_req_ndn, &mc->mc_local_ndn ) ) {
209                         metaconn_t      *tmpmc;
210                         int             lerr;
211
212                         /* wait for all other ops to release the connection */
213 retry_lock:;
214                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
215                         if ( mc->mc_refcnt > 1 ) {
216                                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
217                                 ldap_pvt_thread_yield();
218                                 goto retry_lock;
219                         }
220
221                         assert( mc->mc_refcnt == 1 );
222 #if META_BACK_PRINT_CONNTREE > 0
223                         meta_back_print_conntree( mi, ">>> meta_back_bind" );
224 #endif /* META_BACK_PRINT_CONNTREE */
225                         tmpmc = avl_delete( &mi->mi_conninfo.lai_tree, (caddr_t)mc,
226                                 meta_back_conndn_cmp );
227                         assert( tmpmc == mc );
228
229                         /* delete all cached connections with the current connection */
230                         if ( LDAP_BACK_SINGLECONN( mi ) ) {
231                                 while ( ( tmpmc = avl_delete( &mi->mi_conninfo.lai_tree, (caddr_t)mc, meta_back_conn_cmp ) ) != NULL )
232                                 {
233                                         Debug( LDAP_DEBUG_TRACE,
234                                                 "=>meta_back_bind: destroying conn %ld (refcnt=%u)\n",
235                                                 LDAP_BACK_PCONN_ID( mc ), mc->mc_refcnt, 0 );
236
237                                         if ( tmpmc->mc_refcnt != 0 ) {
238                                                 /* taint it */
239                                                 LDAP_BACK_CONN_TAINTED_SET( tmpmc );
240
241                                         } else {
242                                                 /*
243                                                  * Needs a test because the handler may be corrupted,
244                                                  * and calling ldap_unbind on a corrupted header results
245                                                  * in a segmentation fault
246                                                  */
247                                                 meta_back_conn_free( tmpmc );
248                                         }
249                                 }
250                         }
251
252                         ber_bvreplace( &mc->mc_local_ndn, &op->o_req_ndn );
253                         if ( isroot ) {
254                                 LDAP_BACK_CONN_ISPRIV_SET( mc );
255                                 LDAP_BACK_PCONN_SET( mc, op );
256                         }
257                         lerr = avl_insert( &mi->mi_conninfo.lai_tree, (caddr_t)mc,
258                                 meta_back_conndn_cmp, meta_back_conndn_dup );
259 #if META_BACK_PRINT_CONNTREE > 0
260                         meta_back_print_conntree( mi, "<<< meta_back_bind" );
261 #endif /* META_BACK_PRINT_CONNTREE */
262                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
263                         if ( lerr == -1 ) {
264                                 /* we can do this because mc_refcnt == 1 */
265                                 assert( mc->mc_refcnt == 1 );
266                                 mc->mc_refcnt = 0;
267                                 meta_back_conn_free( mc );
268                                 mc = NULL;
269                         }
270                 }
271         }
272
273         if ( mc != NULL ) {
274                 meta_back_release_conn( op, mc );
275         }
276
277         /*
278          * rc is LDAP_SUCCESS if at least one bind succeeded,
279          * err is the last error that occurred during a bind;
280          * if at least (and at most?) one bind succeeds, fine.
281          */
282         if ( rc != LDAP_SUCCESS ) {
283                 
284                 /*
285                  * deal with bind failure ...
286                  */
287
288                 /*
289                  * no target was found within the naming context, 
290                  * so bind must fail with invalid credentials
291                  */
292                 if ( rs->sr_err == LDAP_SUCCESS && gotit == 0 ) {
293                         rs->sr_err = LDAP_INVALID_CREDENTIALS;
294                 } else {
295                         rs->sr_err = slap_map_api2result( rs );
296                 }
297                 send_ldap_result( op, rs );
298                 return rs->sr_err;
299
300         }
301
302         return LDAP_SUCCESS;
303 }
304
305 static int
306 meta_back_bind_op_result(
307         Operation               *op,
308         SlapReply               *rs,
309         metaconn_t              *mc,
310         int                     candidate,
311         int                     msgid,
312         ldap_back_send_t        sendok )
313 {
314         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
315         metatarget_t            *mt = mi->mi_targets[ candidate ];
316         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
317         LDAPMessage             *res;
318         struct timeval          tv;
319         int                     rc;
320         int                     nretries = mt->mt_nretries;
321         char                    buf[ SLAP_TEXT_BUFLEN ];
322
323         Debug( LDAP_DEBUG_TRACE,
324                 ">>> %s meta_back_bind_op_result[%d]\n",
325                 op->o_log_prefix, candidate, 0 );
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         
459         if ( !BER_BVISNULL( &msc->msc_bound_ndn ) ) {
460                 ch_free( msc->msc_bound_ndn.bv_val );
461                 BER_BVZERO( &msc->msc_bound_ndn );
462         }
463
464         if ( !BER_BVISNULL( &msc->msc_cred ) ) {
465                 /* destroy sensitive data */
466                 memset( msc->msc_cred.bv_val, 0, msc->msc_cred.bv_len );
467                 ch_free( msc->msc_cred.bv_val );
468                 BER_BVZERO( &msc->msc_cred );
469         }
470
471         /*
472          * Rewrite the bind dn if needed
473          */
474         dc.target = mt;
475         dc.conn = op->o_conn;
476         dc.rs = rs;
477         dc.ctx = "bindDN";
478
479         if ( ldap_back_dn_massage( &dc, &op->o_req_dn, &mdn ) ) {
480                 rs->sr_text = "DN rewrite error";
481                 rs->sr_err = LDAP_OTHER;
482                 return rs->sr_err;
483         }
484
485         /* FIXME: this fixes the bind problem right now; we need
486          * to use the asynchronous version to get the "matched"
487          * and more in case of failure ... */
488         /* FIXME: should we check if at least some of the op->o_ctrls
489          * can/should be passed? */
490         for (;;) {
491                 rs->sr_err = ldap_sasl_bind( msc->msc_ld, mdn.bv_val,
492                         LDAP_SASL_SIMPLE, &op->orb_cred,
493                         op->o_ctrls, NULL, &msgid );
494                 if ( rs->sr_err != LDAP_X_CONNECTING ) {
495                         break;
496                 }
497                 ldap_pvt_thread_yield();
498         }
499         meta_back_bind_op_result( op, rs, mc, candidate, msgid, LDAP_BACK_DONTSEND );
500         if ( rs->sr_err != LDAP_SUCCESS ) {
501                 goto return_results;
502         }
503
504         /* If defined, proxyAuthz will be used also when
505          * back-ldap is the authorizing backend; for this
506          * purpose, a successful bind is followed by a
507          * bind with the configured identity assertion */
508         /* NOTE: use with care */
509         if ( mt->mt_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) {
510                 meta_back_proxy_authz_bind( mc, candidate, op, rs, LDAP_BACK_SENDERR );
511                 if ( !LDAP_BACK_CONN_ISBOUND( msc ) ) {
512                         goto return_results;
513                 }
514                 goto cache_refresh;
515         }
516
517         ber_bvreplace( &msc->msc_bound_ndn, &op->o_req_ndn );
518         LDAP_BACK_CONN_ISBOUND_SET( msc );
519         mc->mc_authz_target = candidate;
520
521         if ( LDAP_BACK_SAVECRED( mi ) ) {
522                 if ( !BER_BVISNULL( &msc->msc_cred ) ) {
523                         memset( msc->msc_cred.bv_val, 0,
524                                 msc->msc_cred.bv_len );
525                 }
526                 ber_bvreplace( &msc->msc_cred, &op->orb_cred );
527                 ldap_set_rebind_proc( msc->msc_ld, mt->mt_rebind_f, msc );
528         }
529
530 cache_refresh:;
531         if ( mi->mi_cache.ttl != META_DNCACHE_DISABLED
532                         && !BER_BVISEMPTY( &op->o_req_ndn ) )
533         {
534                 ( void )meta_dncache_update_entry( &mi->mi_cache,
535                                 &op->o_req_ndn, candidate );
536         }
537
538 return_results:;
539         if ( mdn.bv_val != op->o_req_dn.bv_val ) {
540                 free( mdn.bv_val );
541         }
542
543         if ( META_BACK_TGT_QUARANTINE( mt ) ) {
544                 meta_back_quarantine( op, rs, candidate );
545         }
546
547         return rs->sr_err;
548 }
549
550 /*
551  * meta_back_single_dobind
552  */
553 int
554 meta_back_single_dobind(
555         Operation               *op,
556         SlapReply               *rs,
557         metaconn_t              **mcp,
558         int                     candidate,
559         ldap_back_send_t        sendok,
560         int                     nretries,
561         int                     dolock )
562 {
563         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
564         metatarget_t            *mt = mi->mi_targets[ candidate ];
565         metaconn_t              *mc = *mcp;
566         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
567         static struct berval    cred = BER_BVC( "" );
568         int                     msgid;
569
570         assert( !LDAP_BACK_CONN_ISBOUND( msc ) );
571
572         /* NOTE: this obsoletes pseudorootdn */
573         if ( op->o_conn != NULL &&
574                 !op->o_do_not_cache &&
575                 ( BER_BVISNULL( &msc->msc_bound_ndn ) ||
576                         BER_BVISEMPTY( &msc->msc_bound_ndn ) ||
577                         ( LDAP_BACK_CONN_ISPRIV( mc ) && dn_match( &msc->msc_bound_ndn, &mt->mt_idassert_authcDN ) ) ||
578                         ( mt->mt_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) ) )
579         {
580                 (void)meta_back_proxy_authz_bind( mc, candidate, op, rs, sendok );
581
582         } else {
583
584                 /* FIXME: should we check if at least some of the op->o_ctrls
585                  * can/should be passed? */
586                 for (;;) {
587                         rs->sr_err = ldap_sasl_bind( msc->msc_ld,
588                                 "", LDAP_SASL_SIMPLE, &cred,
589                                 NULL, NULL, &msgid );
590                         if ( rs->sr_err != LDAP_X_CONNECTING ) {
591                                 break;
592                         }
593                         ldap_pvt_thread_yield();
594                 }
595
596                 rs->sr_err = meta_back_bind_op_result( op, rs, mc, candidate, msgid, sendok );
597         }
598
599         if ( rs->sr_err != LDAP_SUCCESS ) {
600                 if ( dolock ) {
601                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
602                 }
603                 LDAP_BACK_CONN_BINDING_CLEAR( msc );
604                 if ( META_BACK_ONERR_STOP( mi ) ) {
605                         LDAP_BACK_CONN_TAINTED_SET( mc );
606                         meta_back_release_conn_lock( op, mc, 0 );
607                         *mcp = NULL;
608                 }
609                 if ( dolock ) {
610                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
611                 }
612         }
613
614         if ( META_BACK_TGT_QUARANTINE( mt ) ) {
615                 meta_back_quarantine( op, rs, candidate );
616         }
617
618         return rs->sr_err;
619 }
620
621 /*
622  * meta_back_dobind
623  */
624 int
625 meta_back_dobind(
626         Operation               *op,
627         SlapReply               *rs,
628         metaconn_t              *mc,
629         ldap_back_send_t        sendok )
630 {
631         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
632
633         int                     bound = 0,
634                                 i,
635                                 isroot = 0;
636
637         SlapReply               *candidates = meta_back_candidates_get( op );
638
639         if ( be_isroot( op ) ) {
640                 isroot = 1;
641         }
642
643         Debug( LDAP_DEBUG_TRACE,
644                 "%s meta_back_dobind: conn=%ld%s\n",
645                 op->o_log_prefix,
646                 LDAP_BACK_PCONN_ID( mc ),
647                 isroot ? " (isroot)" : "" );
648
649         /*
650          * all the targets are bound as pseudoroot
651          */
652         if ( mc->mc_authz_target == META_BOUND_ALL ) {
653                 bound = 1;
654                 goto done;
655         }
656
657         for ( i = 0; i < mi->mi_ntargets; i++ ) {
658                 metatarget_t            *mt = mi->mi_targets[ i ];
659                 metasingleconn_t        *msc = &mc->mc_conns[ i ];
660                 int                     rc;
661
662                 /*
663                  * Not a candidate
664                  */
665                 if ( !META_IS_CANDIDATE( &candidates[ i ] ) ) {
666                         continue;
667                 }
668
669                 assert( msc->msc_ld != NULL );
670
671                 /*
672                  * If the target is already bound it is skipped
673                  */
674
675 retry_binding:;
676                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
677                 if ( LDAP_BACK_CONN_ISBOUND( msc )
678                         || ( LDAP_BACK_CONN_ISANON( msc )
679                                 && mt->mt_idassert_authmethod == LDAP_AUTH_NONE ) )
680                 {
681                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
682                         ++bound;
683                         continue;
684
685                 } else if ( META_BACK_CONN_CREATING( msc ) || LDAP_BACK_CONN_BINDING( msc ) )
686                 {
687                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
688                         ldap_pvt_thread_yield();
689                         goto retry_binding;
690
691                 }
692
693                 LDAP_BACK_CONN_BINDING_SET( msc );
694                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
695
696                 rc = meta_back_single_dobind( op, rs, &mc, i,
697                         LDAP_BACK_DONTSEND, mt->mt_nretries, 1 );
698                 /*
699                  * NOTE: meta_back_single_dobind() already retries;
700                  * in case of failure, it resets mc...
701                  */
702                 if ( rc != LDAP_SUCCESS ) {
703                         char            buf[ SLAP_TEXT_BUFLEN ];
704
705                         if ( mc == NULL ) {
706                                 /* meta_back_single_dobind() already sent 
707                                  * response and released connection */
708                                 goto send_err;
709                         }
710
711
712                         if ( rc == LDAP_UNAVAILABLE ) {
713                                 /* FIXME: meta_back_retry() already re-calls
714                                  * meta_back_single_dobind() */
715                                 if ( meta_back_retry( op, rs, &mc, i, sendok ) ) {
716                                         goto retry_ok;
717                                 }
718
719                                 if ( mc != NULL ) {
720                                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
721                                         LDAP_BACK_CONN_BINDING_CLEAR( msc );
722                                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
723                                         meta_back_release_conn( op, mc );
724                                 }
725
726                                 return 0;
727                         }
728
729                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
730                         LDAP_BACK_CONN_BINDING_CLEAR( msc );
731                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
732
733                         snprintf( buf, sizeof( buf ),
734                                 "meta_back_dobind[%d]: (%s) err=%d (%s).",
735                                 i, isroot ? op->o_bd->be_rootdn.bv_val : "anonymous",
736                                 rc, ldap_err2string( rc ) );
737                         Debug( LDAP_DEBUG_ANY,
738                                 "%s %s\n",
739                                 op->o_log_prefix, buf, 0 );
740
741                         /*
742                          * null cred bind should always succeed
743                          * as anonymous, so a failure means
744                          * the target is no longer candidate possibly
745                          * due to technical reasons (remote host down?)
746                          * so better clear the handle
747                          */
748                         /* leave the target candidate, but record the error for later use */
749                         candidates[ i ].sr_err = rc;
750                         if ( META_BACK_ONERR_STOP( mi ) ) {
751                                 bound = 0;
752                                 goto done;
753                         }
754
755                         continue;
756                 } /* else */
757
758 retry_ok:;
759                 Debug( LDAP_DEBUG_TRACE,
760                         "%s meta_back_dobind[%d]: "
761                         "(%s)\n",
762                         op->o_log_prefix, i,
763                         isroot ? op->o_bd->be_rootdn.bv_val : "anonymous" );
764
765                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
766                 LDAP_BACK_CONN_BINDING_CLEAR( msc );
767                 if ( isroot ) {
768                         LDAP_BACK_CONN_ISBOUND_SET( msc );
769                 } else {
770                         LDAP_BACK_CONN_ISANON_SET( msc );
771                 }
772                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
773                 ++bound;
774         }
775
776 done:;
777         Debug( LDAP_DEBUG_TRACE,
778                 "%s meta_back_dobind: conn=%ld bound=%d\n",
779                 op->o_log_prefix, LDAP_BACK_PCONN_ID( mc ), bound );
780
781         if ( bound == 0 ) {
782                 meta_back_release_conn( op, mc );
783
784 send_err:;
785                 if ( sendok & LDAP_BACK_SENDERR ) {
786                         if ( rs->sr_err == LDAP_SUCCESS ) {
787                                 rs->sr_err = LDAP_BUSY;
788                         }
789                         send_ldap_result( op, rs );
790                 }
791
792                 return 0;
793         }
794
795         return ( bound > 0 );
796 }
797
798 /*
799  * meta_back_default_rebind
800  *
801  * This is a callback used for chasing referrals using the same
802  * credentials as the original user on this session.
803  */
804 int 
805 meta_back_default_rebind(
806         LDAP                    *ld,
807         LDAP_CONST char         *url,
808         ber_tag_t               request,
809         ber_int_t               msgid,
810         void                    *params )
811 {
812         metasingleconn_t        *msc = ( metasingleconn_t * )params;
813
814         return ldap_sasl_bind_s( ld, msc->msc_bound_ndn.bv_val,
815                         LDAP_SASL_SIMPLE, &msc->msc_cred,
816                         NULL, NULL, NULL );
817 }
818
819 /*
820  * meta_back_default_urllist
821  *
822  * This is a callback used for mucking with the urllist
823  */
824 int 
825 meta_back_default_urllist(
826         LDAP            *ld,
827         LDAPURLDesc     **urllist,
828         LDAPURLDesc     **url,
829         void            *params )
830 {
831         metatarget_t    *mt = (metatarget_t *)params;
832         LDAPURLDesc     **urltail;
833
834         if ( urllist == url ) {
835                 return LDAP_SUCCESS;
836         }
837
838         for ( urltail = &(*url)->lud_next; *urltail; urltail = &(*urltail)->lud_next )
839                 /* count */ ;
840
841         *urltail = *urllist;
842         *urllist = *url;
843         *url = NULL;
844
845         ldap_pvt_thread_mutex_lock( &mt->mt_uri_mutex );
846         if ( mt->mt_uri ) {
847                 ch_free( mt->mt_uri );
848         }
849
850         ldap_get_option( ld, LDAP_OPT_URI, (void *)&mt->mt_uri );
851         ldap_pvt_thread_mutex_unlock( &mt->mt_uri_mutex );
852
853         return LDAP_SUCCESS;
854 }
855
856 int
857 meta_back_cancel(
858         metaconn_t              *mc,
859         Operation               *op,
860         SlapReply               *rs,
861         ber_int_t               msgid,
862         int                     candidate,
863         ldap_back_send_t        sendok )
864 {
865         metainfo_t              *mi = (metainfo_t *)op->o_bd->be_private;
866
867         metatarget_t            *mt = mi->mi_targets[ candidate ];
868         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
869
870         int                     rc = LDAP_OTHER;
871
872         Debug( LDAP_DEBUG_TRACE, ">>> %s meta_back_cancel[%d] msgid=%d\n",
873                 op->o_log_prefix, candidate, msgid );
874
875         /* default behavior */
876         if ( META_BACK_TGT_ABANDON( mt ) ) {
877                 rc = ldap_abandon_ext( msc->msc_ld, msgid, NULL, NULL );
878
879         } else if ( META_BACK_TGT_IGNORE( mt ) ) {
880                 rc = ldap_pvt_discard( msc->msc_ld, msgid );
881
882         } else if ( META_BACK_TGT_CANCEL( mt ) ) {
883                 rc = ldap_cancel_s( msc->msc_ld, msgid, NULL, NULL );
884
885         } else {
886                 assert( 0 );
887         }
888
889         Debug( LDAP_DEBUG_TRACE, "<<< %s meta_back_cancel[%d] err=%d\n",
890                 op->o_log_prefix, candidate, rc );
891
892         return rc;
893 }
894
895
896
897 /*
898  * FIXME: error return must be handled in a cleaner way ...
899  */
900 int
901 meta_back_op_result(
902         metaconn_t              *mc,
903         Operation               *op,
904         SlapReply               *rs,
905         int                     candidate,
906         ber_int_t               msgid,
907         time_t                  timeout,
908         ldap_back_send_t        sendok )
909 {
910         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
911
912         const char      *save_text = rs->sr_text,
913                         *save_matched = rs->sr_matched;
914         BerVarray       save_ref = rs->sr_ref;
915         LDAPControl     **save_ctrls = rs->sr_ctrls;
916         void            *matched_ctx = NULL;
917
918         char            *matched = NULL;
919         char            *text = NULL;
920         char            **refs = NULL;
921         LDAPControl     **ctrls = NULL;
922
923         assert( mc != NULL );
924
925         rs->sr_text = NULL;
926         rs->sr_matched = NULL;
927         rs->sr_ref = NULL;
928         rs->sr_ctrls = NULL;
929
930         if ( candidate != META_TARGET_NONE ) {
931                 metatarget_t            *mt = mi->mi_targets[ candidate ];
932                 metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
933
934 #define ERR_OK(err) ((err) == LDAP_SUCCESS || (err) == LDAP_COMPARE_FALSE || (err) == LDAP_COMPARE_TRUE)
935
936                 if ( ERR_OK( rs->sr_err ) ) {
937                         int             rc;
938                         struct timeval  tv;
939                         LDAPMessage     *res = NULL;
940                         time_t          stoptime = (time_t)(-1);
941                         int             timeout_err = op->o_protocol >= LDAP_VERSION3 ?
942                                                 LDAP_ADMINLIMIT_EXCEEDED : LDAP_OTHER;
943                         const char      *timeout_text = "Operation timed out";
944
945                         /* if timeout is not specified, compute and use
946                          * the one specific to the ongoing operation */
947                         if ( timeout == (time_t)(-1) ) {
948                                 slap_op_t       opidx = slap_req2op( op->o_tag );
949
950                                 if ( opidx == SLAP_OP_SEARCH ) {
951                                         if ( op->ors_tlimit <= 0 ) {
952                                                 timeout = 0;
953
954                                         } else {
955                                                 timeout = op->ors_tlimit;
956                                                 timeout_err = LDAP_TIMELIMIT_EXCEEDED;
957                                                 timeout_text = NULL;
958                                         }
959
960                                 } else {
961                                         timeout = mt->mt_timeout[ opidx ];
962                                 }
963                         }
964
965                         /* better than nothing :) */
966                         if ( timeout == 0 ) {
967                                 if ( mi->mi_idle_timeout ) {
968                                         timeout = mi->mi_idle_timeout;
969
970                                 } else if ( mi->mi_conn_ttl ) {
971                                         timeout = mi->mi_conn_ttl;
972                                 }
973                         }
974
975                         if ( timeout ) {
976                                 stoptime = op->o_time + timeout;
977                         }
978
979                         LDAP_BACK_TV_SET( &tv );
980
981 retry:;
982                         rc = ldap_result( msc->msc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
983                         switch ( rc ) {
984                         case 0:
985                                 if ( timeout && slap_get_time() > stoptime ) {
986                                         (void)meta_back_cancel( mc, op, rs, msgid, candidate, sendok );
987                                         rs->sr_err = timeout_err;
988                                         rs->sr_text = timeout_text;
989                                         break;
990                                 }
991
992                                 LDAP_BACK_TV_SET( &tv );
993                                 ldap_pvt_thread_yield();
994                                 goto retry;
995
996                         case -1:
997                                 ldap_get_option( msc->msc_ld, LDAP_OPT_RESULT_CODE,
998                                                 &rs->sr_err );
999                                 break;
1000
1001
1002                         /* otherwise get the result; if it is not
1003                          * LDAP_SUCCESS, record it in the reply
1004                          * structure (this includes 
1005                          * LDAP_COMPARE_{TRUE|FALSE}) */
1006                         default:
1007                                 /* only touch when activity actually took place... */
1008                                 if ( mi->mi_idle_timeout != 0 && msc->msc_time < op->o_time ) {
1009                                         msc->msc_time = op->o_time;
1010                                 }
1011
1012                                 rc = ldap_parse_result( msc->msc_ld, res, &rs->sr_err,
1013                                                 &matched, &text, &refs, &ctrls, 1 );
1014                                 res = NULL;
1015                                 rs->sr_text = text;
1016                                 if ( rc != LDAP_SUCCESS ) {
1017                                         rs->sr_err = rc;
1018                                 }
1019                                 if ( refs != NULL ) {
1020                                         int     i;
1021         
1022                                         for ( i = 0; refs[ i ] != NULL; i++ )
1023                                                 /* count */ ;
1024                                         rs->sr_ref = op->o_tmpalloc( sizeof( struct berval ) * ( i + 1 ),
1025                                                 op->o_tmpmemctx );
1026                                         for ( i = 0; refs[ i ] != NULL; i++ ) {
1027                                                 ber_str2bv( refs[ i ], 0, 0, &rs->sr_ref[ i ] );
1028                                         }
1029                                         BER_BVZERO( &rs->sr_ref[ i ] );
1030                                 }
1031                                 if ( ctrls != NULL ) {
1032                                         rs->sr_ctrls = ctrls;
1033                                 }
1034                         }
1035
1036                         assert( res == NULL );
1037                 }
1038
1039                 /* if the error in the reply structure is not
1040                  * LDAP_SUCCESS, try to map it from client 
1041                  * to server error */
1042                 if ( !ERR_OK( rs->sr_err ) ) {
1043                         rs->sr_err = slap_map_api2result( rs );
1044
1045                         /* internal ops ( op->o_conn == NULL ) 
1046                          * must not reply to client */
1047                         if ( op->o_conn && !op->o_do_not_cache && matched ) {
1048
1049                                 /* record the (massaged) matched
1050                                  * DN into the reply structure */
1051                                 rs->sr_matched = matched;
1052                         }
1053                 }
1054
1055                 if ( META_BACK_TGT_QUARANTINE( mt ) ) {
1056                         meta_back_quarantine( op, rs, candidate );
1057                 }
1058
1059         } else {
1060                 int     i,
1061                         err = rs->sr_err;
1062
1063                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
1064                         metasingleconn_t        *msc = &mc->mc_conns[ i ];
1065                         char                    *xtext = NULL;
1066                         char                    *xmatched = NULL;
1067
1068                         rs->sr_err = LDAP_SUCCESS;
1069
1070                         ldap_get_option( msc->msc_ld, LDAP_OPT_RESULT_CODE, &rs->sr_err );
1071                         if ( rs->sr_err != LDAP_SUCCESS ) {
1072                                 /*
1073                                  * better check the type of error. In some cases
1074                                  * (search ?) it might be better to return a
1075                                  * success if at least one of the targets gave
1076                                  * positive result ...
1077                                  */
1078                                 ldap_get_option( msc->msc_ld,
1079                                                 LDAP_OPT_DIAGNOSTIC_MESSAGE, &xtext );
1080                                 if ( xtext != NULL && xtext [ 0 ] == '\0' ) {
1081                                         ldap_memfree( xtext );
1082                                         xtext = NULL;
1083                                 }
1084
1085                                 ldap_get_option( msc->msc_ld,
1086                                                 LDAP_OPT_MATCHED_DN, &xmatched );
1087                                 if ( xmatched != NULL && xmatched[ 0 ] == '\0' ) {
1088                                         ldap_memfree( xmatched );
1089                                         xmatched = NULL;
1090                                 }
1091
1092                                 rs->sr_err = slap_map_api2result( rs );
1093         
1094                                 if ( LogTest( LDAP_DEBUG_ANY ) ) {
1095                                         char    buf[ SLAP_TEXT_BUFLEN ];
1096
1097                                         snprintf( buf, sizeof( buf ),
1098                                                 "meta_back_op_result[%d] "
1099                                                 "err=%d text=\"%s\" matched=\"%s\"", 
1100                                                 i, rs->sr_err,
1101                                                 ( xtext ? xtext : "" ),
1102                                                 ( xmatched ? xmatched : "" ) );
1103                                         Debug( LDAP_DEBUG_ANY, "%s %s.\n",
1104                                                 op->o_log_prefix, buf, 0 );
1105                                 }
1106
1107                                 /*
1108                                  * FIXME: need to rewrite "match" (need rwinfo)
1109                                  */
1110                                 switch ( rs->sr_err ) {
1111                                 default:
1112                                         err = rs->sr_err;
1113                                         if ( xtext != NULL ) {
1114                                                 if ( text ) {
1115                                                         ldap_memfree( text );
1116                                                 }
1117                                                 text = xtext;
1118                                                 xtext = NULL;
1119                                         }
1120                                         if ( xmatched != NULL ) {
1121                                                 if ( matched ) {
1122                                                         ldap_memfree( matched );
1123                                                 }
1124                                                 matched = xmatched;
1125                                                 xmatched = NULL;
1126                                         }
1127                                         break;
1128                                 }
1129
1130                                 if ( xtext ) {
1131                                         ldap_memfree( xtext );
1132                                 }
1133         
1134                                 if ( xmatched ) {
1135                                         ldap_memfree( xmatched );
1136                                 }
1137                         }
1138
1139                         if ( META_BACK_TGT_QUARANTINE( mi->mi_targets[ i ] ) ) {
1140                                 meta_back_quarantine( op, rs, i );
1141                         }
1142                 }
1143
1144                 if ( err != LDAP_SUCCESS ) {
1145                         rs->sr_err = err;
1146                 }
1147         }
1148
1149         if ( matched != NULL ) {
1150                 struct berval   dn, pdn;
1151
1152                 ber_str2bv( matched, 0, 0, &dn );
1153                 if ( dnPretty( NULL, &dn, &pdn, op->o_tmpmemctx ) == LDAP_SUCCESS ) {
1154                         ldap_memfree( matched );
1155                         matched_ctx = op->o_tmpmemctx;
1156                         matched = pdn.bv_val;
1157                 }
1158                 rs->sr_matched = matched;
1159         }
1160
1161         if ( op->o_conn &&
1162                 ( ( sendok & LDAP_BACK_SENDOK ) 
1163                         || ( ( sendok & LDAP_BACK_SENDERR ) && rs->sr_err != LDAP_SUCCESS ) ) )
1164         {
1165                 send_ldap_result( op, rs );
1166         }
1167         if ( matched ) {
1168                 op->o_tmpfree( (char *)rs->sr_matched, matched_ctx );
1169         }
1170         if ( text ) {
1171                 ldap_memfree( text );
1172         }
1173         if ( rs->sr_ref ) {
1174                 assert( refs != NULL );
1175                 ber_memvfree( (void **)refs );
1176                 op->o_tmpfree( rs->sr_ref, op->o_tmpmemctx );
1177         }
1178         if ( ctrls ) {
1179                 assert( rs->sr_ctrls != NULL );
1180                 ldap_controls_free( ctrls );
1181         }
1182
1183         rs->sr_text = save_text;
1184         rs->sr_matched = save_matched;
1185         rs->sr_ref = save_ref;
1186         rs->sr_ctrls = save_ctrls;
1187
1188         return( ERR_OK( rs->sr_err ) ? LDAP_SUCCESS : rs->sr_err );
1189 }
1190
1191 /*
1192  * meta_back_proxy_authz_cred()
1193  *
1194  * prepares credentials & method for meta_back_proxy_authz_bind();
1195  * or, if method is SASL, performs the SASL bind directly.
1196  */
1197 int
1198 meta_back_proxy_authz_cred(
1199         metaconn_t              *mc,
1200         int                     candidate,
1201         Operation               *op,
1202         SlapReply               *rs,
1203         ldap_back_send_t        sendok,
1204         struct berval           *binddn,
1205         struct berval           *bindcred,
1206         int                     *method )
1207 {
1208         metainfo_t              *mi = (metainfo_t *)op->o_bd->be_private;
1209         metatarget_t            *mt = mi->mi_targets[ candidate ];
1210         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
1211         struct berval           ndn;
1212         int                     dobind = 0;
1213
1214         /* don't proxyAuthz if protocol is not LDAPv3 */
1215         switch ( mt->mt_version ) {
1216         case LDAP_VERSION3:
1217                 break;
1218
1219         case 0:
1220                 if ( op->o_protocol == 0 || op->o_protocol == LDAP_VERSION3 ) {
1221                         break;
1222                 }
1223                 /* fall thru */
1224
1225         default:
1226                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1227                 if ( sendok & LDAP_BACK_SENDERR ) {
1228                         send_ldap_result( op, rs );
1229                 }
1230                 LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1231                 goto done;
1232         }
1233
1234         if ( op->o_tag == LDAP_REQ_BIND ) {
1235                 ndn = op->o_req_ndn;
1236
1237         } else if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1238                 ndn = op->o_conn->c_ndn;
1239
1240         } else {
1241                 ndn = op->o_ndn;
1242         }
1243
1244         /*
1245          * FIXME: we need to let clients use proxyAuthz
1246          * otherwise we cannot do symmetric pools of servers;
1247          * we have to live with the fact that a user can
1248          * authorize itself as any ID that is allowed
1249          * by the authzTo directive of the "proxyauthzdn".
1250          */
1251         /*
1252          * NOTE: current Proxy Authorization specification
1253          * and implementation do not allow proxy authorization
1254          * control to be provided with Bind requests
1255          */
1256         /*
1257          * if no bind took place yet, but the connection is bound
1258          * and the "proxyauthzdn" is set, then bind as 
1259          * "proxyauthzdn" and explicitly add the proxyAuthz 
1260          * control to every operation with the dn bound 
1261          * to the connection as control value.
1262          */
1263
1264         /* bind as proxyauthzdn only if no idassert mode
1265          * is requested, or if the client's identity
1266          * is authorized */
1267         switch ( mt->mt_idassert_mode ) {
1268         case LDAP_BACK_IDASSERT_LEGACY:
1269                 if ( !BER_BVISNULL( &ndn ) && !BER_BVISEMPTY( &ndn ) ) {
1270                         if ( !BER_BVISNULL( &mt->mt_idassert_authcDN ) && !BER_BVISEMPTY( &mt->mt_idassert_authcDN ) )
1271                         {
1272                                 *binddn = mt->mt_idassert_authcDN;
1273                                 *bindcred = mt->mt_idassert_passwd;
1274                                 dobind = 1;
1275                         }
1276                 }
1277                 break;
1278
1279         default:
1280                 /* NOTE: rootdn can always idassert */
1281                 if ( BER_BVISNULL( &ndn ) && mt->mt_idassert_authz == NULL ) {
1282                         if ( mt->mt_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1283                                 rs->sr_err = LDAP_INAPPROPRIATE_AUTH;
1284                                 if ( sendok & LDAP_BACK_SENDERR ) {
1285                                         send_ldap_result( op, rs );
1286                                 }
1287                                 LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1288
1289                         } else {
1290                                 rs->sr_err = LDAP_SUCCESS;
1291                                 *binddn = slap_empty_bv;
1292                                 *bindcred = slap_empty_bv;
1293                                 break;
1294                         }
1295
1296                         goto done;
1297
1298                 } else if ( mt->mt_idassert_authz && !be_isroot( op ) ) {
1299                         struct berval authcDN;
1300
1301                         if ( BER_BVISNULL( &ndn ) ) {
1302                                 authcDN = slap_empty_bv;
1303
1304                         } else {
1305                                 authcDN = ndn;
1306                         }       
1307                         rs->sr_err = slap_sasl_matches( op, mt->mt_idassert_authz,
1308                                         &authcDN, &authcDN );
1309                         if ( rs->sr_err != LDAP_SUCCESS ) {
1310                                 if ( mt->mt_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1311                                         if ( sendok & LDAP_BACK_SENDERR ) {
1312                                                 send_ldap_result( op, rs );
1313                                         }
1314                                         LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1315
1316                                 } else {
1317                                         rs->sr_err = LDAP_SUCCESS;
1318                                         *binddn = slap_empty_bv;
1319                                         *bindcred = slap_empty_bv;
1320                                         break;
1321                                 }
1322
1323                                 goto done;
1324                         }
1325                 }
1326
1327                 *binddn = mt->mt_idassert_authcDN;
1328                 *bindcred = mt->mt_idassert_passwd;
1329                 dobind = 1;
1330                 break;
1331         }
1332
1333         if ( dobind && mt->mt_idassert_authmethod == LDAP_AUTH_SASL ) {
1334 #ifdef HAVE_CYRUS_SASL
1335                 void            *defaults = NULL;
1336                 struct berval   authzID = BER_BVNULL;
1337                 int             freeauthz = 0;
1338
1339                 /* if SASL supports native authz, prepare for it */
1340                 if ( ( !op->o_do_not_cache || !op->o_is_auth_check ) &&
1341                                 ( mt->mt_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
1342                 {
1343                         switch ( mt->mt_idassert_mode ) {
1344                         case LDAP_BACK_IDASSERT_OTHERID:
1345                         case LDAP_BACK_IDASSERT_OTHERDN:
1346                                 authzID = mt->mt_idassert_authzID;
1347                                 break;
1348
1349                         case LDAP_BACK_IDASSERT_ANONYMOUS:
1350                                 BER_BVSTR( &authzID, "dn:" );
1351                                 break;
1352
1353                         case LDAP_BACK_IDASSERT_SELF:
1354                                 if ( BER_BVISNULL( &ndn ) ) {
1355                                         /* connection is not authc'd, so don't idassert */
1356                                         BER_BVSTR( &authzID, "dn:" );
1357                                         break;
1358                                 }
1359                                 authzID.bv_len = STRLENOF( "dn:" ) + ndn.bv_len;
1360                                 authzID.bv_val = slap_sl_malloc( authzID.bv_len + 1, op->o_tmpmemctx );
1361                                 AC_MEMCPY( authzID.bv_val, "dn:", STRLENOF( "dn:" ) );
1362                                 AC_MEMCPY( authzID.bv_val + STRLENOF( "dn:" ),
1363                                                 ndn.bv_val, ndn.bv_len + 1 );
1364                                 freeauthz = 1;
1365                                 break;
1366
1367                         default:
1368                                 break;
1369                         }
1370                 }
1371
1372                 if ( mt->mt_idassert_secprops != NULL ) {
1373                         rs->sr_err = ldap_set_option( msc->msc_ld,
1374                                 LDAP_OPT_X_SASL_SECPROPS,
1375                                 (void *)mt->mt_idassert_secprops );
1376
1377                         if ( rs->sr_err != LDAP_OPT_SUCCESS ) {
1378                                 rs->sr_err = LDAP_OTHER;
1379                                 if ( sendok & LDAP_BACK_SENDERR ) {
1380                                         send_ldap_result( op, rs );
1381                                 }
1382                                 LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1383                                 goto done;
1384                         }
1385                 }
1386
1387                 defaults = lutil_sasl_defaults( msc->msc_ld,
1388                                 mt->mt_idassert_sasl_mech.bv_val,
1389                                 mt->mt_idassert_sasl_realm.bv_val,
1390                                 mt->mt_idassert_authcID.bv_val,
1391                                 mt->mt_idassert_passwd.bv_val,
1392                                 authzID.bv_val );
1393
1394                 rs->sr_err = ldap_sasl_interactive_bind_s( msc->msc_ld, binddn->bv_val,
1395                                 mt->mt_idassert_sasl_mech.bv_val, NULL, NULL,
1396                                 LDAP_SASL_QUIET, lutil_sasl_interact,
1397                                 defaults );
1398
1399                 rs->sr_err = slap_map_api2result( rs );
1400                 if ( rs->sr_err != LDAP_SUCCESS ) {
1401                         LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1402                         if ( sendok & LDAP_BACK_SENDERR ) {
1403                                 send_ldap_result( op, rs );
1404                         }
1405
1406                 } else {
1407                         LDAP_BACK_CONN_ISBOUND_SET( msc );
1408                 }
1409
1410                 lutil_sasl_freedefs( defaults );
1411                 if ( freeauthz ) {
1412                         slap_sl_free( authzID.bv_val, op->o_tmpmemctx );
1413                 }
1414
1415                 goto done;
1416 #endif /* HAVE_CYRUS_SASL */
1417         }
1418
1419         *method = mt->mt_idassert_authmethod;
1420         switch ( mt->mt_idassert_authmethod ) {
1421         case LDAP_AUTH_NONE:
1422                 BER_BVSTR( binddn, "" );
1423                 BER_BVSTR( bindcred, "" );
1424                 /* fallthru */
1425
1426         case LDAP_AUTH_SIMPLE:
1427                 break;
1428
1429         default:
1430                 /* unsupported! */
1431                 LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1432                 rs->sr_err = LDAP_AUTH_METHOD_NOT_SUPPORTED;
1433                 if ( sendok & LDAP_BACK_SENDERR ) {
1434                         send_ldap_result( op, rs );
1435                 }
1436                 break;
1437         }
1438
1439 done:;
1440         return rs->sr_err;
1441 }
1442
1443 static int
1444 meta_back_proxy_authz_bind( metaconn_t *mc, int candidate, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1445 {
1446         metainfo_t              *mi = (metainfo_t *)op->o_bd->be_private;
1447         metatarget_t            *mt = mi->mi_targets[ candidate ];
1448         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
1449         struct berval           binddn = BER_BVC( "" ),
1450                                 cred = BER_BVC( "" );
1451         int                     method = LDAP_AUTH_NONE,
1452                                 rc;
1453
1454         rc = meta_back_proxy_authz_cred( mc, candidate, op, rs, sendok, &binddn, &cred, &method );
1455         if ( rc == LDAP_SUCCESS && !LDAP_BACK_CONN_ISBOUND( msc ) ) {
1456                 int     msgid;
1457
1458                 switch ( method ) {
1459                 case LDAP_AUTH_NONE:
1460                 case LDAP_AUTH_SIMPLE:
1461                         for (;;) {
1462                                 rs->sr_err = ldap_sasl_bind( msc->msc_ld,
1463                                         binddn.bv_val, LDAP_SASL_SIMPLE,
1464                                         &cred, NULL, NULL, &msgid );
1465                                 if ( rs->sr_err != LDAP_X_CONNECTING ) {
1466                                         break;
1467                                 }
1468                                 ldap_pvt_thread_yield();
1469                         }
1470                         rc = meta_back_bind_op_result( op, rs, mc, candidate, msgid, sendok );
1471                         if ( rc == LDAP_SUCCESS ) {
1472                                 /* set rebind stuff in case of successful proxyAuthz bind,
1473                                  * so that referral chasing is attempted using the right
1474                                  * identity */
1475                                 LDAP_BACK_CONN_ISBOUND_SET( msc );
1476                                 ber_bvreplace( &msc->msc_bound_ndn, &binddn );
1477
1478                                 if ( LDAP_BACK_SAVECRED( mi ) ) {
1479                                         if ( !BER_BVISNULL( &msc->msc_cred ) ) {
1480                                                 memset( msc->msc_cred.bv_val, 0,
1481                                                         msc->msc_cred.bv_len );
1482                                         }
1483                                         ber_bvreplace( &msc->msc_cred, &cred );
1484                                         ldap_set_rebind_proc( msc->msc_ld, mt->mt_rebind_f, msc );
1485                                 }
1486                         }
1487                         break;
1488
1489                 default:
1490                         assert( 0 );
1491                         break;
1492                 }
1493         }
1494
1495         return LDAP_BACK_CONN_ISBOUND( msc );
1496 }