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