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