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