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