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