]> git.sur5r.net Git - openldap/blob - servers/slapd/back-meta/conn.c
don't risk leaving around client library error codes; try to return additional inform...
[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-2010 The OpenLDAP Foundation.
5  * Portions Copyright 2001-2003 Pierangelo Masarati.
6  * Portions Copyright 1999-2003 Howard Chu.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted only as authorized by the OpenLDAP
11  * Public License.
12  *
13  * A copy of this license is available in the file LICENSE in the
14  * top-level directory of the distribution or, alternatively, at
15  * <http://www.OpenLDAP.org/license.html>.
16  */
17 /* ACKNOWLEDGEMENTS:
18  * This work was initially developed by the Howard Chu for inclusion
19  * in OpenLDAP Software and subsequently enhanced by Pierangelo
20  * Masarati.
21  */
22
23 #include "portable.h"
24
25 #include <stdio.h>
26
27 #include <ac/errno.h>
28 #include <ac/socket.h>
29 #include <ac/string.h>
30
31
32 #define AVL_INTERNAL
33 #include "slap.h"
34 #include "../back-ldap/back-ldap.h"
35 #include "back-meta.h"
36
37 /*
38  * meta_back_conndn_cmp
39  *
40  * compares two struct metaconn based on the value of the conn pointer
41  * and of the local DN; used by avl stuff
42  */
43 int
44 meta_back_conndn_cmp(
45         const void *c1,
46         const void *c2 )
47 {
48         metaconn_t      *mc1 = ( metaconn_t * )c1;
49         metaconn_t      *mc2 = ( metaconn_t * )c2;
50         int             rc;
51         
52         /* If local DNs don't match, it is definitely not a match */
53         /* For shared sessions, conn is NULL. Only explicitly
54          * bound sessions will have non-NULL conn.
55          */
56         rc = SLAP_PTRCMP( mc1->mc_conn, mc2->mc_conn );
57         if ( rc == 0 ) {
58                 rc = ber_bvcmp( &mc1->mc_local_ndn, &mc2->mc_local_ndn );
59         }
60
61         return rc;
62 }
63
64 /*
65  * meta_back_conndnmc_cmp
66  *
67  * compares two struct metaconn based on the value of the conn pointer,
68  * the local DN and the struct pointer; used by avl stuff
69  */
70 static int
71 meta_back_conndnmc_cmp(
72         const void *c1,
73         const void *c2 )
74 {
75         metaconn_t      *mc1 = ( metaconn_t * )c1;
76         metaconn_t      *mc2 = ( metaconn_t * )c2;
77         int             rc;
78         
79         /* If local DNs don't match, it is definitely not a match */
80         /* For shared sessions, conn is NULL. Only explicitly
81          * bound sessions will have non-NULL conn.
82          */
83         rc = SLAP_PTRCMP( mc1->mc_conn, mc2->mc_conn );
84         if ( rc == 0 ) {
85                 rc = ber_bvcmp( &mc1->mc_local_ndn, &mc2->mc_local_ndn );
86                 if ( rc == 0 ) {
87                         rc = SLAP_PTRCMP( mc1, mc2 );
88                 }
89         }
90
91         return rc;
92 }
93
94 /*
95  * meta_back_conn_cmp
96  *
97  * compares two struct metaconn based on the value of the conn pointer;
98  * used by avl stuff
99  */
100 int
101 meta_back_conn_cmp(
102         const void *c1,
103         const void *c2 )
104 {
105         metaconn_t      *mc1 = ( metaconn_t * )c1;
106         metaconn_t      *mc2 = ( metaconn_t * )c2;
107         
108         /* For shared sessions, conn is NULL. Only explicitly
109          * bound sessions will have non-NULL conn.
110          */
111         return SLAP_PTRCMP( mc1->mc_conn, mc2->mc_conn );
112 }
113
114 /*
115  * meta_back_conndn_dup
116  *
117  * returns -1 in case a duplicate struct metaconn has been inserted;
118  * used by avl stuff
119  */
120 int
121 meta_back_conndn_dup(
122         void *c1,
123         void *c2 )
124 {
125         metaconn_t      *mc1 = ( metaconn_t * )c1;
126         metaconn_t      *mc2 = ( metaconn_t * )c2;
127
128         /* Cannot have more than one shared session with same DN */
129         if ( mc1->mc_conn == mc2->mc_conn &&
130                 dn_match( &mc1->mc_local_ndn, &mc2->mc_local_ndn ) )
131         {
132                 return -1;
133         }
134                 
135         return 0;
136 }
137
138 /*
139  * Debug stuff (got it from libavl)
140  */
141 #if META_BACK_PRINT_CONNTREE > 0
142 static void
143 meta_back_print( metaconn_t *mc, char *avlstr )
144 {
145         int     i;
146
147         fputs( "targets=[", stderr );
148         for ( i = 0; i < mc->mc_info->mi_ntargets; i++ ) {
149                 fputc( mc->mc_conns[ i ].msc_ld ? '*' : 'o', stderr);
150         }
151         fputc( ']', stderr );
152
153         fprintf( stderr, " mc=%p local=\"%s\" conn=%p refcnt=%d%s %s\n",
154                 (void *)mc,
155                 mc->mc_local_ndn.bv_val ? mc->mc_local_ndn.bv_val : "",
156                 (void *)mc->mc_conn,
157                 mc->mc_refcnt,
158                 LDAP_BACK_CONN_TAINTED( mc ) ? " tainted" : "",
159                 avlstr );
160 }
161
162 static void
163 meta_back_ravl_print( Avlnode *root, int depth )
164 {
165         int             i;
166
167         if ( root == 0 ) {
168                 return;
169         }
170         
171         meta_back_ravl_print( root->avl_right, depth + 1 );
172         
173         for ( i = 0; i < depth; i++ ) {
174                 fprintf( stderr, "-" );
175         }
176         fputc( ' ', stderr );
177
178         meta_back_print( (metaconn_t *)root->avl_data,
179                 avl_bf2str( root->avl_bf ) );
180
181         meta_back_ravl_print( root->avl_left, depth + 1 );
182 }
183
184 /* NOTE: duplicate from back-ldap/bind.c */
185 static char* priv2str[] = {
186         "privileged",
187         "privileged/TLS",
188         "anonymous",
189         "anonymous/TLS",
190         "bind",
191         "bind/TLS",
192         NULL
193 };
194
195 void
196 meta_back_print_conntree( metainfo_t *mi, char *msg )
197 {
198         int     c;
199
200         fprintf( stderr, "========> %s\n", msg );
201         
202         for ( c = LDAP_BACK_PCONN_FIRST; c < LDAP_BACK_PCONN_LAST; c++ ) {
203                 int             i = 0;
204                 metaconn_t      *mc;
205
206                 fprintf( stderr, "  %s[%d]\n", priv2str[ c ], mi->mi_conn_priv[ c ].mic_num );
207
208                 LDAP_TAILQ_FOREACH( mc, &mi->mi_conn_priv[ c ].mic_priv, mc_q )
209                 {
210                         fprintf( stderr, "    [%d] ", i );
211                         meta_back_print( mc, "" );
212                         i++;
213                 }
214         }
215         
216         if ( mi->mi_conninfo.lai_tree == NULL ) {
217                 fprintf( stderr, "\t(empty)\n" );
218
219         } else {
220                 meta_back_ravl_print( mi->mi_conninfo.lai_tree, 0 );
221         }
222         
223         fprintf( stderr, "<======== %s\n", msg );
224 }
225 #endif /* META_BACK_PRINT_CONNTREE */
226 /*
227  * End of debug stuff
228  */
229
230 /*
231  * metaconn_alloc
232  * 
233  * Allocates a connection structure, making room for all the referenced targets
234  */
235 static metaconn_t *
236 metaconn_alloc(
237         Operation               *op )
238 {
239         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
240         metaconn_t      *mc;
241         int             ntargets = mi->mi_ntargets;
242
243         assert( ntargets > 0 );
244
245         /* malloc all in one */
246         mc = ( metaconn_t * )ch_calloc( 1, sizeof( metaconn_t )
247                 + sizeof( metasingleconn_t ) * ( ntargets - 1 ) );
248         if ( mc == NULL ) {
249                 return NULL;
250         }
251
252         mc->mc_info = mi;
253
254         mc->mc_authz_target = META_BOUND_NONE;
255         mc->mc_refcnt = 1;
256
257         return mc;
258 }
259
260 /*
261  * meta_back_init_one_conn
262  * 
263  * Initializes one connection
264  */
265 int
266 meta_back_init_one_conn(
267         Operation               *op,
268         SlapReply               *rs,
269         metaconn_t              *mc,
270         int                     candidate,
271         int                     ispriv,
272         ldap_back_send_t        sendok,
273         int                     dolock )
274 {
275         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
276         metatarget_t            *mt = mi->mi_targets[ candidate ];
277         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
278         int                     version;
279         dncookie                dc;
280         int                     isauthz = ( candidate == mc->mc_authz_target );
281         int                     do_return = 0;
282 #ifdef HAVE_TLS
283         int                     is_ldaps = 0;
284 #endif /* HAVE_TLS */
285
286         /* if the server is quarantined, and
287          * - the current interval did not expire yet, or
288          * - no more retries should occur,
289          * don't return the connection */
290         if ( mt->mt_isquarantined ) {
291                 slap_retry_info_t       *ri = &mt->mt_quarantine;
292                 int                     dont_retry = 0;
293
294                 if ( mt->mt_quarantine.ri_interval ) {
295                         ldap_pvt_thread_mutex_lock( &mt->mt_quarantine_mutex );
296                         dont_retry = ( mt->mt_isquarantined > LDAP_BACK_FQ_NO );
297                         if ( dont_retry ) {
298                                 dont_retry = ( ri->ri_num[ ri->ri_idx ] == SLAP_RETRYNUM_TAIL
299                                         || slap_get_time() < ri->ri_last + ri->ri_interval[ ri->ri_idx ] );
300                                 if ( !dont_retry ) {
301                                         if ( LogTest( LDAP_DEBUG_ANY ) ) {
302                                                 char    buf[ SLAP_TEXT_BUFLEN ];
303
304                                                 snprintf( buf, sizeof( buf ),
305                                                         "meta_back_init_one_conn[%d]: quarantine "
306                                                         "retry block #%d try #%d",
307                                                         candidate, ri->ri_idx, ri->ri_count );
308                                                 Debug( LDAP_DEBUG_ANY, "%s %s.\n",
309                                                         op->o_log_prefix, buf, 0 );
310                                         }
311
312                                         mt->mt_isquarantined = LDAP_BACK_FQ_RETRYING;
313                                 }
314
315                         }
316                         ldap_pvt_thread_mutex_unlock( &mt->mt_quarantine_mutex );
317                 }
318
319                 if ( dont_retry ) {
320                         rs->sr_err = LDAP_UNAVAILABLE;
321                         if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
322                                 rs->sr_text = "Target is quarantined";
323                                 send_ldap_result( op, rs );
324                         }
325                         return rs->sr_err;
326                 }
327         }
328
329 retry_lock:;
330         if ( dolock ) {
331                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
332         }
333
334         /*
335          * Already init'ed
336          */
337         if ( LDAP_BACK_CONN_ISBOUND( msc )
338                 || LDAP_BACK_CONN_ISANON( msc ) )
339         {
340                 assert( msc->msc_ld != NULL );
341                 rs->sr_err = LDAP_SUCCESS;
342                 do_return = 1;
343
344         } else if ( META_BACK_CONN_CREATING( msc )
345                 || LDAP_BACK_CONN_BINDING( msc ) )
346         {
347                 if ( !LDAP_BACK_USE_TEMPORARIES( mi ) ) {
348                         if ( dolock ) {
349                                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
350                         }
351
352                         ldap_pvt_thread_yield();
353                         goto retry_lock;
354                 }
355
356                 /* sounds more appropriate */
357                 rs->sr_err = LDAP_BUSY;
358                 rs->sr_text = "No connections to target are available";
359                 do_return = 1;
360
361         } else if ( META_BACK_CONN_INITED( msc ) ) {
362                 assert( msc->msc_ld != NULL );
363                 rs->sr_err = LDAP_SUCCESS;
364                 do_return = 1;
365
366         } else {
367                 /*
368                  * creating...
369                  */
370                 META_BACK_CONN_CREATING_SET( msc );
371         }
372
373         if ( dolock ) {
374                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
375         }
376
377         if ( do_return ) {
378                 if ( rs->sr_err != LDAP_SUCCESS
379                         && op->o_conn
380                         && ( sendok & LDAP_BACK_SENDERR ) )
381                 {
382                         send_ldap_result( op, rs );
383                 }
384
385                 return rs->sr_err;
386         }
387
388         assert( msc->msc_ld == NULL );
389        
390         /*
391          * Attempts to initialize the connection to the target ds
392          */
393         ldap_pvt_thread_mutex_lock( &mt->mt_uri_mutex );
394         rs->sr_err = ldap_initialize( &msc->msc_ld, mt->mt_uri );
395 #ifdef HAVE_TLS
396         is_ldaps = ldap_is_ldaps_url( mt->mt_uri );
397 #endif /* HAVE_TLS */
398         ldap_pvt_thread_mutex_unlock( &mt->mt_uri_mutex );
399         if ( rs->sr_err != LDAP_SUCCESS ) {
400                 goto error_return;
401         }
402
403         /*
404          * Set LDAP version. This will always succeed: If the client
405          * bound with a particular version, then so can we.
406          */
407         if ( mt->mt_version != 0 ) {
408                 version = mt->mt_version;
409
410         } else if ( op->o_conn->c_protocol != 0 ) {
411                 version = op->o_conn->c_protocol;
412
413         } else {
414                 version = LDAP_VERSION3;
415         }
416         ldap_set_option( msc->msc_ld, LDAP_OPT_PROTOCOL_VERSION, &version );
417         ldap_set_urllist_proc( msc->msc_ld, mt->mt_urllist_f, mt->mt_urllist_p );
418
419         /* automatically chase referrals ("chase-referrals [{yes|no}]" statement) */
420         ldap_set_option( msc->msc_ld, LDAP_OPT_REFERRALS,
421                 META_BACK_TGT_CHASE_REFERRALS( mt ) ? LDAP_OPT_ON : LDAP_OPT_OFF );
422
423 #ifdef HAVE_TLS
424         /* start TLS ("tls [try-]{start|propagate}" statement) */
425         if ( ( META_BACK_TGT_USE_TLS( mt )
426                 || ( op->o_conn->c_is_tls
427                         && META_BACK_TGT_PROPAGATE_TLS( mt ) ) )
428                 && !is_ldaps )
429         {
430 #ifdef SLAP_STARTTLS_ASYNCHRONOUS
431                 /*
432                  * use asynchronous StartTLS; in case, chase referral
433                  * FIXME: OpenLDAP does not return referral on StartTLS yet
434                  */
435                 int             msgid;
436
437                 rs->sr_err = ldap_start_tls( msc->msc_ld, NULL, NULL, &msgid );
438                 if ( rs->sr_err == LDAP_SUCCESS ) {
439                         LDAPMessage     *res = NULL;
440                         int             rc, nretries = mt->mt_nretries;
441                         struct timeval  tv;
442
443                         LDAP_BACK_TV_SET( &tv );
444
445 retry:;
446                         rc = ldap_result( msc->msc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
447                         switch ( rc ) {
448                         case -1:
449                                 rs->sr_err = LDAP_OTHER;
450                                 break;
451
452                         case 0:
453                                 if ( nretries != 0 ) {
454                                         if ( nretries > 0 ) {
455                                                 nretries--;
456                                         }
457                                         LDAP_BACK_TV_SET( &tv );
458                                         goto retry;
459                                 }
460                                 rs->sr_err = LDAP_OTHER;
461                                 break;
462
463                         default:
464                                 /* only touch when activity actually took place... */
465                                 if ( mi->mi_idle_timeout != 0 && msc->msc_time < op->o_time ) {
466                                         msc->msc_time = op->o_time;
467                                 }
468                                 break;
469                         }
470
471                         if ( rc == LDAP_RES_EXTENDED ) {
472                                 struct berval   *data = NULL;
473
474                                 /* NOTE: right now, data is unused, so don't get it */
475                                 rs->sr_err = ldap_parse_extended_result( msc->msc_ld,
476                                         res, NULL, NULL /* &data */ , 0 );
477                                 if ( rs->sr_err == LDAP_SUCCESS ) {
478                                         int             err;
479
480                                         /* FIXME: matched? referrals? response controls? */
481                                         rs->sr_err = ldap_parse_result( msc->msc_ld,
482                                                 res, &err, NULL, NULL, NULL, NULL, 1 );
483                                         res = NULL;
484
485                                         if ( rs->sr_err == LDAP_SUCCESS ) {
486                                                 rs->sr_err = err;
487                                         }
488                                         rs->sr_err = slap_map_api2result( rs );
489                                         
490                                         /* FIXME: in case a referral 
491                                          * is returned, should we try
492                                          * using it instead of the 
493                                          * configured URI? */
494                                         if ( rs->sr_err == LDAP_SUCCESS ) {
495                                                 ldap_install_tls( msc->msc_ld );
496
497                                         } else if ( rs->sr_err == LDAP_REFERRAL ) {
498                                                 /* FIXME: LDAP_OPERATIONS_ERROR? */
499                                                 rs->sr_err = LDAP_OTHER;
500                                                 rs->sr_text = "Unwilling to chase referral "
501                                                         "returned by Start TLS exop";
502                                         }
503
504                                         if ( data ) {
505                                                 ber_bvfree( data );
506                                         }
507                                 }
508
509                         } else {
510                                 rs->sr_err = LDAP_OTHER;
511                         }
512
513                         if ( res != NULL ) {
514                                 ldap_msgfree( res );
515                         }
516                 }
517 #else /* ! SLAP_STARTTLS_ASYNCHRONOUS */
518                 /*
519                  * use synchronous StartTLS
520                  */
521                 rs->sr_err = ldap_start_tls_s( msc->msc_ld, NULL, NULL );
522 #endif /* ! SLAP_STARTTLS_ASYNCHRONOUS */
523
524                 /* if StartTLS is requested, only attempt it if the URL
525                  * is not "ldaps://"; this may occur not only in case
526                  * of misconfiguration, but also when used in the chain 
527                  * overlay, where the "uri" can be parsed out of a referral */
528                 if ( rs->sr_err == LDAP_SERVER_DOWN
529                         || ( rs->sr_err != LDAP_SUCCESS
530                                 && META_BACK_TGT_TLS_CRITICAL( mt ) ) )
531                 {
532
533 #ifdef DEBUG_205
534                         Debug( LDAP_DEBUG_ANY,
535                                 "### %s meta_back_init_one_conn(TLS) "
536                                 "ldap_unbind_ext[%d] ld=%p\n",
537                                 op->o_log_prefix, candidate,
538                                 (void *)msc->msc_ld );
539 #endif /* DEBUG_205 */
540
541                         /* need to trash a failed Start TLS */
542                         meta_clear_one_candidate( op, mc, candidate );
543                         goto error_return;
544                 }
545         }
546 #endif /* HAVE_TLS */
547
548         /*
549          * Set the network timeout if set
550          */
551         if ( mt->mt_network_timeout != 0 ) {
552                 struct timeval  network_timeout;
553
554                 network_timeout.tv_usec = 0;
555                 network_timeout.tv_sec = mt->mt_network_timeout;
556
557                 ldap_set_option( msc->msc_ld, LDAP_OPT_NETWORK_TIMEOUT,
558                                 (void *)&network_timeout );
559         }
560
561         /*
562          * If the connection DN is not null, an attempt to rewrite it is made
563          */
564
565         if ( ispriv ) {
566                 if ( !BER_BVISNULL( &mt->mt_idassert_authcDN ) ) {
567                         ber_bvreplace( &msc->msc_bound_ndn, &mt->mt_idassert_authcDN );
568                         if ( !BER_BVISNULL( &mt->mt_idassert_passwd ) ) {
569                                 if ( !BER_BVISNULL( &msc->msc_cred ) ) {
570                                         memset( msc->msc_cred.bv_val, 0,
571                                                 msc->msc_cred.bv_len );
572                                 }
573                                 ber_bvreplace( &msc->msc_cred, &mt->mt_idassert_passwd );
574                         }
575
576                 } else {
577                         ber_bvreplace( &msc->msc_bound_ndn, &slap_empty_bv );
578                 }
579
580         } else {
581                 if ( !BER_BVISNULL( &msc->msc_cred ) ) {
582                         memset( msc->msc_cred.bv_val, 0, msc->msc_cred.bv_len );
583                         ber_memfree_x( msc->msc_cred.bv_val, NULL );
584                         BER_BVZERO( &msc->msc_cred );
585                 }
586                 if ( !BER_BVISNULL( &msc->msc_bound_ndn ) ) {
587                         ber_memfree_x( msc->msc_bound_ndn.bv_val, NULL );
588                         BER_BVZERO( &msc->msc_bound_ndn );
589                 }
590                 if ( !BER_BVISEMPTY( &op->o_ndn )
591                         && SLAP_IS_AUTHZ_BACKEND( op )
592                         && isauthz )
593                 {
594                         dc.target = mt;
595                         dc.conn = op->o_conn;
596                         dc.rs = rs;
597                         dc.ctx = "bindDN";
598                 
599                         /*
600                          * Rewrite the bind dn if needed
601                          */
602                         if ( ldap_back_dn_massage( &dc, &op->o_conn->c_dn,
603                                                 &msc->msc_bound_ndn ) )
604                         {
605
606 #ifdef DEBUG_205
607                                 Debug( LDAP_DEBUG_ANY,
608                                         "### %s meta_back_init_one_conn(rewrite) "
609                                         "ldap_unbind_ext[%d] ld=%p\n",
610                                         op->o_log_prefix, candidate,
611                                         (void *)msc->msc_ld );
612 #endif /* DEBUG_205 */
613
614                                 /* need to trash a connection not fully established */
615                                 meta_clear_one_candidate( op, mc, candidate );
616                                 goto error_return;
617                         }
618                         
619                         /* copy the DN if needed */
620                         if ( msc->msc_bound_ndn.bv_val == op->o_conn->c_dn.bv_val ) {
621                                 ber_dupbv( &msc->msc_bound_ndn, &op->o_conn->c_dn );
622                         }
623
624                         assert( !BER_BVISNULL( &msc->msc_bound_ndn ) );
625
626                 } else {
627                         ber_dupbv( &msc->msc_bound_ndn, (struct berval *)&slap_empty_bv );
628                 }
629         }
630
631         assert( !BER_BVISNULL( &msc->msc_bound_ndn ) );
632
633 error_return:;
634         if ( dolock ) {
635                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
636         }
637         META_BACK_CONN_CREATING_CLEAR( msc );
638         if ( rs->sr_err == LDAP_SUCCESS ) {
639                 /*
640                  * Sets a cookie for the rewrite session
641                  */
642                 ( void )rewrite_session_init( mt->mt_rwmap.rwm_rw, op->o_conn );
643                 META_BACK_CONN_INITED_SET( msc );
644         }
645         if ( dolock ) {
646                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
647         }
648
649         if ( rs->sr_err != LDAP_SUCCESS ) {
650                 rs->sr_err = slap_map_api2result( rs );
651                 if ( sendok & LDAP_BACK_SENDERR ) {
652                         send_ldap_result( op, rs );
653                 }
654         }
655
656         return rs->sr_err;
657 }
658
659 /*
660  * meta_back_retry
661  * 
662  * Retries one connection
663  */
664 int
665 meta_back_retry(
666         Operation               *op,
667         SlapReply               *rs,
668         metaconn_t              **mcp,
669         int                     candidate,
670         ldap_back_send_t        sendok )
671 {
672         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
673         metatarget_t            *mt = mi->mi_targets[ candidate ];
674         metaconn_t              *mc = *mcp;
675         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
676         int                     rc = LDAP_UNAVAILABLE,
677                                 binding,
678                                 quarantine = 1;
679
680         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
681
682         assert( !META_BACK_CONN_CREATING( msc ) );
683         binding = LDAP_BACK_CONN_BINDING( msc );
684         LDAP_BACK_CONN_BINDING_CLEAR( msc );
685
686         assert( mc->mc_refcnt > 0 );
687         if ( mc->mc_refcnt == 1 ) {
688                 if ( LogTest( LDAP_DEBUG_ANY ) ) {
689                         char    buf[ SLAP_TEXT_BUFLEN ];
690
691                         /* this lock is required; however,
692                          * it's invoked only when logging is on */
693                         ldap_pvt_thread_mutex_lock( &mt->mt_uri_mutex );
694                         snprintf( buf, sizeof( buf ),
695                                 "retrying URI=\"%s\" DN=\"%s\"",
696                                 mt->mt_uri,
697                                 BER_BVISNULL( &msc->msc_bound_ndn ) ?
698                                         "" : msc->msc_bound_ndn.bv_val );
699                         ldap_pvt_thread_mutex_unlock( &mt->mt_uri_mutex );
700
701                         Debug( LDAP_DEBUG_ANY,
702                                 "%s meta_back_retry[%d]: %s.\n",
703                                 op->o_log_prefix, candidate, buf );
704                 }
705
706                 meta_clear_one_candidate( op, mc, candidate );
707                 LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
708
709                 ( void )rewrite_session_delete( mt->mt_rwmap.rwm_rw, op->o_conn );
710
711                 /* mc here must be the regular mc, reset and ready for init */
712                 rc = meta_back_init_one_conn( op, rs, mc, candidate,
713                         LDAP_BACK_CONN_ISPRIV( mc ), sendok, 0 );
714
715                 /* restore the "binding" flag, in case */
716                 if ( binding ) {
717                         LDAP_BACK_CONN_BINDING_SET( msc );
718                 }
719
720                 if ( rc == LDAP_SUCCESS ) {
721                         quarantine = 0;
722                         rc = meta_back_single_dobind( op, rs, mcp, candidate,
723                                 sendok, mt->mt_nretries, 0 );
724
725                         Debug( LDAP_DEBUG_ANY,
726                                 "%s meta_back_retry[%d]: "
727                                 "meta_back_single_dobind=%d\n",
728                                 op->o_log_prefix, candidate, rc );
729                         if ( rc == LDAP_SUCCESS ) {
730                                 if ( !BER_BVISNULL( &msc->msc_bound_ndn ) &&
731                                         !BER_BVISEMPTY( &msc->msc_bound_ndn ) )
732                                 {
733                                         LDAP_BACK_CONN_ISBOUND_SET( msc );
734
735                                 } else {
736                                         LDAP_BACK_CONN_ISANON_SET( msc );
737                                 }
738
739                                 /* when bound, dispose of the "binding" flag */
740                                 if ( binding ) {
741                                         LDAP_BACK_CONN_BINDING_CLEAR( msc );
742                                 }
743                         }
744                 }
745
746                 /* don't send twice */
747                 sendok &= ~LDAP_BACK_SENDERR;
748         }
749
750         if ( rc != LDAP_SUCCESS ) {
751                 SlapReply               *candidates = meta_back_candidates_get( op );
752
753                 candidates[ candidate ].sr_err = rc;
754
755                 if ( *mcp != NULL ) {
756                         if ( mc->mc_refcnt == 1 ) {
757                                 if ( binding ) {
758                                         LDAP_BACK_CONN_BINDING_CLEAR( msc );
759                                 }
760                                 (void)meta_clear_one_candidate( op, mc, candidate );
761                         }
762
763                         LDAP_BACK_CONN_TAINTED_SET( mc );
764                         /* only release if mandatory; otherwise
765                          * let the caller do what's best before
766                          * releasing */
767                         if ( META_BACK_ONERR_STOP( mi ) ) {
768                                 meta_back_release_conn_lock( mi, mc, 0 );
769                                 *mcp = NULL;
770
771                         } else {
772 #if META_BACK_PRINT_CONNTREE > 0
773                                 meta_back_print_conntree( mi, ">>> meta_back_retry" );
774 #endif /* META_BACK_PRINT_CONNTREE */
775
776                                 /* FIXME: could be done better, reworking meta_back_release_conn_lock() */
777                                 if ( LDAP_BACK_PCONN_ISPRIV( mc ) ) {
778                                         if ( mc->mc_q.tqe_prev != NULL ) {
779                                                 assert( LDAP_BACK_CONN_CACHED( mc ) );
780                                                 assert( mi->mi_conn_priv[ LDAP_BACK_CONN2PRIV( mc ) ].mic_num > 0 );
781                                                 LDAP_TAILQ_REMOVE( &mi->mi_conn_priv[ LDAP_BACK_CONN2PRIV( mc ) ].mic_priv,
782                                                         mc, mc_q );
783                                                 mi->mi_conn_priv[ LDAP_BACK_CONN2PRIV( mc ) ].mic_num--;
784                                                 LDAP_TAILQ_ENTRY_INIT( mc, mc_q );
785
786                                         } else {
787                                                 assert( !LDAP_BACK_CONN_CACHED( mc ) );
788                                         }
789
790                                 } else {
791                                         /* FIXME: check if in tree, for consistency? */
792                                         (void)avl_delete( &mi->mi_conninfo.lai_tree,
793                                                 ( caddr_t )mc, meta_back_conndnmc_cmp );
794                                 }
795                                 LDAP_BACK_CONN_CACHED_CLEAR( mc );
796
797 #if META_BACK_PRINT_CONNTREE > 0
798                                 meta_back_print_conntree( mi, "<<< meta_back_retry" );
799 #endif /* META_BACK_PRINT_CONNTREE */
800                         }
801                 }
802
803                 if ( sendok & LDAP_BACK_SENDERR ) {
804                         rs->sr_err = rc;
805                         rs->sr_text = "Unable to retry";
806                         send_ldap_result( op, rs );
807                 }
808         }
809
810         if ( quarantine && META_BACK_TGT_QUARANTINE( mt ) ) {
811                 meta_back_quarantine( op, rs, candidate );
812         }
813
814         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
815
816         return rc == LDAP_SUCCESS ? 1 : 0;
817 }
818
819 /*
820  * callback for unique candidate selection
821  */
822 static int
823 meta_back_conn_cb( Operation *op, SlapReply *rs )
824 {
825         assert( op->o_tag == LDAP_REQ_SEARCH );
826
827         switch ( rs->sr_type ) {
828         case REP_SEARCH:
829                 ((long *)op->o_callback->sc_private)[0] = (long)op->o_private;
830                 break;
831
832         case REP_SEARCHREF:
833         case REP_RESULT:
834                 break;
835
836         default:
837                 return rs->sr_err;
838         }
839
840         return 0;
841 }
842
843
844 static int
845 meta_back_get_candidate(
846         Operation       *op,
847         SlapReply       *rs,
848         struct berval   *ndn )
849 {
850         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
851         long            candidate;
852
853         /*
854          * tries to get a unique candidate
855          * (takes care of default target)
856          */
857         candidate = meta_back_select_unique_candidate( mi, ndn );
858
859         /*
860          * if any is found, inits the connection
861          */
862         if ( candidate == META_TARGET_NONE ) {
863                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
864                 rs->sr_text = "No suitable candidate target found";
865
866         } else if ( candidate == META_TARGET_MULTIPLE ) {
867                 Operation       op2 = *op;
868                 SlapReply       rs2 = { 0 };
869                 slap_callback   cb2 = { 0 };
870                 int             rc;
871
872                 /* try to get a unique match for the request ndn
873                  * among the multiple candidates available */
874                 op2.o_tag = LDAP_REQ_SEARCH;
875                 op2.o_req_dn = *ndn;
876                 op2.o_req_ndn = *ndn;
877                 op2.ors_scope = LDAP_SCOPE_BASE;
878                 op2.ors_deref = LDAP_DEREF_NEVER;
879                 op2.ors_attrs = slap_anlist_no_attrs;
880                 op2.ors_attrsonly = 0;
881                 op2.ors_limit = NULL;
882                 op2.ors_slimit = 1;
883                 op2.ors_tlimit = SLAP_NO_LIMIT;
884
885                 op2.ors_filter = (Filter *)slap_filter_objectClass_pres;
886                 op2.ors_filterstr = *slap_filterstr_objectClass_pres;
887
888                 op2.o_callback = &cb2;
889                 cb2.sc_response = meta_back_conn_cb;
890                 cb2.sc_private = (void *)&candidate;
891
892                 rc = op->o_bd->be_search( &op2, &rs2 );
893
894                 switch ( rs2.sr_err ) {
895                 case LDAP_SUCCESS:
896                 default:
897                         rs->sr_err = rs2.sr_err;
898                         break;
899
900                 case LDAP_SIZELIMIT_EXCEEDED:
901                         /* if multiple candidates can serve the operation,
902                          * and a default target is defined, and it is
903                          * a candidate, try using it (FIXME: YMMV) */
904                         if ( mi->mi_defaulttarget != META_DEFAULT_TARGET_NONE
905                                 && meta_back_is_candidate( mi->mi_targets[ mi->mi_defaulttarget ],
906                                                 ndn, op->o_tag == LDAP_REQ_SEARCH ? op->ors_scope : LDAP_SCOPE_BASE ) )
907                         {
908                                 candidate = mi->mi_defaulttarget;
909                                 rs->sr_err = LDAP_SUCCESS;
910                                 rs->sr_text = NULL;
911
912                         } else {
913                                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
914                                 rs->sr_text = "Unable to select unique candidate target";
915                         }
916                         break;
917                 }
918
919         } else {
920                 rs->sr_err = LDAP_SUCCESS;
921         }
922
923         return candidate;
924 }
925
926 static void     *meta_back_candidates_dummy;
927
928 static void
929 meta_back_candidates_keyfree(
930         void            *key,
931         void            *data )
932 {
933         metacandidates_t        *mc = (metacandidates_t *)data;
934
935         ber_memfree_x( mc->mc_candidates, NULL );
936         ber_memfree_x( data, NULL );
937 }
938
939 SlapReply *
940 meta_back_candidates_get( Operation *op )
941 {
942         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
943         metacandidates_t        *mc;
944
945         if ( op->o_threadctx ) {
946                 void            *data = NULL;
947
948                 ldap_pvt_thread_pool_getkey( op->o_threadctx,
949                                 &meta_back_candidates_dummy, &data, NULL );
950                 mc = (metacandidates_t *)data;
951
952         } else {
953                 mc = mi->mi_candidates;
954         }
955
956         if ( mc == NULL ) {
957                 mc = ch_calloc( sizeof( metacandidates_t ), 1 );
958                 mc->mc_ntargets = mi->mi_ntargets;
959                 mc->mc_candidates = ch_calloc( sizeof( SlapReply ), mc->mc_ntargets );
960                 if ( op->o_threadctx ) {
961                         void            *data = NULL;
962
963                         data = (void *)mc;
964                         ldap_pvt_thread_pool_setkey( op->o_threadctx,
965                                         &meta_back_candidates_dummy, data,
966                                         meta_back_candidates_keyfree,
967                                         NULL, NULL );
968
969                 } else {
970                         mi->mi_candidates = mc;
971                 }
972
973         } else if ( mc->mc_ntargets < mi->mi_ntargets ) {
974                 /* NOTE: in the future, may want to allow back-config
975                  * to add/remove targets from back-meta... */
976                 mc->mc_candidates = ch_realloc( mc->mc_candidates,
977                                 sizeof( SlapReply ) * mi->mi_ntargets );
978                 memset( &mc->mc_candidates[ mc->mc_ntargets ], 0,
979                         sizeof( SlapReply ) * ( mi->mi_ntargets - mc->mc_ntargets ) );
980                 mc->mc_ntargets = mi->mi_ntargets;
981         }
982
983         return mc->mc_candidates;
984 }
985
986 /*
987  * meta_back_getconn
988  * 
989  * Prepares the connection structure
990  * 
991  * RATIONALE:
992  *
993  * - determine what DN is being requested:
994  *
995  *      op      requires candidate      checks
996  *
997  *      add     unique                  parent of o_req_ndn
998  *      bind    unique^*[/all]          o_req_ndn [no check]
999  *      compare unique^+                o_req_ndn
1000  *      delete  unique                  o_req_ndn
1001  *      modify  unique                  o_req_ndn
1002  *      search  any                     o_req_ndn
1003  *      modrdn  unique[, unique]        o_req_ndn[, orr_nnewSup]
1004  *
1005  * - for ops that require the candidate to be unique, in case of multiple
1006  *   occurrences an internal search with sizeLimit=1 is performed
1007  *   if a unique candidate can actually be determined.  If none is found,
1008  *   the operation aborts; if multiple are found, the default target
1009  *   is used if defined and candidate; otherwise the operation aborts.
1010  *
1011  * *^note: actually, the bind operation is handled much like a search;
1012  *   i.e. the bind is broadcast to all candidate targets.
1013  *
1014  * +^note: actually, the compare operation is handled much like a search;
1015  *   i.e. the compare is broadcast to all candidate targets, while checking
1016  *   that exactly none (noSuchObject) or one (TRUE/FALSE/UNDEFINED) is
1017  *   returned.
1018  */
1019 metaconn_t *
1020 meta_back_getconn(
1021         Operation               *op,
1022         SlapReply               *rs,
1023         int                     *candidate,
1024         ldap_back_send_t        sendok )
1025 {
1026         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
1027         metaconn_t      *mc = NULL,
1028                         mc_curr = {{ 0 }};
1029         int             cached = META_TARGET_NONE,
1030                         i = META_TARGET_NONE,
1031                         err = LDAP_SUCCESS,
1032                         new_conn = 0,
1033                         ncandidates = 0;
1034
1035
1036         meta_op_type    op_type = META_OP_REQUIRE_SINGLE;
1037         enum            {
1038                 META_DNTYPE_ENTRY,
1039                 META_DNTYPE_PARENT,
1040                 META_DNTYPE_NEWPARENT
1041         }               dn_type = META_DNTYPE_ENTRY;
1042         struct berval   ndn = op->o_req_ndn,
1043                         pndn;
1044
1045         SlapReply       *candidates = meta_back_candidates_get( op );
1046
1047         /* Internal searches are privileged and shared. So is root. */
1048         if ( ( !BER_BVISEMPTY( &op->o_ndn ) && META_BACK_PROXYAUTHZ_ALWAYS( mi ) )
1049                 || ( BER_BVISEMPTY( &op->o_ndn ) && META_BACK_PROXYAUTHZ_ANON( mi ) )
1050                 || op->o_do_not_cache || be_isroot( op ) )
1051         {
1052                 LDAP_BACK_CONN_ISPRIV_SET( &mc_curr );
1053                 mc_curr.mc_local_ndn = op->o_bd->be_rootndn;
1054                 LDAP_BACK_PCONN_ROOTDN_SET( &mc_curr, op );
1055
1056         } else if ( BER_BVISEMPTY( &op->o_ndn ) && META_BACK_PROXYAUTHZ_NOANON( mi ) )
1057         {
1058                 LDAP_BACK_CONN_ISANON_SET( &mc_curr );
1059                 BER_BVSTR( &mc_curr.mc_local_ndn, "" );
1060                 LDAP_BACK_PCONN_ANON_SET( &mc_curr, op );
1061
1062         } else {
1063                 mc_curr.mc_local_ndn = op->o_ndn;
1064
1065                 /* Explicit binds must not be shared */
1066                 if ( !BER_BVISEMPTY( &op->o_ndn )
1067                         || op->o_tag == LDAP_REQ_BIND
1068                         || SLAP_IS_AUTHZ_BACKEND( op ) )
1069                 {
1070                         mc_curr.mc_conn = op->o_conn;
1071         
1072                 } else {
1073                         LDAP_BACK_CONN_ISANON_SET( &mc_curr );
1074                         LDAP_BACK_PCONN_ANON_SET( &mc_curr, op );
1075                 }
1076         }
1077
1078         /* Explicit Bind requests always get their own conn */
1079         if ( sendok & LDAP_BACK_BINDING ) {
1080                 mc_curr.mc_conn = op->o_conn;
1081
1082         } else {
1083                 /* Searches for a metaconn in the avl tree */
1084 retry_lock:;
1085                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
1086                 if ( LDAP_BACK_PCONN_ISPRIV( &mc_curr ) ) {
1087                         /* lookup a conn that's not binding */
1088                         LDAP_TAILQ_FOREACH( mc,
1089                                 &mi->mi_conn_priv[ LDAP_BACK_CONN2PRIV( &mc_curr ) ].mic_priv,
1090                                 mc_q )
1091                         {
1092                                 if ( !LDAP_BACK_CONN_BINDING( mc ) && mc->mc_refcnt == 0 ) {
1093                                         break;
1094                                 }
1095                         }
1096
1097                         if ( mc != NULL ) {
1098                                 if ( mc != LDAP_TAILQ_LAST( &mi->mi_conn_priv[ LDAP_BACK_CONN2PRIV( mc ) ].mic_priv,
1099                                         metaconn_t, mc_q ) )
1100                                 {
1101                                         LDAP_TAILQ_REMOVE( &mi->mi_conn_priv[ LDAP_BACK_CONN2PRIV( mc ) ].mic_priv,
1102                                                 mc, mc_q );
1103                                         LDAP_TAILQ_ENTRY_INIT( mc, mc_q );
1104                                         LDAP_TAILQ_INSERT_TAIL( &mi->mi_conn_priv[ LDAP_BACK_CONN2PRIV( mc ) ].mic_priv,
1105                                                 mc, mc_q );
1106                                 }
1107
1108                         } else if ( !LDAP_BACK_USE_TEMPORARIES( mi )
1109                                 && mi->mi_conn_priv[ LDAP_BACK_CONN2PRIV( &mc_curr ) ].mic_num == mi->mi_conn_priv_max )
1110                         {
1111                                 mc = LDAP_TAILQ_FIRST( &mi->mi_conn_priv[ LDAP_BACK_CONN2PRIV( &mc_curr ) ].mic_priv );
1112                         }
1113                         
1114
1115                 } else {
1116                         mc = (metaconn_t *)avl_find( mi->mi_conninfo.lai_tree, 
1117                                 (caddr_t)&mc_curr, meta_back_conndn_cmp );
1118                 }
1119
1120                 if ( mc ) {
1121                         /* catch taint errors */
1122                         assert( !LDAP_BACK_CONN_TAINTED( mc ) );
1123
1124                         /* Don't reuse connections while they're still binding
1125                          * NOTE: only makes sense for binds */
1126                         if ( LDAP_BACK_CONN_BINDING( mc ) ) {
1127                                 if ( !LDAP_BACK_USE_TEMPORARIES( mi ) ) {
1128                                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1129
1130                                         ldap_pvt_thread_yield();
1131                                         goto retry_lock;
1132                                 }
1133
1134                                 /* release conn, and create a temporary */
1135                                 mc = NULL;
1136
1137                         } else {
1138                                 if ( ( mi->mi_conn_ttl != 0 && op->o_time > mc->mc_create_time + mi->mi_conn_ttl )
1139                                         || ( mi->mi_idle_timeout != 0 && op->o_time > mc->mc_time + mi->mi_idle_timeout ) )
1140                                 {
1141 #if META_BACK_PRINT_CONNTREE > 0
1142                                         meta_back_print_conntree( mi,
1143                                                 ">>> meta_back_getconn(expired)" );
1144 #endif /* META_BACK_PRINT_CONNTREE */
1145
1146                                         /* don't let anyone else use this expired connection */
1147                                         if ( LDAP_BACK_PCONN_ISPRIV( mc ) ) {
1148                                                 if ( mc->mc_q.tqe_prev != NULL ) {
1149                                                         assert( LDAP_BACK_CONN_CACHED( mc ) );
1150                                                         assert( mi->mi_conn_priv[ LDAP_BACK_CONN2PRIV( mc ) ].mic_num > 0 );
1151                                                         LDAP_TAILQ_REMOVE( &mi->mi_conn_priv[ LDAP_BACK_CONN2PRIV( mc ) ].mic_priv,
1152                                                                 mc, mc_q );
1153                                                         mi->mi_conn_priv[ LDAP_BACK_CONN2PRIV( mc ) ].mic_num--;
1154                                                         LDAP_TAILQ_ENTRY_INIT( mc, mc_q );
1155
1156                                                 } else {
1157                                                         assert( !LDAP_BACK_CONN_CACHED( mc ) );
1158                                                 }
1159
1160                                         } else {
1161                                                 (void)avl_delete( &mi->mi_conninfo.lai_tree,
1162                                                         (caddr_t)mc, meta_back_conndnmc_cmp );
1163                                         }
1164
1165 #if META_BACK_PRINT_CONNTREE > 0
1166                                         meta_back_print_conntree( mi,
1167                                                 "<<< meta_back_getconn(expired)" );
1168 #endif /* META_BACK_PRINT_CONNTREE */
1169                                         LDAP_BACK_CONN_TAINTED_SET( mc );
1170                                         LDAP_BACK_CONN_CACHED_CLEAR( mc );
1171
1172                                         if ( LogTest( LDAP_DEBUG_TRACE ) ) {
1173                                                 char buf[STRLENOF("4294967295U") + 1] = { 0 };
1174                                                 mi->mi_ldap_extra->connid2str( &mc->mc_base, buf, sizeof(buf) );
1175
1176                                                 Debug( LDAP_DEBUG_TRACE,
1177                                                         "%s meta_back_getconn: mc=%p conn=%s expired (tainted).\n",
1178                                                         op->o_log_prefix, (void *)mc, buf );
1179                                         }
1180                                 }
1181
1182                                 mc->mc_refcnt++;
1183                         }
1184                 }
1185                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1186         }
1187
1188         switch ( op->o_tag ) {
1189         case LDAP_REQ_ADD:
1190                 /* if we go to selection, the entry must not exist,
1191                  * and we must be able to resolve the parent */
1192                 dn_type = META_DNTYPE_PARENT;
1193                 dnParent( &ndn, &pndn );
1194                 break;
1195
1196         case LDAP_REQ_MODRDN:
1197                 /* if nnewSuperior is not NULL, it must resolve
1198                  * to the same candidate as the req_ndn */
1199                 if ( op->orr_nnewSup ) {
1200                         dn_type = META_DNTYPE_NEWPARENT;
1201                 }
1202                 break;
1203
1204         case LDAP_REQ_BIND:
1205                 /* if bound as rootdn, the backend must bind to all targets
1206                  * with the administrative identity
1207                  * (unless pseoudoroot-bind-defer is TRUE) */
1208                 if ( op->orb_method == LDAP_AUTH_SIMPLE && be_isroot_pw( op ) ) {
1209                         op_type = META_OP_REQUIRE_ALL;
1210                 }
1211                 break;
1212
1213         case LDAP_REQ_COMPARE:
1214         case LDAP_REQ_DELETE:
1215         case LDAP_REQ_MODIFY:
1216                 /* just a unique candidate */
1217                 break;
1218
1219         case LDAP_REQ_SEARCH:
1220                 /* allow multiple candidates for the searchBase */
1221                 op_type = META_OP_ALLOW_MULTIPLE;
1222                 break;
1223
1224         default:
1225                 /* right now, just break (exop?) */
1226                 break;
1227         }
1228
1229         /*
1230          * require all connections ...
1231          */
1232         if ( op_type == META_OP_REQUIRE_ALL ) {
1233
1234                 /* Looks like we didn't get a bind. Open a new session... */
1235                 if ( mc == NULL ) {
1236                         assert( new_conn == 0 );
1237                         mc = metaconn_alloc( op );
1238                         mc->mc_conn = mc_curr.mc_conn;
1239                         ber_dupbv( &mc->mc_local_ndn, &mc_curr.mc_local_ndn );
1240                         new_conn = 1;
1241                         if ( sendok & LDAP_BACK_BINDING ) {
1242                                 LDAP_BACK_CONN_BINDING_SET( mc );
1243                         }
1244                         if ( LDAP_BACK_CONN_ISPRIV( &mc_curr ) ) {
1245                                 LDAP_BACK_CONN_ISPRIV_SET( mc );
1246
1247                         } else if ( LDAP_BACK_CONN_ISANON( &mc_curr ) ) {
1248                                 LDAP_BACK_CONN_ISANON_SET( mc );
1249                         }
1250
1251                 } else if ( 0 ) {
1252                         /* TODO: if any of the connections is binding,
1253                          * release mc and create a new one */
1254                 }
1255
1256                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
1257                         /*
1258                          * The target is activated; if needed, it is
1259                          * also init'd
1260                          */
1261                         candidates[ i ].sr_err = meta_back_init_one_conn( op,
1262                                 rs, mc, i, LDAP_BACK_CONN_ISPRIV( &mc_curr ),
1263                                 LDAP_BACK_DONTSEND, !new_conn );
1264                         if ( candidates[ i ].sr_err == LDAP_SUCCESS ) {
1265                                 if ( new_conn && ( sendok & LDAP_BACK_BINDING ) ) {
1266                                         LDAP_BACK_CONN_BINDING_SET( &mc->mc_conns[ i ] );
1267                                 }
1268                                 META_CANDIDATE_SET( &candidates[ i ] );
1269                                 ncandidates++;
1270         
1271                         } else {
1272                                 
1273                                 /*
1274                                  * FIXME: in case one target cannot
1275                                  * be init'd, should the other ones
1276                                  * be tried?
1277                                  */
1278                                 META_CANDIDATE_RESET( &candidates[ i ] );
1279                                 err = candidates[ i ].sr_err;
1280                                 continue;
1281                         }
1282                 }
1283
1284                 if ( ncandidates == 0 ) {
1285                         if ( new_conn ) {
1286                                 mc->mc_refcnt = 0;
1287                                 meta_back_conn_free( mc );
1288
1289                         } else {
1290                                 meta_back_release_conn( mi, mc );
1291                         }
1292
1293                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
1294                         rs->sr_text = "Unable to select valid candidates";
1295
1296                         if ( sendok & LDAP_BACK_SENDERR ) {
1297                                 if ( rs->sr_err == LDAP_NO_SUCH_OBJECT ) {
1298                                         rs->sr_matched = op->o_bd->be_suffix[ 0 ].bv_val;
1299                                 }
1300                                 send_ldap_result( op, rs );
1301                                 rs->sr_matched = NULL;
1302                         }
1303
1304                         return NULL;
1305                 }
1306
1307                 goto done;
1308         }
1309         
1310         /*
1311          * looks in cache, if any
1312          */
1313         if ( mi->mi_cache.ttl != META_DNCACHE_DISABLED ) {
1314                 cached = i = meta_dncache_get_target( &mi->mi_cache, &op->o_req_ndn );
1315         }
1316
1317         if ( op_type == META_OP_REQUIRE_SINGLE ) {
1318                 metatarget_t            *mt = NULL;
1319                 metasingleconn_t        *msc = NULL;
1320
1321                 int                     j;
1322
1323                 for ( j = 0; j < mi->mi_ntargets; j++ ) {
1324                         META_CANDIDATE_RESET( &candidates[ j ] );
1325                 }
1326
1327                 /*
1328                  * tries to get a unique candidate
1329                  * (takes care of default target)
1330                  */
1331                 if ( i == META_TARGET_NONE ) {
1332                         i = meta_back_get_candidate( op, rs, &ndn );
1333
1334                         if ( rs->sr_err == LDAP_NO_SUCH_OBJECT && dn_type == META_DNTYPE_PARENT ) {
1335                                 i = meta_back_get_candidate( op, rs, &pndn );
1336                         }
1337         
1338                         if ( i < 0 || rs->sr_err != LDAP_SUCCESS ) {
1339                                 if ( mc != NULL ) {
1340                                         meta_back_release_conn( mi, mc );
1341                                 }
1342
1343                                 if ( sendok & LDAP_BACK_SENDERR ) {
1344                                         if ( rs->sr_err == LDAP_NO_SUCH_OBJECT ) {
1345                                                 rs->sr_matched = op->o_bd->be_suffix[ 0 ].bv_val;
1346                                         }
1347                                         send_ldap_result( op, rs );
1348                                         rs->sr_matched = NULL;
1349                                 }
1350                         
1351                                 return NULL;
1352                         }
1353                 }
1354
1355                 if ( dn_type == META_DNTYPE_NEWPARENT && meta_back_get_candidate( op, rs, op->orr_nnewSup ) != i )
1356                 {
1357                         if ( mc != NULL ) {
1358                                 meta_back_release_conn( mi, mc );
1359                         }
1360
1361                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1362                         rs->sr_text = "Cross-target rename not supported";
1363                         if ( sendok & LDAP_BACK_SENDERR ) {
1364                                 send_ldap_result( op, rs );
1365                         }
1366
1367                         return NULL;
1368                 }
1369
1370                 Debug( LDAP_DEBUG_TRACE,
1371         "==>meta_back_getconn: got target=%d for ndn=\"%s\" from cache\n",
1372                                 i, op->o_req_ndn.bv_val, 0 );
1373
1374                 if ( mc == NULL ) {
1375                         /* Retries searching for a metaconn in the avl tree
1376                          * the reason is that the connection might have been
1377                          * created by meta_back_get_candidate() */
1378                         if ( !( sendok & LDAP_BACK_BINDING ) ) {
1379 retry_lock2:;
1380                                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
1381                                 mc = (metaconn_t *)avl_find( mi->mi_conninfo.lai_tree, 
1382                                         (caddr_t)&mc_curr, meta_back_conndn_cmp );
1383                                 if ( mc != NULL ) {
1384                                         /* catch taint errors */
1385                                         assert( !LDAP_BACK_CONN_TAINTED( mc ) );
1386
1387                                         /* Don't reuse connections while they're still binding */
1388                                         if ( META_BACK_CONN_CREATING( &mc->mc_conns[ i ] )
1389                                                 || LDAP_BACK_CONN_BINDING( &mc->mc_conns[ i ] ) )
1390                                         {
1391                                                 if ( !LDAP_BACK_USE_TEMPORARIES( mi ) ) {
1392                                                         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1393                                                         ldap_pvt_thread_yield();
1394                                                         goto retry_lock2;
1395                                                 }
1396
1397                                                 mc = NULL;
1398
1399                                         } else {
1400                                                 mc->mc_refcnt++;
1401                                         }
1402                                 }
1403                                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1404                         }
1405
1406                         /* Looks like we didn't get a bind. Open a new session... */
1407                         if ( mc == NULL ) {
1408                                 assert( new_conn == 0 );
1409                                 mc = metaconn_alloc( op );
1410                                 mc->mc_conn = mc_curr.mc_conn;
1411                                 ber_dupbv( &mc->mc_local_ndn, &mc_curr.mc_local_ndn );
1412                                 new_conn = 1;
1413                                 if ( sendok & LDAP_BACK_BINDING ) {
1414                                         LDAP_BACK_CONN_BINDING_SET( mc );
1415                                 }
1416                                 if ( LDAP_BACK_CONN_ISPRIV( &mc_curr ) ) {
1417                                         LDAP_BACK_CONN_ISPRIV_SET( mc );
1418
1419                                 } else if ( LDAP_BACK_CONN_ISANON( &mc_curr ) ) {
1420                                         LDAP_BACK_CONN_ISANON_SET( mc );
1421                                 }
1422                         }
1423                 }
1424
1425                 /*
1426                  * Clear all other candidates
1427                  */
1428                 ( void )meta_clear_unused_candidates( op, i );
1429
1430                 mt = mi->mi_targets[ i ];
1431                 msc = &mc->mc_conns[ i ];
1432
1433                 /*
1434                  * The target is activated; if needed, it is
1435                  * also init'd. In case of error, meta_back_init_one_conn
1436                  * sends the appropriate result.
1437                  */
1438                 err = meta_back_init_one_conn( op, rs, mc, i,
1439                         LDAP_BACK_CONN_ISPRIV( &mc_curr ), sendok, !new_conn );
1440                 if ( err != LDAP_SUCCESS ) {
1441                         /*
1442                          * FIXME: in case one target cannot
1443                          * be init'd, should the other ones
1444                          * be tried?
1445                          */
1446                         META_CANDIDATE_RESET( &candidates[ i ] );
1447                         if ( new_conn ) {
1448                                 mc->mc_refcnt = 0;
1449                                 meta_back_conn_free( mc );
1450
1451                         } else {
1452                                 meta_back_release_conn( mi, mc );
1453                         }
1454                         return NULL;
1455                 }
1456
1457                 if ( new_conn && ( sendok & LDAP_BACK_BINDING ) ) {
1458                         LDAP_BACK_CONN_BINDING_SET( &mc->mc_conns[ i ] );
1459                 }
1460
1461                 candidates[ i ].sr_err = LDAP_SUCCESS;
1462                 META_CANDIDATE_SET( &candidates[ i ] );
1463                 ncandidates++;
1464
1465                 if ( candidate ) {
1466                         *candidate = i;
1467                 }
1468
1469         /*
1470          * if no unique candidate ...
1471          */
1472         } else {
1473
1474                 /* Looks like we didn't get a bind. Open a new session... */
1475                 if ( mc == NULL ) {
1476                         assert( new_conn == 0 );
1477                         mc = metaconn_alloc( op );
1478                         mc->mc_conn = mc_curr.mc_conn;
1479                         ber_dupbv( &mc->mc_local_ndn, &mc_curr.mc_local_ndn );
1480                         new_conn = 1;
1481                         if ( LDAP_BACK_CONN_ISPRIV( &mc_curr ) ) {
1482                                 LDAP_BACK_CONN_ISPRIV_SET( mc );
1483
1484                         } else if ( LDAP_BACK_CONN_ISANON( &mc_curr ) ) {
1485                                 LDAP_BACK_CONN_ISANON_SET( mc );
1486                         }
1487                 }
1488
1489                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
1490                         metatarget_t            *mt = mi->mi_targets[ i ];
1491
1492                         META_CANDIDATE_RESET( &candidates[ i ] );
1493
1494                         if ( i == cached 
1495                                 || meta_back_is_candidate( mt, &op->o_req_ndn,
1496                                         LDAP_SCOPE_SUBTREE ) )
1497                         {
1498
1499                                 /*
1500                                  * The target is activated; if needed, it is
1501                                  * also init'd
1502                                  */
1503                                 int lerr = meta_back_init_one_conn( op, rs, mc, i,
1504                                         LDAP_BACK_CONN_ISPRIV( &mc_curr ),
1505                                         LDAP_BACK_DONTSEND, !new_conn );
1506                                 candidates[ i ].sr_err = lerr;
1507                                 if ( lerr == LDAP_SUCCESS ) {
1508                                         META_CANDIDATE_SET( &candidates[ i ] );
1509                                         ncandidates++;
1510
1511                                         Debug( LDAP_DEBUG_TRACE, "%s: meta_back_getconn[%d]\n",
1512                                                 op->o_log_prefix, i, 0 );
1513
1514                                 } else if ( lerr == LDAP_UNAVAILABLE && !META_BACK_ONERR_STOP( mi ) ) {
1515                                         META_CANDIDATE_SET( &candidates[ i ] );
1516
1517                                         Debug( LDAP_DEBUG_TRACE, "%s: meta_back_getconn[%d] %s\n",
1518                                                 op->o_log_prefix, i,
1519                                                 mt->mt_isquarantined != LDAP_BACK_FQ_NO ? "quarantined" : "unavailable" );
1520
1521                                 } else {
1522                                 
1523                                         /*
1524                                          * FIXME: in case one target cannot
1525                                          * be init'd, should the other ones
1526                                          * be tried?
1527                                          */
1528                                         if ( new_conn ) {
1529                                                 ( void )meta_clear_one_candidate( op, mc, i );
1530                                         }
1531                                         /* leave the target candidate, but record the error for later use */
1532                                         err = lerr;
1533
1534                                         if ( lerr == LDAP_UNAVAILABLE && mt->mt_isquarantined != LDAP_BACK_FQ_NO ) {
1535                                                 Debug( LDAP_DEBUG_TRACE, "%s: meta_back_getconn[%d] quarantined err=%d\n",
1536                                                         op->o_log_prefix, i, lerr );
1537
1538                                         } else {
1539                                                 Debug( LDAP_DEBUG_ANY, "%s: meta_back_getconn[%d] failed err=%d\n",
1540                                                         op->o_log_prefix, i, lerr );
1541                                         }
1542
1543                                         if ( META_BACK_ONERR_STOP( mi ) ) {
1544                                                 if ( sendok & LDAP_BACK_SENDERR ) {
1545                                                         send_ldap_result( op, rs );
1546                                                 }
1547                                                 if ( new_conn ) {
1548                                                         mc->mc_refcnt = 0;
1549                                                         meta_back_conn_free( mc );
1550
1551                                                 } else {
1552                                                         meta_back_release_conn( mi, mc );
1553                                                 }
1554
1555                                                 return NULL;
1556                                         }
1557
1558                                         continue;
1559                                 }
1560
1561                         } else {
1562                                 if ( new_conn ) {
1563                                         ( void )meta_clear_one_candidate( op, mc, i );
1564                                 }
1565                         }
1566                 }
1567
1568                 if ( ncandidates == 0 ) {
1569                         if ( new_conn ) {
1570                                 mc->mc_refcnt = 0;
1571                                 meta_back_conn_free( mc );
1572
1573                         } else {
1574                                 meta_back_release_conn( mi, mc );
1575                         }
1576
1577                         if ( rs->sr_err == LDAP_SUCCESS ) {
1578                                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
1579                                 rs->sr_text = "Unable to select valid candidates";
1580                         }
1581
1582                         if ( sendok & LDAP_BACK_SENDERR ) {
1583                                 if ( rs->sr_err == LDAP_NO_SUCH_OBJECT ) {
1584                                         rs->sr_matched = op->o_bd->be_suffix[ 0 ].bv_val;
1585                                 }
1586                                 send_ldap_result( op, rs );
1587                                 rs->sr_matched = NULL;
1588                         }
1589
1590                         return NULL;
1591                 }
1592         }
1593
1594 done:;
1595         /* clear out meta_back_init_one_conn non-fatal errors */
1596         rs->sr_err = LDAP_SUCCESS;
1597         rs->sr_text = NULL;
1598
1599         /* touch the timestamp */
1600         if ( mi->mi_idle_timeout != 0 ) {
1601                 mc->mc_time = op->o_time;
1602         }
1603
1604         if ( new_conn ) {
1605                 if ( mi->mi_conn_ttl ) {
1606                         mc->mc_create_time = op->o_time;
1607                 }
1608
1609                 /*
1610                  * Inserts the newly created metaconn in the avl tree
1611                  */
1612                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
1613 #if META_BACK_PRINT_CONNTREE > 0
1614                 meta_back_print_conntree( mi, ">>> meta_back_getconn" );
1615 #endif /* META_BACK_PRINT_CONNTREE */
1616
1617                 err = 0;
1618                 if ( LDAP_BACK_PCONN_ISPRIV( mc ) ) {
1619                         if ( mi->mi_conn_priv[ LDAP_BACK_CONN2PRIV( mc ) ].mic_num < mi->mi_conn_priv_max ) {
1620                                 LDAP_TAILQ_INSERT_TAIL( &mi->mi_conn_priv[ LDAP_BACK_CONN2PRIV( mc ) ].mic_priv, mc, mc_q );
1621                                 mi->mi_conn_priv[ LDAP_BACK_CONN2PRIV( mc ) ].mic_num++;
1622                                 LDAP_BACK_CONN_CACHED_SET( mc );
1623
1624                         } else {
1625                                 LDAP_BACK_CONN_TAINTED_SET( mc );
1626                         }
1627                         rs->sr_err = 0;
1628
1629                 } else if ( !( sendok & LDAP_BACK_BINDING ) ) {
1630                         err = avl_insert( &mi->mi_conninfo.lai_tree, ( caddr_t )mc,
1631                                 meta_back_conndn_cmp, meta_back_conndn_dup );
1632                         LDAP_BACK_CONN_CACHED_SET( mc );
1633                 }
1634
1635 #if META_BACK_PRINT_CONNTREE > 0
1636                 meta_back_print_conntree( mi, "<<< meta_back_getconn" );
1637 #endif /* META_BACK_PRINT_CONNTREE */
1638                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1639
1640                 if ( !LDAP_BACK_PCONN_ISPRIV( mc ) ) {
1641                         /*
1642                          * Err could be -1 in case a duplicate metaconn is inserted
1643                          */
1644                         switch ( err ) {
1645                         case 0:
1646                                 break;
1647
1648                         case -1:
1649                                 LDAP_BACK_CONN_CACHED_CLEAR( mc );
1650                                 /* duplicate: free and try to get the newly created one */
1651                                 if ( !( sendok & LDAP_BACK_BINDING ) && !LDAP_BACK_USE_TEMPORARIES( mi ) ) {
1652                                         mc->mc_refcnt = 0;      
1653                                         meta_back_conn_free( mc );
1654         
1655                                         new_conn = 0;
1656                                         goto retry_lock;
1657                                 }
1658
1659                                 LDAP_BACK_CONN_TAINTED_SET( mc );
1660                                 break;
1661
1662                         default:
1663                                 LDAP_BACK_CONN_CACHED_CLEAR( mc );
1664                                 if ( LogTest( LDAP_DEBUG_ANY ) ) {
1665                                         char buf[STRLENOF("4294967295U") + 1] = { 0 };
1666                                         mi->mi_ldap_extra->connid2str( &mc->mc_base, buf, sizeof(buf) );
1667
1668                                         Debug( LDAP_DEBUG_ANY,
1669                                                 "%s meta_back_getconn: candidates=%d conn=%s insert failed\n",
1670                                                 op->o_log_prefix, ncandidates, buf );
1671                                 }
1672         
1673                                 mc->mc_refcnt = 0;      
1674                                 meta_back_conn_free( mc );
1675
1676                                 rs->sr_err = LDAP_OTHER;
1677                                 rs->sr_text = "Proxy bind collision";
1678                                 if ( sendok & LDAP_BACK_SENDERR ) {
1679                                         send_ldap_result( op, rs );
1680                                 }
1681                                 return NULL;
1682                         }
1683                 }
1684
1685                 if ( LogTest( LDAP_DEBUG_TRACE ) ) {
1686                         char buf[STRLENOF("4294967295U") + 1] = { 0 };
1687                         mi->mi_ldap_extra->connid2str( &mc->mc_base, buf, sizeof(buf) );
1688
1689                         Debug( LDAP_DEBUG_TRACE,
1690                                 "%s meta_back_getconn: candidates=%d conn=%s inserted\n",
1691                                 op->o_log_prefix, ncandidates, buf );
1692                 }
1693
1694         } else {
1695                 if ( LogTest( LDAP_DEBUG_TRACE ) ) {
1696                         char buf[STRLENOF("4294967295U") + 1] = { 0 };
1697                         mi->mi_ldap_extra->connid2str( &mc->mc_base, buf, sizeof(buf) );
1698
1699                         Debug( LDAP_DEBUG_TRACE,
1700                                 "%s meta_back_getconn: candidates=%d conn=%s fetched\n",
1701                                 op->o_log_prefix, ncandidates, buf );
1702                 }
1703         }
1704
1705         return mc;
1706 }
1707
1708 void
1709 meta_back_release_conn_lock(
1710         metainfo_t              *mi,
1711         metaconn_t              *mc,
1712         int                     dolock )
1713 {
1714         assert( mc != NULL );
1715
1716         if ( dolock ) {
1717                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
1718         }
1719         assert( mc->mc_refcnt > 0 );
1720         mc->mc_refcnt--;
1721         /* NOTE: the connection is removed if either it is tainted
1722          * or if it is shared and no one else is using it.  This needs
1723          * to occur because for intrinsic reasons cached connections
1724          * that are not privileged would live forever and pollute
1725          * the connection space (and eat up resources).  Maybe this
1726          * should be configurable... */
1727         if ( LDAP_BACK_CONN_TAINTED( mc ) || !LDAP_BACK_CONN_CACHED( mc ) ) {
1728 #if META_BACK_PRINT_CONNTREE > 0
1729                 meta_back_print_conntree( mi, ">>> meta_back_release_conn" );
1730 #endif /* META_BACK_PRINT_CONNTREE */
1731
1732                 if ( LDAP_BACK_PCONN_ISPRIV( mc ) ) {
1733                         if ( mc->mc_q.tqe_prev != NULL ) {
1734                                 assert( LDAP_BACK_CONN_CACHED( mc ) );
1735                                 assert( mi->mi_conn_priv[ LDAP_BACK_CONN2PRIV( mc ) ].mic_num > 0 );
1736                                 LDAP_TAILQ_REMOVE( &mi->mi_conn_priv[ LDAP_BACK_CONN2PRIV( mc ) ].mic_priv, mc, mc_q );
1737                                 mi->mi_conn_priv[ LDAP_BACK_CONN2PRIV( mc ) ].mic_num--;
1738                                 LDAP_TAILQ_ENTRY_INIT( mc, mc_q );
1739
1740                         } else {
1741                                 assert( !LDAP_BACK_CONN_CACHED( mc ) );
1742                         }
1743
1744                 } else if ( LDAP_BACK_CONN_CACHED( mc ) ) {
1745                         metaconn_t      *tmpmc;
1746
1747                         tmpmc = avl_delete( &mi->mi_conninfo.lai_tree,
1748                                 ( caddr_t )mc, meta_back_conndnmc_cmp );
1749
1750                         /* Overparanoid, but useful... */
1751                         assert( tmpmc == NULL || tmpmc == mc );
1752                 }
1753
1754                 LDAP_BACK_CONN_CACHED_CLEAR( mc );
1755
1756 #if META_BACK_PRINT_CONNTREE > 0
1757                 meta_back_print_conntree( mi, "<<< meta_back_release_conn" );
1758 #endif /* META_BACK_PRINT_CONNTREE */
1759
1760                 if ( mc->mc_refcnt == 0 ) {
1761                         meta_back_conn_free( mc );
1762                         mc = NULL;
1763                 }
1764         }
1765
1766         if ( mc != NULL && LDAP_BACK_CONN_BINDING( mc ) ) {
1767                 LDAP_BACK_CONN_BINDING_CLEAR( mc );
1768         }
1769
1770         if ( dolock ) {
1771                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1772         }
1773 }
1774
1775 void
1776 meta_back_quarantine(
1777         Operation       *op,
1778         SlapReply       *rs,
1779         int             candidate )
1780 {
1781         metainfo_t              *mi = (metainfo_t *)op->o_bd->be_private;
1782         metatarget_t            *mt = mi->mi_targets[ candidate ];
1783
1784         slap_retry_info_t       *ri = &mt->mt_quarantine;
1785
1786         ldap_pvt_thread_mutex_lock( &mt->mt_quarantine_mutex );
1787
1788         if ( rs->sr_err == LDAP_UNAVAILABLE ) {
1789                 time_t  new_last = slap_get_time();
1790
1791                 switch ( mt->mt_isquarantined ) {
1792                 case LDAP_BACK_FQ_NO:
1793                         if ( ri->ri_last == new_last ) {
1794                                 goto done;
1795                         }
1796
1797                         Debug( LDAP_DEBUG_ANY,
1798                                 "%s meta_back_quarantine[%d]: enter.\n",
1799                                 op->o_log_prefix, candidate, 0 );
1800
1801                         ri->ri_idx = 0;
1802                         ri->ri_count = 0;
1803                         break;
1804
1805                 case LDAP_BACK_FQ_RETRYING:
1806                         if ( LogTest( LDAP_DEBUG_ANY ) ) {
1807                                 char    buf[ SLAP_TEXT_BUFLEN ];
1808
1809                                 snprintf( buf, sizeof( buf ),
1810                                         "meta_back_quarantine[%d]: block #%d try #%d failed",
1811                                         candidate, ri->ri_idx, ri->ri_count );
1812                                 Debug( LDAP_DEBUG_ANY, "%s %s.\n",
1813                                         op->o_log_prefix, buf, 0 );
1814                         }
1815
1816                         ++ri->ri_count;
1817                         if ( ri->ri_num[ ri->ri_idx ] != SLAP_RETRYNUM_FOREVER
1818                                 && ri->ri_count == ri->ri_num[ ri->ri_idx ] )
1819                         {
1820                                 ri->ri_count = 0;
1821                                 ++ri->ri_idx;
1822                         }
1823                         break;
1824
1825                 default:
1826                         break;
1827                 }
1828
1829                 mt->mt_isquarantined = LDAP_BACK_FQ_YES;
1830                 ri->ri_last = new_last;
1831
1832         } else if ( mt->mt_isquarantined == LDAP_BACK_FQ_RETRYING ) {
1833                 Debug( LDAP_DEBUG_ANY,
1834                         "%s meta_back_quarantine[%d]: exit.\n",
1835                         op->o_log_prefix, candidate, 0 );
1836
1837                 if ( mi->mi_quarantine_f ) {
1838                         (void)mi->mi_quarantine_f( mi, candidate,
1839                                 mi->mi_quarantine_p );
1840                 }
1841
1842                 ri->ri_count = 0;
1843                 ri->ri_idx = 0;
1844                 mt->mt_isquarantined = LDAP_BACK_FQ_NO;
1845         }
1846
1847 done:;
1848         ldap_pvt_thread_mutex_unlock( &mt->mt_quarantine_mutex );
1849 }
1850