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