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