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