]> git.sur5r.net Git - openldap/blob - servers/slapd/back-meta/bind.c
don't risk leaving around client library error codes; try to return additional inform...
[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                         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         static struct berval    cred = BER_BVC( "" );
590         int                     msgid;
591
592         assert( !LDAP_BACK_CONN_ISBOUND( msc ) );
593
594         /* NOTE: this obsoletes pseudorootdn */
595         if ( op->o_conn != NULL &&
596                 !op->o_do_not_cache &&
597                 ( BER_BVISNULL( &msc->msc_bound_ndn ) ||
598                         BER_BVISEMPTY( &msc->msc_bound_ndn ) ||
599                         ( LDAP_BACK_CONN_ISPRIV( mc ) && dn_match( &msc->msc_bound_ndn, &mt->mt_idassert_authcDN ) ) ||
600                         ( mt->mt_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) ) )
601         {
602                 (void)meta_back_proxy_authz_bind( mc, candidate, op, rs, sendok );
603
604         } else {
605
606                 /* FIXME: should we check if at least some of the op->o_ctrls
607                  * can/should be passed? */
608                 for (;;) {
609                         rs->sr_err = ldap_sasl_bind( msc->msc_ld,
610                                 "", LDAP_SASL_SIMPLE, &cred,
611                                 NULL, NULL, &msgid );
612                         if ( rs->sr_err != LDAP_X_CONNECTING ) {
613                                 break;
614                         }
615                         ldap_pvt_thread_yield();
616                 }
617
618                 rs->sr_err = meta_back_bind_op_result( op, rs, mc, candidate, msgid, sendok );
619         }
620
621         if ( rs->sr_err != LDAP_SUCCESS ) {
622                 if ( dolock ) {
623                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
624                 }
625                 LDAP_BACK_CONN_BINDING_CLEAR( msc );
626                 if ( META_BACK_ONERR_STOP( mi ) ) {
627                         LDAP_BACK_CONN_TAINTED_SET( mc );
628                         meta_back_release_conn_lock( mi, mc, 0 );
629                         *mcp = NULL;
630                 }
631                 if ( dolock ) {
632                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
633                 }
634         }
635
636         if ( META_BACK_TGT_QUARANTINE( mt ) ) {
637                 meta_back_quarantine( op, rs, candidate );
638         }
639
640         return rs->sr_err;
641 }
642
643 /*
644  * meta_back_dobind
645  */
646 int
647 meta_back_dobind(
648         Operation               *op,
649         SlapReply               *rs,
650         metaconn_t              *mc,
651         ldap_back_send_t        sendok )
652 {
653         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
654
655         int                     bound = 0,
656                                 i,
657                                 isroot = 0;
658
659         SlapReply               *candidates;
660
661         if ( be_isroot( op ) ) {
662                 isroot = 1;
663         }
664
665         if ( LogTest( LDAP_DEBUG_TRACE ) ) {
666                 char buf[STRLENOF("4294967295U") + 1] = { 0 };
667                 mi->mi_ldap_extra->connid2str( &mc->mc_base, buf, sizeof(buf) );
668
669                 Debug( LDAP_DEBUG_TRACE,
670                         "%s meta_back_dobind: conn=%s%s\n",
671                         op->o_log_prefix, buf,
672                         isroot ? " (isroot)" : "" );
673         }
674
675         /*
676          * all the targets are bound as pseudoroot
677          */
678         if ( mc->mc_authz_target == META_BOUND_ALL ) {
679                 bound = 1;
680                 goto done;
681         }
682
683         candidates = meta_back_candidates_get( op );
684
685         for ( i = 0; i < mi->mi_ntargets; i++ ) {
686                 metatarget_t            *mt = mi->mi_targets[ i ];
687                 metasingleconn_t        *msc = &mc->mc_conns[ i ];
688                 int                     rc;
689
690                 /*
691                  * Not a candidate
692                  */
693                 if ( !META_IS_CANDIDATE( &candidates[ i ] ) ) {
694                         continue;
695                 }
696
697                 assert( msc->msc_ld != NULL );
698
699                 /*
700                  * If the target is already bound it is skipped
701                  */
702
703 retry_binding:;
704                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
705                 if ( LDAP_BACK_CONN_ISBOUND( msc )
706                         || ( LDAP_BACK_CONN_ISANON( msc )
707                                 && mt->mt_idassert_authmethod == LDAP_AUTH_NONE ) )
708                 {
709                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
710                         ++bound;
711                         continue;
712
713                 } else if ( META_BACK_CONN_CREATING( msc ) || LDAP_BACK_CONN_BINDING( msc ) )
714                 {
715                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
716                         ldap_pvt_thread_yield();
717                         goto retry_binding;
718
719                 }
720
721                 LDAP_BACK_CONN_BINDING_SET( msc );
722                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
723
724                 rc = meta_back_single_dobind( op, rs, &mc, i,
725                         LDAP_BACK_DONTSEND, mt->mt_nretries, 1 );
726                 /*
727                  * NOTE: meta_back_single_dobind() already retries;
728                  * in case of failure, it resets mc...
729                  */
730                 if ( rc != LDAP_SUCCESS ) {
731                         char            buf[ SLAP_TEXT_BUFLEN ];
732
733                         if ( mc == NULL ) {
734                                 /* meta_back_single_dobind() already sent 
735                                  * response and released connection */
736                                 goto send_err;
737                         }
738
739
740                         if ( rc == LDAP_UNAVAILABLE ) {
741                                 /* FIXME: meta_back_retry() already re-calls
742                                  * meta_back_single_dobind() */
743                                 if ( meta_back_retry( op, rs, &mc, i, sendok ) ) {
744                                         goto retry_ok;
745                                 }
746
747                                 if ( mc != NULL ) {
748                                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
749                                         LDAP_BACK_CONN_BINDING_CLEAR( msc );
750                                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
751                                         meta_back_release_conn( mi, mc );
752                                 }
753
754                                 return 0;
755                         }
756
757                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
758                         LDAP_BACK_CONN_BINDING_CLEAR( msc );
759                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
760
761                         snprintf( buf, sizeof( buf ),
762                                 "meta_back_dobind[%d]: (%s) err=%d (%s).",
763                                 i, isroot ? op->o_bd->be_rootdn.bv_val : "anonymous",
764                                 rc, ldap_err2string( rc ) );
765                         Debug( LDAP_DEBUG_ANY,
766                                 "%s %s\n",
767                                 op->o_log_prefix, buf, 0 );
768
769                         /*
770                          * null cred bind should always succeed
771                          * as anonymous, so a failure means
772                          * the target is no longer candidate possibly
773                          * due to technical reasons (remote host down?)
774                          * so better clear the handle
775                          */
776                         /* leave the target candidate, but record the error for later use */
777                         candidates[ i ].sr_err = rc;
778                         if ( META_BACK_ONERR_STOP( mi ) ) {
779                                 bound = 0;
780                                 goto done;
781                         }
782
783                         continue;
784                 } /* else */
785
786 retry_ok:;
787                 Debug( LDAP_DEBUG_TRACE,
788                         "%s meta_back_dobind[%d]: "
789                         "(%s)\n",
790                         op->o_log_prefix, i,
791                         isroot ? op->o_bd->be_rootdn.bv_val : "anonymous" );
792
793                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
794                 LDAP_BACK_CONN_BINDING_CLEAR( msc );
795                 if ( isroot ) {
796                         LDAP_BACK_CONN_ISBOUND_SET( msc );
797                 } else {
798                         LDAP_BACK_CONN_ISANON_SET( msc );
799                 }
800                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
801                 ++bound;
802         }
803
804 done:;
805         if ( LogTest( LDAP_DEBUG_TRACE ) ) {
806                 char buf[STRLENOF("4294967295U") + 1] = { 0 };
807                 mi->mi_ldap_extra->connid2str( &mc->mc_base, buf, sizeof(buf) );
808
809                 Debug( LDAP_DEBUG_TRACE,
810                         "%s meta_back_dobind: conn=%s bound=%d\n",
811                         op->o_log_prefix, buf, bound );
812         }
813
814         if ( bound == 0 ) {
815                 meta_back_release_conn( mi, mc );
816
817 send_err:;
818                 if ( sendok & LDAP_BACK_SENDERR ) {
819                         if ( rs->sr_err == LDAP_SUCCESS ) {
820                                 rs->sr_err = LDAP_BUSY;
821                         }
822                         send_ldap_result( op, rs );
823                 }
824
825                 return 0;
826         }
827
828         return ( bound > 0 );
829 }
830
831 /*
832  * meta_back_default_rebind
833  *
834  * This is a callback used for chasing referrals using the same
835  * credentials as the original user on this session.
836  */
837 int 
838 meta_back_default_rebind(
839         LDAP                    *ld,
840         LDAP_CONST char         *url,
841         ber_tag_t               request,
842         ber_int_t               msgid,
843         void                    *params )
844 {
845         metasingleconn_t        *msc = ( metasingleconn_t * )params;
846
847         return ldap_sasl_bind_s( ld, msc->msc_bound_ndn.bv_val,
848                         LDAP_SASL_SIMPLE, &msc->msc_cred,
849                         NULL, NULL, NULL );
850 }
851
852 /*
853  * meta_back_default_urllist
854  *
855  * This is a callback used for mucking with the urllist
856  */
857 int 
858 meta_back_default_urllist(
859         LDAP            *ld,
860         LDAPURLDesc     **urllist,
861         LDAPURLDesc     **url,
862         void            *params )
863 {
864         metatarget_t    *mt = (metatarget_t *)params;
865         LDAPURLDesc     **urltail;
866
867         if ( urllist == url ) {
868                 return LDAP_SUCCESS;
869         }
870
871         for ( urltail = &(*url)->lud_next; *urltail; urltail = &(*urltail)->lud_next )
872                 /* count */ ;
873
874         *urltail = *urllist;
875         *urllist = *url;
876         *url = NULL;
877
878         ldap_pvt_thread_mutex_lock( &mt->mt_uri_mutex );
879         if ( mt->mt_uri ) {
880                 ch_free( mt->mt_uri );
881         }
882
883         ldap_get_option( ld, LDAP_OPT_URI, (void *)&mt->mt_uri );
884         ldap_pvt_thread_mutex_unlock( &mt->mt_uri_mutex );
885
886         return LDAP_SUCCESS;
887 }
888
889 int
890 meta_back_cancel(
891         metaconn_t              *mc,
892         Operation               *op,
893         SlapReply               *rs,
894         ber_int_t               msgid,
895         int                     candidate,
896         ldap_back_send_t        sendok )
897 {
898         metainfo_t              *mi = (metainfo_t *)op->o_bd->be_private;
899
900         metatarget_t            *mt = mi->mi_targets[ candidate ];
901         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
902
903         int                     rc = LDAP_OTHER;
904
905         Debug( LDAP_DEBUG_TRACE, ">>> %s meta_back_cancel[%d] msgid=%d\n",
906                 op->o_log_prefix, candidate, msgid );
907
908         /* default behavior */
909         if ( META_BACK_TGT_ABANDON( mt ) ) {
910                 rc = ldap_abandon_ext( msc->msc_ld, msgid, NULL, NULL );
911
912         } else if ( META_BACK_TGT_IGNORE( mt ) ) {
913                 rc = ldap_pvt_discard( msc->msc_ld, msgid );
914
915         } else if ( META_BACK_TGT_CANCEL( mt ) ) {
916                 rc = ldap_cancel_s( msc->msc_ld, msgid, NULL, NULL );
917
918         } else {
919                 assert( 0 );
920         }
921
922         Debug( LDAP_DEBUG_TRACE, "<<< %s meta_back_cancel[%d] err=%d\n",
923                 op->o_log_prefix, candidate, rc );
924
925         return rc;
926 }
927
928
929
930 /*
931  * FIXME: error return must be handled in a cleaner way ...
932  */
933 int
934 meta_back_op_result(
935         metaconn_t              *mc,
936         Operation               *op,
937         SlapReply               *rs,
938         int                     candidate,
939         ber_int_t               msgid,
940         time_t                  timeout,
941         ldap_back_send_t        sendok )
942 {
943         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
944
945         const char      *save_text = rs->sr_text,
946                         *save_matched = rs->sr_matched;
947         BerVarray       save_ref = rs->sr_ref;
948         LDAPControl     **save_ctrls = rs->sr_ctrls;
949         void            *matched_ctx = NULL;
950
951         char            *matched = NULL;
952         char            *text = NULL;
953         char            **refs = NULL;
954         LDAPControl     **ctrls = NULL;
955
956         assert( mc != NULL );
957
958         rs->sr_text = NULL;
959         rs->sr_matched = NULL;
960         rs->sr_ref = NULL;
961         rs->sr_ctrls = NULL;
962
963         if ( candidate != META_TARGET_NONE ) {
964                 metatarget_t            *mt = mi->mi_targets[ candidate ];
965                 metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
966
967                 if ( LDAP_ERR_OK( rs->sr_err ) ) {
968                         int             rc;
969                         struct timeval  tv;
970                         LDAPMessage     *res = NULL;
971                         time_t          stoptime = (time_t)(-1);
972                         int             timeout_err = op->o_protocol >= LDAP_VERSION3 ?
973                                                 LDAP_ADMINLIMIT_EXCEEDED : LDAP_OTHER;
974                         const char      *timeout_text = "Operation timed out";
975
976                         /* if timeout is not specified, compute and use
977                          * the one specific to the ongoing operation */
978                         if ( timeout == (time_t)(-1) ) {
979                                 slap_op_t       opidx = slap_req2op( op->o_tag );
980
981                                 if ( opidx == SLAP_OP_SEARCH ) {
982                                         if ( op->ors_tlimit <= 0 ) {
983                                                 timeout = 0;
984
985                                         } else {
986                                                 timeout = op->ors_tlimit;
987                                                 timeout_err = LDAP_TIMELIMIT_EXCEEDED;
988                                                 timeout_text = NULL;
989                                         }
990
991                                 } else {
992                                         timeout = mt->mt_timeout[ opidx ];
993                                 }
994                         }
995
996                         /* better than nothing :) */
997                         if ( timeout == 0 ) {
998                                 if ( mi->mi_idle_timeout ) {
999                                         timeout = mi->mi_idle_timeout;
1000
1001                                 } else if ( mi->mi_conn_ttl ) {
1002                                         timeout = mi->mi_conn_ttl;
1003                                 }
1004                         }
1005
1006                         if ( timeout ) {
1007                                 stoptime = op->o_time + timeout;
1008                         }
1009
1010                         LDAP_BACK_TV_SET( &tv );
1011
1012 retry:;
1013                         rc = ldap_result( msc->msc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
1014                         switch ( rc ) {
1015                         case 0:
1016                                 if ( timeout && slap_get_time() > stoptime ) {
1017                                         (void)meta_back_cancel( mc, op, rs, msgid, candidate, sendok );
1018                                         rs->sr_err = timeout_err;
1019                                         rs->sr_text = timeout_text;
1020                                         break;
1021                                 }
1022
1023                                 LDAP_BACK_TV_SET( &tv );
1024                                 ldap_pvt_thread_yield();
1025                                 goto retry;
1026
1027                         case -1:
1028                                 ldap_get_option( msc->msc_ld, LDAP_OPT_RESULT_CODE,
1029                                                 &rs->sr_err );
1030                                 break;
1031
1032
1033                         /* otherwise get the result; if it is not
1034                          * LDAP_SUCCESS, record it in the reply
1035                          * structure (this includes 
1036                          * LDAP_COMPARE_{TRUE|FALSE}) */
1037                         default:
1038                                 /* only touch when activity actually took place... */
1039                                 if ( mi->mi_idle_timeout != 0 && msc->msc_time < op->o_time ) {
1040                                         msc->msc_time = op->o_time;
1041                                 }
1042
1043                                 rc = ldap_parse_result( msc->msc_ld, res, &rs->sr_err,
1044                                                 &matched, &text, &refs, &ctrls, 1 );
1045                                 res = NULL;
1046                                 if ( rc == LDAP_SUCCESS ) {
1047                                         rs->sr_text = text;
1048                                 } else {
1049                                         rs->sr_err = rc;
1050                                 }
1051                                 rs->sr_err = slap_map_api2result( rs );
1052
1053                                 /* RFC 4511: referrals can only appear
1054                                  * if result code is LDAP_REFERRAL */
1055                                 if ( refs != NULL
1056                                         && refs[ 0 ] != NULL
1057                                         && refs[ 0 ][ 0 ] != '\0' )
1058                                 {
1059                                         if ( rs->sr_err != LDAP_REFERRAL ) {
1060                                                 Debug( LDAP_DEBUG_ANY,
1061                                                         "%s meta_back_op_result[%d]: "
1062                                                         "got referrals with err=%d\n",
1063                                                         op->o_log_prefix,
1064                                                         candidate, rs->sr_err );
1065
1066                                         } else {
1067                                                 int     i;
1068         
1069                                                 for ( i = 0; refs[ i ] != NULL; i++ )
1070                                                         /* count */ ;
1071                                                 rs->sr_ref = op->o_tmpalloc( sizeof( struct berval ) * ( i + 1 ),
1072                                                         op->o_tmpmemctx );
1073                                                 for ( i = 0; refs[ i ] != NULL; i++ ) {
1074                                                         ber_str2bv( refs[ i ], 0, 0, &rs->sr_ref[ i ] );
1075                                                 }
1076                                                 BER_BVZERO( &rs->sr_ref[ i ] );
1077                                         }
1078
1079                                 } else if ( rs->sr_err == LDAP_REFERRAL ) {
1080                                         Debug( LDAP_DEBUG_ANY,
1081                                                 "%s meta_back_op_result[%d]: "
1082                                                 "got err=%d with null "
1083                                                 "or empty referrals\n",
1084                                                 op->o_log_prefix,
1085                                                 candidate, rs->sr_err );
1086
1087                                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
1088                                 }
1089
1090                                 if ( ctrls != NULL ) {
1091                                         rs->sr_ctrls = ctrls;
1092                                 }
1093                         }
1094
1095                         assert( res == NULL );
1096                 }
1097
1098                 /* if the error in the reply structure is not
1099                  * LDAP_SUCCESS, try to map it from client 
1100                  * to server error */
1101                 if ( !LDAP_ERR_OK( rs->sr_err ) ) {
1102                         rs->sr_err = slap_map_api2result( rs );
1103
1104                         /* internal ops ( op->o_conn == NULL ) 
1105                          * must not reply to client */
1106                         if ( op->o_conn && !op->o_do_not_cache && matched ) {
1107
1108                                 /* record the (massaged) matched
1109                                  * DN into the reply structure */
1110                                 rs->sr_matched = matched;
1111                         }
1112                 }
1113
1114                 if ( META_BACK_TGT_QUARANTINE( mt ) ) {
1115                         meta_back_quarantine( op, rs, candidate );
1116                 }
1117
1118         } else {
1119                 int     i,
1120                         err = rs->sr_err;
1121
1122                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
1123                         metasingleconn_t        *msc = &mc->mc_conns[ i ];
1124                         char                    *xtext = NULL;
1125                         char                    *xmatched = NULL;
1126
1127                         rs->sr_err = LDAP_SUCCESS;
1128
1129                         ldap_get_option( msc->msc_ld, LDAP_OPT_RESULT_CODE, &rs->sr_err );
1130                         if ( rs->sr_err != LDAP_SUCCESS ) {
1131                                 /*
1132                                  * better check the type of error. In some cases
1133                                  * (search ?) it might be better to return a
1134                                  * success if at least one of the targets gave
1135                                  * positive result ...
1136                                  */
1137                                 ldap_get_option( msc->msc_ld,
1138                                                 LDAP_OPT_DIAGNOSTIC_MESSAGE, &xtext );
1139                                 if ( xtext != NULL && xtext [ 0 ] == '\0' ) {
1140                                         ldap_memfree( xtext );
1141                                         xtext = NULL;
1142                                 }
1143
1144                                 ldap_get_option( msc->msc_ld,
1145                                                 LDAP_OPT_MATCHED_DN, &xmatched );
1146                                 if ( xmatched != NULL && xmatched[ 0 ] == '\0' ) {
1147                                         ldap_memfree( xmatched );
1148                                         xmatched = NULL;
1149                                 }
1150
1151                                 rs->sr_err = slap_map_api2result( rs );
1152         
1153                                 if ( LogTest( LDAP_DEBUG_ANY ) ) {
1154                                         char    buf[ SLAP_TEXT_BUFLEN ];
1155
1156                                         snprintf( buf, sizeof( buf ),
1157                                                 "meta_back_op_result[%d] "
1158                                                 "err=%d text=\"%s\" matched=\"%s\"", 
1159                                                 i, rs->sr_err,
1160                                                 ( xtext ? xtext : "" ),
1161                                                 ( xmatched ? xmatched : "" ) );
1162                                         Debug( LDAP_DEBUG_ANY, "%s %s.\n",
1163                                                 op->o_log_prefix, buf, 0 );
1164                                 }
1165
1166                                 /*
1167                                  * FIXME: need to rewrite "match" (need rwinfo)
1168                                  */
1169                                 switch ( rs->sr_err ) {
1170                                 default:
1171                                         err = rs->sr_err;
1172                                         if ( xtext != NULL ) {
1173                                                 if ( text ) {
1174                                                         ldap_memfree( text );
1175                                                 }
1176                                                 text = xtext;
1177                                                 xtext = NULL;
1178                                         }
1179                                         if ( xmatched != NULL ) {
1180                                                 if ( matched ) {
1181                                                         ldap_memfree( matched );
1182                                                 }
1183                                                 matched = xmatched;
1184                                                 xmatched = NULL;
1185                                         }
1186                                         break;
1187                                 }
1188
1189                                 if ( xtext ) {
1190                                         ldap_memfree( xtext );
1191                                 }
1192         
1193                                 if ( xmatched ) {
1194                                         ldap_memfree( xmatched );
1195                                 }
1196                         }
1197
1198                         if ( META_BACK_TGT_QUARANTINE( mi->mi_targets[ i ] ) ) {
1199                                 meta_back_quarantine( op, rs, i );
1200                         }
1201                 }
1202
1203                 if ( err != LDAP_SUCCESS ) {
1204                         rs->sr_err = err;
1205                 }
1206         }
1207
1208         if ( matched != NULL ) {
1209                 struct berval   dn, pdn;
1210
1211                 ber_str2bv( matched, 0, 0, &dn );
1212                 if ( dnPretty( NULL, &dn, &pdn, op->o_tmpmemctx ) == LDAP_SUCCESS ) {
1213                         ldap_memfree( matched );
1214                         matched_ctx = op->o_tmpmemctx;
1215                         matched = pdn.bv_val;
1216                 }
1217                 rs->sr_matched = matched;
1218         }
1219
1220         if ( rs->sr_err == LDAP_UNAVAILABLE ) {
1221                 if ( !( sendok & LDAP_BACK_RETRYING ) ) {
1222                         if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
1223                                 if ( rs->sr_text == NULL ) rs->sr_text = "Proxy operation retry failed";
1224                                 send_ldap_result( op, rs );
1225                         }
1226                 }
1227
1228         } else if ( op->o_conn &&
1229                 ( ( ( sendok & LDAP_BACK_SENDOK ) && LDAP_ERR_OK( rs->sr_err ) )
1230                         || ( ( sendok & LDAP_BACK_SENDERR ) && !LDAP_ERR_OK( rs->sr_err ) ) ) )
1231         {
1232                 send_ldap_result( op, rs );
1233         }
1234         if ( matched ) {
1235                 op->o_tmpfree( (char *)rs->sr_matched, matched_ctx );
1236         }
1237         if ( text ) {
1238                 ldap_memfree( text );
1239         }
1240         if ( rs->sr_ref ) {
1241                 op->o_tmpfree( rs->sr_ref, op->o_tmpmemctx );
1242                 rs->sr_ref = NULL;
1243         }
1244         if ( refs ) {
1245                 ber_memvfree( (void **)refs );
1246         }
1247         if ( ctrls ) {
1248                 assert( rs->sr_ctrls != NULL );
1249                 ldap_controls_free( ctrls );
1250         }
1251
1252         rs->sr_text = save_text;
1253         rs->sr_matched = save_matched;
1254         rs->sr_ref = save_ref;
1255         rs->sr_ctrls = save_ctrls;
1256
1257         return( LDAP_ERR_OK( rs->sr_err ) ? LDAP_SUCCESS : rs->sr_err );
1258 }
1259
1260 /*
1261  * meta_back_proxy_authz_cred()
1262  *
1263  * prepares credentials & method for meta_back_proxy_authz_bind();
1264  * or, if method is SASL, performs the SASL bind directly.
1265  */
1266 int
1267 meta_back_proxy_authz_cred(
1268         metaconn_t              *mc,
1269         int                     candidate,
1270         Operation               *op,
1271         SlapReply               *rs,
1272         ldap_back_send_t        sendok,
1273         struct berval           *binddn,
1274         struct berval           *bindcred,
1275         int                     *method )
1276 {
1277         metainfo_t              *mi = (metainfo_t *)op->o_bd->be_private;
1278         metatarget_t            *mt = mi->mi_targets[ candidate ];
1279         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
1280         struct berval           ndn;
1281         int                     dobind = 0;
1282
1283         /* don't proxyAuthz if protocol is not LDAPv3 */
1284         switch ( mt->mt_version ) {
1285         case LDAP_VERSION3:
1286                 break;
1287
1288         case 0:
1289                 if ( op->o_protocol == 0 || op->o_protocol == LDAP_VERSION3 ) {
1290                         break;
1291                 }
1292                 /* fall thru */
1293
1294         default:
1295                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1296                 if ( sendok & LDAP_BACK_SENDERR ) {
1297                         send_ldap_result( op, rs );
1298                 }
1299                 LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1300                 goto done;
1301         }
1302
1303         if ( op->o_tag == LDAP_REQ_BIND ) {
1304                 ndn = op->o_req_ndn;
1305
1306         } else if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1307                 ndn = op->o_conn->c_ndn;
1308
1309         } else {
1310                 ndn = op->o_ndn;
1311         }
1312
1313         /*
1314          * FIXME: we need to let clients use proxyAuthz
1315          * otherwise we cannot do symmetric pools of servers;
1316          * we have to live with the fact that a user can
1317          * authorize itself as any ID that is allowed
1318          * by the authzTo directive of the "proxyauthzdn".
1319          */
1320         /*
1321          * NOTE: current Proxy Authorization specification
1322          * and implementation do not allow proxy authorization
1323          * control to be provided with Bind requests
1324          */
1325         /*
1326          * if no bind took place yet, but the connection is bound
1327          * and the "proxyauthzdn" is set, then bind as 
1328          * "proxyauthzdn" and explicitly add the proxyAuthz 
1329          * control to every operation with the dn bound 
1330          * to the connection as control value.
1331          */
1332
1333         /* bind as proxyauthzdn only if no idassert mode
1334          * is requested, or if the client's identity
1335          * is authorized */
1336         switch ( mt->mt_idassert_mode ) {
1337         case LDAP_BACK_IDASSERT_LEGACY:
1338                 if ( !BER_BVISNULL( &ndn ) && !BER_BVISEMPTY( &ndn ) ) {
1339                         if ( !BER_BVISNULL( &mt->mt_idassert_authcDN ) && !BER_BVISEMPTY( &mt->mt_idassert_authcDN ) )
1340                         {
1341                                 *binddn = mt->mt_idassert_authcDN;
1342                                 *bindcred = mt->mt_idassert_passwd;
1343                                 dobind = 1;
1344                         }
1345                 }
1346                 break;
1347
1348         default:
1349                 /* NOTE: rootdn can always idassert */
1350                 if ( BER_BVISNULL( &ndn )
1351                         && mt->mt_idassert_authz == NULL
1352                         && !( mt->mt_idassert_flags & LDAP_BACK_AUTH_AUTHZ_ALL ) )
1353                 {
1354                         if ( mt->mt_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1355                                 rs->sr_err = LDAP_INAPPROPRIATE_AUTH;
1356                                 if ( sendok & LDAP_BACK_SENDERR ) {
1357                                         send_ldap_result( op, rs );
1358                                 }
1359                                 LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1360                                 goto done;
1361
1362                         }
1363
1364                         rs->sr_err = LDAP_SUCCESS;
1365                         *binddn = slap_empty_bv;
1366                         *bindcred = slap_empty_bv;
1367                         break;
1368
1369                 } else if ( mt->mt_idassert_authz && !be_isroot( op ) ) {
1370                         struct berval authcDN;
1371
1372                         if ( BER_BVISNULL( &ndn ) ) {
1373                                 authcDN = slap_empty_bv;
1374
1375                         } else {
1376                                 authcDN = ndn;
1377                         }       
1378                         rs->sr_err = slap_sasl_matches( op, mt->mt_idassert_authz,
1379                                         &authcDN, &authcDN );
1380                         if ( rs->sr_err != LDAP_SUCCESS ) {
1381                                 if ( mt->mt_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1382                                         if ( sendok & LDAP_BACK_SENDERR ) {
1383                                                 send_ldap_result( op, rs );
1384                                         }
1385                                         LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1386                                         goto done;
1387                                 }
1388
1389                                 rs->sr_err = LDAP_SUCCESS;
1390                                 *binddn = slap_empty_bv;
1391                                 *bindcred = slap_empty_bv;
1392                                 break;
1393                         }
1394                 }
1395
1396                 *binddn = mt->mt_idassert_authcDN;
1397                 *bindcred = mt->mt_idassert_passwd;
1398                 dobind = 1;
1399                 break;
1400         }
1401
1402         if ( dobind && mt->mt_idassert_authmethod == LDAP_AUTH_SASL ) {
1403 #ifdef HAVE_CYRUS_SASL
1404                 void            *defaults = NULL;
1405                 struct berval   authzID = BER_BVNULL;
1406                 int             freeauthz = 0;
1407
1408                 /* if SASL supports native authz, prepare for it */
1409                 if ( ( !op->o_do_not_cache || !op->o_is_auth_check ) &&
1410                                 ( mt->mt_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
1411                 {
1412                         switch ( mt->mt_idassert_mode ) {
1413                         case LDAP_BACK_IDASSERT_OTHERID:
1414                         case LDAP_BACK_IDASSERT_OTHERDN:
1415                                 authzID = mt->mt_idassert_authzID;
1416                                 break;
1417
1418                         case LDAP_BACK_IDASSERT_ANONYMOUS:
1419                                 BER_BVSTR( &authzID, "dn:" );
1420                                 break;
1421
1422                         case LDAP_BACK_IDASSERT_SELF:
1423                                 if ( BER_BVISNULL( &ndn ) ) {
1424                                         /* connection is not authc'd, so don't idassert */
1425                                         BER_BVSTR( &authzID, "dn:" );
1426                                         break;
1427                                 }
1428                                 authzID.bv_len = STRLENOF( "dn:" ) + ndn.bv_len;
1429                                 authzID.bv_val = slap_sl_malloc( authzID.bv_len + 1, op->o_tmpmemctx );
1430                                 AC_MEMCPY( authzID.bv_val, "dn:", STRLENOF( "dn:" ) );
1431                                 AC_MEMCPY( authzID.bv_val + STRLENOF( "dn:" ),
1432                                                 ndn.bv_val, ndn.bv_len + 1 );
1433                                 freeauthz = 1;
1434                                 break;
1435
1436                         default:
1437                                 break;
1438                         }
1439                 }
1440
1441                 if ( mt->mt_idassert_secprops != NULL ) {
1442                         rs->sr_err = ldap_set_option( msc->msc_ld,
1443                                 LDAP_OPT_X_SASL_SECPROPS,
1444                                 (void *)mt->mt_idassert_secprops );
1445
1446                         if ( rs->sr_err != LDAP_OPT_SUCCESS ) {
1447                                 rs->sr_err = LDAP_OTHER;
1448                                 if ( sendok & LDAP_BACK_SENDERR ) {
1449                                         send_ldap_result( op, rs );
1450                                 }
1451                                 LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1452                                 goto done;
1453                         }
1454                 }
1455
1456                 defaults = lutil_sasl_defaults( msc->msc_ld,
1457                                 mt->mt_idassert_sasl_mech.bv_val,
1458                                 mt->mt_idassert_sasl_realm.bv_val,
1459                                 mt->mt_idassert_authcID.bv_val,
1460                                 mt->mt_idassert_passwd.bv_val,
1461                                 authzID.bv_val );
1462                 if ( defaults == NULL ) {
1463                         rs->sr_err = LDAP_OTHER;
1464                         LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1465                         if ( sendok & LDAP_BACK_SENDERR ) {
1466                                 send_ldap_result( op, rs );
1467                         }
1468                         goto done;
1469                 }
1470
1471                 rs->sr_err = ldap_sasl_interactive_bind_s( msc->msc_ld, binddn->bv_val,
1472                                 mt->mt_idassert_sasl_mech.bv_val, NULL, NULL,
1473                                 LDAP_SASL_QUIET, lutil_sasl_interact,
1474                                 defaults );
1475
1476                 rs->sr_err = slap_map_api2result( rs );
1477                 if ( rs->sr_err != LDAP_SUCCESS ) {
1478                         LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1479                         if ( sendok & LDAP_BACK_SENDERR ) {
1480                                 send_ldap_result( op, rs );
1481                         }
1482
1483                 } else {
1484                         LDAP_BACK_CONN_ISBOUND_SET( msc );
1485                 }
1486
1487                 lutil_sasl_freedefs( defaults );
1488                 if ( freeauthz ) {
1489                         slap_sl_free( authzID.bv_val, op->o_tmpmemctx );
1490                 }
1491
1492                 goto done;
1493 #endif /* HAVE_CYRUS_SASL */
1494         }
1495
1496         *method = mt->mt_idassert_authmethod;
1497         switch ( mt->mt_idassert_authmethod ) {
1498         case LDAP_AUTH_NONE:
1499                 BER_BVSTR( binddn, "" );
1500                 BER_BVSTR( bindcred, "" );
1501                 /* fallthru */
1502
1503         case LDAP_AUTH_SIMPLE:
1504                 break;
1505
1506         default:
1507                 /* unsupported! */
1508                 LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
1509                 rs->sr_err = LDAP_AUTH_METHOD_NOT_SUPPORTED;
1510                 if ( sendok & LDAP_BACK_SENDERR ) {
1511                         send_ldap_result( op, rs );
1512                 }
1513                 break;
1514         }
1515
1516 done:;
1517         return rs->sr_err;
1518 }
1519
1520 static int
1521 meta_back_proxy_authz_bind( metaconn_t *mc, int candidate, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1522 {
1523         metainfo_t              *mi = (metainfo_t *)op->o_bd->be_private;
1524         metatarget_t            *mt = mi->mi_targets[ candidate ];
1525         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
1526         struct berval           binddn = BER_BVC( "" ),
1527                                 cred = BER_BVC( "" );
1528         int                     method = LDAP_AUTH_NONE,
1529                                 rc;
1530
1531         rc = meta_back_proxy_authz_cred( mc, candidate, op, rs, sendok, &binddn, &cred, &method );
1532         if ( rc == LDAP_SUCCESS && !LDAP_BACK_CONN_ISBOUND( msc ) ) {
1533                 int     msgid;
1534
1535                 switch ( method ) {
1536                 case LDAP_AUTH_NONE:
1537                 case LDAP_AUTH_SIMPLE:
1538                         for (;;) {
1539                                 rs->sr_err = ldap_sasl_bind( msc->msc_ld,
1540                                         binddn.bv_val, LDAP_SASL_SIMPLE,
1541                                         &cred, NULL, NULL, &msgid );
1542                                 if ( rs->sr_err != LDAP_X_CONNECTING ) {
1543                                         break;
1544                                 }
1545                                 ldap_pvt_thread_yield();
1546                         }
1547                         rc = meta_back_bind_op_result( op, rs, mc, candidate, msgid, sendok );
1548                         if ( rc == LDAP_SUCCESS ) {
1549                                 /* set rebind stuff in case of successful proxyAuthz bind,
1550                                  * so that referral chasing is attempted using the right
1551                                  * identity */
1552                                 LDAP_BACK_CONN_ISBOUND_SET( msc );
1553                                 ber_bvreplace( &msc->msc_bound_ndn, &binddn );
1554
1555                                 if ( META_BACK_TGT_SAVECRED( mt ) ) {
1556                                         if ( !BER_BVISNULL( &msc->msc_cred ) ) {
1557                                                 memset( msc->msc_cred.bv_val, 0,
1558                                                         msc->msc_cred.bv_len );
1559                                         }
1560                                         ber_bvreplace( &msc->msc_cred, &cred );
1561                                         ldap_set_rebind_proc( msc->msc_ld, mt->mt_rebind_f, msc );
1562                                 }
1563                         }
1564                         break;
1565
1566                 default:
1567                         assert( 0 );
1568                         break;
1569                 }
1570         }
1571
1572         return LDAP_BACK_CONN_ISBOUND( msc );
1573 }
1574
1575 /*
1576  * Add controls;
1577  *
1578  * if any needs to be added, it is prepended to existing ones,
1579  * in a newly allocated array.  The companion function
1580  * mi->mi_ldap_extra->controls_free() must be used to restore the original
1581  * status of op->o_ctrls.
1582  */
1583 int
1584 meta_back_controls_add(
1585                 Operation       *op,
1586                 SlapReply       *rs,
1587                 metaconn_t      *mc,
1588                 int             candidate,
1589                 LDAPControl     ***pctrls )
1590 {
1591         metainfo_t              *mi = (metainfo_t *)op->o_bd->be_private;
1592         metatarget_t            *mt = mi->mi_targets[ candidate ];
1593         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
1594
1595         LDAPControl             **ctrls = NULL;
1596         /* set to the maximum number of controls this backend can add */
1597         LDAPControl             c[ 2 ] = {{ 0 }};
1598         int                     n = 0, i, j1 = 0, j2 = 0;
1599
1600         *pctrls = NULL;
1601
1602         rs->sr_err = LDAP_SUCCESS;
1603
1604         /* don't add controls if protocol is not LDAPv3 */
1605         switch ( mt->mt_version ) {
1606         case LDAP_VERSION3:
1607                 break;
1608
1609         case 0:
1610                 if ( op->o_protocol == 0 || op->o_protocol == LDAP_VERSION3 ) {
1611                         break;
1612                 }
1613                 /* fall thru */
1614
1615         default:
1616                 goto done;
1617         }
1618
1619         /* put controls that go __before__ existing ones here */
1620
1621         /* proxyAuthz for identity assertion */
1622         switch ( mi->mi_ldap_extra->proxy_authz_ctrl( op, rs, &msc->msc_bound_ndn,
1623                 mt->mt_version, &mt->mt_idassert, &c[ j1 ] ) )
1624         {
1625         case SLAP_CB_CONTINUE:
1626                 break;
1627
1628         case LDAP_SUCCESS:
1629                 j1++;
1630                 break;
1631
1632         default:
1633                 goto done;
1634         }
1635
1636         /* put controls that go __after__ existing ones here */
1637
1638 #ifdef SLAP_CONTROL_X_SESSION_TRACKING
1639         /* session tracking */
1640         if ( META_BACK_TGT_ST_REQUEST( mt ) ) {
1641                 switch ( slap_ctrl_session_tracking_request_add( op, rs, &c[ j1 + j2 ] ) ) {
1642                 case SLAP_CB_CONTINUE:
1643                         break;
1644
1645                 case LDAP_SUCCESS:
1646                         j2++;
1647                         break;
1648
1649                 default:
1650                         goto done;
1651                 }
1652         }
1653 #endif /* SLAP_CONTROL_X_SESSION_TRACKING */
1654
1655         if ( rs->sr_err == SLAP_CB_CONTINUE ) {
1656                 rs->sr_err = LDAP_SUCCESS;
1657         }
1658
1659         /* if nothing to do, just bail out */
1660         if ( j1 == 0 && j2 == 0 ) {
1661                 goto done;
1662         }
1663
1664         assert( j1 + j2 <= (int) (sizeof( c )/sizeof( c[0] )) );
1665
1666         if ( op->o_ctrls ) {
1667                 for ( n = 0; op->o_ctrls[ n ]; n++ )
1668                         /* just count ctrls */ ;
1669         }
1670
1671         ctrls = op->o_tmpalloc( (n + j1 + j2 + 1) * sizeof( LDAPControl * ) + ( j1 + j2 ) * sizeof( LDAPControl ),
1672                         op->o_tmpmemctx );
1673         if ( j1 ) {
1674                 ctrls[ 0 ] = (LDAPControl *)&ctrls[ n + j1 + j2 + 1 ];
1675                 *ctrls[ 0 ] = c[ 0 ];
1676                 for ( i = 1; i < j1; i++ ) {
1677                         ctrls[ i ] = &ctrls[ 0 ][ i ];
1678                         *ctrls[ i ] = c[ i ];
1679                 }
1680         }
1681
1682         i = 0;
1683         if ( op->o_ctrls ) {
1684                 for ( i = 0; op->o_ctrls[ i ]; i++ ) {
1685                         ctrls[ i + j1 ] = op->o_ctrls[ i ];
1686                 }
1687         }
1688
1689         n += j1;
1690         if ( j2 ) {
1691                 ctrls[ n ] = (LDAPControl *)&ctrls[ n + j2 + 1 ] + j1;
1692                 *ctrls[ n ] = c[ j1 ];
1693                 for ( i = 1; i < j2; i++ ) {
1694                         ctrls[ n + i ] = &ctrls[ n ][ i ];
1695                         *ctrls[ n + i ] = c[ i ];
1696                 }
1697         }
1698
1699         ctrls[ n + j2 ] = NULL;
1700
1701 done:;
1702         if ( ctrls == NULL ) {
1703                 ctrls = op->o_ctrls;
1704         }
1705
1706         *pctrls = ctrls;
1707         
1708         return rs->sr_err;
1709 }
1710