]> git.sur5r.net Git - openldap/blob - servers/slapd/back-meta/conn.c
650ab4b558bf7520cbd725c142c34e9f026dca9b
[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/socket.h>
28 #include <ac/string.h>
29
30
31 #define AVL_INTERNAL
32 #include "slap.h"
33 #include "../back-ldap/back-ldap.h"
34 #include "back-meta.h"
35
36 /*
37  * Set PRINT_CONNTREE larger than 0 to dump the connection tree (debug only)
38  */
39 #define PRINT_CONNTREE 0
40
41 /*
42  * meta_back_conn_cmp
43  *
44  * compares two struct metaconn based on the value of the conn pointer;
45  * used by avl stuff
46  */
47 int
48 meta_back_conn_cmp(
49         const void *c1,
50         const void *c2 )
51 {
52         struct metaconn *mc1 = ( struct metaconn * )c1;
53         struct metaconn *mc2 = ( struct metaconn * )c2;
54         
55         return SLAP_PTRCMP( mc1->mc_conn, mc2->mc_conn );
56 }
57
58 /*
59  * meta_back_conn_dup
60  *
61  * returns -1 in case a duplicate struct metaconn has been inserted;
62  * used by avl stuff
63  */
64 int
65 meta_back_conn_dup(
66         void *c1,
67         void *c2 )
68 {
69         struct metaconn *mc1 = ( struct metaconn * )c1;
70         struct metaconn *mc2 = ( struct metaconn * )c2;
71
72         return( ( mc1->mc_conn == mc2->mc_conn ) ? -1 : 0 );
73 }
74
75 /*
76  * Debug stuff (got it from libavl)
77  */
78 #if PRINT_CONNTREE > 0
79 static void
80 ravl_print( Avlnode *root, int depth )
81 {
82         int     i;
83         
84         if ( root == 0 ) {
85                 return;
86         }
87         
88         ravl_print( root->avl_right, depth + 1 );
89         
90         for ( i = 0; i < depth; i++ ) {
91                 printf( "    " );
92         }
93
94         printf( "c(%d) %d\n", ( ( struct metaconn * )root->avl_data )->mc_conn->c_connid, root->avl_bf );
95         
96         ravl_print( root->avl_left, depth + 1 );
97 }
98
99 static void
100 myprint( Avlnode *root )
101 {
102         printf( "********\n" );
103         
104         if ( root == 0 ) {
105                 printf( "\tNULL\n" );
106         } else {
107                 ravl_print( root, 0 );
108         }
109         
110         printf( "********\n" );
111 }
112 #endif /* PRINT_CONNTREE */
113 /*
114  * End of debug stuff
115  */
116
117 /*
118  * metaconn_alloc
119  * 
120  * Allocates a connection structure, making room for all the referenced targets
121  */
122 static struct metaconn *
123 metaconn_alloc( int ntargets )
124 {
125         struct metaconn *mc;
126
127         assert( ntargets > 0 );
128
129         /* malloc once only; leave an extra one for one-past-end */
130         mc = ch_malloc( sizeof( struct metaconn )
131                         + sizeof( struct metasingleconn ) * ( ntargets + 1 ) );
132         if ( mc == NULL ) {
133                 return NULL;
134         }
135
136         mc->mc_conns = (struct metasingleconn *)&mc[ 1 ];
137
138         /* FIXME: needed by META_LAST() */
139         mc->mc_conns[ ntargets ].msc_candidate = META_LAST_CONN;
140
141         for ( ; ntargets-- > 0; ) {
142                 mc->mc_conns[ ntargets ].msc_ld = NULL;
143                 BER_BVZERO( &mc->mc_conns[ ntargets ].msc_bound_ndn );
144                 BER_BVZERO( &mc->mc_conns[ ntargets ].msc_cred );
145                 mc->mc_conns[ ntargets ].msc_bound = META_UNBOUND;
146         }
147
148         mc->mc_auth_target = META_BOUND_NONE;
149         ldap_pvt_thread_mutex_init( &mc->mc_mutex );
150
151         return mc;
152 }
153
154 /*
155  * meta_back_conn_free
156  *
157  * clears a metaconn
158  */
159 void
160 meta_back_conn_free( struct metaconn *mc )
161 {
162         if ( mc == NULL ) {
163                 return;
164         }
165
166         ldap_pvt_thread_mutex_destroy( &mc->mc_mutex );
167         
168         free( mc );
169 }
170
171 /*
172  * meta_back_init_one_conn
173  * 
174  * Initializes one connection
175  */
176 static int
177 meta_back_init_one_conn(
178                 Operation               *op,
179                 SlapReply               *rs,
180                 struct metatarget       *lt, 
181                 struct metasingleconn   *msc,
182                 ldap_back_send_t        sendok )
183 {
184         struct metainfo *mi = ( struct metainfo * )op->o_bd->be_private;
185         int             vers;
186         dncookie        dc;
187
188         /*
189          * Already init'ed
190          */
191         if ( msc->msc_ld != NULL ) {
192                 rs->sr_err = LDAP_SUCCESS;
193                 goto error_return;
194         }
195        
196         /*
197          * Attempts to initialize the connection to the target ds
198          */
199         rs->sr_err = ldap_initialize( &msc->msc_ld, lt->mt_uri );
200         if ( rs->sr_err != LDAP_SUCCESS ) {
201                 goto error_return;
202         }
203
204         /*
205          * Set LDAP version. This will always succeed: If the client
206          * bound with a particular version, then so can we.
207          */
208         vers = op->o_conn->c_protocol;
209         ldap_set_option( msc->msc_ld, LDAP_OPT_PROTOCOL_VERSION, &vers );
210
211         /* automatically chase referrals ("chase-referrals"/"dont-chase-referrals" statement) */
212         if ( LDAP_BACK_CHASE_REFERRALS( mi ) ) {
213                 ldap_set_option( msc->msc_ld, LDAP_OPT_REFERRALS, LDAP_OPT_ON );
214         }
215
216 #ifdef HAVE_TLS
217         /* start TLS ("start-tls"/"try-start-tls" statements) */
218         if ( ( LDAP_BACK_USE_TLS( mi ) || ( op->o_conn->c_is_tls && LDAP_BACK_PROPAGATE_TLS( mi ) ) )
219                         && !ldap_is_ldaps_url( lt->mt_uri ) )
220         {
221 #ifdef SLAP_STARTTLS_ASYNCHRONOUS
222                 /*
223                  * use asynchronous StartTLS
224                  * in case, chase referral (not implemented yet)
225                  */
226                 int             msgid;
227
228                 rs->sr_err = ldap_start_tls( msc->msc_ld, NULL, NULL, &msgid );
229                 if ( rs->sr_err == LDAP_SUCCESS ) {
230                         LDAPMessage     *res = NULL;
231                         int             rc, retries = 1;
232                         struct timeval  tv = { 0, 0 };
233
234 retry:;
235                         rc = ldap_result( msc->msc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
236                         if ( rc < 0 ) {
237                                 rs->sr_err = LDAP_OTHER;
238
239                         } else if ( rc == 0 ) {
240                                 if ( retries ) {
241                                         retries--;
242                                         tv.tv_sec = 0;
243                                         tv.tv_usec = 100000;
244                                         goto retry;
245                                 }
246                                 rs->sr_err = LDAP_OTHER;
247
248                         } else if ( rc == LDAP_RES_EXTENDED ) {
249                                 struct berval   *data = NULL;
250
251                                 rs->sr_err = ldap_parse_extended_result( msc->msc_ld, res,
252                                                 NULL, &data, 0 );
253                                 if ( rs->sr_err == LDAP_SUCCESS ) {
254                                         rs->sr_err = ldap_result2error( msc->msc_ld, res, 1 );
255                                         res = NULL;
256                                         
257                                         /* FIXME: in case a referral 
258                                          * is returned, should we try
259                                          * using it instead of the 
260                                          * configured URI? */
261                                         if ( rs->sr_err == LDAP_SUCCESS ) {
262                                                 ldap_install_tls( msc->msc_ld );
263
264                                         } else if ( rs->sr_err == LDAP_REFERRAL ) {
265                                                 rs->sr_err = LDAP_OTHER;
266                                                 rs->sr_text = "unwilling to chase referral returned by Start TLS exop";
267                                         }
268
269                                         if ( data ) {
270                                                 if ( data->bv_val ) {
271                                                         ber_memfree( data->bv_val );
272                                                 }
273                                                 ber_memfree( data );
274                                         }
275                                 }
276
277                         } else {
278                                 rs->sr_err = LDAP_OTHER;
279                         }
280
281                         if ( res != NULL ) {
282                                 ldap_msgfree( res );
283                         }
284                 }
285 #else /* ! SLAP_STARTTLS_ASYNCHRONOUS */
286                 /*
287                  * use synchronous StartTLS
288                  */
289                 rs->sr_err = ldap_start_tls_s( msc->msc_ld, NULL, NULL );
290 #endif /* ! SLAP_STARTTLS_ASYNCHRONOUS */
291
292                 /* if StartTLS is requested, only attempt it if the URL
293                  * is not "ldaps://"; this may occur not only in case
294                  * of misconfiguration, but also when used in the chain 
295                  * overlay, where the "uri" can be parsed out of a referral */
296                 if ( rs->sr_err == LDAP_SERVER_DOWN
297                                 || ( rs->sr_err != LDAP_SUCCESS && LDAP_BACK_TLS_CRITICAL( mi ) ) )
298                 {
299                         ldap_unbind_ext_s( msc->msc_ld, NULL, NULL );
300                         goto error_return;
301                 }
302         }
303 #endif /* HAVE_TLS */
304
305         /*
306          * Set the network timeout if set
307          */
308         if ( mi->mi_network_timeout != 0 ) {
309                 struct timeval  network_timeout;
310
311                 network_timeout.tv_usec = 0;
312                 network_timeout.tv_sec = mi->mi_network_timeout;
313
314                 ldap_set_option( msc->msc_ld, LDAP_OPT_NETWORK_TIMEOUT,
315                                 (void *)&network_timeout );
316         }
317
318         /*
319          * Sets a cookie for the rewrite session
320          */
321         ( void )rewrite_session_init( lt->mt_rwmap.rwm_rw, op->o_conn );
322
323         /*
324          * If the connection DN is not null, an attempt to rewrite it is made
325          */
326         if ( !BER_BVISEMPTY( &op->o_conn->c_dn ) ) {
327                 dc.rwmap = &lt->mt_rwmap;
328                 dc.conn = op->o_conn;
329                 dc.rs = rs;
330                 dc.ctx = "bindDN";
331                 
332                 /*
333                  * Rewrite the bind dn if needed
334                  */
335                 if ( ldap_back_dn_massage( &dc, &op->o_conn->c_dn,
336                                         &msc->msc_bound_ndn ) )
337                 {
338                         goto error_return;
339                 }
340
341                 /* copy the DN idf needed */
342                 if ( msc->msc_bound_ndn.bv_val == op->o_conn->c_dn.bv_val ) {
343                         ber_dupbv( &msc->msc_bound_ndn, &op->o_conn->c_dn );
344                 }
345
346                 assert( !BER_BVISNULL( &msc->msc_bound_ndn ) );
347
348         } else {
349                 ber_str2bv( "", 0, 1, &msc->msc_bound_ndn );
350         }
351
352         msc->msc_bound = META_UNBOUND;
353
354 error_return:;
355         if ( rs->sr_err != LDAP_SUCCESS ) {
356                 rs->sr_err = slap_map_api2result( rs );
357                 if ( sendok & LDAP_BACK_SENDERR ) {
358                         send_ldap_result( op, rs );
359                         rs->sr_text = NULL;
360                 }
361         }
362
363         return rs->sr_err;
364 }
365
366 /*
367  * meta_back_retry
368  * 
369  * Retries one connection
370  */
371 int
372 meta_back_retry(
373                 Operation               *op,
374                 SlapReply               *rs,
375                 struct metaconn         *mc,
376                 int                     candidate,
377                 ldap_back_send_t        sendok )
378 {
379         struct metainfo         *mi = (struct metainfo *)op->o_bd->be_private;
380         struct metatarget       *lt = mi->mi_targets[ candidate ];
381         int                     rc;
382         struct metasingleconn   *msc = &mc->mc_conns[ candidate ];
383
384         ldap_pvt_thread_mutex_lock( &mc->mc_mutex );
385
386         ldap_unbind_ext_s( msc->msc_ld, NULL, NULL );
387         msc->msc_ld = NULL;
388         msc->msc_bound = 0;
389
390         /* mc here must be the regular mc, reset and ready for init */
391         rc = meta_back_init_one_conn( op, rs, lt, msc, sendok );
392
393         if ( rc == LDAP_SUCCESS ) {
394                 rc = meta_back_single_dobind( op, msc, sendok, 0 );
395         }
396
397         ldap_pvt_thread_mutex_unlock( &mc->mc_mutex );
398
399         return rc == LDAP_SUCCESS ? 1 : 0;
400 }
401
402 /*
403  * callback for unique candidate selection
404  */
405 static int
406 meta_back_conn_cb( Operation *op, SlapReply *rs )
407 {
408         assert( op->o_tag == LDAP_REQ_SEARCH );
409
410         switch ( rs->sr_type ) {
411         case REP_SEARCH:
412                 ((int *)op->o_callback->sc_private)[0] = (int)op->o_private;
413                 break;
414
415         case REP_SEARCHREF:
416         case REP_RESULT:
417                 break;
418
419         default:
420                 return rs->sr_err;
421         }
422
423         return 0;
424 }
425
426
427 static int
428 meta_back_get_candidate(
429         Operation       *op,
430         SlapReply       *rs,
431         struct berval   *ndn )
432 {
433         struct metainfo *mi = ( struct metainfo * )op->o_bd->be_private;
434         int             candidate;
435
436         /*
437          * tries to get a unique candidate
438          * (takes care of default target)
439          */
440         candidate = meta_back_select_unique_candidate( mi, ndn );
441
442         /*
443          * if any is found, inits the connection
444          */
445         if ( candidate == META_TARGET_NONE ) {
446                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
447                 rs->sr_text = "no suitable candidate target found";
448
449         } else if ( candidate == META_TARGET_MULTIPLE ) {
450                 Filter          f = { 0 };
451                 Operation       op2 = *op;
452                 SlapReply       rs2 = { 0 };
453                 slap_callback   cb2 = { 0 };
454                 int             rc;
455
456                 /* try to get a unique match for the request ndn
457                  * among the multiple candidates available */
458                 op2.o_tag = LDAP_REQ_SEARCH;
459                 op2.o_req_dn = *ndn;
460                 op2.o_req_ndn = *ndn;
461                 op2.ors_scope = LDAP_SCOPE_BASE;
462                 op2.ors_deref = LDAP_DEREF_NEVER;
463                 op2.ors_attrs = slap_anlist_no_attrs;
464                 op2.ors_attrsonly = 0;
465                 op2.ors_limit = NULL;
466                 op2.ors_slimit = 1;
467                 op2.ors_tlimit = SLAP_NO_LIMIT;
468
469                 f.f_choice = LDAP_FILTER_PRESENT;
470                 f.f_desc = slap_schema.si_ad_objectClass;
471                 op2.ors_filter = &f;
472                 BER_BVSTR( &op2.ors_filterstr, "(objectClass=*)" );
473
474                 op2.o_callback = &cb2;
475                 cb2.sc_response = meta_back_conn_cb;
476                 cb2.sc_private = (void *)&candidate;
477
478                 rc = op->o_bd->be_search( &op2, &rs2 );
479
480                 switch ( rs2.sr_err ) {
481                 case LDAP_SUCCESS:
482                 default:
483                         rs->sr_err = rs2.sr_err;
484                         break;
485
486                 case LDAP_SIZELIMIT_EXCEEDED:
487                         /* if multiple candidates can serve the operation,
488                          * and a default target is defined, and it is
489                          * a candidate, try using it (FIXME: YMMV) */
490                         if ( mi->mi_defaulttarget != META_DEFAULT_TARGET_NONE
491                                 && meta_back_is_candidate( &mi->mi_targets[ mi->mi_defaulttarget ]->mt_nsuffix,
492                                                 ndn, op->o_tag == LDAP_REQ_SEARCH ? op->ors_scope : LDAP_SCOPE_BASE ) )
493                         {
494                                 candidate = mi->mi_defaulttarget;
495                                 rs->sr_err = LDAP_SUCCESS;
496                                 rs->sr_text = NULL;
497
498                         } else {
499                                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
500                                 rs->sr_text = "cannot select unique candidate target";
501                         }
502                         break;
503                 }
504         }
505
506         return candidate;
507 }
508
509 static void
510 meta_back_candidate_keyfree( void *key, void *data )
511 {
512         ber_memfree_x( data, NULL );
513 }
514
515 SlapReply *
516 meta_back_candidates_get( Operation *op )
517 {
518         struct metainfo *mi = ( struct metainfo * )op->o_bd->be_private;
519         void            *data = NULL;
520
521         if ( op->o_threadctx ) {
522                 ldap_pvt_thread_pool_getkey( op->o_threadctx,
523                                 meta_back_candidate_keyfree, &data, NULL );
524         } else {
525                 data = (void *)mi->mi_candidates;
526         }
527
528         if ( data == NULL ) {
529                 data = ber_memalloc( sizeof( SlapReply ) * mi->mi_ntargets );
530                 if ( op->o_threadctx ) {
531                         ldap_pvt_thread_pool_setkey( op->o_threadctx,
532                                         meta_back_candidate_keyfree, data,
533                                         meta_back_candidate_keyfree );
534
535                 } else {
536                         mi->mi_candidates = (SlapReply *)data;
537                 }
538         }
539
540         return (SlapReply *)data;
541 }
542
543 /*
544  * meta_back_getconn
545  * 
546  * Prepares the connection structure
547  * 
548  * RATIONALE:
549  *
550  * - determine what DN is being requested:
551  *
552  *      op      requires candidate      checks
553  *
554  *      add     unique                  parent of o_req_ndn
555  *      bind    unique^*[/all]          o_req_ndn [no check]
556  *      compare unique^+                o_req_ndn
557  *      delete  unique                  o_req_ndn
558  *      modify  unique                  o_req_ndn
559  *      search  any                     o_req_ndn
560  *      modrdn  unique[, unique]        o_req_ndn[, orr_nnewSup]
561  *
562  * - for ops that require the candidate to be unique, in case of multiple
563  *   occurrences an internal search with sizeLimit=1 is performed
564  *   if a unique candidate can actually be determined.  If none is found,
565  *   the operation aborts; if multiple are found, the default target
566  *   is used if defined and candidate; otherwise the operation aborts.
567  *
568  * *^note: actually, the bind operation is handled much like a search;
569  *   i.e. the bind is broadcast to all candidate targets.
570  *
571  * +^note: actually, the compare operation is handled much like a search;
572  *   i.e. the compare is broadcast to all candidate targets, while checking
573  *   that exactly none (noSuchObject) or one (TRUE/FALSE/UNDEFINED) is
574  *   returned.
575  */
576 struct metaconn *
577 meta_back_getconn(
578                 Operation               *op,
579                 SlapReply               *rs,
580                 int                     *candidate,
581                 ldap_back_send_t        sendok )
582 {
583         struct metainfo *mi = ( struct metainfo * )op->o_bd->be_private;
584         struct metaconn *mc, mc_curr;
585         int             cached = META_TARGET_NONE,
586                         i = META_TARGET_NONE,
587                         err = LDAP_SUCCESS,
588                         new_conn = 0;
589
590         meta_op_type    op_type = META_OP_REQUIRE_SINGLE;
591         int             parent = 0,
592                         newparent = 0;
593         struct berval   ndn = op->o_req_ndn,
594                         pndn;
595
596         SlapReply       *candidates = meta_back_candidates_get( op );
597
598         /* Searches for a metaconn in the avl tree */
599         mc_curr.mc_conn = op->o_conn;
600         ldap_pvt_thread_mutex_lock( &mi->mi_conn_mutex );
601         mc = (struct metaconn *)avl_find( mi->mi_conntree, 
602                 (caddr_t)&mc_curr, meta_back_conn_cmp );
603         ldap_pvt_thread_mutex_unlock( &mi->mi_conn_mutex );
604
605         switch ( op->o_tag ) {
606         case LDAP_REQ_ADD:
607                 /* if we go to selection, the entry must not exist,
608                  * and we must be able to resolve the parent */
609                 parent = 1;
610                 dnParent( &ndn, &pndn );
611                 break;
612
613         case LDAP_REQ_MODRDN:
614                 /* if nnewSuperior is not NULL, it must resolve
615                  * to the same candidate as the req_ndn */
616                 if ( op->orr_nnewSup ) {
617                         newparent = 1;
618                 }
619                 break;
620
621         case LDAP_REQ_BIND:
622                 /* if bound as rootdn, the backend must bind to all targets
623                  * with the administrative identity */
624                 if ( op->orb_method == LDAP_AUTH_SIMPLE && be_isroot_pw( op ) ) {
625                         op_type = META_OP_REQUIRE_ALL;
626                 }
627                 break;
628
629         case LDAP_REQ_DELETE:
630         case LDAP_REQ_MODIFY:
631                 /* just a unique candidate */
632                 break;
633
634         case LDAP_REQ_COMPARE:
635         case LDAP_REQ_SEARCH:
636                 /* allow multiple candidates for the searchBase */
637                 op_type = META_OP_ALLOW_MULTIPLE;
638                 break;
639
640         default:
641                 /* right now, just break (exop?) */
642                 break;
643         }
644
645         /*
646          * require all connections ...
647          */
648         if ( op_type == META_OP_REQUIRE_ALL ) {
649
650                 /* Looks like we didn't get a bind. Open a new session... */
651                 if ( !mc ) {
652                         mc = metaconn_alloc( mi->mi_ntargets );
653                         mc->mc_conn = op->o_conn;
654                         new_conn = 1;
655                 }
656
657                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
658
659                         /*
660                          * The target is activated; if needed, it is
661                          * also init'd
662                          */
663                         int lerr = meta_back_init_one_conn( op, rs, mi->mi_targets[ i ],
664                                         &mc->mc_conns[ i ], sendok );
665                         if ( lerr == LDAP_SUCCESS ) {
666                                 candidates[ i ].sr_tag = META_CANDIDATE;
667                                 
668                         } else {
669                                 
670                                 /*
671                                  * FIXME: in case one target cannot
672                                  * be init'd, should the other ones
673                                  * be tried?
674                                  */
675                                 candidates[ i ].sr_tag = META_NOT_CANDIDATE;
676                                 err = lerr;
677                                 continue;
678                         }
679                 }
680                 goto done;
681         }
682         
683         /*
684          * looks in cache, if any
685          */
686         if ( mi->mi_cache.ttl != META_DNCACHE_DISABLED ) {
687                 cached = i = meta_dncache_get_target( &mi->mi_cache, &op->o_req_ndn );
688         }
689
690         if ( op_type == META_OP_REQUIRE_SINGLE ) {
691                 int     j;
692
693                 for ( j = 0; j < mi->mi_ntargets; j++ ) {
694                         candidates[ j ].sr_tag = META_NOT_CANDIDATE;
695                 }
696
697                 /*
698                  * tries to get a unique candidate
699                  * (takes care of default target)
700                  */
701                 if ( i == META_TARGET_NONE ) {
702                         i = meta_back_get_candidate( op, rs, &ndn );
703
704                         if ( rs->sr_err == LDAP_NO_SUCH_OBJECT && parent ) {
705                                 i = meta_back_get_candidate( op, rs, &pndn );
706                         }
707         
708                         if ( rs->sr_err != LDAP_SUCCESS ) {
709                                 if ( sendok & LDAP_BACK_SENDERR ) {
710                                         send_ldap_result( op, rs );
711                                         rs->sr_text = NULL;
712                                 }
713                                 return NULL;
714                         }
715                 }
716
717                 if ( newparent && meta_back_get_candidate( op, rs, op->orr_nnewSup ) != i )
718                 {
719                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
720                         rs->sr_text = "cross-target rename not supported";
721                         if ( sendok & LDAP_BACK_SENDERR ) {
722                                 send_ldap_result( op, rs );
723                                 rs->sr_text = NULL;
724                         }
725                         return NULL;
726                 }
727
728                 Debug( LDAP_DEBUG_CACHE,
729         "==>meta_back_getconn: got target %d for ndn=\"%s\" from cache\n",
730                                 i, op->o_req_ndn.bv_val, 0 );
731
732                 /* Retries searching for a metaconn in the avl tree */
733                 mc_curr.mc_conn = op->o_conn;
734                 ldap_pvt_thread_mutex_lock( &mi->mi_conn_mutex );
735                 mc = (struct metaconn *)avl_find( mi->mi_conntree, 
736                         (caddr_t)&mc_curr, meta_back_conn_cmp );
737                 ldap_pvt_thread_mutex_unlock( &mi->mi_conn_mutex );
738
739                 /* Looks like we didn't get a bind. Open a new session... */
740                 if ( !mc ) {
741                         mc = metaconn_alloc( mi->mi_ntargets );
742                         mc->mc_conn = op->o_conn;
743                         new_conn = 1;
744                 }
745
746                 /*
747                  * Clear all other candidates
748                  */
749                 ( void )meta_clear_unused_candidates( op, mc, i );
750
751                 /*
752                  * The target is activated; if needed, it is
753                  * also init'd. In case of error, meta_back_init_one_conn
754                  * sends the appropriate result.
755                  */
756                 err = meta_back_init_one_conn( op, rs, mi->mi_targets[ i ],
757                                 &mc->mc_conns[ i ], sendok );
758                 if ( err == LDAP_SUCCESS ) {
759                         candidates[ i ].sr_tag = META_CANDIDATE;
760
761                 } else {
762                 
763                         /*
764                          * FIXME: in case one target cannot
765                          * be init'd, should the other ones
766                          * be tried?
767                          */
768                         candidates[ i ].sr_tag = META_NOT_CANDIDATE;
769                         if ( new_conn ) {
770                                 ( void )meta_clear_one_candidate( &mc->mc_conns[ i ] );
771                                 meta_back_conn_free( mc );
772                         }
773                         return NULL;
774                 }
775
776                 if ( candidate ) {
777                         *candidate = i;
778                 }
779
780         /*
781          * if no unique candidate ...
782          */
783         } else {
784
785                 /* Looks like we didn't get a bind. Open a new session... */
786                 if ( !mc ) {
787                         mc = metaconn_alloc( mi->mi_ntargets );
788                         mc->mc_conn = op->o_conn;
789                         new_conn = 1;
790                 }
791
792                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
793                         if ( i == cached 
794                                 || meta_back_is_candidate( &mi->mi_targets[ i ]->mt_nsuffix,
795                                                 &op->o_req_ndn, LDAP_SCOPE_SUBTREE ) )
796                         {
797
798                                 /*
799                                  * The target is activated; if needed, it is
800                                  * also init'd
801                                  */
802                                 int lerr = meta_back_init_one_conn( op, rs,
803                                                 mi->mi_targets[ i ],
804                                                 &mc->mc_conns[ i ], sendok );
805                                 if ( lerr == LDAP_SUCCESS ) {
806                                         candidates[ i ].sr_tag = META_CANDIDATE;
807
808                                 } else {
809                                 
810                                         /*
811                                          * FIXME: in case one target cannot
812                                          * be init'd, should the other ones
813                                          * be tried?
814                                          */
815                                         candidates[ i ].sr_tag = META_NOT_CANDIDATE;
816                                         err = lerr;
817
818                                         Debug( LDAP_DEBUG_ANY, "%s: meta_back_init_one_conn(%d) failed: %d\n",
819                                                 op->o_log_prefix, i, lerr );
820
821                                         continue;
822                                 }
823
824                         } else {
825                                 candidates[ i ].sr_tag = META_NOT_CANDIDATE;
826                         }
827                 }
828         }
829
830 done:;
831         /* clear out meta_back_init_one_conn non-fatal errors */
832         rs->sr_err = LDAP_SUCCESS;
833         rs->sr_text = NULL;
834
835         if ( new_conn ) {
836                 
837                 /*
838                  * Inserts the newly created metaconn in the avl tree
839                  */
840                 ldap_pvt_thread_mutex_lock( &mi->mi_conn_mutex );
841                 err = avl_insert( &mi->mi_conntree, ( caddr_t )mc,
842                                 meta_back_conn_cmp, meta_back_conn_dup );
843
844 #if PRINT_CONNTREE > 0
845                 myprint( mi->mi_conntree );
846 #endif /* PRINT_CONNTREE */
847                 
848                 ldap_pvt_thread_mutex_unlock( &mi->mi_conn_mutex );
849
850                 Debug( LDAP_DEBUG_TRACE,
851                         "=>meta_back_getconn: conn %ld inserted\n",
852                         mc->mc_conn->c_connid, 0, 0 );
853                 
854                 /*
855                  * Err could be -1 in case a duplicate metaconn is inserted
856                  */
857                 if ( err != 0 ) {
858                         rs->sr_err = LDAP_OTHER;
859                         rs->sr_text = "Internal server error";
860                         meta_back_conn_free( mc );
861                         if ( sendok & LDAP_BACK_SENDERR ) {
862                                 send_ldap_result( op, rs );
863                                 rs->sr_text = NULL;
864                         }
865                         return NULL;
866                 }
867
868         } else {
869                 Debug( LDAP_DEBUG_TRACE,
870                         "=>meta_back_getconn: conn %ld fetched\n",
871                         mc->mc_conn->c_connid, 0, 0 );
872         }
873         
874         return mc;
875 }
876