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