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