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