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