]> git.sur5r.net Git - openldap/blob - servers/slapd/back-meta/bind.c
fcbe0fd21eb967340d26d1b06ba8bfd2e134d7ef
[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-2006 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
37 int
38 meta_back_bind( Operation *op, SlapReply *rs )
39 {
40         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
41         metaconn_t      *mc = NULL;
42
43         int             rc = LDAP_OTHER,
44                         i,
45                         gotit = 0,
46                         isroot = 0;
47
48         SlapReply       *candidates = meta_back_candidates_get( op );
49
50         rs->sr_err = LDAP_SUCCESS;
51
52         Debug( LDAP_DEBUG_ARGS, "%s meta_back_bind: dn=\"%s\".\n",
53                 op->o_log_prefix, op->o_req_dn.bv_val, 0 );
54
55         /* the test on the bind method should be superfluous */
56         if ( op->orb_method == LDAP_AUTH_SIMPLE
57                 && be_isroot_dn( op->o_bd, &op->o_req_ndn ) )
58         {
59                 if ( !be_isroot_pw( op ) ) {
60                         rs->sr_err = LDAP_INVALID_CREDENTIALS;
61                         rs->sr_text = NULL;
62                         send_ldap_result( op, rs );
63                         return rs->sr_err;
64                 }
65
66                 if ( META_BACK_DEFER_ROOTDN_BIND( mi ) ) {
67                         rs->sr_err = LDAP_SUCCESS;
68                         rs->sr_text = NULL;
69                         /* frontend will return success */
70                         return rs->sr_err;
71                 }
72
73                 isroot = 1;
74         }
75
76         /* we need meta_back_getconn() not send result even on error,
77          * because we want to intercept the error and make it
78          * invalidCredentials */
79         mc = meta_back_getconn( op, rs, NULL, LDAP_BACK_BIND_DONTSEND );
80         if ( !mc ) {
81                 char    buf[ SLAP_TEXT_BUFLEN ];
82
83                 snprintf( buf, sizeof( buf ),
84                         "meta_back_bind: no target "
85                         "for dn \"%s\" (%d%s%s).",
86                         op->o_req_dn.bv_val, rs->sr_err,
87                         rs->sr_text ? ". " : "",
88                         rs->sr_text ? rs->sr_text : "" );
89                 Debug( LDAP_DEBUG_ANY,
90                         "%s %s\n",
91                         op->o_log_prefix, buf, 0 );
92
93                 /* FIXME: there might be cases where we don't want
94                  * to map the error onto invalidCredentials */
95                 switch ( rs->sr_err ) {
96                 case LDAP_NO_SUCH_OBJECT:
97                 case LDAP_UNWILLING_TO_PERFORM:
98                         rs->sr_err = LDAP_INVALID_CREDENTIALS;
99                         rs->sr_text = NULL;
100                         break;
101                 }
102                 send_ldap_result( op, rs );
103                 return rs->sr_err;
104         }
105
106         /*
107          * Each target is scanned ...
108          */
109         mc->mc_authz_target = META_BOUND_NONE;
110         for ( i = 0; i < mi->mi_ntargets; i++ ) {
111                 metatarget_t    *mt = mi->mi_targets[ i ];
112                 int             lerr;
113                 Operation       op2 = *op;
114                 int             massage = 1;
115
116                 /*
117                  * Skip non-candidates
118                  */
119                 if ( candidates[ i ].sr_tag != META_CANDIDATE ) {
120                         continue;
121                 }
122
123                 if ( gotit == 0 ) {
124                         /* set rc to LDAP_SUCCESS only if at least
125                          * one candidate has been tried */
126                         rc = LDAP_SUCCESS;
127                         gotit = 1;
128
129                 } else if ( isroot == 0 ) {
130                         /*
131                          * A bind operation is expected to have
132                          * ONE CANDIDATE ONLY!
133                          */
134                         Debug( LDAP_DEBUG_ANY,
135                                 "### %s meta_back_bind: more than one"
136                                 " candidate selected...\n",
137                                 op->o_log_prefix, 0, 0 );
138                 }
139
140                 if ( isroot ) {
141                         if ( BER_BVISNULL( &mt->mt_pseudorootdn ) )
142                         {
143                                 metasingleconn_t        *msc = &mc->mc_conns[ i ];
144
145                                 /* skip the target if no pseudorootdn is provided */
146                                 if ( !BER_BVISNULL( &msc->msc_bound_ndn ) ) {
147                                         ch_free( msc->msc_bound_ndn.bv_val );
148                                         BER_BVZERO( &msc->msc_bound_ndn );
149                                 }
150
151                                 if ( LDAP_BACK_SAVECRED( mi ) &&
152                                         !BER_BVISNULL( &msc->msc_cred ) )
153                                 {
154                                         /* destroy sensitive data */
155                                         memset( msc->msc_cred.bv_val, 0,
156                                                 msc->msc_cred.bv_len );
157                                         ch_free( msc->msc_cred.bv_val );
158                                         BER_BVZERO( &msc->msc_cred );
159                                 }
160
161                                 continue;
162                         }
163
164                         op2.o_req_dn = mt->mt_pseudorootdn;
165                         op2.o_req_ndn = mt->mt_pseudorootdn;
166                         op2.orb_cred = mt->mt_pseudorootpw;
167                         op2.orb_method = LDAP_AUTH_SIMPLE;
168
169                         massage = 0;
170                 }
171                 
172                 lerr = meta_back_single_bind( &op2, rs, mc, i, massage );
173
174                 if ( lerr != LDAP_SUCCESS ) {
175                         rc = rs->sr_err = lerr;
176                         /* FIXME: in some cases (e.g. unavailable)
177                          * do not assume it's not candidate; rather
178                          * mark this as an error to be eventually
179                          * reported to client */
180                         candidates[ i ].sr_tag = META_NOT_CANDIDATE;
181                         break;
182                 }
183         }
184
185         /* must re-insert if local DN changed as result of bind */
186         if ( rc == LDAP_SUCCESS ) {
187                 if ( isroot ) {
188                         mc->mc_authz_target = META_BOUND_ALL;
189                         ber_dupbv( &op->orb_edn, be_root_dn( op->o_bd ) );
190                 }
191
192                 if ( !dn_match( &op->o_req_ndn, &mc->mc_local_ndn ) ) {
193                         metaconn_t      *tmpmc;
194                         int             lerr;
195
196                         /* wait for all other ops to release the connection */
197 retry_lock:;
198                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
199                         if ( mc->mc_refcnt > 1 ) {
200                                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
201                                 ldap_pvt_thread_yield();
202                                 goto retry_lock;
203                         }
204
205                         assert( mc->mc_refcnt == 1 );
206                         tmpmc = avl_delete( &mi->mi_conninfo.lai_tree, (caddr_t)mc,
207                                 meta_back_conndn_cmp );
208                         assert( tmpmc == mc );
209
210                         /* delete all cached connections with the current connection */
211                         if ( LDAP_BACK_SINGLECONN( mi ) ) {
212                                 while ( ( tmpmc = avl_delete( &mi->mi_conninfo.lai_tree, (caddr_t)mc, meta_back_conn_cmp ) ) != NULL )
213                                 {
214                                         Debug( LDAP_DEBUG_TRACE,
215                                                 "=>meta_back_bind: destroying conn %ld (refcnt=%u)\n",
216                                                 LDAP_BACK_PCONN_ID( mc->mc_conn ), mc->mc_refcnt, 0 );
217
218                                         if ( mc->mc_refcnt != 0 ) {
219                                                 /* taint it */
220                                                 LDAP_BACK_CONN_TAINTED_SET( tmpmc );
221
222                                         } else {
223                                                 /*
224                                                  * Needs a test because the handler may be corrupted,
225                                                  * and calling ldap_unbind on a corrupted header results
226                                                  * in a segmentation fault
227                                                  */
228                                                 meta_back_conn_free( tmpmc );
229                                         }
230                                 }
231                         }
232
233                         ber_bvreplace( &mc->mc_local_ndn, &op->o_req_ndn );
234                         lerr = avl_insert( &mi->mi_conninfo.lai_tree, (caddr_t)mc,
235                                 meta_back_conndn_cmp, meta_back_conndn_dup );
236                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
237                         if ( lerr == -1 ) {
238                                 meta_clear_candidates( op, mc );
239
240                                 /* we can do this because mc_refcnt == 1 */
241                                 mc->mc_refcnt = 0;
242                                 meta_back_conn_free( mc );
243                                 mc = NULL;
244                         }
245                 }
246         }
247
248         if ( mc != NULL ) {
249                 meta_back_release_conn( op, mc );
250         }
251
252         /*
253          * rc is LDAP_SUCCESS if at least one bind succeeded,
254          * err is the last error that occurred during a bind;
255          * if at least (and at most?) one bind succeeds, fine.
256          */
257         if ( rc != LDAP_SUCCESS ) {
258                 
259                 /*
260                  * deal with bind failure ...
261                  */
262
263                 /*
264                  * no target was found within the naming context, 
265                  * so bind must fail with invalid credentials
266                  */
267                 if ( rs->sr_err == LDAP_SUCCESS && gotit == 0 ) {
268                         rs->sr_err = LDAP_INVALID_CREDENTIALS;
269                 } else {
270                         rs->sr_err = slap_map_api2result( rs );
271                 }
272                 send_ldap_result( op, rs );
273                 return rs->sr_err;
274
275         }
276
277         return LDAP_SUCCESS;
278 }
279
280 /*
281  * meta_back_single_bind
282  *
283  * attempts to perform a bind with creds
284  */
285 int
286 meta_back_single_bind(
287         Operation               *op,
288         SlapReply               *rs,
289         metaconn_t              *mc,
290         int                     candidate,
291         int                     massage )
292 {
293         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
294         metatarget_t            *mt = mi->mi_targets[ candidate ];
295         struct berval           mdn = BER_BVNULL;
296         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
297         int                     msgid,
298                                 rebinding = 0;
299
300         
301         if ( !BER_BVISNULL( &msc->msc_bound_ndn ) ) {
302                 ch_free( msc->msc_bound_ndn.bv_val );
303                 BER_BVZERO( &msc->msc_bound_ndn );
304         }
305
306         if ( LDAP_BACK_SAVECRED( mi ) && !BER_BVISNULL( &msc->msc_cred ) ) {
307                 /* destroy sensitive data */
308                 memset( msc->msc_cred.bv_val, 0, msc->msc_cred.bv_len );
309                 ch_free( msc->msc_cred.bv_val );
310                 BER_BVZERO( &msc->msc_cred );
311         }
312
313         /*
314          * Rewrite the bind dn if needed
315          */
316         if ( massage ) {
317                 dncookie                dc;
318
319                 dc.target = mt;
320                 dc.conn = op->o_conn;
321                 dc.rs = rs;
322                 dc.ctx = "bindDN";
323
324                 if ( ldap_back_dn_massage( &dc, &op->o_req_dn, &mdn ) ) {
325                         rs->sr_text = "DN rewrite error";
326                         rs->sr_err = LDAP_OTHER;
327                         return rs->sr_err;
328                 }
329
330         } else {
331                 mdn = op->o_req_dn;
332         }
333
334         /* FIXME: this fixes the bind problem right now; we need
335          * to use the asynchronous version to get the "matched"
336          * and more in case of failure ... */
337         /* FIXME: should we check if at least some of the op->o_ctrls
338          * can/should be passed? */
339 rebind:;
340         rs->sr_err = ldap_sasl_bind( msc->msc_ld, mdn.bv_val,
341                         LDAP_SASL_SIMPLE, &op->orb_cred,
342                         op->o_ctrls, NULL, &msgid );
343         if ( rs->sr_err == LDAP_SUCCESS ) {
344                 LDAPMessage     *res;
345                 struct timeval  tv;
346                 int             rc;
347                 int             nretries = mt->mt_nretries;
348                 char            buf[ SLAP_TEXT_BUFLEN ];
349
350                 LDAP_BACK_TV_SET( &tv );
351
352                 /*
353                  * handle response!!!
354                  */
355 retry:;
356                 switch ( ldap_result( msc->msc_ld, msgid, LDAP_MSG_ALL, &tv, &res ) ) {
357                 case 0:
358                         snprintf( buf, sizeof( buf ),
359                                 "ldap_result=0 nretries=%d%s",
360                                 nretries, rebinding ? " rebinding" : "" );
361                         Debug( LDAP_DEBUG_ANY,
362                                 "%s meta_back_single_bind[%d]: %s.\n",
363                                 op->o_log_prefix, candidate, buf );
364
365                         if ( nretries != META_RETRY_NEVER ) {
366                                 ldap_pvt_thread_yield();
367                                 if ( nretries > 0 ) {
368                                         nretries--;
369                                 }
370                                 tv = mt->mt_bind_timeout;
371                                 goto retry;
372                         }
373
374                         rs->sr_err = LDAP_BUSY;
375                         if ( rebinding ) {
376                                 ldap_abandon_ext( msc->msc_ld, msgid, NULL, NULL );
377                                 break;
378                         }
379
380                         /* FIXME: some times the request times out
381                          * while the other party is not willing to
382                          * send a response any more.  Give it a second
383                          * chance with a freshly bound connection */
384                         rebinding = 1;
385                         nretries = mt->mt_nretries;
386                         /* fallthru */
387
388                 case -1:
389                         ldap_get_option( msc->msc_ld, LDAP_OPT_ERROR_NUMBER,
390                                 &rs->sr_err );
391
392                         if ( rebinding ) {
393                                 ldap_abandon_ext( msc->msc_ld, msgid, NULL, NULL );
394                         }
395
396                         snprintf( buf, sizeof( buf ),
397                                 "err=%d (%s) nretries=%d",
398                                 rs->sr_err, ldap_err2string( rs->sr_err ), nretries );
399                         Debug( LDAP_DEBUG_ANY,
400                                 "### %s meta_back_single_bind[%d]: %s.\n",
401                                 op->o_log_prefix, candidate, buf );
402
403                         rc = slap_map_api2result( rs );
404                         if ( rs->sr_err == LDAP_UNAVAILABLE && nretries != META_RETRY_NEVER ) {
405                                 rc = meta_back_retry( op, rs, &mc, candidate, LDAP_BACK_DONTSEND );
406                                 if ( rc ) {
407                                         if ( nretries > 0 ) {
408                                                 nretries--;
409                                         }
410                                         ldap_pvt_thread_yield();
411                                         goto rebind;
412                                 }
413                                 goto return_results;
414                         }
415                         break;
416
417                 default:
418                         rc = ldap_parse_result( msc->msc_ld, res, &rs->sr_err,
419                                         NULL, NULL, NULL, NULL, 1 );
420                         if ( rc != LDAP_SUCCESS ) {
421                                 rs->sr_err = rc;
422                         }
423                         break;
424                 }
425         }
426
427         if ( rs->sr_err != LDAP_SUCCESS ) {
428                 rs->sr_err = slap_map_api2result( rs );
429                 goto return_results;
430         }
431
432         ber_bvreplace( &msc->msc_bound_ndn, &op->o_req_dn );
433         LDAP_BACK_CONN_ISBOUND_SET( msc );
434         mc->mc_authz_target = candidate;
435
436         if ( LDAP_BACK_SAVECRED( mi ) ) {
437                 ber_bvreplace( &msc->msc_cred, &op->orb_cred );
438                 ldap_set_rebind_proc( msc->msc_ld, mt->mt_rebind_f, msc );
439         }
440
441         if ( mi->mi_cache.ttl != META_DNCACHE_DISABLED
442                         && op->o_req_ndn.bv_len != 0 )
443         {
444                 ( void )meta_dncache_update_entry( &mi->mi_cache,
445                                 &op->o_req_ndn, candidate );
446         }
447
448 return_results:;
449         if ( mdn.bv_val != op->o_req_dn.bv_val ) {
450                 free( mdn.bv_val );
451         }
452
453         return rs->sr_err;
454 }
455
456 /*
457  * meta_back_single_dobind
458  */
459 int
460 meta_back_single_dobind(
461         Operation               *op,
462         SlapReply               *rs,
463         metaconn_t              **mcp,
464         int                     candidate,
465         ldap_back_send_t        sendok,
466         int                     nretries,
467         int                     dolock )
468 {
469         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
470         metatarget_t            *mt = mi->mi_targets[ candidate ];
471         metaconn_t              *mc = *mcp;
472         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
473         int                     rc;
474         static struct berval    cred = BER_BVC( "" );
475         int                     msgid,
476                                 rebinding = 0,
477                                 save_nretries = nretries;
478
479         assert( !LDAP_BACK_CONN_ISBOUND( msc ) );
480
481         /*
482          * meta_back_single_dobind() calls meta_back_single_bind()
483          * if required.
484          */
485         if ( be_isroot( op ) && !BER_BVISNULL( &mt->mt_pseudorootdn ) )
486         {
487                 Operation       op2 = *op;
488
489                 op2.o_tag = LDAP_REQ_BIND;
490                 op2.o_req_dn = mt->mt_pseudorootdn;
491                 op2.o_req_ndn = mt->mt_pseudorootdn;
492                 op2.orb_cred = mt->mt_pseudorootpw;
493                 op2.orb_method = LDAP_AUTH_SIMPLE;
494
495                 rc = meta_back_single_bind( &op2, rs, *mcp, candidate, 0 );
496                 goto done;
497         }
498
499         /*
500          * Otherwise an anonymous bind is performed
501          * (note: if the target was already bound, the anonymous
502          * bind clears the previous bind).
503          */
504         if ( !BER_BVISNULL( &msc->msc_bound_ndn ) ) {
505                 ber_memfree( msc->msc_bound_ndn.bv_val );
506                 BER_BVZERO( &msc->msc_bound_ndn );
507         }
508                 
509         if ( LDAP_BACK_SAVECRED( mi ) && !BER_BVISNULL( &msc->msc_cred ) ) {
510                 /* destroy sensitive data */
511                 memset( msc->msc_cred.bv_val, 0, msc->msc_cred.bv_len );
512                 ber_memfree( msc->msc_cred.bv_val );
513                 BER_BVZERO( &msc->msc_cred );
514         }
515
516         /* FIXME: should we check if at least some of the op->o_ctrls
517          * can/should be passed? */
518 rebind:;
519         rc = ldap_sasl_bind( msc->msc_ld, "", LDAP_SASL_SIMPLE, &cred,
520                         NULL, NULL, &msgid );
521         if ( rc == LDAP_SUCCESS ) {
522                 LDAPMessage     *res;
523                 struct timeval  tv;
524                 char            buf[ SLAP_TEXT_BUFLEN ];
525
526                 LDAP_BACK_TV_SET( &tv );
527
528                 /*
529                  * handle response!!!
530                  */
531 retry:;
532                 switch ( ldap_result( msc->msc_ld, msgid, LDAP_MSG_ALL, &tv, &res ) ) {
533                 case 0:
534                         snprintf( buf, sizeof( buf ),
535                                 "ldap_result=0 nretries=%d%s",
536                                 nretries, rebinding ? " rebinding" : "" );
537                         Debug( LDAP_DEBUG_ANY,
538                                 "%s meta_back_single_dobind[%d]: %s.\n",
539                                 op->o_log_prefix, candidate, buf );
540
541                         if ( nretries != META_RETRY_NEVER ) {
542                                 ldap_pvt_thread_yield();
543                                 if ( nretries > 0 ) {
544                                         nretries--;
545                                 }
546                                 tv = mt->mt_bind_timeout;
547                                 goto retry;
548                         }
549
550                         rc = LDAP_BUSY;
551                         if ( rebinding ) {
552                                 ldap_abandon_ext( msc->msc_ld, msgid, NULL, NULL );
553                                 break;
554                         }
555
556                         /* FIXME: some times the request times out
557                          * while the other party is not willing to
558                          * send a response any more.  Give it a second
559                          * chance with a freshly bound connection */
560                         rebinding = 1;
561                         nretries = save_nretries;
562                         /* fallthru */
563
564                 case -1:
565                         ldap_get_option( msc->msc_ld, LDAP_OPT_ERROR_NUMBER,
566                                 &rs->sr_err );
567
568                         if ( rebinding ) {
569                                 ldap_abandon_ext( msc->msc_ld, msgid, NULL, NULL );
570                         }
571
572                         snprintf( buf, sizeof( buf ),
573                                 "err=%d (%s) nretries=%d",
574                                 rs->sr_err, ldap_err2string( rs->sr_err ), nretries );
575                         Debug( LDAP_DEBUG_ANY,
576                                 "### %s meta_back_single_dobind[%d]: %s.\n",
577                                 op->o_log_prefix, candidate, buf );
578
579                         rc = slap_map_api2result( rs );
580                         if ( rc == LDAP_UNAVAILABLE && nretries != META_RETRY_NEVER ) {
581                                 if ( dolock ) {
582                                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
583                                 }
584
585                                 if ( mc->mc_refcnt == 1 ) {
586                                         meta_clear_one_candidate( msc );
587                                         LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
588
589                                         ( void )rewrite_session_delete( mt->mt_rwmap.rwm_rw, op->o_conn );
590
591                                         /* mc here must be the regular mc,
592                                          * reset and ready for init */
593                                         rc = meta_back_init_one_conn( op, rs,
594                                                 mt, mc, candidate,
595                                                 LDAP_BACK_CONN_ISPRIV( mc ),
596                                                 LDAP_BACK_DONTSEND );
597                                         if ( rc == LDAP_SUCCESS ) {
598                                                 LDAP_BACK_CONN_BINDING_SET( msc );
599                                         }
600
601                                 } else {
602                                         /* can't do anything about it */
603                                         rc = LDAP_UNAVAILABLE;
604                                 }
605
606                                 if ( dolock ) {
607                                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
608                                 }
609
610                                 if ( rc == LDAP_SUCCESS ) {
611                                         ldap_pvt_thread_yield();
612                                         if ( nretries > 0 ) {
613                                                 nretries--;
614                                         }
615                                         goto rebind;
616                                 }
617                         }
618                         break;
619
620                 default:
621                         rc = ldap_parse_result( msc->msc_ld, res, &rs->sr_err,
622                                         NULL, NULL, NULL, NULL, 1 );
623                         if ( rc == LDAP_SUCCESS ) {
624                                 rc = slap_map_api2result( rs );
625                         }
626                         break;
627                 }
628
629         } else {
630                 rs->sr_err = rc;
631                 rc = slap_map_api2result( rs );
632         }
633
634 done:;
635         rs->sr_err = rc;
636         if ( rc != LDAP_SUCCESS && META_BACK_ONERR_STOP( mi ) ) {
637                 LDAP_BACK_CONN_BINDING_CLEAR( msc );
638                 LDAP_BACK_CONN_TAINTED_SET( mc );
639                 meta_back_release_conn_lock( op, mc, dolock );
640                 *mcp = NULL;
641
642                 if ( sendok & LDAP_BACK_SENDERR ) {
643                         send_ldap_result( op, rs );
644                 }
645         }
646
647         return rc;
648 }
649
650 /*
651  * meta_back_dobind
652  */
653 int
654 meta_back_dobind(
655         Operation               *op,
656         SlapReply               *rs,
657         metaconn_t              *mc,
658         ldap_back_send_t        sendok )
659 {
660         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
661
662         int                     bound = 0,
663                                 i,
664                                 isroot = 0;
665
666         SlapReply               *candidates = meta_back_candidates_get( op );
667
668         if ( be_isroot( op ) ) {
669                 isroot = 1;
670         }
671
672         Debug( LDAP_DEBUG_TRACE,
673                 "%s meta_back_dobind: conn=%ld%s\n",
674                 op->o_log_prefix,
675                 LDAP_BACK_PCONN_ID( mc->mc_conn ),
676                 isroot ? " (isroot)" : "" );
677
678         /*
679          * all the targets are bound as pseudoroot
680          */
681         if ( mc->mc_authz_target == META_BOUND_ALL ) {
682                 bound = 1;
683                 goto done;
684         }
685
686         for ( i = 0; i < mi->mi_ntargets; i++ ) {
687                 metatarget_t            *mt = mi->mi_targets[ i ];
688                 metasingleconn_t        *msc = &mc->mc_conns[ i ];
689                 int                     rc, do_retry = 1;
690
691                 /*
692                  * Not a candidate
693                  */
694                 if ( candidates[ i ].sr_tag != META_CANDIDATE ) {
695                         continue;
696                 }
697
698                 assert( msc->msc_ld != NULL );
699
700                 /*
701                  * If the target is already bound it is skipped
702                  */
703
704 retry_binding:;
705                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
706                 if ( LDAP_BACK_CONN_ISBOUND( msc ) || LDAP_BACK_CONN_ISANON( msc ) ) {
707                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
708                         ++bound;
709                         continue;
710
711                 } else if ( LDAP_BACK_CONN_BINDING( msc ) ) {
712                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
713                         ldap_pvt_thread_yield();
714                         goto retry_binding;
715
716                 } else {
717                         LDAP_BACK_CONN_BINDING_SET( msc );
718                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
719                 } 
720
721 retry:;
722                 rc = meta_back_single_dobind( op, rs, &mc, i,
723                         LDAP_BACK_DONTSEND, mt->mt_nretries, 1 );
724                 /*
725                  * NOTE: meta_back_single_dobind() already retries;
726                  * in case of failure, it resets mc...
727                  */
728                 if ( rc != LDAP_SUCCESS ) {
729                         char            buf[ SLAP_TEXT_BUFLEN ];
730
731                         if ( mc == NULL ) {
732                                 /* meta_back_single_dobind() already sent 
733                                  * response and released connection */
734                                 goto send_err;
735                         }
736
737
738                         if ( rc == LDAP_UNAVAILABLE && do_retry ) {
739                                 do_retry = 0;
740                                 if ( meta_back_retry( op, rs, &mc, i, sendok ) ) {
741                                         goto retry;
742                                 }
743
744                                 if ( mc != NULL ) {
745                                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
746                                         LDAP_BACK_CONN_BINDING_CLEAR( msc );
747                                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
748                                 }
749
750                                 return 0;
751                         }
752
753                         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
754                         LDAP_BACK_CONN_BINDING_CLEAR( msc );
755                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
756
757                         snprintf( buf, sizeof( buf ),
758                                 "meta_back_dobind[%d]: (%s) err=%d (%s).",
759                                 i, isroot ? op->o_bd->be_rootdn.bv_val : "anonymous",
760                                 rc, ldap_err2string( rc ) );
761                         Debug( LDAP_DEBUG_ANY,
762                                 "%s %s\n",
763                                 op->o_log_prefix, buf, 0 );
764
765                         /*
766                          * null cred bind should always succeed
767                          * as anonymous, so a failure means
768                          * the target is no longer candidate possibly
769                          * due to technical reasons (remote host down?)
770                          * so better clear the handle
771                          */
772                         /* leave the target candidate, but record the error for later use */
773                         candidates[ i ].sr_err = rc;
774                         if ( META_BACK_ONERR_STOP( mi ) ) {
775                                 bound = 0;
776                                 goto done;
777                         }
778
779                         continue;
780                 } /* else */
781                 
782                 Debug( LDAP_DEBUG_TRACE,
783                         "%s meta_back_dobind[%d]: "
784                         "(%s)\n",
785                         op->o_log_prefix, i,
786                         isroot ? op->o_bd->be_rootdn.bv_val : "anonymous" );
787
788                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
789                 LDAP_BACK_CONN_BINDING_CLEAR( msc );
790                 if ( isroot ) {
791                         LDAP_BACK_CONN_ISBOUND_SET( msc );
792                 } else {
793                         LDAP_BACK_CONN_ISANON_SET( msc );
794                 }
795                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
796                 ++bound;
797         }
798
799 done:;
800         Debug( LDAP_DEBUG_TRACE,
801                 "%s meta_back_dobind: conn=%ld bound=%d\n",
802                 op->o_log_prefix, LDAP_BACK_PCONN_ID( mc->mc_conn ), bound );
803
804         if ( bound == 0 ) {
805                 meta_back_release_conn( op, mc );
806
807 send_err:;
808                 if ( sendok & LDAP_BACK_SENDERR ) {
809                         if ( rs->sr_err == LDAP_SUCCESS ) {
810                                 rs->sr_err = LDAP_BUSY;
811                         }
812                         send_ldap_result( op, rs );
813                 }
814
815                 return 0;
816         }
817
818         return ( bound > 0 );
819 }
820
821 /*
822  * meta_back_default_rebind
823  *
824  * This is a callback used for chasing referrals using the same
825  * credentials as the original user on this session.
826  */
827 int 
828 meta_back_default_rebind(
829         LDAP                    *ld,
830         LDAP_CONST char         *url,
831         ber_tag_t               request,
832         ber_int_t               msgid,
833         void                    *params )
834 {
835         metasingleconn_t        *msc = ( metasingleconn_t * )params;
836
837         return ldap_sasl_bind_s( ld, msc->msc_bound_ndn.bv_val,
838                         LDAP_SASL_SIMPLE, &msc->msc_cred,
839                         NULL, NULL, NULL );
840 }
841
842 /*
843  * meta_back_default_urllist
844  *
845  * This is a callback used for mucking with the urllist
846  */
847 int 
848 meta_back_default_urllist(
849         LDAP            *ld,
850         LDAPURLDesc     **urllist,
851         LDAPURLDesc     **url,
852         void            *params )
853 {
854         metatarget_t    *mt = (metatarget_t *)params;
855         LDAPURLDesc     **urltail;
856
857         if ( urllist == url ) {
858                 return LDAP_SUCCESS;
859         }
860
861         for ( urltail = &(*url)->lud_next; *urltail; urltail = &(*urltail)->lud_next )
862                 /* count */ ;
863
864         *urltail = *urllist;
865         *urllist = *url;
866         *url = NULL;
867
868         ldap_pvt_thread_mutex_lock( &mt->mt_uri_mutex );
869         if ( mt->mt_uri ) {
870                 ch_free( mt->mt_uri );
871         }
872
873         ldap_get_option( ld, LDAP_OPT_URI, (void *)&mt->mt_uri );
874         ldap_pvt_thread_mutex_unlock( &mt->mt_uri_mutex );
875
876         return LDAP_SUCCESS;
877 }
878
879 /*
880  * FIXME: error return must be handled in a cleaner way ...
881  */
882 int
883 meta_back_op_result(
884         metaconn_t      *mc,
885         Operation       *op,
886         SlapReply       *rs,
887         int             candidate )
888 {
889         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
890
891         int                     i,
892                                 rerr = LDAP_SUCCESS;
893         char                    *rmsg = NULL,
894                                 *rmatch = NULL;
895         const char              *save_rmsg = NULL,
896                                 *save_rmatch = NULL;
897         void                    *rmatch_ctx = NULL;
898
899         assert( mc != NULL );
900
901         if ( candidate != META_TARGET_NONE ) {
902                 metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
903
904                 rs->sr_err = LDAP_SUCCESS;
905
906                 ldap_get_option( msc->msc_ld, LDAP_OPT_ERROR_NUMBER, &rs->sr_err );
907                 if ( rs->sr_err != LDAP_SUCCESS ) {
908                         /*
909                          * better check the type of error. In some cases
910                          * (search ?) it might be better to return a
911                          * success if at least one of the targets gave
912                          * positive result ...
913                          */
914                         ldap_get_option( msc->msc_ld,
915                                         LDAP_OPT_ERROR_STRING, &rmsg );
916                         if ( rmsg != NULL && rmsg[ 0 ] == '\0' ) {
917                                 ldap_memfree( rmsg );
918                                 rmsg = NULL;
919                         }
920
921                         ldap_get_option( msc->msc_ld,
922                                         LDAP_OPT_MATCHED_DN, &rmatch );
923                         if ( rmatch != NULL && rmatch[ 0 ] == '\0' ) {
924                                 ldap_memfree( rmatch );
925                                 rmatch = NULL;
926                         }
927
928                         rerr = rs->sr_err = slap_map_api2result( rs );
929
930                         Debug(LDAP_DEBUG_ANY,
931                                         "==> meta_back_op_result: target"
932                                         " <%d> sending msg \"%s\""
933                                         " (matched \"%s\")\n", 
934                                         candidate, ( rmsg ? rmsg : "" ),
935                                         ( rmatch ? rmatch : "" ) );
936                 }
937
938         } else {
939                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
940                         metasingleconn_t        *msc = &mc->mc_conns[ i ];
941                         char                    *msg = NULL;
942                         char                    *match = NULL;
943
944                         rs->sr_err = LDAP_SUCCESS;
945
946                         ldap_get_option( msc->msc_ld, LDAP_OPT_ERROR_NUMBER, &rs->sr_err );
947                         if ( rs->sr_err != LDAP_SUCCESS ) {
948                                 /*
949                                  * better check the type of error. In some cases
950                                  * (search ?) it might be better to return a
951                                  * success if at least one of the targets gave
952                                  * positive result ...
953                                  */
954                                 ldap_get_option( msc->msc_ld,
955                                                 LDAP_OPT_ERROR_STRING, &msg );
956                                 if ( msg != NULL && msg[ 0 ] == '\0' ) {
957                                         ldap_memfree( msg );
958                                         msg = NULL;
959                                 }
960
961                                 ldap_get_option( msc->msc_ld,
962                                                 LDAP_OPT_MATCHED_DN, &match );
963                                 if ( match != NULL && match[ 0 ] == '\0' ) {
964                                         ldap_memfree( match );
965                                         match = NULL;
966                                 }
967
968                                 rs->sr_err = slap_map_api2result( rs );
969         
970                                 Debug(LDAP_DEBUG_ANY,
971                                                 "==> meta_back_op_result: target"
972                                                 " <%d> sending msg \"%s\""
973                                                 " (matched \"%s\")\n", 
974                                                 i, ( msg ? msg : "" ),
975                                                 ( match ? match : "" ) );
976         
977                                 /*
978                                  * FIXME: need to rewrite "match" (need rwinfo)
979                                  */
980                                 switch ( rs->sr_err ) {
981                                 default:
982                                         rerr = rs->sr_err;
983                                         if ( msg != NULL ) {
984                                                 if ( rmsg ) {
985                                                         ldap_memfree( rmsg );
986                                                 }
987                                                 rmsg = msg;
988                                                 msg = NULL;
989                                         }
990                                         if ( match != NULL ) {
991                                                 if ( rmatch ) {
992                                                         ldap_memfree( rmatch );
993                                                 }
994                                                 rmatch = match;
995                                                 match = NULL;
996                                         }
997                                         break;
998                                 }
999
1000                                 if ( msg ) {
1001                                         ldap_memfree( msg );
1002                                 }
1003         
1004                                 if ( match ) {
1005                                         ldap_memfree( match );
1006                                 }
1007                         }
1008                 }
1009         }
1010         
1011         rs->sr_err = rerr;
1012         if ( rmsg != NULL ) {
1013                 save_rmsg = rs->sr_text;
1014                 rs->sr_text = rmsg;
1015         }
1016         if ( rmatch != NULL ) {
1017                 struct berval   dn, pdn;
1018
1019                 ber_str2bv( rmatch, 0, 0, &dn );
1020                 if ( dnPretty( NULL, &dn, &pdn, op->o_tmpmemctx ) == LDAP_SUCCESS ) {
1021                         ldap_memfree( rmatch );
1022                         rmatch_ctx = op->o_tmpmemctx;
1023                         rmatch = pdn.bv_val;
1024                 }
1025                 save_rmatch = rs->sr_matched;
1026                 rs->sr_matched = rmatch;
1027         }
1028         send_ldap_result( op, rs );
1029         if ( rmsg != NULL ) {
1030                 ber_memfree( rmsg );
1031                 rs->sr_text = save_rmsg;
1032         }
1033         if ( rmatch != NULL ) {
1034                 ber_memfree_x( rmatch, rmatch_ctx );
1035                 rs->sr_matched = save_rmatch;
1036         }
1037
1038         return ( ( rerr == LDAP_SUCCESS ) ? 0 : -1 );
1039 }
1040