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