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