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