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