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