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