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