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