]> git.sur5r.net Git - openldap/blob - servers/slapd/back-meta/conn.c
actually, if a connection is already in the AVL tree, use it if not binding; otherwis...
[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-2006 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_conndn_cmp
44  *
45  * compares two struct metaconn based on the value of the conn pointer
46  * and of the local DN; used by avl stuff
47  */
48 int
49 meta_back_conndn_cmp(
50         const void *c1,
51         const void *c2 )
52 {
53         metaconn_t      *mc1 = ( metaconn_t * )c1;
54         metaconn_t      *mc2 = ( metaconn_t * )c2;
55         int             rc;
56         
57         /* If local DNs don't match, it is definitely not a match */
58         /* For shared sessions, conn is NULL. Only explicitly
59          * bound sessions will have non-NULL conn.
60          */
61         rc = SLAP_PTRCMP( mc1->mc_conn, mc2->mc_conn );
62         if ( rc == 0 ) {
63                 rc = ber_bvcmp( &mc1->mc_local_ndn, &mc2->mc_local_ndn );
64         }
65
66         return rc;
67 }
68
69 /*
70  * meta_back_conndnmc_cmp
71  *
72  * compares two struct metaconn based on the value of the conn pointer,
73  * the local DN and the struct pointer; used by avl stuff
74  */
75 static int
76 meta_back_conndnmc_cmp(
77         const void *c1,
78         const void *c2 )
79 {
80         metaconn_t      *mc1 = ( metaconn_t * )c1;
81         metaconn_t      *mc2 = ( metaconn_t * )c2;
82         int             rc;
83         
84         /* If local DNs don't match, it is definitely not a match */
85         /* For shared sessions, conn is NULL. Only explicitly
86          * bound sessions will have non-NULL conn.
87          */
88         rc = SLAP_PTRCMP( mc1->mc_conn, mc2->mc_conn );
89         if ( rc == 0 ) {
90                 rc = ber_bvcmp( &mc1->mc_local_ndn, &mc2->mc_local_ndn );
91                 if ( rc == 0 ) {
92                         rc = SLAP_PTRCMP( mc1, mc2 );
93                 }
94         }
95
96         return rc;
97 }
98
99 /*
100  * meta_back_conn_cmp
101  *
102  * compares two struct metaconn based on the value of the conn pointer;
103  * used by avl stuff
104  */
105 int
106 meta_back_conn_cmp(
107         const void *c1,
108         const void *c2 )
109 {
110         metaconn_t      *mc1 = ( metaconn_t * )c1;
111         metaconn_t      *mc2 = ( metaconn_t * )c2;
112         
113         /* For shared sessions, conn is NULL. Only explicitly
114          * bound sessions will have non-NULL conn.
115          */
116         return SLAP_PTRCMP( mc1->mc_conn, mc2->mc_conn );
117 }
118
119 /*
120  * meta_back_conndn_dup
121  *
122  * returns -1 in case a duplicate struct metaconn has been inserted;
123  * used by avl stuff
124  */
125 int
126 meta_back_conndn_dup(
127         void *c1,
128         void *c2 )
129 {
130         metaconn_t      *mc1 = ( metaconn_t * )c1;
131         metaconn_t      *mc2 = ( metaconn_t * )c2;
132
133         /* Cannot have more than one shared session with same DN */
134         if ( mc1->mc_conn == mc2->mc_conn &&
135                 dn_match( &mc1->mc_local_ndn, &mc2->mc_local_ndn ) )
136         {
137                 return -1;
138         }
139                 
140         return 0;
141 }
142
143 /*
144  * Debug stuff (got it from libavl)
145  */
146 #if PRINT_CONNTREE > 0
147 static void
148 ravl_print( Avlnode *root, int depth )
149 {
150         int             i;
151         metaconn_t      *mc = (metaconn_t *)root->avl_data;
152         
153         if ( root == 0 ) {
154                 return;
155         }
156         
157         ravl_print( root->avl_right, depth + 1 );
158         
159         for ( i = 0; i < depth; i++ ) {
160                 printf( "    " );
161         }
162
163         printf( "c(%d%s%s) %d\n",
164                 LDAP_BACK_PCONN_ID( mc->mc_conn ),
165                 BER_BVISNULL( &mc->mc_local_ndn ) ? "" : ": ",
166                 BER_BVISNULL( &mc->mc_local_ndn ) ? "" : mc->mc_local_ndn.bv_val,
167                 root->avl_bf );
168         
169         ravl_print( root->avl_left, depth + 1 );
170 }
171
172 static void
173 myprint( Avlnode *root )
174 {
175         printf( "********\n" );
176         
177         if ( root == 0 ) {
178                 printf( "\tNULL\n" );
179         } else {
180                 ravl_print( root, 0 );
181         }
182         
183         printf( "********\n" );
184 }
185 #endif /* PRINT_CONNTREE */
186 /*
187  * End of debug stuff
188  */
189
190 /*
191  * metaconn_alloc
192  * 
193  * Allocates a connection structure, making room for all the referenced targets
194  */
195 static metaconn_t *
196 metaconn_alloc(
197         Operation               *op )
198 {
199         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
200         metaconn_t      *mc;
201         int             i, ntargets = mi->mi_ntargets;
202
203         assert( ntargets > 0 );
204
205         /* malloc all in one */
206         mc = ( metaconn_t * )ch_malloc( sizeof( metaconn_t )
207                         + sizeof( metasingleconn_t ) * ntargets );
208         if ( mc == NULL ) {
209                 return NULL;
210         }
211
212         for ( i = 0; i < ntargets; i++ ) {
213                 mc->mc_conns[ i ].msc_ld = NULL;
214                 BER_BVZERO( &mc->mc_conns[ i ].msc_bound_ndn );
215                 BER_BVZERO( &mc->mc_conns[ i ].msc_cred );
216                 mc->mc_conns[ i ].msc_mscflags = 0;
217                 mc->mc_conns[ i ].msc_info = mi;
218         }
219
220         BER_BVZERO( &mc->mc_local_ndn );
221         mc->msc_mscflags = 0;
222         mc->mc_authz_target = META_BOUND_NONE;
223         mc->mc_refcnt = 1;
224
225         return mc;
226 }
227
228 static void
229 meta_back_freeconn(
230         Operation       *op,
231         metaconn_t      *mc )
232 {
233         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
234
235         assert( mc != NULL );
236
237         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
238
239         if ( --mc->mc_refcnt == 0 ) {
240                 meta_back_conn_free( mc );
241         }
242
243         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
244 }
245
246 /*
247  * meta_back_init_one_conn
248  * 
249  * Initializes one connection
250  */
251 int
252 meta_back_init_one_conn(
253         Operation               *op,
254         SlapReply               *rs,
255         metatarget_t            *mt, 
256         metaconn_t              *mc,
257         int                     candidate,
258         int                     ispriv,
259         ldap_back_send_t        sendok )
260 {
261         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
262         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
263         int                     vers;
264         dncookie                dc;
265         int                     isauthz = ( candidate == mc->mc_authz_target );
266
267         /*
268          * Already init'ed
269          */
270         if ( msc->msc_ld != NULL ) {
271                 return rs->sr_err = LDAP_SUCCESS;
272         }
273
274         msc->msc_mscflags = 0;
275        
276         /*
277          * Attempts to initialize the connection to the target ds
278          */
279         rs->sr_err = ldap_initialize( &msc->msc_ld, mt->mt_uri );
280         if ( rs->sr_err != LDAP_SUCCESS ) {
281                 goto error_return;
282         }
283
284         /*
285          * Set LDAP version. This will always succeed: If the client
286          * bound with a particular version, then so can we.
287          */
288         vers = op->o_conn->c_protocol;
289         ldap_set_option( msc->msc_ld, LDAP_OPT_PROTOCOL_VERSION, &vers );
290
291         /* automatically chase referrals ("chase-referrals [{yes|no}]" statement) */
292         ldap_set_option( msc->msc_ld, LDAP_OPT_REFERRALS,
293                 LDAP_BACK_CHASE_REFERRALS( mi ) ? LDAP_OPT_ON : LDAP_OPT_OFF );
294
295 #ifdef HAVE_TLS
296         /* start TLS ("tls [try-]{start|propagate}" statement) */
297         if ( ( LDAP_BACK_USE_TLS( mi ) || ( op->o_conn->c_is_tls && LDAP_BACK_PROPAGATE_TLS( mi ) ) )
298                         && !ldap_is_ldaps_url( mt->mt_uri ) )
299         {
300 #ifdef SLAP_STARTTLS_ASYNCHRONOUS
301                 /*
302                  * use asynchronous StartTLS; in case, chase referral
303                  * FIXME: OpenLDAP does not return referral on StartTLS yet
304                  */
305                 int             msgid;
306
307                 rs->sr_err = ldap_start_tls( msc->msc_ld, NULL, NULL, &msgid );
308                 if ( rs->sr_err == LDAP_SUCCESS ) {
309                         LDAPMessage     *res = NULL;
310                         int             rc, nretries = mt->mt_nretries;
311                         struct timeval  tv;
312
313                         LDAP_BACK_TV_SET( &tv );
314
315 retry:;
316                         rc = ldap_result( msc->msc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
317                         if ( rc < 0 ) {
318                                 rs->sr_err = LDAP_OTHER;
319
320                         } else if ( rc == 0 ) {
321                                 if ( nretries != 0 ) {
322                                         if ( nretries > 0 ) {
323                                                 nretries--;
324                                         }
325                                         LDAP_BACK_TV_SET( &tv );
326                                         goto retry;
327                                 }
328                                 rs->sr_err = LDAP_OTHER;
329
330                         } else if ( rc == LDAP_RES_EXTENDED ) {
331                                 struct berval   *data = NULL;
332
333                                 rs->sr_err = ldap_parse_extended_result( msc->msc_ld, res,
334                                                 NULL, &data, 0 );
335                                 if ( rs->sr_err == LDAP_SUCCESS ) {
336                                         int             err;
337
338                                         rs->sr_err = ldap_parse_result( msc->msc_ld, res,
339                                                 &err, NULL, NULL, NULL, NULL, 1 );
340                                         res = NULL;
341
342                                         if ( rs->sr_err == LDAP_SUCCESS ) {
343                                                 rs->sr_err = err;
344                                         }
345                                         
346                                         /* FIXME: in case a referral 
347                                          * is returned, should we try
348                                          * using it instead of the 
349                                          * configured URI? */
350                                         if ( rs->sr_err == LDAP_SUCCESS ) {
351                                                 ldap_install_tls( msc->msc_ld );
352
353                                         } else if ( rs->sr_err == LDAP_REFERRAL ) {
354                                                 rs->sr_err = LDAP_OTHER;
355                                                 rs->sr_text = "unwilling to chase referral returned by Start TLS exop";
356                                         }
357
358                                         if ( data ) {
359                                                 if ( data->bv_val ) {
360                                                         ber_memfree( data->bv_val );
361                                                 }
362                                                 ber_memfree( data );
363                                         }
364                                 }
365
366                         } else {
367                                 rs->sr_err = LDAP_OTHER;
368                         }
369
370                         if ( res != NULL ) {
371                                 ldap_msgfree( res );
372                         }
373                 }
374 #else /* ! SLAP_STARTTLS_ASYNCHRONOUS */
375                 /*
376                  * use synchronous StartTLS
377                  */
378                 rs->sr_err = ldap_start_tls_s( msc->msc_ld, NULL, NULL );
379 #endif /* ! SLAP_STARTTLS_ASYNCHRONOUS */
380
381                 /* if StartTLS is requested, only attempt it if the URL
382                  * is not "ldaps://"; this may occur not only in case
383                  * of misconfiguration, but also when used in the chain 
384                  * overlay, where the "uri" can be parsed out of a referral */
385                 if ( rs->sr_err == LDAP_SERVER_DOWN
386                                 || ( rs->sr_err != LDAP_SUCCESS && LDAP_BACK_TLS_CRITICAL( mi ) ) )
387                 {
388                         ldap_unbind_ext_s( msc->msc_ld, NULL, NULL );
389                         goto error_return;
390                 }
391         }
392 #endif /* HAVE_TLS */
393
394         /*
395          * Set the network timeout if set
396          */
397         if ( mt->mt_network_timeout != 0 ) {
398                 struct timeval  network_timeout;
399
400                 network_timeout.tv_usec = 0;
401                 network_timeout.tv_sec = mt->mt_network_timeout;
402
403                 ldap_set_option( msc->msc_ld, LDAP_OPT_NETWORK_TIMEOUT,
404                                 (void *)&network_timeout );
405         }
406
407         /*
408          * If the connection DN is not null, an attempt to rewrite it is made
409          */
410
411         if ( ispriv ) {
412                 if ( !BER_BVISNULL( &mt->mt_pseudorootdn ) ) {
413                         ber_dupbv( &msc->msc_bound_ndn, &mt->mt_pseudorootdn );
414                         if ( !BER_BVISNULL( &mt->mt_pseudorootpw ) ) {
415                                 ber_dupbv( &msc->msc_cred, &mt->mt_pseudorootpw );
416                         }
417
418                 } else {
419                         ber_str2bv( "", 0, 1, &msc->msc_bound_ndn );
420                 }
421
422                 LDAP_BACK_CONN_ISPRIV_SET( msc );
423
424         } else {
425                 BER_BVZERO( &msc->msc_cred );
426                 BER_BVZERO( &msc->msc_bound_ndn );
427                 if ( !BER_BVISEMPTY( &op->o_ndn )
428                         && SLAP_IS_AUTHZ_BACKEND( op )
429                         && isauthz )
430                 {
431                         dc.target = mt;
432                         dc.conn = op->o_conn;
433                         dc.rs = rs;
434                         dc.ctx = "bindDN";
435                 
436                         /*
437                          * Rewrite the bind dn if needed
438                          */
439                         if ( ldap_back_dn_massage( &dc, &op->o_conn->c_dn,
440                                                 &msc->msc_bound_ndn ) )
441                         {
442                                 ldap_unbind_ext_s( msc->msc_ld, NULL, NULL );
443                                 goto error_return;
444                         }
445                         
446                         /* copy the DN idf needed */
447                         if ( msc->msc_bound_ndn.bv_val == op->o_conn->c_dn.bv_val ) {
448                                 ber_dupbv( &msc->msc_bound_ndn, &op->o_conn->c_dn );
449                         }
450
451                 } else {
452                         ber_str2bv( "", 0, 1, &msc->msc_bound_ndn );
453                 }
454         }
455
456         assert( !BER_BVISNULL( &msc->msc_bound_ndn ) );
457
458 error_return:;
459         if ( rs->sr_err == LDAP_SUCCESS ) {
460                 /*
461                  * Sets a cookie for the rewrite session
462                  */
463                 ( void )rewrite_session_init( mt->mt_rwmap.rwm_rw, op->o_conn );
464
465         } else {
466                 rs->sr_err = slap_map_api2result( rs );
467                 if ( sendok & LDAP_BACK_SENDERR ) {
468                         send_ldap_result( op, rs );
469                         rs->sr_text = NULL;
470                 }
471         }
472
473         return rs->sr_err;
474 }
475
476 /*
477  * meta_back_retry
478  * 
479  * Retries one connection
480  */
481 int
482 meta_back_retry(
483         Operation               *op,
484         SlapReply               *rs,
485         metaconn_t              **mcp,
486         int                     candidate,
487         ldap_back_send_t        sendok )
488 {
489         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
490         metatarget_t            *mt = &mi->mi_targets[ candidate ];
491         metaconn_t              *mc = *mcp;
492         metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
493         int                     rc = LDAP_UNAVAILABLE,
494                                 binding = LDAP_BACK_CONN_BINDING( msc );
495
496         ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
497
498         assert( mc->mc_refcnt > 0 );
499         if ( mc->mc_refcnt == 1 ) {
500                 char    buf[ SLAP_TEXT_BUFLEN ];
501
502                 snprintf( buf, sizeof( buf ),
503                         "retrying URI=\"%s\" DN=\"%s\"",
504                         mt->mt_uri,
505                         BER_BVISNULL( &msc->msc_bound_ndn ) ?
506                                 "" : msc->msc_bound_ndn.bv_val );
507                 Debug( LDAP_DEBUG_ANY,
508                         "%s meta_back_retry[%d]: %s.\n",
509                         op->o_log_prefix, candidate, buf );
510
511                 meta_clear_one_candidate( msc );
512                 LDAP_BACK_CONN_ISBOUND_CLEAR( msc );
513
514                 ( void )rewrite_session_delete( mt->mt_rwmap.rwm_rw, op->o_conn );
515
516                 /* mc here must be the regular mc, reset and ready for init */
517                 rc = meta_back_init_one_conn( op, rs, mt, mc, candidate,
518                         LDAP_BACK_CONN_ISPRIV( mc ), sendok );
519                 if ( binding ) {
520                         LDAP_BACK_CONN_BINDING_SET( msc );
521                 }
522
523                 if ( rc == LDAP_SUCCESS ) {
524                         rc = meta_back_single_dobind( op, rs, mcp, candidate,
525                                 sendok, mt->mt_nretries, 0 );
526                 }
527         }
528
529         if ( rc != LDAP_SUCCESS ) {
530                 if ( *mcp != NULL ) {
531                         if ( binding ) {
532                                 LDAP_BACK_CONN_BINDING_CLEAR( msc );
533                         }
534                         LDAP_BACK_CONN_TAINTED_SET( mc );
535                         meta_back_release_conn_lock( op, mc, 0 );
536                         *mcp = NULL;
537                 }
538
539                 if ( sendok ) {
540                         rs->sr_err = LDAP_UNAVAILABLE;
541                         rs->sr_text = NULL;
542                         send_ldap_result( op, rs );
543                 }
544         }
545
546         ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
547
548         return rc == LDAP_SUCCESS ? 1 : 0;
549 }
550
551 /*
552  * callback for unique candidate selection
553  */
554 static int
555 meta_back_conn_cb( Operation *op, SlapReply *rs )
556 {
557         assert( op->o_tag == LDAP_REQ_SEARCH );
558
559         switch ( rs->sr_type ) {
560         case REP_SEARCH:
561                 ((long *)op->o_callback->sc_private)[0] = (long)op->o_private;
562                 break;
563
564         case REP_SEARCHREF:
565         case REP_RESULT:
566                 break;
567
568         default:
569                 return rs->sr_err;
570         }
571
572         return 0;
573 }
574
575
576 static int
577 meta_back_get_candidate(
578         Operation       *op,
579         SlapReply       *rs,
580         struct berval   *ndn )
581 {
582         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
583         long            candidate;
584
585         /*
586          * tries to get a unique candidate
587          * (takes care of default target)
588          */
589         candidate = meta_back_select_unique_candidate( mi, ndn );
590
591         /*
592          * if any is found, inits the connection
593          */
594         if ( candidate == META_TARGET_NONE ) {
595                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
596                 rs->sr_text = "no suitable candidate target found";
597
598         } else if ( candidate == META_TARGET_MULTIPLE ) {
599                 Filter          f = { 0 };
600                 Operation       op2 = *op;
601                 SlapReply       rs2 = { 0 };
602                 slap_callback   cb2 = { 0 };
603                 int             rc;
604
605                 /* try to get a unique match for the request ndn
606                  * among the multiple candidates available */
607                 op2.o_tag = LDAP_REQ_SEARCH;
608                 op2.o_req_dn = *ndn;
609                 op2.o_req_ndn = *ndn;
610                 op2.ors_scope = LDAP_SCOPE_BASE;
611                 op2.ors_deref = LDAP_DEREF_NEVER;
612                 op2.ors_attrs = slap_anlist_no_attrs;
613                 op2.ors_attrsonly = 0;
614                 op2.ors_limit = NULL;
615                 op2.ors_slimit = 1;
616                 op2.ors_tlimit = SLAP_NO_LIMIT;
617
618                 f.f_choice = LDAP_FILTER_PRESENT;
619                 f.f_desc = slap_schema.si_ad_objectClass;
620                 op2.ors_filter = &f;
621                 BER_BVSTR( &op2.ors_filterstr, "(objectClass=*)" );
622
623                 op2.o_callback = &cb2;
624                 cb2.sc_response = meta_back_conn_cb;
625                 cb2.sc_private = (void *)&candidate;
626
627                 rc = op->o_bd->be_search( &op2, &rs2 );
628
629                 switch ( rs2.sr_err ) {
630                 case LDAP_SUCCESS:
631                 default:
632                         rs->sr_err = rs2.sr_err;
633                         break;
634
635                 case LDAP_SIZELIMIT_EXCEEDED:
636                         /* if multiple candidates can serve the operation,
637                          * and a default target is defined, and it is
638                          * a candidate, try using it (FIXME: YMMV) */
639                         if ( mi->mi_defaulttarget != META_DEFAULT_TARGET_NONE
640                                 && meta_back_is_candidate( &mi->mi_targets[ mi->mi_defaulttarget ].mt_nsuffix,
641                                                 mi->mi_targets[ mi->mi_defaulttarget ].mt_scope,
642                                                 mi->mi_targets[ mi->mi_defaulttarget ].mt_subtree_exclude,
643                                                 ndn, op->o_tag == LDAP_REQ_SEARCH ? op->ors_scope : LDAP_SCOPE_BASE ) )
644                         {
645                                 candidate = mi->mi_defaulttarget;
646                                 rs->sr_err = LDAP_SUCCESS;
647                                 rs->sr_text = NULL;
648
649                         } else {
650                                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
651                                 rs->sr_text = "cannot select unique candidate target";
652                         }
653                         break;
654                 }
655
656         } else {
657                 rs->sr_err = LDAP_SUCCESS;
658         }
659
660         return candidate;
661 }
662
663 static void     *meta_back_candidates_dummy;
664
665 static void
666 meta_back_candidates_keyfree(
667         void            *key,
668         void            *data )
669 {
670         metacandidates_t        *mc = (metacandidates_t *)data;
671
672         ber_memfree_x( mc->mc_candidates, NULL );
673         ber_memfree_x( data, NULL );
674 }
675
676 SlapReply *
677 meta_back_candidates_get( Operation *op )
678 {
679         metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
680         metacandidates_t        *mc;
681
682         if ( op->o_threadctx ) {
683                 void            *data = NULL;
684
685                 ldap_pvt_thread_pool_getkey( op->o_threadctx,
686                                 &meta_back_candidates_dummy, &data, NULL );
687                 mc = (metacandidates_t *)data;
688
689         } else {
690                 mc = mi->mi_candidates;
691         }
692
693         if ( mc == NULL ) {
694                 mc = ch_calloc( sizeof( metacandidates_t ), 1 );
695                 mc->mc_ntargets = mi->mi_ntargets;
696                 mc->mc_candidates = ch_calloc( sizeof( SlapReply ), mc->mc_ntargets );
697                 if ( op->o_threadctx ) {
698                         void            *data = NULL;
699
700                         data = (void *)mc;
701                         ldap_pvt_thread_pool_setkey( op->o_threadctx,
702                                         &meta_back_candidates_dummy, data,
703                                         meta_back_candidates_keyfree );
704
705                 } else {
706                         mi->mi_candidates = mc;
707                 }
708
709         } else if ( mc->mc_ntargets < mi->mi_ntargets ) {
710                 /* NOTE: in the future, may want to allow back-config
711                  * to add/remove targets from back-meta... */
712                 mc->mc_ntargets = mi->mi_ntargets;
713                 mc->mc_candidates = ch_realloc( mc->mc_candidates,
714                                 sizeof( SlapReply ) * mc->mc_ntargets );
715         }
716
717         return mc->mc_candidates;
718 }
719
720 /*
721  * meta_back_getconn
722  * 
723  * Prepares the connection structure
724  * 
725  * RATIONALE:
726  *
727  * - determine what DN is being requested:
728  *
729  *      op      requires candidate      checks
730  *
731  *      add     unique                  parent of o_req_ndn
732  *      bind    unique^*[/all]          o_req_ndn [no check]
733  *      compare unique^+                o_req_ndn
734  *      delete  unique                  o_req_ndn
735  *      modify  unique                  o_req_ndn
736  *      search  any                     o_req_ndn
737  *      modrdn  unique[, unique]        o_req_ndn[, orr_nnewSup]
738  *
739  * - for ops that require the candidate to be unique, in case of multiple
740  *   occurrences an internal search with sizeLimit=1 is performed
741  *   if a unique candidate can actually be determined.  If none is found,
742  *   the operation aborts; if multiple are found, the default target
743  *   is used if defined and candidate; otherwise the operation aborts.
744  *
745  * *^note: actually, the bind operation is handled much like a search;
746  *   i.e. the bind is broadcast to all candidate targets.
747  *
748  * +^note: actually, the compare operation is handled much like a search;
749  *   i.e. the compare is broadcast to all candidate targets, while checking
750  *   that exactly none (noSuchObject) or one (TRUE/FALSE/UNDEFINED) is
751  *   returned.
752  */
753 metaconn_t *
754 meta_back_getconn(
755         Operation               *op,
756         SlapReply               *rs,
757         int                     *candidate,
758         ldap_back_send_t        sendok )
759 {
760         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
761         metaconn_t      *mc = NULL,
762                         mc_curr = { 0 };
763         int             cached = META_TARGET_NONE,
764                         i = META_TARGET_NONE,
765                         err = LDAP_SUCCESS,
766                         new_conn = 0,
767                         ncandidates = 0;
768
769
770         meta_op_type    op_type = META_OP_REQUIRE_SINGLE;
771         enum            {
772                 META_DNTYPE_ENTRY,
773                 META_DNTYPE_PARENT,
774                 META_DNTYPE_NEWPARENT
775                         } dn_type = META_DNTYPE_ENTRY;
776         struct berval   ndn = op->o_req_ndn,
777                         pndn;
778
779         SlapReply       *candidates = meta_back_candidates_get( op );
780
781         /* Internal searches are privileged and shared. So is root. */
782         /* FIXME: there seem to be concurrency issues */
783         if ( op->o_do_not_cache || be_isroot( op ) ) {
784                 mc_curr.mc_local_ndn = op->o_bd->be_rootndn;
785                 LDAP_BACK_CONN_ISPRIV_SET( &mc_curr );
786                 mc_curr.mc_conn = LDAP_BACK_PCONN_SET( op );
787
788         } else {
789                 mc_curr.mc_local_ndn = op->o_ndn;
790
791                 /* Explicit binds must not be shared */
792                 if ( op->o_tag == LDAP_REQ_BIND || SLAP_IS_AUTHZ_BACKEND( op ) ) {
793                         mc_curr.mc_conn = op->o_conn;
794         
795                 } else {
796                         mc_curr.mc_conn = LDAP_BACK_PCONN_SET( op );
797                 }
798         }
799
800         /* Explicit Bind requests always get their own conn */
801         if ( !( sendok & LDAP_BACK_BINDING ) ) {
802                 /* Searches for a metaconn in the avl tree */
803 retry_lock:
804                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
805                 mc = (metaconn_t *)avl_find( mi->mi_conninfo.lai_tree, 
806                         (caddr_t)&mc_curr, meta_back_conndn_cmp );
807                 if ( mc ) {
808                         if ( ( mi->mi_conn_ttl != 0 && op->o_time > mc->mc_create_time + mi->mi_conn_ttl )
809                                 || ( mi->mi_idle_timeout != 0 && op->o_time > mc->mc_time + mi->mi_idle_timeout ) )
810                         {
811                                 /* don't let anyone else use this expired connection */
812                                 (void)avl_delete( &mi->mi_conninfo.lai_tree,
813                                         (caddr_t)mc, meta_back_conndnmc_cmp );
814                                 LDAP_BACK_CONN_TAINTED_SET( mc );
815
816                                 Debug( LDAP_DEBUG_TRACE, "%s meta_back_getconn: mc=%p conn=%ld expired.\n",
817                                         op->o_log_prefix, (void *)mc, LDAP_BACK_PCONN_ID( mc->mc_conn ) );
818                         }
819
820                         /* Don't reuse connections while they're still binding */
821                         if ( LDAP_BACK_CONN_BINDING( mc ) ) {
822                                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
823                                 ldap_pvt_thread_yield();
824                                 goto retry_lock;
825                         }
826
827                         mc->mc_refcnt++;
828                 }
829                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
830         }
831
832         switch ( op->o_tag ) {
833         case LDAP_REQ_ADD:
834                 /* if we go to selection, the entry must not exist,
835                  * and we must be able to resolve the parent */
836                 dn_type = META_DNTYPE_PARENT;
837                 dnParent( &ndn, &pndn );
838                 break;
839
840         case LDAP_REQ_MODRDN:
841                 /* if nnewSuperior is not NULL, it must resolve
842                  * to the same candidate as the req_ndn */
843                 if ( op->orr_nnewSup ) {
844                         dn_type = META_DNTYPE_NEWPARENT;
845                 }
846                 break;
847
848         case LDAP_REQ_BIND:
849                 /* if bound as rootdn, the backend must bind to all targets
850                  * with the administrative identity */
851                 if ( op->orb_method == LDAP_AUTH_SIMPLE && be_isroot_pw( op ) ) {
852                         op_type = META_OP_REQUIRE_ALL;
853                 }
854                 break;
855
856         case LDAP_REQ_DELETE:
857         case LDAP_REQ_MODIFY:
858                 /* just a unique candidate */
859                 break;
860
861         case LDAP_REQ_COMPARE:
862         case LDAP_REQ_SEARCH:
863                 /* allow multiple candidates for the searchBase */
864                 op_type = META_OP_ALLOW_MULTIPLE;
865                 break;
866
867         default:
868                 /* right now, just break (exop?) */
869                 break;
870         }
871
872         /*
873          * require all connections ...
874          */
875         if ( op_type == META_OP_REQUIRE_ALL ) {
876
877                 /* Looks like we didn't get a bind. Open a new session... */
878                 if ( mc == NULL ) {
879                         mc = metaconn_alloc( op );
880                         mc->mc_conn = mc_curr.mc_conn;
881                         ber_dupbv( &mc->mc_local_ndn, &mc_curr.mc_local_ndn );
882                         new_conn = 1;
883                         if ( sendok & LDAP_BACK_BINDING ) {
884                                 LDAP_BACK_CONN_BINDING_SET( mc );
885                         }
886                 }
887
888                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
889                         metatarget_t            *mt = &mi->mi_targets[ i ];
890
891                         /*
892                          * The target is activated; if needed, it is
893                          * also init'd
894                          */
895                         candidates[ i ].sr_err = meta_back_init_one_conn( op,
896                                 rs, mt, mc, i,
897                                 LDAP_BACK_CONN_ISPRIV( &mc_curr ), sendok );
898                         if ( candidates[ i ].sr_err == LDAP_SUCCESS ) {
899                                 candidates[ i ].sr_tag = META_CANDIDATE;
900                                 ncandidates++;
901         
902                         } else {
903                                 
904                                 /*
905                                  * FIXME: in case one target cannot
906                                  * be init'd, should the other ones
907                                  * be tried?
908                                  */
909                                 candidates[ i ].sr_tag = META_NOT_CANDIDATE;
910                                 err = candidates[ i ].sr_err;
911                                 continue;
912                         }
913                 }
914
915                 if ( ncandidates == 0 ) {
916                         if ( new_conn ) {
917                                 meta_back_freeconn( op, mc );
918
919                         } else {
920                                 meta_back_release_conn( op, mc );
921                         }
922
923                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
924                         rs->sr_text = "Unable to select valid candidates";
925
926                         if ( sendok & LDAP_BACK_SENDERR ) {
927                                 if ( rs->sr_err == LDAP_NO_SUCH_OBJECT ) {
928                                         rs->sr_matched = op->o_bd->be_suffix[ 0 ].bv_val;
929                                 }
930                                 send_ldap_result( op, rs );
931                                 rs->sr_text = NULL;
932                                 rs->sr_matched = NULL;
933                         }
934
935                         return NULL;
936                 }
937
938                 goto done;
939         }
940         
941         /*
942          * looks in cache, if any
943          */
944         if ( mi->mi_cache.ttl != META_DNCACHE_DISABLED ) {
945                 cached = i = meta_dncache_get_target( &mi->mi_cache, &op->o_req_ndn );
946         }
947
948         if ( op_type == META_OP_REQUIRE_SINGLE ) {
949                 metatarget_t            *mt = NULL;
950                 metasingleconn_t        *msc = NULL;
951
952                 int                     j;
953
954                 for ( j = 0; j < mi->mi_ntargets; j++ ) {
955                         candidates[ j ].sr_tag = META_NOT_CANDIDATE;
956                 }
957
958                 /*
959                  * tries to get a unique candidate
960                  * (takes care of default target)
961                  */
962                 if ( i == META_TARGET_NONE ) {
963                         i = meta_back_get_candidate( op, rs, &ndn );
964
965                         if ( rs->sr_err == LDAP_NO_SUCH_OBJECT && dn_type == META_DNTYPE_PARENT ) {
966                                 i = meta_back_get_candidate( op, rs, &pndn );
967                         }
968         
969                         if ( i < 0 || rs->sr_err != LDAP_SUCCESS ) {
970                                 if ( mc != NULL ) {
971                                         meta_back_release_conn( op, mc );
972                                 }
973
974                                 if ( sendok & LDAP_BACK_SENDERR ) {
975                                         if ( rs->sr_err == LDAP_NO_SUCH_OBJECT ) {
976                                                 rs->sr_matched = op->o_bd->be_suffix[ 0 ].bv_val;
977                                         }
978                                         send_ldap_result( op, rs );
979                                         rs->sr_text = NULL;
980                                         rs->sr_matched = NULL;
981                                 }
982                         
983                                 return NULL;
984                         }
985                 }
986
987                 if ( dn_type == META_DNTYPE_NEWPARENT && meta_back_get_candidate( op, rs, op->orr_nnewSup ) != i )
988                 {
989                         if ( mc != NULL ) {
990                                 meta_back_release_conn( op, mc );
991                         }
992
993                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
994                         rs->sr_text = "cross-target rename not supported";
995                         if ( sendok & LDAP_BACK_SENDERR ) {
996                                 send_ldap_result( op, rs );
997                                 rs->sr_text = NULL;
998                         }
999
1000                         return NULL;
1001                 }
1002
1003                 Debug( LDAP_DEBUG_TRACE,
1004         "==>meta_back_getconn: got target=%d for ndn=\"%s\" from cache\n",
1005                                 i, op->o_req_ndn.bv_val, 0 );
1006
1007                 if ( mc == NULL ) {
1008                         /* Retries searching for a metaconn in the avl tree
1009                          * the reason is that the connection might have been
1010                          * created by meta_back_get_candidate() */
1011                         if ( !( sendok & LDAP_BACK_BINDING ) ) {
1012 retry_lock2:;
1013                                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
1014                                 mc = (metaconn_t *)avl_find( mi->mi_conninfo.lai_tree, 
1015                                         (caddr_t)&mc_curr, meta_back_conndn_cmp );
1016                                 if ( mc != NULL ) {
1017                                         /* Don't reuse connections while they're still binding */
1018                                         if ( LDAP_BACK_CONN_BINDING( mc ) ) {
1019                                                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1020                                                 ldap_pvt_thread_yield();
1021                                                 goto retry_lock2;
1022                                         }
1023
1024                                         mc->mc_refcnt++;
1025                                 }
1026                                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1027                         }
1028
1029                         /* Looks like we didn't get a bind. Open a new session... */
1030                         if ( mc == NULL ) {
1031                                 mc = metaconn_alloc( op );
1032                                 mc->mc_conn = mc_curr.mc_conn;
1033                                 ber_dupbv( &mc->mc_local_ndn, &mc_curr.mc_local_ndn );
1034                                 new_conn = 1;
1035                                 if ( sendok & LDAP_BACK_BINDING ) {
1036                                         LDAP_BACK_CONN_BINDING_SET( mc );
1037                                 }
1038                         }
1039                 }
1040
1041                 /*
1042                  * Clear all other candidates
1043                  */
1044                 ( void )meta_clear_unused_candidates( op, i );
1045
1046                 mt = &mi->mi_targets[ i ];
1047                 msc = &mc->mc_conns[ i ];
1048
1049                 /*
1050                  * The target is activated; if needed, it is
1051                  * also init'd. In case of error, meta_back_init_one_conn
1052                  * sends the appropriate result.
1053                  */
1054                 err = meta_back_init_one_conn( op, rs, mt, mc, i,
1055                         LDAP_BACK_CONN_ISPRIV( &mc_curr ), sendok );
1056                 if ( err != LDAP_SUCCESS ) {
1057                         /*
1058                          * FIXME: in case one target cannot
1059                          * be init'd, should the other ones
1060                          * be tried?
1061                          */
1062                         candidates[ i ].sr_tag = META_NOT_CANDIDATE;
1063                         if ( new_conn ) {
1064                                 (void)meta_clear_one_candidate( msc );
1065                                 meta_back_freeconn( op, mc );
1066
1067                         } else {
1068                                 meta_back_release_conn( op, mc );
1069                         }
1070                         return NULL;
1071                 }
1072
1073                 candidates[ i ].sr_err = LDAP_SUCCESS;
1074                 candidates[ i ].sr_tag = META_CANDIDATE;
1075                 ncandidates++;
1076
1077                 if ( candidate ) {
1078                         *candidate = i;
1079                 }
1080
1081         /*
1082          * if no unique candidate ...
1083          */
1084         } else {
1085
1086                 /* Looks like we didn't get a bind. Open a new session... */
1087                 if ( mc == NULL ) {
1088                         mc = metaconn_alloc( op );
1089                         mc->mc_conn = mc_curr.mc_conn;
1090                         ber_dupbv( &mc->mc_local_ndn, &mc_curr.mc_local_ndn );
1091                         new_conn = 1;
1092                         if ( sendok & LDAP_BACK_BINDING ) {
1093                                 LDAP_BACK_CONN_BINDING_SET( mc );
1094                         }
1095                 }
1096
1097                 for ( i = 0; i < mi->mi_ntargets; i++ ) {
1098                         metatarget_t            *mt = &mi->mi_targets[ i ];
1099                         metasingleconn_t        *msc = &mc->mc_conns[ i ];
1100
1101                         if ( i == cached 
1102                                 || meta_back_is_candidate( &mt->mt_nsuffix,
1103                                                 mt->mt_scope,
1104                                                 mt->mt_subtree_exclude,
1105                                                 &op->o_req_ndn,
1106                                                 LDAP_SCOPE_SUBTREE ) )
1107                         {
1108
1109                                 /*
1110                                  * The target is activated; if needed, it is
1111                                  * also init'd
1112                                  */
1113                                 int lerr = meta_back_init_one_conn( op, rs,
1114                                                 mt, mc, i,
1115                                                 LDAP_BACK_CONN_ISPRIV( &mc_curr ),
1116                                                 sendok );
1117                                 if ( lerr == LDAP_SUCCESS ) {
1118                                         candidates[ i ].sr_tag = META_CANDIDATE;
1119                                         candidates[ i ].sr_err = LDAP_SUCCESS;
1120                                         ncandidates++;
1121
1122                                         Debug( LDAP_DEBUG_TRACE, "%s: meta_back_getconn[%d]\n",
1123                                                 op->o_log_prefix, i, 0 );
1124
1125                                 } else {
1126                                 
1127                                         /*
1128                                          * FIXME: in case one target cannot
1129                                          * be init'd, should the other ones
1130                                          * be tried?
1131                                          */
1132                                         if ( new_conn ) {
1133                                                 ( void )meta_clear_one_candidate( msc );
1134                                         }
1135                                         /* leave the target candidate, but record the error for later use */
1136                                         candidates[ i ].sr_err = lerr;
1137                                         err = lerr;
1138
1139                                         Debug( LDAP_DEBUG_ANY, "%s: meta_back_getconn[%d] failed: %d\n",
1140                                                 op->o_log_prefix, i, lerr );
1141
1142                                         continue;
1143                                 }
1144
1145                         } else {
1146                                 if ( new_conn ) {
1147                                         ( void )meta_clear_one_candidate( msc );
1148                                 }
1149                                 candidates[ i ].sr_tag = META_NOT_CANDIDATE;
1150                         }
1151                 }
1152
1153                 if ( ncandidates == 0 ) {
1154                         if ( new_conn ) {
1155                                 meta_back_freeconn( op, mc );
1156
1157                         } else {
1158                                 meta_back_release_conn( op, mc );
1159                         }
1160
1161                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
1162                         rs->sr_text = "Unable to select valid candidates";
1163
1164                         if ( sendok & LDAP_BACK_SENDERR ) {
1165                                 if ( rs->sr_err == LDAP_NO_SUCH_OBJECT ) {
1166                                         rs->sr_matched = op->o_bd->be_suffix[ 0 ].bv_val;
1167                                 }
1168                                 send_ldap_result( op, rs );
1169                                 rs->sr_text = NULL;
1170                                 rs->sr_matched = NULL;
1171                         }
1172
1173                         return NULL;
1174                 }
1175         }
1176
1177 done:;
1178         /* clear out meta_back_init_one_conn non-fatal errors */
1179         rs->sr_err = LDAP_SUCCESS;
1180         rs->sr_text = NULL;
1181
1182         /* touch the timestamp */
1183         if ( mi->mi_idle_timeout != 0 ) {
1184                 mc->mc_time = op->o_time;
1185         }
1186
1187         if ( new_conn ) {
1188                 if ( mi->mi_conn_ttl ) {
1189                         mc->mc_create_time = op->o_time;
1190                 }
1191
1192                 /*
1193                  * Inserts the newly created metaconn in the avl tree
1194                  */
1195                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
1196                 err = avl_insert( &mi->mi_conninfo.lai_tree, ( caddr_t )mc,
1197                                 meta_back_conndn_cmp, meta_back_conndn_dup );
1198
1199 #if PRINT_CONNTREE > 0
1200                 myprint( mi->mi_conninfo.lai_tree );
1201 #endif /* PRINT_CONNTREE */
1202                 
1203                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1204
1205                 /*
1206                  * Err could be -1 in case a duplicate metaconn is inserted
1207                  */
1208                 switch ( err ) {
1209                 case 0:
1210                         break;
1211
1212                 case -1:
1213                         if ( !( sendok & LDAP_BACK_BINDING ) ) {
1214                                 /* duplicate: free and try to get the newly created one */
1215                                 goto retry_lock;
1216                         }
1217                         LDAP_BACK_CONN_TAINTED_SET( mc );
1218                         break;
1219
1220                 default:
1221                         Debug( LDAP_DEBUG_ANY,
1222                                 "%s meta_back_getconn: candidates=%d conn=%ld insert failed\n",
1223                                 op->o_log_prefix, ncandidates,
1224                                 LDAP_BACK_PCONN_ID( mc->mc_conn ) );
1225                 
1226                         meta_back_freeconn( op, mc );
1227
1228                         rs->sr_err = LDAP_OTHER;
1229                         rs->sr_text = "proxy bind collision";
1230                         if ( sendok & LDAP_BACK_SENDERR ) {
1231                                 send_ldap_result( op, rs );
1232                                 rs->sr_text = NULL;
1233                         }
1234                         return NULL;
1235                 }
1236
1237                 Debug( LDAP_DEBUG_TRACE,
1238                         "%s meta_back_getconn: candidates=%d conn=%ld inserted\n",
1239                         op->o_log_prefix, ncandidates,
1240                         LDAP_BACK_PCONN_ID( mc->mc_conn ) );
1241
1242         } else {
1243                 Debug( LDAP_DEBUG_TRACE,
1244                         "%s meta_back_getconn: candidates=%d conn=%ld fetched\n",
1245                         op->o_log_prefix, ncandidates,
1246                         LDAP_BACK_PCONN_ID( mc->mc_conn ) );
1247         }
1248         
1249         return mc;
1250 }
1251
1252 void
1253 meta_back_release_conn_lock(
1254         Operation               *op,
1255         metaconn_t              *mc,
1256         int                     dolock )
1257 {
1258         metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
1259
1260         assert( mc != NULL );
1261
1262         if ( dolock ) {
1263                 ldap_pvt_thread_mutex_lock( &mi->mi_conninfo.lai_mutex );
1264         }
1265         assert( mc->mc_refcnt > 0 );
1266         mc->mc_refcnt--;
1267         LDAP_BACK_CONN_BINDING_CLEAR( mc );
1268         if ( LDAP_BACK_CONN_TAINTED( mc ) ) {
1269                 Debug( LDAP_DEBUG_TRACE, "%s meta_back_release_conn: mc=%p conn=%ld expired.\n",
1270                         op->o_log_prefix, (void *)mc, LDAP_BACK_PCONN_ID( mc->mc_conn ) );
1271                 (void)avl_delete( &mi->mi_conninfo.lai_tree,
1272                         ( caddr_t )mc, meta_back_conndnmc_cmp );
1273                 if ( mc->mc_refcnt == 0 ) {
1274                         meta_clear_candidates( op, mc );
1275                         meta_back_conn_free( mc );
1276                 }
1277         }
1278         if ( dolock ) {
1279                 ldap_pvt_thread_mutex_unlock( &mi->mi_conninfo.lai_mutex );
1280         }
1281 }