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