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