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