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