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