]> git.sur5r.net Git - openldap/blob - servers/slapd/back-meta/conn.c
remove unnecessary locks and resource cleanup
[openldap] / servers / slapd / back-meta / conn.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 /*
38  * Set PRINT_CONNTREE larger than 0 to dump the connection tree (debug only)
39  */
40 #ifndef PRINT_CONNTREE
41 #define PRINT_CONNTREE 0
42 #endif /* !PRINT_CONNTREE */
43
44 /*
45  * meta_back_conndn_cmp
46  *
47  * compares two struct metaconn based on the value of the conn pointer
48  * and of the local DN; used by avl stuff
49  */
50 int
51 meta_back_conndn_cmp(
52         const void *c1,
53         const void *c2 )
54 {
55         metaconn_t      *mc1 = ( metaconn_t * )c1;
56         metaconn_t      *mc2 = ( metaconn_t * )c2;
57         int             rc;
58         
59         /* If local DNs don't match, it is definitely not a match */
60         /* For shared sessions, conn is NULL. Only explicitly
61          * bound sessions will have non-NULL conn.
62          */
63         rc = SLAP_PTRCMP( mc1->mc_conn, mc2->mc_conn );
64         if ( rc == 0 ) {
65                 rc = ber_bvcmp( &mc1->mc_local_ndn, &mc2->mc_local_ndn );
66         }
67
68         return rc;
69 }
70
71 /*
72  * meta_back_conndnmc_cmp
73  *
74  * compares two struct metaconn based on the value of the conn pointer,
75  * the local DN and the struct pointer; used by avl stuff
76  */
77 static int
78 meta_back_conndnmc_cmp(
79         const void *c1,
80         const void *c2 )
81 {
82         metaconn_t      *mc1 = ( metaconn_t * )c1;
83         metaconn_t      *mc2 = ( metaconn_t * )c2;
84         int             rc;
85         
86         /* If local DNs don't match, it is definitely not a match */
87         /* For shared sessions, conn is NULL. Only explicitly
88          * bound sessions will have non-NULL conn.
89          */
90         rc = SLAP_PTRCMP( mc1->mc_conn, mc2->mc_conn );
91         if ( rc == 0 ) {
92                 rc = ber_bvcmp( &mc1->mc_local_ndn, &mc2->mc_local_ndn );
93                 if ( rc == 0 ) {
94                         rc = SLAP_PTRCMP( mc1, mc2 );
95                 }
96         }
97
98         return rc;
99 }
100
101 /*
102  * meta_back_conn_cmp
103  *
104  * compares two struct metaconn based on the value of the conn pointer;
105  * used by avl stuff
106  */
107 int
108 meta_back_conn_cmp(
109         const void *c1,
110         const void *c2 )
111 {
112         metaconn_t      *mc1 = ( metaconn_t * )c1;
113         metaconn_t      *mc2 = ( metaconn_t * )c2;
114         
115         /* For shared sessions, conn is NULL. Only explicitly
116          * bound sessions will have non-NULL conn.
117          */
118         return SLAP_PTRCMP( mc1->mc_conn, mc2->mc_conn );
119 }
120
121 /*
122  * meta_back_conndn_dup
123  *
124  * returns -1 in case a duplicate struct metaconn has been inserted;
125  * used by avl stuff
126  */
127 int
128 meta_back_conndn_dup(
129         void *c1,
130         void *c2 )
131 {
132         metaconn_t      *mc1 = ( metaconn_t * )c1;
133         metaconn_t      *mc2 = ( metaconn_t * )c2;
134
135         /* Cannot have more than one shared session with same DN */
136         if ( mc1->mc_conn == mc2->mc_conn &&
137                 dn_match( &mc1->mc_local_ndn, &mc2->mc_local_ndn ) )
138         {
139                 return -1;
140         }
141                 
142         return 0;
143 }
144
145 /*
146  * Debug stuff (got it from libavl)
147  */
148 #if PRINT_CONNTREE > 0
149 static void
150 ravl_print( Avlnode *root, int depth )
151 {
152         int             i;
153         metaconn_t      *mc;
154         
155         if ( root == 0 ) {
156                 return;
157         }
158         
159         ravl_print( root->avl_right, depth + 1 );
160         
161         for ( i = 0; i < depth; i++ ) {
162                 fprintf( stderr, "-" );
163         }
164
165         mc = (metaconn_t *)root->avl_data;
166         fprintf( stderr, "mc=%p local=\"%s\" conn=%p %s refcnt=%d\n",
167                 (void *)mc,
168                 mc->mc_local_ndn.bv_val ? mc->mc_local_ndn.bv_val : "",
169                 (void *)mc->mc_conn,
170                 avl_bf2str( root->avl_bf ), mc->mc_refcnt );
171         
172         ravl_print( root->avl_left, depth + 1 );
173 }
174
175 static void
176 myprint( Avlnode *root, char *msg )
177 {
178         fprintf( stderr, "========> %s\n", msg );
179         
180         if ( root == 0 ) {
181                 fprintf( stderr, "\tNULL\n" );
182
183         } else {
184                 ravl_print( root, 0 );
185         }
186         
187         fprintf( stderr, "<======== %s\n", msg );
188 }
189 #endif /* PRINT_CONNTREE */
190 /*
191  * End of debug stuff
192  */
193
194 /*
195  * metaconn_alloc
196  * 
197  * Allocates a connection structure, making room for all the referenced targets
198  */
199 static metaconn_t *
200 metaconn_alloc(
201         Operation               *op )
202 {
203         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
204         metaconn_t      *mc;
205         int             i, ntargets = mi->mi_ntargets;
206
207         assert( ntargets > 0 );
208
209         /* malloc all in one */
210         mc = ( metaconn_t * )ch_calloc( 1, sizeof( metaconn_t )
211                         + sizeof( metasingleconn_t ) * ntargets );
212         if ( mc == NULL ) {
213                 return NULL;
214         }
215
216         for ( i = 0; i < ntargets; i++ ) {
217                 mc->mc_conns[ i ].msc_info = mi;
218         }
219
220         mc->mc_authz_target = META_BOUND_NONE;
221         mc->mc_refcnt = 1;
222
223         return mc;
224 }
225
226 /*
227  * meta_back_init_one_conn
228  * 
229  * Initializes one connection
230  */
231 int
232 meta_back_init_one_conn(
233         Operation               *op,
234         SlapReply               *rs,
235         metaconn_t              *mc,
236         int                     candidate,
237         int                     ispriv,
238         ldap_back_send_t        sendok )
239 {
240         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
241         metatarget_t            *mt = mi->mi_targets[ candidate ];
242         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
243         int                     version;
244         dncookie                dc;
245         int                     isauthz = ( candidate == mc->mc_authz_target );
246 #ifdef HAVE_TLS
247         int                     is_ldaps = 0;
248 #endif /* HAVE_TLS */
249
250         /* if the server is quarantined, and
251          * - the current interval did not expire yet, or
252          * - no more retries should occur,
253          * don't return the connection */
254         if ( mt->mt_isquarantined ) {
255                 slap_retry_info_t       *ri = &mt->mt_quarantine;
256                 int                     dont_retry = 1;
257
258                 if ( mt->mt_isquarantined == LDAP_BACK_FQ_YES ) {
259                         dont_retry = ( ri->ri_num[ ri->ri_idx ] == SLAP_RETRYNUM_TAIL
260                                 || slap_get_time() < ri->ri_last + ri->ri_interval[ ri->ri_idx ] );
261                         if ( !dont_retry ) {
262                                 if ( LogTest( LDAP_DEBUG_ANY ) ) {
263                                         char    buf[ SLAP_TEXT_BUFLEN ];
264
265                                         snprintf( buf, sizeof( buf ),
266                                                 "meta_back_init_one_conn[%d]: quarantine "
267                                                 "retry block #%d try #%d",
268                                                 candidate, ri->ri_idx, ri->ri_count );
269                                         Debug( LDAP_DEBUG_ANY, "%s %s.\n",
270                                                 op->o_log_prefix, buf, 0 );
271                                 }
272
273                                 mt->mt_isquarantined = LDAP_BACK_FQ_RETRYING;
274                         }
275                 }
276
277                 if ( dont_retry ) {
278                         rs->sr_err = LDAP_UNAVAILABLE;
279                         if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
280                                 send_ldap_result( op, rs );
281                         }
282                         return rs->sr_err;
283                 }
284         }
285
286         /*
287          * Already init'ed
288          */
289         if ( msc->msc_ld != NULL ) {
290                 return rs->sr_err = LDAP_SUCCESS;
291         }
292
293         msc->msc_mscflags = 0;
294        
295         /*
296          * Attempts to initialize the connection to the target ds
297          */
298         ldap_pvt_thread_mutex_lock( &mt->mt_uri_mutex );
299         rs->sr_err = ldap_initialize( &msc->msc_ld, mt->mt_uri );
300 #ifdef HAVE_TLS
301         is_ldaps = ldap_is_ldaps_url( mt->mt_uri );
302 #endif /* HAVE_TLS */
303         ldap_pvt_thread_mutex_unlock( &mt->mt_uri_mutex );
304         if ( rs->sr_err != LDAP_SUCCESS ) {
305                 goto error_return;
306         }
307
308         /*
309          * Set LDAP version. This will always succeed: If the client
310          * bound with a particular version, then so can we.
311          */
312         if ( mt->mt_version != 0 ) {
313                 version = mt->mt_version;
314
315         } else if ( op->o_conn->c_protocol != 0 ) {
316                 version = op->o_conn->c_protocol;
317
318         } else {
319                 version = LDAP_VERSION3;
320         }
321         ldap_set_option( msc->msc_ld, LDAP_OPT_PROTOCOL_VERSION, &version );
322         ldap_set_urllist_proc( msc->msc_ld, mt->mt_urllist_f, mt->mt_urllist_p );
323
324         /* automatically chase referrals ("chase-referrals [{yes|no}]" statement) */
325         ldap_set_option( msc->msc_ld, LDAP_OPT_REFERRALS,
326                 LDAP_BACK_CHASE_REFERRALS( mi ) ? LDAP_OPT_ON : LDAP_OPT_OFF );
327
328 #ifdef HAVE_TLS
329         /* start TLS ("tls [try-]{start|propagate}" statement) */
330         if ( ( LDAP_BACK_USE_TLS( mi ) || ( op->o_conn->c_is_tls && LDAP_BACK_PROPAGATE_TLS( mi ) ) )
331                         && !is_ldaps )
332         {
333 #ifdef SLAP_STARTTLS_ASYNCHRONOUS
334                 /*
335                  * use asynchronous StartTLS; in case, chase referral
336                  * FIXME: OpenLDAP does not return referral on StartTLS yet
337                  */
338                 int             msgid;
339
340                 rs->sr_err = ldap_start_tls( msc->msc_ld, NULL, NULL, &msgid );
341                 if ( rs->sr_err == LDAP_SUCCESS ) {
342                         LDAPMessage     *res = NULL;
343                         int             rc, nretries = mt->mt_nretries;
344                         struct timeval  tv;
345
346                         LDAP_BACK_TV_SET( &tv );
347
348 retry:;
349                         rc = ldap_result( msc->msc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
350                         if ( rc < 0 ) {
351                                 rs->sr_err = LDAP_OTHER;
352
353                         } else if ( rc == 0 ) {
354                                 if ( nretries != 0 ) {
355                                         if ( nretries > 0 ) {
356                                                 nretries--;
357                                         }
358                                         LDAP_BACK_TV_SET( &tv );
359                                         goto retry;
360                                 }
361                                 rs->sr_err = LDAP_OTHER;
362
363                         } else if ( rc == LDAP_RES_EXTENDED ) {
364                                 struct berval   *data = NULL;
365
366                                 rs->sr_err = ldap_parse_extended_result( msc->msc_ld, res,
367                                                 NULL, &data, 0 );
368                                 if ( rs->sr_err == LDAP_SUCCESS ) {
369                                         int             err;
370
371                                         rs->sr_err = ldap_parse_result( msc->msc_ld, res,
372                                                 &err, NULL, NULL, NULL, NULL, 1 );
373                                         res = NULL;
374
375                                         if ( rs->sr_err == LDAP_SUCCESS ) {
376                                                 rs->sr_err = err;
377                                         }
378                                         
379                                         /* FIXME: in case a referral 
380                                          * is returned, should we try
381                                          * using it instead of the 
382                                          * configured URI? */
383                                         if ( rs->sr_err == LDAP_SUCCESS ) {
384                                                 ldap_install_tls( msc->msc_ld );
385
386                                         } else if ( rs->sr_err == LDAP_REFERRAL ) {
387                                                 rs->sr_err = LDAP_OTHER;
388                                                 rs->sr_text = "unwilling to chase referral returned by Start TLS exop";
389                                         }
390
391                                         if ( data ) {
392                                                 if ( data->bv_val ) {
393                                                         ber_memfree( data->bv_val );
394                                                 }
395                                                 ber_memfree( data );
396                                         }
397                                 }
398
399                         } else {
400                                 rs->sr_err = LDAP_OTHER;
401                         }
402
403                         if ( res != NULL ) {
404                                 ldap_msgfree( res );
405                         }
406                 }
407 #else /* ! SLAP_STARTTLS_ASYNCHRONOUS */
408                 /*
409                  * use synchronous StartTLS
410                  */
411                 rs->sr_err = ldap_start_tls_s( msc->msc_ld, NULL, NULL );
412 #endif /* ! SLAP_STARTTLS_ASYNCHRONOUS */
413
414                 /* if StartTLS is requested, only attempt it if the URL
415                  * is not "ldaps://"; this may occur not only in case
416                  * of misconfiguration, but also when used in the chain 
417                  * overlay, where the "uri" can be parsed out of a referral */
418                 if ( rs->sr_err == LDAP_SERVER_DOWN
419                                 || ( rs->sr_err != LDAP_SUCCESS && LDAP_BACK_TLS_CRITICAL( mi ) ) )
420                 {
421                         ldap_unbind_ext( msc->msc_ld, NULL, NULL );
422                         msc->msc_ld = NULL;
423                         goto error_return;
424                 }
425         }
426 #endif /* HAVE_TLS */
427
428         /*
429          * Set the network timeout if set
430          */
431         if ( mt->mt_network_timeout != 0 ) {
432                 struct timeval  network_timeout;
433
434                 network_timeout.tv_usec = 0;
435                 network_timeout.tv_sec = mt->mt_network_timeout;
436
437                 ldap_set_option( msc->msc_ld, LDAP_OPT_NETWORK_TIMEOUT,
438                                 (void *)&network_timeout );
439         }
440
441         /*
442          * If the connection DN is not null, an attempt to rewrite it is made
443          */
444
445         if ( ispriv ) {
446                 if ( !BER_BVISNULL( &mt->mt_pseudorootdn ) ) {
447                         ber_dupbv( &msc->msc_bound_ndn, &mt->mt_pseudorootdn );
448                         if ( !BER_BVISNULL( &mt->mt_pseudorootpw ) ) {
449                                 ber_dupbv( &msc->msc_cred, &mt->mt_pseudorootpw );
450                         }
451
452                 } else {
453                         ber_str2bv( "", 0, 1, &msc->msc_bound_ndn );
454                 }
455
456                 LDAP_BACK_CONN_ISPRIV_SET( msc );
457
458         } else {
459                 BER_BVZERO( &msc->msc_cred );
460                 BER_BVZERO( &msc->msc_bound_ndn );
461                 if ( !BER_BVISEMPTY( &op->o_ndn )
462                         && SLAP_IS_AUTHZ_BACKEND( op )
463                         && isauthz )
464                 {
465                         dc.target = mt;
466                         dc.conn = op->o_conn;
467                         dc.rs = rs;
468                         dc.ctx = "bindDN";
469                 
470                         /*
471                          * Rewrite the bind dn if needed
472                          */
473                         if ( ldap_back_dn_massage( &dc, &op->o_conn->c_dn,
474                                                 &msc->msc_bound_ndn ) )
475                         {
476                                 ldap_unbind_ext( msc->msc_ld, NULL, NULL );
477                                 msc->msc_ld = NULL;
478                                 goto error_return;
479                         }
480                         
481                         /* copy the DN if needed */
482                         if ( msc->msc_bound_ndn.bv_val == op->o_conn->c_dn.bv_val ) {
483                                 ber_dupbv( &msc->msc_bound_ndn, &op->o_conn->c_dn );
484                         }
485
486                 } else {
487                         ber_str2bv( "", 0, 1, &msc->msc_bound_ndn );
488                 }
489         }
490
491         assert( !BER_BVISNULL( &msc->msc_bound_ndn ) );
492
493 error_return:;
494         if ( rs->sr_err == LDAP_SUCCESS ) {
495                 /*
496                  * Sets a cookie for the rewrite session
497                  */
498                 ( void )rewrite_session_init( mt->mt_rwmap.rwm_rw, op->o_conn );
499
500         } else {
501                 rs->sr_err = slap_map_api2result( rs );
502                 if ( sendok & LDAP_BACK_SENDERR ) {
503                         send_ldap_result( op, rs );
504                         rs->sr_text = NULL;
505                 }
506         }
507
508         return rs->sr_err;
509 }
510
511 /*
512  * meta_back_retry
513  * 
514  * Retries one connection
515  */
516 int
517 meta_back_retry(
518         Operation               *op,
519         SlapReply               *rs,
520         metaconn_t              **mcp,
521         int                     candidate,
522         ldap_back_send_t        sendok )
523 {
524         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
525         metatarget_t            *mt = mi->mi_targets[ candidate ];
526         metaconn_t              *mc = *mcp;
527         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
528         int                     rc = LDAP_UNAVAILABLE,
529                                 binding = LDAP_BACK_CONN_BINDING( msc );
530
531         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
532
533         assert( mc->mc_refcnt > 0 );
534         if ( mc->mc_refcnt == 1 ) {
535                 if ( LogTest( LDAP_DEBUG_ANY ) ) {
536                         char    buf[ SLAP_TEXT_BUFLEN ];
537
538                         ldap_pvt_thread_mutex_lock( &mt->mt_uri_mutex );
539                         snprintf( buf, sizeof( buf ),
540                                 "retrying URI=\"%s\" DN=\"%s\"",
541                                 mt->mt_uri,
542                                 BER_BVISNULL( &msc->msc_bound_ndn ) ?
543                                         "" : msc->msc_bound_ndn.bv_val );
544                         ldap_pvt_thread_mutex_unlock( &mt->mt_uri_mutex );
545
546                         Debug( LDAP_DEBUG_ANY,
547                                 "%s meta_back_retry[%d]: %s.\n",
548                                 op->o_log_prefix, candidate, buf );
549                 }
550
551                 meta_clear_one_candidate( msc );
552                 LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
553
554                 ( void )rewrite_session_delete( mt->mt_rwmap.rwm_rw, op->o_conn );
555
556                 /* mc here must be the regular mc, reset and ready for init */
557                 rc = meta_back_init_one_conn( op, rs, mc, candidate,
558                         LDAP_BACK_CONN_ISPRIV( mc ), sendok );
559                 if ( binding ) {
560                         LDAP_BACK_CONN_BINDING_SET( msc );
561                 }
562
563                 if ( rc == LDAP_SUCCESS ) {
564                         rc = meta_back_single_dobind( op, rs, mcp, candidate,
565                                 sendok, mt->mt_nretries, 0 );
566
567                         Debug( LDAP_DEBUG_ANY,
568                                 "%s meta_back_retry[%d]: "
569                                 "meta_back_single_dobind=%d\n",
570                                 op->o_log_prefix, candidate, rc );
571                         if ( rc == LDAP_SUCCESS ) {
572                                 if ( be_isroot( op )  ) {
573                                         LDAP_BACK_CONN_ISBOUND_SET( msc );
574                                 } else {
575                                         LDAP_BACK_CONN_ISANON_SET( msc );
576                                 }
577                         }
578                 }
579         }
580
581         if ( rc != LDAP_SUCCESS ) {
582                 SlapReply               *candidates = meta_back_candidates_get( op );
583
584                 candidates[ candidate ].sr_err = rc;
585
586                 if ( *mcp != NULL ) {
587                         if ( binding ) {
588                                 LDAP_BACK_CONN_BINDING_CLEAR( msc );
589                         }
590                         LDAP_BACK_CONN_TAINTED_SET( mc );
591                         /* only release if mandatory; otherwise
592                          * let the caller do what's best before
593                          * releasing */
594                         if ( META_BACK_ONERR_STOP( mi ) ) {
595                                 meta_back_release_conn_lock( op, mc, 0 );
596                                 *mcp = NULL;
597                         }
598                 }
599
600                 if ( sendok ) {
601                         rs->sr_err = rc;
602                         rs->sr_text = NULL;
603                         send_ldap_result( op, rs );
604                 }
605         }
606
607         if ( META_BACK_TGT_QUARANTINE( mt ) ) {
608                 meta_back_quarantine( op, rs, candidate );
609         }
610
611         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
612
613         return rc == LDAP_SUCCESS ? 1 : 0;
614 }
615
616 /*
617  * callback for unique candidate selection
618  */
619 static int
620 meta_back_conn_cb( Operation *op, SlapReply *rs )
621 {
622         assert( op->o_tag == LDAP_REQ_SEARCH );
623
624         switch ( rs->sr_type ) {
625         case REP_SEARCH:
626                 ((long *)op->o_callback->sc_private)[0] = (long)op->o_private;
627                 break;
628
629         case REP_SEARCHREF:
630         case REP_RESULT:
631                 break;
632
633         default:
634                 return rs->sr_err;
635         }
636
637         return 0;
638 }
639
640
641 static int
642 meta_back_get_candidate(
643         Operation       *op,
644         SlapReply       *rs,
645         struct berval   *ndn )
646 {
647         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
648         long            candidate;
649
650         /*
651          * tries to get a unique candidate
652          * (takes care of default target)
653          */
654         candidate = meta_back_select_unique_candidate( mi, ndn );
655
656         /*
657          * if any is found, inits the connection
658          */
659         if ( candidate == META_TARGET_NONE ) {
660                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
661                 rs->sr_text = "no suitable candidate target found";
662
663         } else if ( candidate == META_TARGET_MULTIPLE ) {
664                 Filter          f = { 0 };
665                 Operation       op2 = *op;
666                 SlapReply       rs2 = { 0 };
667                 slap_callback   cb2 = { 0 };
668                 int             rc;
669
670                 /* try to get a unique match for the request ndn
671                  * among the multiple candidates available */
672                 op2.o_tag = LDAP_REQ_SEARCH;
673                 op2.o_req_dn = *ndn;
674                 op2.o_req_ndn = *ndn;
675                 op2.ors_scope = LDAP_SCOPE_BASE;
676                 op2.ors_deref = LDAP_DEREF_NEVER;
677                 op2.ors_attrs = slap_anlist_no_attrs;
678                 op2.ors_attrsonly = 0;
679                 op2.ors_limit = NULL;
680                 op2.ors_slimit = 1;
681                 op2.ors_tlimit = SLAP_NO_LIMIT;
682
683                 f.f_choice = LDAP_FILTER_PRESENT;
684                 f.f_desc = slap_schema.si_ad_objectClass;
685                 op2.ors_filter = &f;
686                 BER_BVSTR( &op2.ors_filterstr, "(objectClass=*)" );
687
688                 op2.o_callback = &cb2;
689                 cb2.sc_response = meta_back_conn_cb;
690                 cb2.sc_private = (void *)&candidate;
691
692                 rc = op->o_bd->be_search( &op2, &rs2 );
693
694                 switch ( rs2.sr_err ) {
695                 case LDAP_SUCCESS:
696                 default:
697                         rs->sr_err = rs2.sr_err;
698                         break;
699
700                 case LDAP_SIZELIMIT_EXCEEDED:
701                         /* if multiple candidates can serve the operation,
702                          * and a default target is defined, and it is
703                          * a candidate, try using it (FIXME: YMMV) */
704                         if ( mi->mi_defaulttarget != META_DEFAULT_TARGET_NONE
705                                 && meta_back_is_candidate( mi->mi_targets[ mi->mi_defaulttarget ],
706                                                 ndn, op->o_tag == LDAP_REQ_SEARCH ? op->ors_scope : LDAP_SCOPE_BASE ) )
707                         {
708                                 candidate = mi->mi_defaulttarget;
709                                 rs->sr_err = LDAP_SUCCESS;
710                                 rs->sr_text = NULL;
711
712                         } else {
713                                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
714                                 rs->sr_text = "cannot select unique candidate target";
715                         }
716                         break;
717                 }
718
719         } else {
720                 rs->sr_err = LDAP_SUCCESS;
721         }
722
723         return candidate;
724 }
725
726 static void     *meta_back_candidates_dummy;
727
728 static void
729 meta_back_candidates_keyfree(
730         void            *key,
731         void            *data )
732 {
733         metacandidates_t        *mc = (metacandidates_t *)data;
734
735         ber_memfree_x( mc->mc_candidates, NULL );
736         ber_memfree_x( data, NULL );
737 }
738
739 SlapReply *
740 meta_back_candidates_get( Operation *op )
741 {
742         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
743         metacandidates_t        *mc;
744
745         if ( op->o_threadctx ) {
746                 void            *data = NULL;
747
748                 ldap_pvt_thread_pool_getkey( op->o_threadctx,
749                                 &meta_back_candidates_dummy, &data, NULL );
750                 mc = (metacandidates_t *)data;
751
752         } else {
753                 mc = mi->mi_candidates;
754         }
755
756         if ( mc == NULL ) {
757                 mc = ch_calloc( sizeof( metacandidates_t ), 1 );
758                 mc->mc_ntargets = mi->mi_ntargets;
759                 mc->mc_candidates = ch_calloc( sizeof( SlapReply ), mc->mc_ntargets );
760                 if ( op->o_threadctx ) {
761                         void            *data = NULL;
762
763                         data = (void *)mc;
764                         ldap_pvt_thread_pool_setkey( op->o_threadctx,
765                                         &meta_back_candidates_dummy, data,
766                                         meta_back_candidates_keyfree );
767
768                 } else {
769                         mi->mi_candidates = mc;
770                 }
771
772         } else if ( mc->mc_ntargets < mi->mi_ntargets ) {
773                 /* NOTE: in the future, may want to allow back-config
774                  * to add/remove targets from back-meta... */
775                 mc->mc_candidates = ch_realloc( mc->mc_candidates,
776                                 sizeof( SlapReply ) * mi->mi_ntargets );
777                 memset( &mc->mc_candidates[ mc->mc_ntargets ], 0,
778                         sizeof( SlapReply ) * ( mi->mi_ntargets - mc->mc_ntargets ) );
779                 mc->mc_ntargets = mi->mi_ntargets;
780         }
781
782         return mc->mc_candidates;
783 }
784
785 /*
786  * meta_back_getconn
787  * 
788  * Prepares the connection structure
789  * 
790  * RATIONALE:
791  *
792  * - determine what DN is being requested:
793  *
794  *      op      requires candidate      checks
795  *
796  *      add     unique                  parent of o_req_ndn
797  *      bind    unique^*[/all]          o_req_ndn [no check]
798  *      compare unique^+                o_req_ndn
799  *      delete  unique                  o_req_ndn
800  *      modify  unique                  o_req_ndn
801  *      search  any                     o_req_ndn
802  *      modrdn  unique[, unique]        o_req_ndn[, orr_nnewSup]
803  *
804  * - for ops that require the candidate to be unique, in case of multiple
805  *   occurrences an internal search with sizeLimit=1 is performed
806  *   if a unique candidate can actually be determined.  If none is found,
807  *   the operation aborts; if multiple are found, the default target
808  *   is used if defined and candidate; otherwise the operation aborts.
809  *
810  * *^note: actually, the bind operation is handled much like a search;
811  *   i.e. the bind is broadcast to all candidate targets.
812  *
813  * +^note: actually, the compare operation is handled much like a search;
814  *   i.e. the compare is broadcast to all candidate targets, while checking
815  *   that exactly none (noSuchObject) or one (TRUE/FALSE/UNDEFINED) is
816  *   returned.
817  */
818 metaconn_t *
819 meta_back_getconn(
820         Operation               *op,
821         SlapReply               *rs,
822         int                     *candidate,
823         ldap_back_send_t        sendok )
824 {
825         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
826         metaconn_t      *mc = NULL,
827                         mc_curr = { 0 };
828         int             cached = META_TARGET_NONE,
829                         i = META_TARGET_NONE,
830                         err = LDAP_SUCCESS,
831                         new_conn = 0,
832                         ncandidates = 0;
833
834
835         meta_op_type    op_type = META_OP_REQUIRE_SINGLE;
836         enum            {
837                 META_DNTYPE_ENTRY,
838                 META_DNTYPE_PARENT,
839                 META_DNTYPE_NEWPARENT
840                         } dn_type = META_DNTYPE_ENTRY;
841         struct berval   ndn = op->o_req_ndn,
842                         pndn;
843
844         SlapReply       *candidates = meta_back_candidates_get( op );
845
846         /* Internal searches are privileged and shared. So is root. */
847         /* FIXME: there seem to be concurrency issues */
848         if ( op->o_do_not_cache || be_isroot( op ) ) {
849                 mc_curr.mc_local_ndn = op->o_bd->be_rootndn;
850                 LDAP_BACK_CONN_ISPRIV_SET( &mc_curr );
851                 mc_curr.mc_conn = LDAP_BACK_PCONN_SET( op );
852
853         } else {
854                 mc_curr.mc_local_ndn = op->o_ndn;
855
856                 /* Explicit binds must not be shared */
857                 if ( op->o_tag == LDAP_REQ_BIND || SLAP_IS_AUTHZ_BACKEND( op ) ) {
858                         mc_curr.mc_conn = op->o_conn;
859         
860                 } else {
861                         mc_curr.mc_conn = LDAP_BACK_PCONN_SET( op );
862                 }
863         }
864
865         /* Explicit Bind requests always get their own conn */
866         if ( !( sendok & LDAP_BACK_BINDING ) ) {
867                 /* Searches for a metaconn in the avl tree */
868 retry_lock:;
869                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
870                 mc = (metaconn_t *)avl_find( mi->mi_conninfo.lai_tree, 
871                         (caddr_t)&mc_curr, meta_back_conndn_cmp );
872                 if ( mc ) {
873                         if ( ( mi->mi_conn_ttl != 0 && op->o_time > mc->mc_create_time + mi->mi_conn_ttl )
874                                 || ( mi->mi_idle_timeout != 0 && op->o_time > mc->mc_time + mi->mi_idle_timeout ) )
875                         {
876                                 /* don't let anyone else use this expired connection */
877                                 (void)avl_delete( &mi->mi_conninfo.lai_tree,
878                                         (caddr_t)mc, meta_back_conndnmc_cmp );
879                                 LDAP_BACK_CONN_TAINTED_SET( mc );
880
881                                 Debug( LDAP_DEBUG_TRACE, "%s meta_back_getconn: mc=%p conn=%ld expired.\n",
882                                         op->o_log_prefix, (void *)mc, LDAP_BACK_PCONN_ID( mc->mc_conn ) );
883                         }
884
885                         /* Don't reuse connections while they're still binding */
886                         if ( LDAP_BACK_CONN_BINDING( mc ) ) {
887                                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
888                                 ldap_pvt_thread_yield();
889                                 goto retry_lock;
890                         }
891
892                         mc->mc_refcnt++;
893                 }
894                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
895         }
896
897         switch ( op->o_tag ) {
898         case LDAP_REQ_ADD:
899                 /* if we go to selection, the entry must not exist,
900                  * and we must be able to resolve the parent */
901                 dn_type = META_DNTYPE_PARENT;
902                 dnParent( &ndn, &pndn );
903                 break;
904
905         case LDAP_REQ_MODRDN:
906                 /* if nnewSuperior is not NULL, it must resolve
907                  * to the same candidate as the req_ndn */
908                 if ( op->orr_nnewSup ) {
909                         dn_type = META_DNTYPE_NEWPARENT;
910                 }
911                 break;
912
913         case LDAP_REQ_BIND:
914                 /* if bound as rootdn, the backend must bind to all targets
915                  * with the administrative identity */
916                 if ( op->orb_method == LDAP_AUTH_SIMPLE && be_isroot_pw( op ) ) {
917                         op_type = META_OP_REQUIRE_ALL;
918                 }
919                 break;
920
921         case LDAP_REQ_DELETE:
922         case LDAP_REQ_MODIFY:
923                 /* just a unique candidate */
924                 break;
925
926         case LDAP_REQ_COMPARE:
927         case LDAP_REQ_SEARCH:
928                 /* allow multiple candidates for the searchBase */
929                 op_type = META_OP_ALLOW_MULTIPLE;
930                 break;
931
932         default:
933                 /* right now, just break (exop?) */
934                 break;
935         }
936
937         /*
938          * require all connections ...
939          */
940         if ( op_type == META_OP_REQUIRE_ALL ) {
941
942                 /* Looks like we didn't get a bind. Open a new session... */
943                 if ( mc == NULL ) {
944                         assert( new_conn == 0 );
945                         mc = metaconn_alloc( op );
946                         mc->mc_conn = mc_curr.mc_conn;
947                         ber_dupbv( &mc->mc_local_ndn, &mc_curr.mc_local_ndn );
948                         new_conn = 1;
949                         if ( sendok & LDAP_BACK_BINDING ) {
950                                 LDAP_BACK_CONN_BINDING_SET( mc );
951                         }
952                 }
953
954                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
955                         /*
956                          * The target is activated; if needed, it is
957                          * also init'd
958                          */
959                         candidates[ i ].sr_err = meta_back_init_one_conn( op,
960                                 rs, mc, i, LDAP_BACK_CONN_ISPRIV( &mc_curr ),
961                                 sendok );
962                         if ( candidates[ i ].sr_err == LDAP_SUCCESS ) {
963                                 META_CANDIDATE_SET( &candidates[ i ] );
964                                 ncandidates++;
965         
966                         } else {
967                                 
968                                 /*
969                                  * FIXME: in case one target cannot
970                                  * be init'd, should the other ones
971                                  * be tried?
972                                  */
973                                 META_CANDIDATE_RESET( &candidates[ i ] );
974                                 err = candidates[ i ].sr_err;
975                                 continue;
976                         }
977                 }
978
979                 if ( ncandidates == 0 ) {
980                         if ( new_conn ) {
981                                 mc->mc_refcnt = 0;
982                                 meta_back_conn_free( mc );
983
984                         } else {
985                                 meta_back_release_conn( op, mc );
986                         }
987
988                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
989                         rs->sr_text = "Unable to select valid candidates";
990
991                         if ( sendok & LDAP_BACK_SENDERR ) {
992                                 if ( rs->sr_err == LDAP_NO_SUCH_OBJECT ) {
993                                         rs->sr_matched = op->o_bd->be_suffix[ 0 ].bv_val;
994                                 }
995                                 send_ldap_result( op, rs );
996                                 rs->sr_text = NULL;
997                                 rs->sr_matched = NULL;
998                         }
999
1000                         return NULL;
1001                 }
1002
1003                 goto done;
1004         }
1005         
1006         /*
1007          * looks in cache, if any
1008          */
1009         if ( mi->mi_cache.ttl != META_DNCACHE_DISABLED ) {
1010                 cached = i = meta_dncache_get_target( &mi->mi_cache, &op->o_req_ndn );
1011         }
1012
1013         if ( op_type == META_OP_REQUIRE_SINGLE ) {
1014                 metatarget_t            *mt = NULL;
1015                 metasingleconn_t        *msc = NULL;
1016
1017                 int                     j;
1018
1019                 for ( j = 0; j < mi->mi_ntargets; j++ ) {
1020                         META_CANDIDATE_RESET( &candidates[ j ] );
1021                 }
1022
1023                 /*
1024                  * tries to get a unique candidate
1025                  * (takes care of default target)
1026                  */
1027                 if ( i == META_TARGET_NONE ) {
1028                         i = meta_back_get_candidate( op, rs, &ndn );
1029
1030                         if ( rs->sr_err == LDAP_NO_SUCH_OBJECT && dn_type == META_DNTYPE_PARENT ) {
1031                                 i = meta_back_get_candidate( op, rs, &pndn );
1032                         }
1033         
1034                         if ( i < 0 || rs->sr_err != LDAP_SUCCESS ) {
1035                                 if ( mc != NULL ) {
1036                                         meta_back_release_conn( op, mc );
1037                                 }
1038
1039                                 if ( sendok & LDAP_BACK_SENDERR ) {
1040                                         if ( rs->sr_err == LDAP_NO_SUCH_OBJECT ) {
1041                                                 rs->sr_matched = op->o_bd->be_suffix[ 0 ].bv_val;
1042                                         }
1043                                         send_ldap_result( op, rs );
1044                                         rs->sr_text = NULL;
1045                                         rs->sr_matched = NULL;
1046                                 }
1047                         
1048                                 return NULL;
1049                         }
1050                 }
1051
1052                 if ( dn_type == META_DNTYPE_NEWPARENT && meta_back_get_candidate( op, rs, op->orr_nnewSup ) != i )
1053                 {
1054                         if ( mc != NULL ) {
1055                                 meta_back_release_conn( op, mc );
1056                         }
1057
1058                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1059                         rs->sr_text = "cross-target rename not supported";
1060                         if ( sendok & LDAP_BACK_SENDERR ) {
1061                                 send_ldap_result( op, rs );
1062                                 rs->sr_text = NULL;
1063                         }
1064
1065                         return NULL;
1066                 }
1067
1068                 Debug( LDAP_DEBUG_TRACE,
1069         "==>meta_back_getconn: got target=%d for ndn=\"%s\" from cache\n",
1070                                 i, op->o_req_ndn.bv_val, 0 );
1071
1072                 if ( mc == NULL ) {
1073                         /* Retries searching for a metaconn in the avl tree
1074                          * the reason is that the connection might have been
1075                          * created by meta_back_get_candidate() */
1076                         if ( !( sendok & LDAP_BACK_BINDING ) ) {
1077 retry_lock2:;
1078                                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
1079                                 mc = (metaconn_t *)avl_find( mi->mi_conninfo.lai_tree, 
1080                                         (caddr_t)&mc_curr, meta_back_conndn_cmp );
1081                                 if ( mc != NULL ) {
1082                                         /* Don't reuse connections while they're still binding */
1083                                         if ( LDAP_BACK_CONN_BINDING( mc ) ) {
1084                                                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1085                                                 ldap_pvt_thread_yield();
1086                                                 goto retry_lock2;
1087                                         }
1088
1089                                         mc->mc_refcnt++;
1090                                 }
1091                                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1092                         }
1093
1094                         /* Looks like we didn't get a bind. Open a new session... */
1095                         if ( mc == NULL ) {
1096                                 assert( new_conn == 0 );
1097                                 mc = metaconn_alloc( op );
1098                                 mc->mc_conn = mc_curr.mc_conn;
1099                                 ber_dupbv( &mc->mc_local_ndn, &mc_curr.mc_local_ndn );
1100                                 new_conn = 1;
1101                                 if ( sendok & LDAP_BACK_BINDING ) {
1102                                         LDAP_BACK_CONN_BINDING_SET( mc );
1103                                 }
1104                         }
1105                 }
1106
1107                 /*
1108                  * Clear all other candidates
1109                  */
1110                 ( void )meta_clear_unused_candidates( op, i );
1111
1112                 mt = mi->mi_targets[ i ];
1113                 msc = &mc->mc_conns[ i ];
1114
1115                 /*
1116                  * The target is activated; if needed, it is
1117                  * also init'd. In case of error, meta_back_init_one_conn
1118                  * sends the appropriate result.
1119                  */
1120                 err = meta_back_init_one_conn( op, rs, mc, i,
1121                         LDAP_BACK_CONN_ISPRIV( &mc_curr ), sendok );
1122                 if ( err != LDAP_SUCCESS ) {
1123                         /*
1124                          * FIXME: in case one target cannot
1125                          * be init'd, should the other ones
1126                          * be tried?
1127                          */
1128                         META_CANDIDATE_RESET( &candidates[ i ] );
1129                         if ( new_conn ) {
1130                                 mc->mc_refcnt = 0;
1131                                 meta_back_conn_free( mc );
1132
1133                         } else {
1134                                 meta_back_release_conn( op, mc );
1135                         }
1136                         return NULL;
1137                 }
1138
1139                 candidates[ i ].sr_err = LDAP_SUCCESS;
1140                 META_CANDIDATE_SET( &candidates[ i ] );
1141                 ncandidates++;
1142
1143                 if ( candidate ) {
1144                         *candidate = i;
1145                 }
1146
1147         /*
1148          * if no unique candidate ...
1149          */
1150         } else {
1151
1152                 /* Looks like we didn't get a bind. Open a new session... */
1153                 if ( mc == NULL ) {
1154                         assert( new_conn == 0 );
1155                         mc = metaconn_alloc( op );
1156                         mc->mc_conn = mc_curr.mc_conn;
1157                         ber_dupbv( &mc->mc_local_ndn, &mc_curr.mc_local_ndn );
1158                         new_conn = 1;
1159                         if ( sendok & LDAP_BACK_BINDING ) {
1160                                 LDAP_BACK_CONN_BINDING_SET( mc );
1161                         }
1162                 }
1163
1164                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
1165                         metatarget_t            *mt = mi->mi_targets[ i ];
1166                         metasingleconn_t        *msc = &mc->mc_conns[ i ];
1167
1168                         if ( i == cached 
1169                                 || meta_back_is_candidate( mt, &op->o_req_ndn,
1170                                         LDAP_SCOPE_SUBTREE ) )
1171                         {
1172
1173                                 /*
1174                                  * The target is activated; if needed, it is
1175                                  * also init'd
1176                                  */
1177                                 int lerr = meta_back_init_one_conn( op, rs, mc, i,
1178                                         LDAP_BACK_CONN_ISPRIV( &mc_curr ), LDAP_BACK_DONTSEND );
1179                                 if ( lerr == LDAP_SUCCESS ) {
1180                                         META_CANDIDATE_SET( &candidates[ i ] );
1181                                         candidates[ i ].sr_err = LDAP_SUCCESS;
1182                                         ncandidates++;
1183
1184                                         Debug( LDAP_DEBUG_TRACE, "%s: meta_back_getconn[%d]\n",
1185                                                 op->o_log_prefix, i, 0 );
1186
1187                                 } else {
1188                                 
1189                                         /*
1190                                          * FIXME: in case one target cannot
1191                                          * be init'd, should the other ones
1192                                          * be tried?
1193                                          */
1194                                         if ( new_conn ) {
1195                                                 ( void )meta_clear_one_candidate( msc );
1196                                         }
1197                                         /* leave the target candidate, but record the error for later use */
1198                                         candidates[ i ].sr_err = lerr;
1199                                         err = lerr;
1200
1201                                         if ( lerr == LDAP_UNAVAILABLE && mt->mt_isquarantined != LDAP_BACK_FQ_NO ) {
1202                                                 Debug( LDAP_DEBUG_TRACE, "%s: meta_back_getconn[%d] quarantined: %d\n",
1203                                                         op->o_log_prefix, i, lerr );
1204
1205                                         } else {
1206                                                 Debug( LDAP_DEBUG_ANY, "%s: meta_back_getconn[%d] failed: %d\n",
1207                                                         op->o_log_prefix, i, lerr );
1208                                         }
1209
1210                                         if ( META_BACK_ONERR_STOP( mi ) ) {
1211                                                 if ( sendok & LDAP_BACK_SENDERR ) {
1212                                                         send_ldap_result( op, rs );
1213                                                         rs->sr_text = NULL;
1214                                                 }
1215                                                 if ( new_conn ) {
1216                                                         mc->mc_refcnt = 0;
1217                                                         meta_back_conn_free( mc );
1218
1219                                                 } else {
1220                                                         meta_back_release_conn( op, mc );
1221                                                 }
1222
1223                                                 return NULL;
1224                                         }
1225
1226                                         rs->sr_text = NULL;
1227                                         continue;
1228                                 }
1229
1230                         } else {
1231                                 if ( new_conn ) {
1232                                         ( void )meta_clear_one_candidate( msc );
1233                                 }
1234                                 META_CANDIDATE_RESET( &candidates[ i ] );
1235                         }
1236                 }
1237
1238                 if ( ncandidates == 0 ) {
1239                         if ( new_conn ) {
1240                                 mc->mc_refcnt = 0;
1241                                 meta_back_conn_free( mc );
1242
1243                         } else {
1244                                 meta_back_release_conn( op, mc );
1245                         }
1246
1247                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
1248                         rs->sr_text = "Unable to select valid candidates";
1249
1250                         if ( sendok & LDAP_BACK_SENDERR ) {
1251                                 if ( rs->sr_err == LDAP_NO_SUCH_OBJECT ) {
1252                                         rs->sr_matched = op->o_bd->be_suffix[ 0 ].bv_val;
1253                                 }
1254                                 send_ldap_result( op, rs );
1255                                 rs->sr_text = NULL;
1256                                 rs->sr_matched = NULL;
1257                         }
1258
1259                         return NULL;
1260                 }
1261         }
1262
1263 done:;
1264         /* clear out meta_back_init_one_conn non-fatal errors */
1265         rs->sr_err = LDAP_SUCCESS;
1266         rs->sr_text = NULL;
1267
1268         /* touch the timestamp */
1269         if ( mi->mi_idle_timeout != 0 ) {
1270                 mc->mc_time = op->o_time;
1271         }
1272
1273         if ( new_conn ) {
1274                 if ( mi->mi_conn_ttl ) {
1275                         mc->mc_create_time = op->o_time;
1276                 }
1277
1278                 /*
1279                  * Inserts the newly created metaconn in the avl tree
1280                  */
1281                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
1282                 err = avl_insert( &mi->mi_conninfo.lai_tree, ( caddr_t )mc,
1283                                 meta_back_conndn_cmp, meta_back_conndn_dup );
1284
1285 #if PRINT_CONNTREE > 0
1286                 myprint( mi->mi_conninfo.lai_tree, "meta_back_getconn" );
1287 #endif /* PRINT_CONNTREE */
1288                 
1289                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1290
1291                 /*
1292                  * Err could be -1 in case a duplicate metaconn is inserted
1293                  */
1294                 switch ( err ) {
1295                 case 0:
1296                         break;
1297
1298                 case -1:
1299                         /* duplicate: free and try to get the newly created one */
1300                         if ( !( sendok & LDAP_BACK_BINDING ) ) {
1301                                 new_conn = 0;
1302                                 goto retry_lock;
1303                         }
1304                         LDAP_BACK_CONN_TAINTED_SET( mc );
1305                         break;
1306
1307                 default:
1308                         Debug( LDAP_DEBUG_ANY,
1309                                 "%s meta_back_getconn: candidates=%d conn=%ld insert failed\n",
1310                                 op->o_log_prefix, ncandidates,
1311                                 LDAP_BACK_PCONN_ID( mc->mc_conn ) );
1312         
1313                         mc->mc_refcnt = 0;      
1314                         meta_back_conn_free( mc );
1315
1316                         rs->sr_err = LDAP_OTHER;
1317                         rs->sr_text = "proxy bind collision";
1318                         if ( sendok & LDAP_BACK_SENDERR ) {
1319                                 send_ldap_result( op, rs );
1320                                 rs->sr_text = NULL;
1321                         }
1322                         return NULL;
1323                 }
1324
1325                 Debug( LDAP_DEBUG_TRACE,
1326                         "%s meta_back_getconn: candidates=%d conn=%ld inserted\n",
1327                         op->o_log_prefix, ncandidates,
1328                         LDAP_BACK_PCONN_ID( mc->mc_conn ) );
1329
1330         } else {
1331                 Debug( LDAP_DEBUG_TRACE,
1332                         "%s meta_back_getconn: candidates=%d conn=%ld fetched\n",
1333                         op->o_log_prefix, ncandidates,
1334                         LDAP_BACK_PCONN_ID( mc->mc_conn ) );
1335         }
1336         
1337         return mc;
1338 }
1339
1340 void
1341 meta_back_release_conn_lock(
1342         Operation               *op,
1343         metaconn_t              *mc,
1344         int                     dolock )
1345 {
1346         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
1347
1348         assert( mc != NULL );
1349
1350         if ( dolock ) {
1351                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
1352         }
1353         assert( mc->mc_refcnt > 0 );
1354         mc->mc_refcnt--;
1355         LDAP_BACK_CONN_BINDING_CLEAR( mc );
1356         if ( LDAP_BACK_CONN_TAINTED( mc ) ) {
1357                 Debug( LDAP_DEBUG_TRACE, "%s meta_back_release_conn: mc=%p conn=%ld tainted.\n",
1358                         op->o_log_prefix, (void *)mc, LDAP_BACK_PCONN_ID( mc->mc_conn ) );
1359                 (void)avl_delete( &mi->mi_conninfo.lai_tree,
1360                         ( caddr_t )mc, meta_back_conndnmc_cmp );
1361                 if ( mc->mc_refcnt == 0 ) {
1362                         meta_back_conn_free( mc );
1363                 }
1364         }
1365         if ( dolock ) {
1366                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1367         }
1368 }
1369
1370 void
1371 meta_back_quarantine(
1372         Operation       *op,
1373         SlapReply       *rs,
1374         int             candidate )
1375 {
1376         metainfo_t              *mi = (metainfo_t *)op->o_bd->be_private;
1377         metatarget_t            *mt = mi->mi_targets[ candidate ];
1378
1379         slap_retry_info_t       *ri = &mt->mt_quarantine;
1380
1381         ldap_pvt_thread_mutex_lock( &mt->mt_quarantine_mutex );
1382
1383         if ( rs->sr_err == LDAP_UNAVAILABLE ) {
1384                 time_t  new_last = slap_get_time();
1385
1386                 switch ( mt->mt_isquarantined ) {
1387                 case LDAP_BACK_FQ_NO:
1388                         if ( ri->ri_last == new_last ) {
1389                                 goto done;
1390                         }
1391
1392                         Debug( LDAP_DEBUG_ANY,
1393                                 "%s meta_back_quarantine[%d]: enter.\n",
1394                                 op->o_log_prefix, candidate, 0 );
1395
1396                         ri->ri_idx = 0;
1397                         ri->ri_count = 0;
1398                         break;
1399
1400                 case LDAP_BACK_FQ_RETRYING:
1401                         if ( LogTest( LDAP_DEBUG_ANY ) ) {
1402                                 char    buf[ SLAP_TEXT_BUFLEN ];
1403
1404                                 snprintf( buf, sizeof( buf ),
1405                                         "meta_back_quarantine[%d]: block #%d try #%d failed",
1406                                         candidate, ri->ri_idx, ri->ri_count );
1407                                 Debug( LDAP_DEBUG_ANY, "%s %s.\n",
1408                                         op->o_log_prefix, buf, 0 );
1409                         }
1410
1411                         ++ri->ri_count;
1412                         if ( ri->ri_num[ ri->ri_idx ] != SLAP_RETRYNUM_FOREVER
1413                                 && ri->ri_count == ri->ri_num[ ri->ri_idx ] )
1414                         {
1415                                 ri->ri_count = 0;
1416                                 ++ri->ri_idx;
1417                         }
1418                         break;
1419
1420                 default:
1421                         break;
1422                 }
1423
1424                 mt->mt_isquarantined = LDAP_BACK_FQ_YES;
1425                 ri->ri_last = new_last;
1426
1427         } else if ( mt->mt_isquarantined == LDAP_BACK_FQ_RETRYING ) {
1428                 Debug( LDAP_DEBUG_ANY,
1429                         "%s meta_back_quarantine[%d]: exit.\n",
1430                         op->o_log_prefix, candidate, 0 );
1431
1432                 if ( mi->mi_quarantine_f ) {
1433                         (void)mi->mi_quarantine_f( mi, candidate,
1434                                 mi->mi_quarantine_p );
1435                 }
1436
1437                 ri->ri_count = 0;
1438                 ri->ri_idx = 0;
1439                 mt->mt_isquarantined = LDAP_BACK_FQ_NO;
1440         }
1441
1442 done:;
1443         ldap_pvt_thread_mutex_unlock( &mt->mt_quarantine_mutex );
1444 }
1445