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