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