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