]> git.sur5r.net Git - openldap/blob - servers/slapd/back-ldap/bind.c
213d36b392c2860cd8938b319b5bad83e2fe5b57
[openldap] / servers / slapd / back-ldap / bind.c
1 /* bind.c - ldap backend bind function */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 1999-2006 The OpenLDAP Foundation.
6  * Portions Copyright 2000-2003 Pierangelo Masarati.
7  * Portions Copyright 1999-2003 Howard Chu.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted only as authorized by the OpenLDAP
12  * Public License.
13  *
14  * A copy of this license is available in the file LICENSE in the
15  * top-level directory of the distribution or, alternatively, at
16  * <http://www.OpenLDAP.org/license.html>.
17  */
18 /* ACKNOWLEDGEMENTS:
19  * This work was initially developed by Howard Chu for inclusion
20  * in OpenLDAP Software and subsequently enhanced by Pierangelo
21  * Masarati.
22  */
23
24 #include "portable.h"
25
26 #include <stdio.h>
27
28 #include <ac/errno.h>
29 #include <ac/socket.h>
30 #include <ac/string.h>
31
32 #define AVL_INTERNAL
33 #include "slap.h"
34 #include "back-ldap.h"
35
36 #include "lutil_ldap.h"
37
38 #ifndef PRINT_CONNTREE
39 #define PRINT_CONNTREE 0
40 #endif /* !PRINT_CONNTREE */
41
42 #define LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ       "2.16.840.1.113730.3.4.12"
43
44 #if PRINT_CONNTREE > 0
45 static void
46 ravl_print( Avlnode *root, int depth )
47 {
48         int             i;
49         ldapconn_t      *lc;
50         
51         if ( root == 0 ) {
52                 return;
53         }
54         
55         ravl_print( root->avl_right, depth+1 );
56         
57         for ( i = 0; i < depth; i++ ) {
58                 fprintf( stderr, "-" );
59         }
60
61         lc = root->avl_data;
62         fprintf( stderr, "lc=%p local=\"%s\" conn=%p %s refcnt=%d\n",
63                 (void *)lc,
64                 lc->lc_local_ndn.bv_val ? lc->lc_local_ndn.bv_val : "",
65                 (void *)lc->lc_conn,
66                 avl_bf2str( root->avl_bf ), lc->lc_refcnt );
67         
68         ravl_print( root->avl_left, depth+1 );
69 }
70
71 static void
72 myprint( Avlnode *root, char *msg )
73 {
74         fprintf( stderr, "========> %s\n", msg );
75         
76         if ( root == 0 ) {
77                 fprintf( stderr, "\tNULL\n" );
78
79         } else {
80                 ravl_print( root, 0 );
81         }
82         
83         fprintf( stderr, "<======== %s\n", msg );
84 }
85 #endif /* PRINT_CONNTREE */
86
87 static int
88 ldap_back_proxy_authz_bind( ldapconn_t *lc, Operation *op, SlapReply *rs, ldap_back_send_t sendok );
89
90 static int
91 ldap_back_prepare_conn( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok );
92
93 static int
94 ldap_back_conndnlc_cmp( const void *c1, const void *c2 );
95
96 int
97 ldap_back_bind( Operation *op, SlapReply *rs )
98 {
99         ldapinfo_t      *li = (ldapinfo_t *) op->o_bd->be_private;
100         ldapconn_t      *lc;
101
102         int rc = 0;
103         ber_int_t msgid;
104
105         lc = ldap_back_getconn( op, rs, LDAP_BACK_BIND_SERR );
106         if ( !lc ) {
107                 return rs->sr_err;
108         }
109
110         if ( !BER_BVISNULL( &lc->lc_bound_ndn ) ) {
111                 ch_free( lc->lc_bound_ndn.bv_val );
112                 BER_BVZERO( &lc->lc_bound_ndn );
113         }
114         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
115
116         /* method is always LDAP_AUTH_SIMPLE if we got here */
117         rs->sr_err = ldap_sasl_bind( lc->lc_ld, op->o_req_dn.bv_val,
118                         LDAP_SASL_SIMPLE,
119                         &op->orb_cred, op->o_ctrls, NULL, &msgid );
120         rc = ldap_back_op_result( lc, op, rs, msgid,
121                 li->li_timeout[ SLAP_OP_BIND ],
122                 LDAP_BACK_BIND_SERR );
123         if ( rc == LDAP_SUCCESS ) {
124                 /* If defined, proxyAuthz will be used also when
125                  * back-ldap is the authorizing backend; for this
126                  * purpose, after a successful bind the connection
127                  * is trashed and further operations will use
128                  * a default connections with identity assertion */
129                 /* NOTE: use with care */
130                 if ( li->li_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) {
131                         LDAP_BACK_CONN_TAINTED_SET( lc );
132                         ldap_back_release_conn( op, rs, lc );
133
134                         return( rc );
135                 }
136
137                 /* rebind is now done inside ldap_back_proxy_authz_bind()
138                  * in case of success */
139                 LDAP_BACK_CONN_ISBOUND_SET( lc );
140                 ber_dupbv( &lc->lc_bound_ndn, &op->o_req_ndn );
141
142                 if ( LDAP_BACK_SAVECRED( li ) ) {
143                         if ( !BER_BVISNULL( &lc->lc_cred ) ) {
144                                 memset( lc->lc_cred.bv_val, 0,
145                                                 lc->lc_cred.bv_len );
146                         }
147                         ber_bvreplace( &lc->lc_cred, &op->orb_cred );
148                         ldap_set_rebind_proc( lc->lc_ld, li->li_rebind_f, lc );
149                 }
150         }
151
152         assert( lc->lc_binding == 1 );
153         lc->lc_binding = 0;
154
155         /* must re-insert if local DN changed as result of bind */
156         if ( !LDAP_BACK_CONN_ISBOUND( lc )
157                 || ( LDAP_BACK_CONN_ISBOUND( lc )
158                         && !dn_match( &op->o_req_ndn, &lc->lc_local_ndn ) ) )
159         {
160                 int             lerr = -1;
161                 ldapconn_t      *tmplc;
162
163                 /* wait for all other ops to release the connection */
164 retry_lock:;
165                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
166                 if ( lc->lc_refcnt > 1 ) {
167                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
168                         ldap_pvt_thread_yield();
169                         goto retry_lock;
170                 }
171
172                 assert( lc->lc_refcnt == 1 );
173                 tmplc = avl_delete( &li->li_conninfo.lai_tree, (caddr_t)lc,
174                                 ldap_back_conndnlc_cmp );
175                 assert( tmplc == NULL || lc == tmplc );
176
177                 /* delete all cached connections with the current connection */
178                 if ( LDAP_BACK_SINGLECONN( li ) ) {
179                         while ( ( tmplc = avl_delete( &li->li_conninfo.lai_tree, (caddr_t)lc, ldap_back_conn_cmp ) ) != NULL )
180                         {
181                                 Debug( LDAP_DEBUG_TRACE,
182                                         "=>ldap_back_bind: destroying conn %ld (refcnt=%u)\n",
183                                         LDAP_BACK_PCONN_ID( lc->lc_conn ), lc->lc_refcnt, 0 );
184
185                                 if ( tmplc->lc_refcnt != 0 ) {
186                                         /* taint it */
187                                         LDAP_BACK_CONN_TAINTED_SET( tmplc );
188
189                                 } else {
190                                         /*
191                                          * Needs a test because the handler may be corrupted,
192                                          * and calling ldap_unbind on a corrupted header results
193                                          * in a segmentation fault
194                                          */
195                                         ldap_back_conn_free( tmplc );
196                                 }
197                         }
198                 }
199
200                 if ( LDAP_BACK_CONN_ISBOUND( lc ) ) {
201                         ber_bvreplace( &lc->lc_local_ndn, &op->o_req_ndn );
202                         if ( be_isroot_dn( op->o_bd, &op->o_req_ndn ) ) {
203                                 lc->lc_conn = LDAP_BACK_PCONN_SET( op );
204                         }
205                         lerr = avl_insert( &li->li_conninfo.lai_tree, (caddr_t)lc,
206                                 ldap_back_conndn_cmp, ldap_back_conndn_dup );
207                 }
208
209 #if PRINT_CONNTREE > 0
210                 myprint( li->li_conninfo.lai_tree, "ldap_back_bind" );
211 #endif /* PRINT_CONNTREE */
212         
213                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
214                 switch ( lerr ) {
215                 case 0:
216                         break;
217
218                 case -1:
219                         /* duplicate; someone else successfully bound
220                          * on the same connection with the same identity;
221                          * we can do this because lc_refcnt == 1 */
222                         ldap_back_conn_free( lc );
223                         lc = NULL;
224                 }
225         }
226
227         if ( lc != NULL ) {
228                 ldap_back_release_conn( op, rs, lc );
229         }
230
231         return( rc );
232 }
233
234 /*
235  * ldap_back_conndn_cmp
236  *
237  * compares two ldapconn_t based on the value of the conn pointer
238  * and of the local DN; used by avl stuff for insert, lookup
239  * and direct delete
240  */
241 int
242 ldap_back_conndn_cmp( const void *c1, const void *c2 )
243 {
244         const ldapconn_t        *lc1 = (const ldapconn_t *)c1;
245         const ldapconn_t        *lc2 = (const ldapconn_t *)c2;
246         int rc;
247
248         /* If local DNs don't match, it is definitely not a match */
249         /* For shared sessions, conn is NULL. Only explicitly
250          * bound sessions will have non-NULL conn.
251          */
252         rc = SLAP_PTRCMP( lc1->lc_conn, lc2->lc_conn );
253         if ( rc == 0 ) {
254                 rc = ber_bvcmp( &lc1->lc_local_ndn, &lc2->lc_local_ndn );
255         }
256
257         return rc;
258 }
259
260 /*
261  * ldap_back_conndnlc_cmp
262  *
263  * compares two ldapconn_t based on the value of the conn pointer,
264  * the local DN and the lc pointer; used by avl stuff for insert, lookup
265  * and direct delete
266  */
267 static int
268 ldap_back_conndnlc_cmp( const void *c1, const void *c2 )
269 {
270         const ldapconn_t        *lc1 = (const ldapconn_t *)c1;
271         const ldapconn_t        *lc2 = (const ldapconn_t *)c2;
272         int rc;
273
274         /* If local DNs don't match, it is definitely not a match */
275         /* For shared sessions, conn is NULL. Only explicitly
276          * bound sessions will have non-NULL conn.
277          */
278         rc = SLAP_PTRCMP( lc1->lc_conn, lc2->lc_conn );
279         if ( rc == 0 ) {
280                 rc = ber_bvcmp( &lc1->lc_local_ndn, &lc2->lc_local_ndn );
281                 if ( rc == 0 ) {
282                         rc = SLAP_PTRCMP( lc1, lc2 );
283                 }
284         }
285
286         return rc;
287 }
288
289 /*
290  * ldap_back_conn_cmp
291  *
292  * compares two ldapconn_t based on the value of the conn pointer;
293  * used by avl stuff for delete of all conns with the same connid
294  */
295 int
296 ldap_back_conn_cmp( const void *c1, const void *c2 )
297 {
298         const ldapconn_t        *lc1 = (const ldapconn_t *)c1;
299         const ldapconn_t        *lc2 = (const ldapconn_t *)c2;
300
301         /* For shared sessions, conn is NULL. Only explicitly
302          * bound sessions will have non-NULL conn.
303          */
304         return SLAP_PTRCMP( lc1->lc_conn, lc2->lc_conn );
305 }
306
307 /*
308  * ldap_back_conndn_dup
309  *
310  * returns -1 in case a duplicate ldapconn_t has been inserted;
311  * used by avl stuff
312  */
313 int
314 ldap_back_conndn_dup( void *c1, void *c2 )
315 {
316         ldapconn_t      *lc1 = (ldapconn_t *)c1;
317         ldapconn_t      *lc2 = (ldapconn_t *)c2;
318
319         /* Cannot have more than one shared session with same DN */
320         if ( lc1->lc_conn == lc2->lc_conn &&
321                 dn_match( &lc1->lc_local_ndn, &lc2->lc_local_ndn ) )
322         {
323                 return -1;
324         }
325                 
326         return 0;
327 }
328
329 int
330 ldap_back_freeconn( Operation *op, ldapconn_t *lc, int dolock )
331 {
332         ldapinfo_t      *li = (ldapinfo_t *) op->o_bd->be_private;
333         ldapconn_t      *tmplc;
334
335         if ( dolock ) {
336                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
337         }
338
339         tmplc = avl_delete( &li->li_conninfo.lai_tree, (caddr_t)lc,
340                         ldap_back_conndnlc_cmp );
341         assert( LDAP_BACK_CONN_TAINTED( lc ) || tmplc == lc );
342         if ( lc->lc_refcnt == 0 ) {
343                 ldap_back_conn_free( (void *)lc );
344         }
345
346         if ( dolock ) {
347                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
348         }
349
350         return 0;
351 }
352
353 #ifdef HAVE_TLS
354 static int
355 ldap_back_start_tls(
356         LDAP            *ld,
357         int             protocol,
358         int             *is_tls,
359         const char      *url,
360         unsigned        flags,
361         int             retries,
362         const char      **text )
363 {
364         int             rc = LDAP_SUCCESS;
365         ldapinfo_t      dummy;
366
367         /* this is ridiculous... */
368         dummy.li_flags = flags;
369
370         /* start TLS ("tls-[try-]{start,propagate}" statements) */
371         if ( ( LDAP_BACK_USE_TLS( &dummy ) || ( *is_tls && LDAP_BACK_PROPAGATE_TLS( &dummy ) ) )
372                                 && !ldap_is_ldaps_url( url ) )
373         {
374 #ifdef SLAP_STARTTLS_ASYNCHRONOUS
375                 /*
376                  * use asynchronous StartTLS
377                  * in case, chase referral (not implemented yet)
378                  */
379                 int             msgid;
380
381                 if ( protocol == 0 ) {
382                         ldap_get_option( ld, LDAP_OPT_PROTOCOL_VERSION,
383                                         (void *)&protocol );
384                 }
385
386                 if ( protocol < LDAP_VERSION3 ) {
387                         /* we should rather bail out... */
388                         rc = LDAP_UNWILLING_TO_PERFORM;
389                         *text = "invalid protocol version";
390                 }
391
392                 if ( rc == LDAP_SUCCESS ) {
393                         rc = ldap_start_tls( ld, NULL, NULL, &msgid );
394                 }
395
396                 if ( rc == LDAP_SUCCESS ) {
397                         LDAPMessage     *res = NULL;
398                         struct timeval  tv;
399
400                         LDAP_BACK_TV_SET( &tv );
401
402 retry:;
403                         rc = ldap_result( ld, msgid, LDAP_MSG_ALL, &tv, &res );
404                         if ( rc < 0 ) {
405                                 rc = LDAP_UNAVAILABLE;
406
407                         } else if ( rc == 0 ) {
408                                 if ( retries != LDAP_BACK_RETRY_NEVER ) {
409                                         ldap_pvt_thread_yield();
410                                         if ( retries > 0 ) {
411                                                 retries--;
412                                         }
413                                         LDAP_BACK_TV_SET( &tv );
414                                         goto retry;
415                                 }
416                                 rc = LDAP_UNAVAILABLE;
417
418                         } else if ( rc == LDAP_RES_EXTENDED ) {
419                                 struct berval   *data = NULL;
420
421                                 rc = ldap_parse_extended_result( ld, res,
422                                                 NULL, &data, 0 );
423                                 if ( rc == LDAP_SUCCESS ) {
424                                         int err;
425                                         rc = ldap_parse_result( ld, res, &err,
426                                                 NULL, NULL, NULL, NULL, 1 );
427                                         if ( rc == LDAP_SUCCESS ) {
428                                                 rc = err;
429                                         }
430                                         res = NULL;
431                                         
432                                         /* FIXME: in case a referral 
433                                          * is returned, should we try
434                                          * using it instead of the 
435                                          * configured URI? */
436                                         if ( rc == LDAP_SUCCESS ) {
437                                                 rc = ldap_install_tls( ld );
438
439                                         } else if ( rc == LDAP_REFERRAL ) {
440                                                 rc = LDAP_UNWILLING_TO_PERFORM;
441                                                 *text = "unwilling to chase referral returned by Start TLS exop";
442                                         }
443
444                                         if ( data ) {
445                                                 if ( data->bv_val ) {
446                                                         ber_memfree( data->bv_val );
447                                                 }
448                                                 ber_memfree( data );
449                                         }
450                                 }
451
452                         } else {
453                                 rc = LDAP_OTHER;
454                         }
455
456                         if ( res != NULL ) {
457                                 ldap_msgfree( res );
458                         }
459                 }
460 #else /* ! SLAP_STARTTLS_ASYNCHRONOUS */
461                 /*
462                  * use synchronous StartTLS
463                  */
464                 rc = ldap_start_tls_s( ld, NULL, NULL );
465 #endif /* ! SLAP_STARTTLS_ASYNCHRONOUS */
466
467                 /* if StartTLS is requested, only attempt it if the URL
468                  * is not "ldaps://"; this may occur not only in case
469                  * of misconfiguration, but also when used in the chain 
470                  * overlay, where the "uri" can be parsed out of a referral */
471                 switch ( rc ) {
472                 case LDAP_SUCCESS:
473                         *is_tls = 1;
474                         break;
475
476                 case LDAP_SERVER_DOWN:
477                         break;
478
479                 default:
480                         if ( LDAP_BACK_TLS_CRITICAL( &dummy ) ) {
481                                 *text = "could not start TLS";
482                                 break;
483                         }
484
485                         /* in case Start TLS is not critical */
486                         *is_tls = 0;
487                         rc = LDAP_SUCCESS;
488                         break;
489                 }
490
491         } else {
492                 *is_tls = 0;
493         }
494
495         return rc;
496 }
497 #endif /* HAVE_TLS */
498
499 static int
500 ldap_back_prepare_conn( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
501 {
502         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
503         int             version;
504         LDAP            *ld = NULL;
505 #ifdef HAVE_TLS
506         int             is_tls = op->o_conn->c_is_tls;
507         time_t          lc_time = (time_t)(-1);
508 #endif /* HAVE_TLS */
509
510         assert( lcp != NULL );
511
512         ldap_pvt_thread_mutex_lock( &li->li_uri_mutex );
513         rs->sr_err = ldap_initialize( &ld, li->li_uri );
514         ldap_pvt_thread_mutex_unlock( &li->li_uri_mutex );
515         if ( rs->sr_err != LDAP_SUCCESS ) {
516                 goto error_return;
517         }
518
519         if ( li->li_urllist_f ) {
520                 ldap_set_urllist_proc( ld, li->li_urllist_f, li->li_urllist_p );
521         }
522
523         /* Set LDAP version. This will always succeed: If the client
524          * bound with a particular version, then so can we.
525          */
526         if ( li->li_version != 0 ) {
527                 version = li->li_version;
528
529         } else if ( op->o_protocol != 0 ) {
530                 version = op->o_protocol;
531
532         } else {
533                 /* assume it's an internal op; set to LDAPv3 */
534                 version = LDAP_VERSION3;
535         }
536         ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, (const void *)&version );
537
538         /* automatically chase referrals ("chase-referrals [{yes|no}]" statement) */
539         ldap_set_option( ld, LDAP_OPT_REFERRALS,
540                 LDAP_BACK_CHASE_REFERRALS( li ) ? LDAP_OPT_ON : LDAP_OPT_OFF );
541
542         if ( li->li_network_timeout > 0 ) {
543                 struct timeval          tv;
544
545                 tv.tv_sec = li->li_network_timeout;
546                 tv.tv_usec = 0;
547                 ldap_set_option( ld, LDAP_OPT_NETWORK_TIMEOUT, (const void *)&tv );
548         }
549
550 #ifdef HAVE_TLS
551         ldap_pvt_thread_mutex_lock( &li->li_uri_mutex );
552         rs->sr_err = ldap_back_start_tls( ld, op->o_protocol, &is_tls,
553                         li->li_uri, li->li_flags, li->li_nretries, &rs->sr_text );
554         ldap_pvt_thread_mutex_unlock( &li->li_uri_mutex );
555         if ( rs->sr_err != LDAP_SUCCESS ) {
556                 ldap_unbind_ext( ld, NULL, NULL );
557                 goto error_return;
558
559         } else if ( li->li_idle_timeout ) {
560                 /* only touch when activity actually took place... */
561                 lc_time = op->o_time;
562         }
563 #endif /* HAVE_TLS */
564
565         if ( *lcp == NULL ) {
566                 *lcp = (ldapconn_t *)ch_calloc( 1, sizeof( ldapconn_t ) );
567                 (*lcp)->lc_flags = li->li_flags;
568         }
569         (*lcp)->lc_ld = ld;
570         (*lcp)->lc_refcnt = 1;
571         (*lcp)->lc_binding = 1;
572 #ifdef HAVE_TLS
573         if ( is_tls ) {
574                 LDAP_BACK_CONN_ISTLS_SET( *lcp );
575         } else {
576                 LDAP_BACK_CONN_ISTLS_CLEAR( *lcp );
577         }
578         if ( lc_time != (time_t)(-1) ) {
579                 (*lcp)->lc_time = lc_time;
580         }
581 #endif /* HAVE_TLS */
582
583 error_return:;
584         if ( rs->sr_err != LDAP_SUCCESS ) {
585                 rs->sr_err = slap_map_api2result( rs );
586                 if ( sendok & LDAP_BACK_SENDERR ) {
587                         if ( rs->sr_text == NULL ) {
588                                 rs->sr_text = "ldap_initialize() failed";
589                         }
590                         send_ldap_result( op, rs );
591                         rs->sr_text = NULL;
592                 }
593
594         } else {
595                 if ( li->li_conn_ttl > 0 ) {
596                         (*lcp)->lc_create_time = op->o_time;
597                 }
598         }
599
600         return rs->sr_err;
601 }
602
603 ldapconn_t *
604 ldap_back_getconn( Operation *op, SlapReply *rs, ldap_back_send_t sendok )
605 {
606         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
607         ldapconn_t      *lc = NULL,
608                         lc_curr = { 0 };
609         int             refcnt = 1, binding = 1;
610
611         /* if the server is quarantined, and
612          * - the current interval did not expire yet, or
613          * - no more retries should occur,
614          * don't return the connection */
615         if ( li->li_isquarantined ) {
616                 slap_retry_info_t       *ri = &li->li_quarantine;
617                 int                     dont_retry = 1;
618
619                 ldap_pvt_thread_mutex_lock( &li->li_quarantine_mutex );
620                 if ( li->li_isquarantined == LDAP_BACK_FQ_YES ) {
621                         dont_retry = ( ri->ri_num[ ri->ri_idx ] == SLAP_RETRYNUM_TAIL
622                                 || slap_get_time() < ri->ri_last + ri->ri_interval[ ri->ri_idx ] );
623                         if ( !dont_retry ) {
624                                 Debug( LDAP_DEBUG_ANY,
625                                         "%s: ldap_back_getconn quarantine "
626                                         "retry block #%d try #%d.\n",
627                                         op->o_log_prefix, ri->ri_idx, ri->ri_count );
628                                 li->li_isquarantined = LDAP_BACK_FQ_RETRYING;
629                         }
630                 }
631                 ldap_pvt_thread_mutex_unlock( &li->li_quarantine_mutex );
632
633                 if ( dont_retry ) {
634                         rs->sr_err = LDAP_UNAVAILABLE;
635                         if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
636                                 send_ldap_result( op, rs );
637                         }
638                         return NULL;
639                 }
640         }
641
642         /* Internal searches are privileged and shared. So is root. */
643         if ( op->o_do_not_cache || be_isroot( op ) ) {
644                 LDAP_BACK_CONN_ISPRIV_SET( &lc_curr );
645                 lc_curr.lc_local_ndn = op->o_bd->be_rootndn;
646                 lc_curr.lc_conn = LDAP_BACK_PCONN_SET( op );
647
648         } else {
649                 lc_curr.lc_local_ndn = op->o_ndn;
650                 /* Explicit binds must not be shared */
651                 if ( op->o_tag == LDAP_REQ_BIND || SLAP_IS_AUTHZ_BACKEND( op ) ) {
652                         lc_curr.lc_conn = op->o_conn;
653         
654                 } else {
655                         lc_curr.lc_conn = LDAP_BACK_PCONN_SET( op );
656                 }
657         }
658
659         /* Explicit Bind requests always get their own conn */
660         if ( !( sendok & LDAP_BACK_BINDING ) ) {
661                 /* Searches for a ldapconn in the avl tree */
662 retry_lock:
663                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
664
665                 lc = (ldapconn_t *)avl_find( li->li_conninfo.lai_tree, 
666                                 (caddr_t)&lc_curr, ldap_back_conndn_cmp );
667                 if ( lc != NULL ) {
668                         /* Don't reuse connections while they're still binding */
669                         if ( LDAP_BACK_CONN_BINDING( lc ) ) {
670                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
671                                 ldap_pvt_thread_yield();
672                                 goto retry_lock;
673                         }
674
675                         refcnt = ++lc->lc_refcnt;
676                         binding = ++lc->lc_binding;
677                 }
678                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
679         }
680
681         /* Looks like we didn't get a bind. Open a new session... */
682         if ( lc == NULL ) {
683                 if ( ldap_back_prepare_conn( &lc, op, rs, sendok ) != LDAP_SUCCESS ) {
684                         return NULL;
685                 }
686                 if ( sendok & LDAP_BACK_BINDING ) {
687                         LDAP_BACK_CONN_BINDING_SET( lc );
688                 }
689                 lc->lc_conn = lc_curr.lc_conn;
690                 ber_dupbv( &lc->lc_local_ndn, &lc_curr.lc_local_ndn );
691
692                 if ( LDAP_BACK_CONN_ISPRIV( &lc_curr ) ) {
693                         ber_dupbv( &lc->lc_cred, &li->li_acl_passwd );
694                         ber_dupbv( &lc->lc_bound_ndn, &li->li_acl_authcDN );
695                         LDAP_BACK_CONN_ISPRIV_SET( lc );
696
697                 } else {
698                         BER_BVZERO( &lc->lc_cred );
699                         BER_BVZERO( &lc->lc_bound_ndn );
700                         if ( !BER_BVISEMPTY( &op->o_ndn )
701                                 && SLAP_IS_AUTHZ_BACKEND( op ) )
702                         {
703                                 ber_dupbv( &lc->lc_bound_ndn, &op->o_ndn );
704                         }
705                 }
706
707 #ifdef HAVE_TLS
708                 /* if start TLS failed but it was not mandatory,
709                  * check if the non-TLS connection was already
710                  * in cache; in case, destroy the newly created
711                  * connection and use the existing one */
712                 if ( lc->lc_conn == LDAP_BACK_PCONN_TLS
713                                 && !ldap_tls_inplace( lc->lc_ld ) )
714                 {
715                         ldapconn_t *tmplc;
716                         
717                         lc_curr.lc_conn = LDAP_BACK_PCONN;
718                         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
719                         tmplc = (ldapconn_t *)avl_find( li->li_conninfo.lai_tree, 
720                                         (caddr_t)&lc_curr, ldap_back_conndn_cmp );
721                         if ( tmplc != NULL ) {
722                                 refcnt = ++tmplc->lc_refcnt;
723                                 binding = ++tmplc->lc_binding;
724                                 ldap_back_conn_free( lc );
725                                 lc = tmplc;
726                         }
727                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
728
729                         if ( tmplc != NULL ) {
730                                 goto done;
731                         }
732                 }
733 #endif /* HAVE_TLS */
734
735                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
736
737                 /* Inserts the newly created ldapconn in the avl tree */
738                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
739
740                 assert( lc->lc_refcnt == 1 );
741                 assert( lc->lc_binding == 1 );
742                 rs->sr_err = avl_insert( &li->li_conninfo.lai_tree, (caddr_t)lc,
743                         ldap_back_conndn_cmp, ldap_back_conndn_dup );
744
745 #if PRINT_CONNTREE > 0
746                 myprint( li->li_conninfo.lai_tree, "ldap_back_getconn" );
747 #endif /* PRINT_CONNTREE */
748         
749                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
750
751                 Debug( LDAP_DEBUG_TRACE,
752                         "=>ldap_back_getconn: conn %p inserted refcnt=%u binding=%u\n",
753                         (void *)lc, refcnt, binding );
754         
755                 /* Err could be -1 in case a duplicate ldapconn is inserted */
756                 switch ( rs->sr_err ) {
757                 case 0:
758                         break;
759
760                 case -1:
761                         if ( !( sendok & LDAP_BACK_BINDING ) ) {
762                                 /* duplicate: free and try to get the newly created one */
763                                 goto retry_lock;
764                         }
765                         /* taint connection, so that it'll be freed when released */
766                         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
767                         (void *)avl_delete( &li->li_conninfo.lai_tree, (caddr_t)lc,
768                                         ldap_back_conndnlc_cmp );
769                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
770                         LDAP_BACK_CONN_TAINTED_SET( lc );
771                         break;
772
773                 default:
774                         ldap_back_conn_free( lc );
775                         rs->sr_err = LDAP_OTHER;
776                         rs->sr_text = "proxy bind collision";
777                         if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
778                                 send_ldap_result( op, rs );
779                                 rs->sr_text = NULL;
780                         }
781                         return NULL;
782                 }
783
784         } else {
785                 int     expiring = 0;
786
787                 if ( ( li->li_idle_timeout != 0 && op->o_time > lc->lc_time + li->li_idle_timeout )
788                         || ( li->li_conn_ttl != 0 && op->o_time > lc->lc_create_time + li->li_conn_ttl ) )
789                 {
790                         expiring = 1;
791
792                         /* let it be used, but taint/delete it so that 
793                          * no-one else can look it up any further */
794                         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
795                         (void *)avl_delete( &li->li_conninfo.lai_tree, (caddr_t)lc,
796                                         ldap_back_conndnlc_cmp );
797                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
798                         LDAP_BACK_CONN_TAINTED_SET( lc );
799                 }
800
801                 if ( LogTest( LDAP_DEBUG_TRACE ) ) {
802                         char    buf[ SLAP_TEXT_BUFLEN ];
803
804                         snprintf( buf, sizeof( buf ),
805                                 "conn %p fetched refcnt=%u binding=%u%s",
806                                 (void *)lc, refcnt, binding, expiring ? " expiring" : "" );
807                         Debug( LDAP_DEBUG_TRACE,
808                                 "=>ldap_back_getconn: %s.\n", buf, 0, 0 );
809                 }
810         }
811
812 #ifdef HAVE_TLS
813 done:;
814 #endif /* HAVE_TLS */
815
816         return lc;
817 }
818
819 void
820 ldap_back_release_conn_lock(
821         Operation               *op,
822         SlapReply               *rs,
823         ldapconn_t              **lcp,
824         int                     dolock )
825 {
826         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
827
828         ldapconn_t      *lc = *lcp;
829
830         if ( dolock ) {
831                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
832         }
833         assert( lc->lc_refcnt > 0 );
834         LDAP_BACK_CONN_BINDING_CLEAR( lc );
835         lc->lc_refcnt--;
836         if ( LDAP_BACK_CONN_TAINTED( lc ) ) {
837                 ldap_back_freeconn( op, lc, 0 );
838                 *lcp = NULL;
839         }
840         if ( dolock ) {
841                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
842         }
843 }
844
845 void
846 ldap_back_quarantine(
847         Operation       *op,
848         SlapReply       *rs )
849 {
850         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
851
852         slap_retry_info_t       *ri = &li->li_quarantine;
853
854         ldap_pvt_thread_mutex_lock( &li->li_quarantine_mutex );
855
856         if ( rs->sr_err == LDAP_UNAVAILABLE ) {
857                 time_t          new_last = slap_get_time();
858
859                 switch ( li->li_isquarantined ) {
860                 case LDAP_BACK_FQ_NO:
861                         if ( ri->ri_last == new_last ) {
862                                 goto done;
863                         }
864
865                         Debug( LDAP_DEBUG_ANY,
866                                 "%s: ldap_back_quarantine enter.\n",
867                                 op->o_log_prefix, 0, 0 );
868
869                         ri->ri_idx = 0;
870                         ri->ri_count = 0;
871                         break;
872
873                 case LDAP_BACK_FQ_RETRYING:
874                         Debug( LDAP_DEBUG_ANY,
875                                 "%s: ldap_back_quarantine block #%d try #%d failed.\n",
876                                 op->o_log_prefix, ri->ri_idx, ri->ri_count );
877
878                         ++ri->ri_count;
879                         if ( ri->ri_num[ ri->ri_idx ] != SLAP_RETRYNUM_FOREVER
880                                 && ri->ri_count == ri->ri_num[ ri->ri_idx ] )
881                         {
882                                 ri->ri_count = 0;
883                                 ++ri->ri_idx;
884                         }
885                         break;
886
887                 default:
888                         break;
889                 }
890
891                 li->li_isquarantined = LDAP_BACK_FQ_YES;
892                 ri->ri_last = new_last;
893
894         } else if ( li->li_isquarantined != LDAP_BACK_FQ_NO ) {
895                 Debug( LDAP_DEBUG_ANY,
896                         "%s: ldap_back_quarantine exit.\n",
897                         op->o_log_prefix, ri->ri_idx, ri->ri_count );
898
899                 if ( li->li_quarantine_f ) {
900                         (void)li->li_quarantine_f( li, li->li_quarantine_p );
901                 }
902
903                 ri->ri_count = 0;
904                 ri->ri_idx = 0;
905                 li->li_isquarantined = LDAP_BACK_FQ_NO;
906         }
907
908 done:;
909         ldap_pvt_thread_mutex_unlock( &li->li_quarantine_mutex );
910 }
911
912 /*
913  * ldap_back_dobind
914  *
915  * Note: as the check for the value of lc->lc_bound was already here, I removed
916  * it from all the callers, and I made the function return the flag, so
917  * it can be used to simplify the check.
918  *
919  * Note: dolock indicates whether li->li_conninfo.lai_mutex must be locked or not
920  */
921 static int
922 ldap_back_dobind_int(
923         ldapconn_t              **lcp,
924         Operation               *op,
925         SlapReply               *rs,
926         ldap_back_send_t        sendok,
927         int                     retries,
928         int                     dolock )
929 {       
930         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
931
932         ldapconn_t      *lc = *lcp;
933
934         int             rc,
935                         isbound,
936                         binding = 0;
937         ber_int_t       msgid;
938
939         assert( retries >= 0 );
940
941 retry_lock:;
942         if ( dolock ) {
943                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
944         }
945
946         if ( binding == 0 ) {
947                 /* check if already bound */
948                 rc = isbound = LDAP_BACK_CONN_ISBOUND( lc );
949                 if ( isbound ) {
950                         lc->lc_binding--;
951                         if ( dolock ) {
952                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
953                         }
954                         return rc;
955                 }
956
957                 if ( LDAP_BACK_CONN_BINDING( lc ) ) {
958                         /* if someone else is about to bind it, give up and retry */
959                         if ( dolock ) {
960                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
961                         }
962                         ldap_pvt_thread_yield();
963                         goto retry_lock;
964
965                 } else {
966                         /* otherwise this thread will bind it */
967                         LDAP_BACK_CONN_BINDING_SET( lc );
968                         binding = 1;
969                 }
970         }
971
972         /* wait for pending operations to finish */
973         /* FIXME: may become a bottleneck! */
974         if ( lc->lc_refcnt != lc->lc_binding ) {
975                 if ( dolock ) {
976                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
977                 }
978                 ldap_pvt_thread_yield();
979                 goto retry_lock;
980         }
981
982         if ( dolock ) {
983                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
984         }
985
986         /*
987          * FIXME: we need to let clients use proxyAuthz
988          * otherwise we cannot do symmetric pools of servers;
989          * we have to live with the fact that a user can
990          * authorize itself as any ID that is allowed
991          * by the authzTo directive of the "proxyauthzdn".
992          */
993         /*
994          * NOTE: current Proxy Authorization specification
995          * and implementation do not allow proxy authorization
996          * control to be provided with Bind requests
997          */
998         /*
999          * if no bind took place yet, but the connection is bound
1000          * and the "idassert-authcDN" (or other ID) is set, 
1001          * then bind as the asserting identity and explicitly 
1002          * add the proxyAuthz control to every operation with the
1003          * dn bound to the connection as control value.
1004          * This is done also if this is the authrizing backend,
1005          * but the "override" flag is given to idassert.
1006          * It allows to use SASL bind and yet proxyAuthz users
1007          */
1008         if ( op->o_conn != NULL && !op->o_do_not_cache &&
1009                 ( !LDAP_BACK_CONN_ISPRIV( lc ) ||
1010                         LDAP_BACK_CONN_ISIDASSERT( lc ) ||
1011                         BER_BVISEMPTY( &lc->lc_bound_ndn ) ) &&
1012                 ( !isbound || ( li->li_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) ) )
1013         {
1014                 (void)ldap_back_proxy_authz_bind( lc, op, rs, sendok );
1015                 goto done;
1016         }
1017
1018 #ifdef HAVE_CYRUS_SASL
1019         if ( LDAP_BACK_CONN_ISPRIV( lc )
1020                 && li->li_acl_authmethod == LDAP_AUTH_SASL )
1021         {
1022                 void            *defaults = NULL;
1023
1024                 if ( li->li_acl_secprops != NULL ) {
1025                         rc = ldap_set_option( lc->lc_ld,
1026                                 LDAP_OPT_X_SASL_SECPROPS, li->li_acl_secprops );
1027
1028                         if ( rc != LDAP_OPT_SUCCESS ) {
1029                                 Debug( LDAP_DEBUG_ANY, "Error: ldap_set_option "
1030                                         "(SECPROPS,\"%s\") failed!\n",
1031                                         li->li_acl_secprops, 0, 0 );
1032                                 goto done;
1033                         }
1034                 }
1035
1036                 defaults = lutil_sasl_defaults( lc->lc_ld,
1037                                 li->li_acl_sasl_mech.bv_val,
1038                                 li->li_acl_sasl_realm.bv_val,
1039                                 li->li_acl_authcID.bv_val,
1040                                 li->li_acl_passwd.bv_val,
1041                                 NULL );
1042
1043                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld,
1044                                 li->li_acl_authcDN.bv_val,
1045                                 li->li_acl_sasl_mech.bv_val, NULL, NULL,
1046                                 LDAP_SASL_QUIET, lutil_sasl_interact,
1047                                 defaults );
1048
1049                 lutil_sasl_freedefs( defaults );
1050
1051                 rs->sr_err = slap_map_api2result( rs );
1052                 if ( rs->sr_err != LDAP_SUCCESS ) {
1053                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1054                         send_ldap_result( op, rs );
1055
1056                 } else {
1057                         LDAP_BACK_CONN_ISBOUND_SET( lc );
1058                 }
1059
1060                 if ( LDAP_BACK_QUARANTINE( li ) ) {
1061                         ldap_back_quarantine( op, rs );
1062                 }
1063
1064                 goto done;
1065         }
1066 #endif /* HAVE_CYRUS_SASL */
1067
1068 retry:;
1069         rs->sr_err = ldap_sasl_bind( lc->lc_ld,
1070                         BER_BVISNULL( &lc->lc_cred ) ? "" : lc->lc_bound_ndn.bv_val,
1071                         LDAP_SASL_SIMPLE, &lc->lc_cred,
1072                         NULL, NULL, &msgid );
1073
1074         if ( rs->sr_err == LDAP_SERVER_DOWN ) {
1075                 if ( retries != LDAP_BACK_RETRY_NEVER ) {
1076                         if ( dolock ) {
1077                                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1078                         }
1079
1080                         assert( lc->lc_refcnt > 0 );
1081                         if ( lc->lc_refcnt == 1 ) {
1082                                 ldap_unbind_ext( lc->lc_ld, NULL, NULL );
1083                                 lc->lc_ld = NULL;
1084
1085                                 /* lc here must be the regular lc, reset and ready for init */
1086                                 rs->sr_err = ldap_back_prepare_conn( &lc, op, rs, sendok );
1087                                 if ( rs->sr_err != LDAP_SUCCESS ) {
1088                                         lc->lc_binding--;
1089                                         lc->lc_refcnt = 0;
1090                                 }
1091                         }
1092
1093                         if ( dolock ) {
1094                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1095                         }
1096
1097                         if ( rs->sr_err == LDAP_SUCCESS ) {
1098                                 if ( retries > 0 ) {
1099                                         retries--;
1100                                 }
1101                                 goto retry;
1102                         }
1103
1104                 } else {
1105                         if ( dolock ) {
1106                                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1107                         }
1108                         lc->lc_binding--;
1109                         if ( dolock ) {
1110                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1111                         }
1112                 }
1113
1114                 /* FIXME: one binding-- too many? */
1115                 lc->lc_binding--;
1116                 ldap_back_freeconn( op, lc, dolock );
1117                 *lcp = NULL;
1118                 rs->sr_err = slap_map_api2result( rs );
1119
1120                 if ( LDAP_BACK_QUARANTINE( li ) ) {
1121                         ldap_back_quarantine( op, rs );
1122                 }
1123
1124                 return 0;
1125         }
1126
1127         rc = ldap_back_op_result( lc, op, rs, msgid,
1128                 -1, (sendok|LDAP_BACK_BINDING) );
1129         if ( rc == LDAP_SUCCESS ) {
1130                 LDAP_BACK_CONN_ISBOUND_SET( lc );
1131         }
1132
1133 done:;
1134         lc->lc_binding--;
1135         LDAP_BACK_CONN_BINDING_CLEAR( lc );
1136         rc = LDAP_BACK_CONN_ISBOUND( lc );
1137         if ( !rc ) {
1138                 ldap_back_release_conn_lock( op, rs, lcp, dolock );
1139         }
1140
1141         return rc;
1142 }
1143
1144 int
1145 ldap_back_dobind( ldapconn_t *lc, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1146 {
1147         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1148
1149         /* NOTE: ldap_back_dobind_int() may free lc;
1150          * callers of ldap_back_dobind() MUST no longer deal with lc
1151          * in case of failure */
1152         return ldap_back_dobind_int( &lc, op, rs, sendok, li->li_nretries, 1 );
1153 }
1154
1155 /*
1156  * ldap_back_default_rebind
1157  *
1158  * This is a callback used for chasing referrals using the same
1159  * credentials as the original user on this session.
1160  */
1161 int 
1162 ldap_back_default_rebind( LDAP *ld, LDAP_CONST char *url, ber_tag_t request,
1163         ber_int_t msgid, void *params )
1164 {
1165         ldapconn_t      *lc = (ldapconn_t *)params;
1166
1167 #ifdef HAVE_TLS
1168         /* ... otherwise we couldn't get here */
1169         assert( lc != NULL );
1170
1171         if ( !ldap_tls_inplace( ld ) ) {
1172                 int             is_tls = LDAP_BACK_CONN_ISTLS( lc ),
1173                                 rc;
1174                 const char      *text = NULL;
1175
1176                 rc = ldap_back_start_tls( ld, 0, &is_tls, url, lc->lc_flags,
1177                         LDAP_BACK_RETRY_DEFAULT, &text );
1178                 if ( rc != LDAP_SUCCESS ) {
1179                         return rc;
1180                 }
1181         }
1182 #endif /* HAVE_TLS */
1183
1184         /* FIXME: add checks on the URL/identity? */
1185
1186         return ldap_sasl_bind_s( ld,
1187                         BER_BVISNULL( &lc->lc_cred ) ? "" : lc->lc_bound_ndn.bv_val,
1188                         LDAP_SASL_SIMPLE, &lc->lc_cred, NULL, NULL, NULL );
1189 }
1190
1191 /*
1192  * ldap_back_default_urllist
1193  */
1194 int 
1195 ldap_back_default_urllist(
1196         LDAP            *ld,
1197         LDAPURLDesc     **urllist,
1198         LDAPURLDesc     **url,
1199         void            *params )
1200 {
1201         ldapinfo_t      *li = (ldapinfo_t *)params;
1202         LDAPURLDesc     **urltail;
1203
1204         if ( urllist == url ) {
1205                 return LDAP_SUCCESS;
1206         }
1207
1208         for ( urltail = &(*url)->lud_next; *urltail; urltail = &(*urltail)->lud_next )
1209                 /* count */ ;
1210
1211         *urltail = *urllist;
1212         *urllist = *url;
1213         *url = NULL;
1214
1215         ldap_pvt_thread_mutex_lock( &li->li_uri_mutex );
1216         if ( li->li_uri ) {
1217                 ch_free( li->li_uri );
1218         }
1219
1220         ldap_get_option( ld, LDAP_OPT_URI, (void *)&li->li_uri );
1221         ldap_pvt_thread_mutex_unlock( &li->li_uri_mutex );
1222
1223         return LDAP_SUCCESS;
1224 }
1225
1226 int
1227 ldap_back_cancel(
1228                 ldapconn_t              *lc,
1229                 Operation               *op,
1230                 SlapReply               *rs,
1231                 ber_int_t               msgid,
1232                 ldap_back_send_t        sendok )
1233 {
1234         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1235
1236         /* default behavior */
1237         if ( LDAP_BACK_ABANDON( li ) ) {
1238                 return ldap_abandon_ext( lc->lc_ld, msgid, NULL, NULL );
1239         }
1240
1241         if ( LDAP_BACK_IGNORE( li ) ) {
1242                 return LDAP_SUCCESS;
1243         }
1244
1245         if ( LDAP_BACK_CANCEL( li ) ) {
1246                 /* FIXME: asynchronous? */
1247                 return ldap_cancel_s( lc->lc_ld, msgid, NULL, NULL );
1248         }
1249
1250         assert( 0 );
1251
1252         return LDAP_OTHER;
1253 }
1254
1255 int
1256 ldap_back_op_result(
1257                 ldapconn_t              *lc,
1258                 Operation               *op,
1259                 SlapReply               *rs,
1260                 ber_int_t               msgid,
1261                 time_t                  timeout,
1262                 ldap_back_send_t        sendok )
1263 {
1264         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1265
1266         char            *match = NULL;
1267         char            *text = NULL;
1268         char            **refs = NULL;
1269         LDAPControl     **ctrls = NULL;
1270
1271 #define ERR_OK(err) ((err) == LDAP_SUCCESS || (err) == LDAP_COMPARE_FALSE || (err) == LDAP_COMPARE_TRUE)
1272
1273         rs->sr_text = NULL;
1274         rs->sr_matched = NULL;
1275         rs->sr_ref = NULL;
1276         rs->sr_ctrls = NULL;
1277
1278         /* if the error recorded in the reply corresponds
1279          * to a successful state, get the error from the
1280          * remote server response */
1281         if ( ERR_OK( rs->sr_err ) ) {
1282                 int             rc;
1283                 struct timeval  tv;
1284                 LDAPMessage     *res = NULL;
1285                 time_t          stoptime = (time_t)(-1);
1286                 int             timeout_err = op->o_protocol >= LDAP_VERSION3 ?
1287                                         LDAP_ADMINLIMIT_EXCEEDED : LDAP_OTHER;
1288                 const char      *timeout_text = "Operation timed out";
1289
1290                 /* if timeout is not specified, compute and use
1291                  * the one specific to the ongoing operation */
1292                 if ( timeout == (time_t)(-1) ) {
1293                         slap_op_t       opidx = slap_req2op( op->o_tag );
1294
1295                         if ( opidx == SLAP_OP_SEARCH ) {
1296                                 if ( op->ors_tlimit <= 0 ) {
1297                                         timeout = 0;
1298
1299                                 } else {
1300                                         timeout = op->ors_tlimit;
1301                                         timeout_err = LDAP_TIMELIMIT_EXCEEDED;
1302                                         timeout_text = NULL;
1303                                 }
1304
1305                         } else {
1306                                 timeout = li->li_timeout[ opidx ];
1307                         }
1308                 }
1309
1310                 /* better than nothing :) */
1311                 if ( timeout == 0 ) {
1312                         if ( li->li_idle_timeout ) {
1313                                 timeout = li->li_idle_timeout;
1314
1315                         } else if ( li->li_conn_ttl ) {
1316                                 timeout = li->li_conn_ttl;
1317                         }
1318                 }
1319
1320                 if ( timeout ) {
1321                         stoptime = op->o_time + timeout;
1322                 }
1323
1324                 LDAP_BACK_TV_SET( &tv );
1325
1326 retry:;
1327                 /* if result parsing fails, note the failure reason */
1328                 rc = ldap_result( lc->lc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
1329                 switch ( rc ) {
1330                 case 0:
1331                         if ( timeout && slap_get_time() > stoptime ) {
1332                                 if ( sendok & LDAP_BACK_BINDING ) {
1333                                         ldap_unbind_ext( lc->lc_ld, NULL, NULL );
1334                                         lc->lc_ld = NULL;
1335                                         LDAP_BACK_CONN_TAINTED_SET( lc );
1336
1337                                 } else {
1338                                         (void)ldap_back_cancel( lc, op, rs, msgid, sendok );
1339                                 }
1340                                 rs->sr_err = timeout_err;
1341                                 rs->sr_text = timeout_text;
1342                                 break;
1343                         }
1344
1345                         /* timeout == 0 */
1346                         LDAP_BACK_TV_SET( &tv );
1347                         ldap_pvt_thread_yield();
1348                         goto retry;
1349
1350                 case -1:
1351                         ldap_get_option( lc->lc_ld, LDAP_OPT_ERROR_NUMBER,
1352                                         &rs->sr_err );
1353                         break;
1354
1355
1356                 /* otherwise get the result; if it is not
1357                  * LDAP_SUCCESS, record it in the reply
1358                  * structure (this includes 
1359                  * LDAP_COMPARE_{TRUE|FALSE}) */
1360                 default:
1361                         /* only touch when activity actually took place... */
1362                         if ( li->li_idle_timeout && lc ) {
1363                                 lc->lc_time = op->o_time;
1364                         }
1365
1366                         rc = ldap_parse_result( lc->lc_ld, res, &rs->sr_err,
1367                                         &match, &text, &refs, &ctrls, 1 );
1368                         rs->sr_text = text;
1369                         if ( rc != LDAP_SUCCESS ) {
1370                                 rs->sr_err = rc;
1371                         }
1372                         if ( refs != NULL ) {
1373                                 int     i;
1374
1375                                 for ( i = 0; refs[ i ] != NULL; i++ )
1376                                         /* count */ ;
1377                                 rs->sr_ref = op->o_tmpalloc( sizeof( struct berval ) * ( i + 1 ),
1378                                         op->o_tmpmemctx );
1379                                 for ( i = 0; refs[ i ] != NULL; i++ ) {
1380                                         ber_str2bv( refs[ i ], 0, 0, &rs->sr_ref[ i ] );
1381                                 }
1382                                 BER_BVZERO( &rs->sr_ref[ i ] );
1383                         }
1384                         if ( ctrls != NULL ) {
1385                                 rs->sr_ctrls = ctrls;
1386                         }
1387                 }
1388         }
1389
1390         /* if the error in the reply structure is not
1391          * LDAP_SUCCESS, try to map it from client 
1392          * to server error */
1393         if ( !ERR_OK( rs->sr_err ) ) {
1394                 rs->sr_err = slap_map_api2result( rs );
1395
1396                 /* internal ops ( op->o_conn == NULL ) 
1397                  * must not reply to client */
1398                 if ( op->o_conn && !op->o_do_not_cache && match ) {
1399
1400                         /* record the (massaged) matched
1401                          * DN into the reply structure */
1402                         rs->sr_matched = match;
1403                 }
1404         }
1405
1406         if ( rs->sr_err == LDAP_UNAVAILABLE ) {
1407                 if ( !( sendok & LDAP_BACK_RETRYING ) ) {
1408                         if ( LDAP_BACK_QUARANTINE( li ) ) {
1409                                 ldap_back_quarantine( op, rs );
1410                         }
1411                         if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
1412                                 send_ldap_result( op, rs );
1413                         }
1414                 }
1415
1416         } else if ( op->o_conn &&
1417                 ( ( ( sendok & LDAP_BACK_SENDOK ) && ERR_OK( rs->sr_err ) )
1418                         || ( ( sendok & LDAP_BACK_SENDERR ) && rs->sr_err != LDAP_SUCCESS ) ) )
1419         {
1420                 send_ldap_result( op, rs );
1421         }
1422
1423         if ( match ) {
1424                 if ( rs->sr_matched != match ) {
1425                         free( (char *)rs->sr_matched );
1426                 }
1427                 rs->sr_matched = NULL;
1428                 ldap_memfree( match );
1429         }
1430
1431         if ( text ) {
1432                 ldap_memfree( text );
1433         }
1434         rs->sr_text = NULL;
1435
1436         if ( rs->sr_ref ) {
1437                 assert( refs != NULL );
1438                 ber_memvfree( (void **)refs );
1439                 op->o_tmpfree( rs->sr_ref, op->o_tmpmemctx );
1440                 rs->sr_ref = NULL;
1441         }
1442
1443         if ( ctrls ) {
1444                 assert( rs->sr_ctrls != NULL );
1445                 ldap_controls_free( ctrls );
1446                 rs->sr_ctrls = NULL;
1447         }
1448
1449         return( ERR_OK( rs->sr_err ) ? LDAP_SUCCESS : rs->sr_err );
1450 }
1451
1452 /* return true if bound, false if failed */
1453 int
1454 ldap_back_retry( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1455 {
1456         int             rc = 0;
1457         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1458
1459         assert( lcp != NULL );
1460         assert( *lcp != NULL );
1461
1462         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1463
1464         if ( (*lcp)->lc_refcnt == 1 ) {
1465                 ldap_pvt_thread_mutex_lock( &li->li_uri_mutex );
1466                 Debug( LDAP_DEBUG_ANY,
1467                         "%s ldap_back_retry: retrying URI=\"%s\" DN=\"%s\"\n",
1468                         op->o_log_prefix, li->li_uri,
1469                         BER_BVISNULL( &(*lcp)->lc_bound_ndn ) ?
1470                                 "" : (*lcp)->lc_bound_ndn.bv_val );
1471                 ldap_pvt_thread_mutex_unlock( &li->li_uri_mutex );
1472
1473                 ldap_unbind_ext( (*lcp)->lc_ld, NULL, NULL );
1474                 (*lcp)->lc_ld = NULL;
1475                 LDAP_BACK_CONN_ISBOUND_CLEAR( (*lcp) );
1476
1477                 /* lc here must be the regular lc, reset and ready for init */
1478                 rc = ldap_back_prepare_conn( lcp, op, rs, sendok );
1479                 if ( rc != LDAP_SUCCESS ) {
1480                         /* freeit, because lc_refcnt == 1 */
1481                         (*lcp)->lc_refcnt = 0;
1482                         (void)ldap_back_freeconn( op, *lcp, 0 );
1483                         *lcp = NULL;
1484                         rc = 0;
1485
1486                 } else {
1487                         rc = ldap_back_dobind_int( lcp, op, rs, sendok, 0, 0 );
1488                         if ( rc == 0 && *lcp != NULL ) {
1489                                 /* freeit, because lc_refcnt == 1 */
1490                                 (*lcp)->lc_refcnt = 0;
1491                                 LDAP_BACK_CONN_TAINTED_SET( *lcp );
1492                                 (void)ldap_back_freeconn( op, *lcp, 0 );
1493                                 *lcp = NULL;
1494                         }
1495                 }
1496
1497         } else {
1498                 Debug( LDAP_DEBUG_TRACE,
1499                         "ldap_back_retry: conn %p refcnt=%u unable to retry.\n",
1500                         (void *)(*lcp), (*lcp)->lc_refcnt, 0 );
1501
1502                 LDAP_BACK_CONN_TAINTED_SET( *lcp );
1503                 ldap_back_release_conn_lock( op, rs, lcp, 0 );
1504                 assert( *lcp == NULL );
1505
1506                 if ( sendok ) {
1507                         rs->sr_err = LDAP_UNAVAILABLE;
1508                         rs->sr_text = "unable to retry";
1509                         send_ldap_result( op, rs );
1510                 }
1511         }
1512
1513         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1514
1515         return rc;
1516 }
1517
1518 static int
1519 ldap_back_proxy_authz_bind( ldapconn_t *lc, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1520 {
1521         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1522         struct berval   binddn = slap_empty_bv;
1523         struct berval   bindcred = slap_empty_bv;
1524         struct berval   ndn;
1525         int             dobind = 0;
1526         int             msgid;
1527         int             rc;
1528
1529         /* don't proxyAuthz if protocol is not LDAPv3 */
1530         switch ( li->li_version ) {
1531         case LDAP_VERSION3:
1532                 break;
1533
1534         case 0:
1535                 if ( op->o_protocol == 0 || op->o_protocol == LDAP_VERSION3 ) {
1536                         break;
1537                 }
1538                 /* fall thru */
1539
1540         default:
1541                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1542                 if ( sendok & LDAP_BACK_SENDERR ) {
1543                         send_ldap_result( op, rs );
1544                 }
1545                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1546                 goto done;
1547         }
1548
1549         LDAP_BACK_CONN_ISIDASSERT_SET( lc );
1550
1551         if ( op->o_tag == LDAP_REQ_BIND ) {
1552                 ndn = op->o_req_ndn;
1553
1554         } else if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1555                 ndn = op->o_conn->c_ndn;
1556
1557         } else {
1558                 ndn = op->o_ndn;
1559         }
1560
1561         /*
1562          * FIXME: we need to let clients use proxyAuthz
1563          * otherwise we cannot do symmetric pools of servers;
1564          * we have to live with the fact that a user can
1565          * authorize itself as any ID that is allowed
1566          * by the authzTo directive of the "proxyauthzdn".
1567          */
1568         /*
1569          * NOTE: current Proxy Authorization specification
1570          * and implementation do not allow proxy authorization
1571          * control to be provided with Bind requests
1572          */
1573         /*
1574          * if no bind took place yet, but the connection is bound
1575          * and the "proxyauthzdn" is set, then bind as 
1576          * "proxyauthzdn" and explicitly add the proxyAuthz 
1577          * control to every operation with the dn bound 
1578          * to the connection as control value.
1579          */
1580         /* bind as proxyauthzdn only if no idassert mode
1581          * is requested, or if the client's identity
1582          * is authorized */
1583         switch ( li->li_idassert_mode ) {
1584         case LDAP_BACK_IDASSERT_LEGACY:
1585                 if ( !BER_BVISNULL( &ndn ) && !BER_BVISEMPTY( &ndn ) ) {
1586                         if ( !BER_BVISNULL( &li->li_idassert_authcDN ) && !BER_BVISEMPTY( &li->li_idassert_authcDN ) )
1587                         {
1588                                 binddn = li->li_idassert_authcDN;
1589                                 bindcred = li->li_idassert_passwd;
1590                                 dobind = 1;
1591                         }
1592                 }
1593                 break;
1594
1595         default:
1596                 /* NOTE: rootdn can always idassert */
1597                 if ( BER_BVISNULL( &ndn ) && li->li_idassert_authz == NULL ) {
1598                         if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1599                                 rs->sr_err = LDAP_INAPPROPRIATE_AUTH;
1600                                 if ( sendok & LDAP_BACK_SENDERR ) {
1601                                         send_ldap_result( op, rs );
1602                                 }
1603                                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1604
1605                         } else {
1606                                 rs->sr_err = LDAP_SUCCESS;
1607                                 binddn = slap_empty_bv;
1608                                 bindcred = slap_empty_bv;
1609                                 break;
1610                         }
1611
1612                         goto done;
1613
1614                 } else if ( li->li_idassert_authz && !be_isroot( op ) ) {
1615                         struct berval authcDN;
1616
1617                         if ( BER_BVISNULL( &ndn ) ) {
1618                                 authcDN = slap_empty_bv;
1619
1620                         } else {
1621                                 authcDN = ndn;
1622                         }       
1623                         rs->sr_err = slap_sasl_matches( op, li->li_idassert_authz,
1624                                         &authcDN, &authcDN );
1625                         if ( rs->sr_err != LDAP_SUCCESS ) {
1626                                 if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1627                                         if ( sendok & LDAP_BACK_SENDERR ) {
1628                                                 send_ldap_result( op, rs );
1629                                         }
1630                                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1631
1632                                 } else {
1633                                         rs->sr_err = LDAP_SUCCESS;
1634                                         binddn = slap_empty_bv;
1635                                         bindcred = slap_empty_bv;
1636                                         break;
1637                                 }
1638
1639                                 goto done;
1640                         }
1641                 }
1642
1643                 binddn = li->li_idassert_authcDN;
1644                 bindcred = li->li_idassert_passwd;
1645                 dobind = 1;
1646                 break;
1647         }
1648
1649         if ( dobind && li->li_idassert_authmethod == LDAP_AUTH_SASL ) {
1650 #ifdef HAVE_CYRUS_SASL
1651                 void            *defaults = NULL;
1652                 struct berval   authzID = BER_BVNULL;
1653                 int             freeauthz = 0;
1654
1655                 /* if SASL supports native authz, prepare for it */
1656                 if ( ( !op->o_do_not_cache || !op->o_is_auth_check ) &&
1657                                 ( li->li_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
1658                 {
1659                         switch ( li->li_idassert_mode ) {
1660                         case LDAP_BACK_IDASSERT_OTHERID:
1661                         case LDAP_BACK_IDASSERT_OTHERDN:
1662                                 authzID = li->li_idassert_authzID;
1663                                 break;
1664
1665                         case LDAP_BACK_IDASSERT_ANONYMOUS:
1666                                 BER_BVSTR( &authzID, "dn:" );
1667                                 break;
1668
1669                         case LDAP_BACK_IDASSERT_SELF:
1670                                 if ( BER_BVISNULL( &ndn ) ) {
1671                                         /* connection is not authc'd, so don't idassert */
1672                                         BER_BVSTR( &authzID, "dn:" );
1673                                         break;
1674                                 }
1675                                 authzID.bv_len = STRLENOF( "dn:" ) + ndn.bv_len;
1676                                 authzID.bv_val = slap_sl_malloc( authzID.bv_len + 1, op->o_tmpmemctx );
1677                                 AC_MEMCPY( authzID.bv_val, "dn:", STRLENOF( "dn:" ) );
1678                                 AC_MEMCPY( authzID.bv_val + STRLENOF( "dn:" ),
1679                                                 ndn.bv_val, ndn.bv_len + 1 );
1680                                 freeauthz = 1;
1681                                 break;
1682
1683                         default:
1684                                 break;
1685                         }
1686                 }
1687
1688                 if ( li->li_idassert_secprops != NULL ) {
1689                         rs->sr_err = ldap_set_option( lc->lc_ld,
1690                                 LDAP_OPT_X_SASL_SECPROPS,
1691                                 (void *)li->li_idassert_secprops );
1692
1693                         if ( rs->sr_err != LDAP_OPT_SUCCESS ) {
1694                                 rs->sr_err = LDAP_OTHER;
1695                                 if ( sendok & LDAP_BACK_SENDERR ) {
1696                                         send_ldap_result( op, rs );
1697                                 }
1698                                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1699                                 goto done;
1700                         }
1701                 }
1702
1703                 defaults = lutil_sasl_defaults( lc->lc_ld,
1704                                 li->li_idassert_sasl_mech.bv_val,
1705                                 li->li_idassert_sasl_realm.bv_val,
1706                                 li->li_idassert_authcID.bv_val,
1707                                 li->li_idassert_passwd.bv_val,
1708                                 authzID.bv_val );
1709
1710                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld, binddn.bv_val,
1711                                 li->li_idassert_sasl_mech.bv_val, NULL, NULL,
1712                                 LDAP_SASL_QUIET, lutil_sasl_interact,
1713                                 defaults );
1714
1715                 rs->sr_err = slap_map_api2result( rs );
1716                 if ( rs->sr_err != LDAP_SUCCESS ) {
1717                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1718                         if ( sendok & LDAP_BACK_SENDERR ) {
1719                                 send_ldap_result( op, rs );
1720                         }
1721
1722                 } else {
1723                         LDAP_BACK_CONN_ISBOUND_SET( lc );
1724                 }
1725
1726                 lutil_sasl_freedefs( defaults );
1727                 if ( freeauthz ) {
1728                         slap_sl_free( authzID.bv_val, op->o_tmpmemctx );
1729                 }
1730
1731                 goto done;
1732 #endif /* HAVE_CYRUS_SASL */
1733         }
1734
1735         switch ( li->li_idassert_authmethod ) {
1736         case LDAP_AUTH_NONE:
1737                 BER_BVSTR( &binddn, "" );
1738                 BER_BVSTR( &bindcred, "" );
1739                 /* fallthru */
1740
1741         case LDAP_AUTH_SIMPLE:
1742                 rs->sr_err = ldap_sasl_bind( lc->lc_ld,
1743                                 binddn.bv_val, LDAP_SASL_SIMPLE,
1744                                 &bindcred, NULL, NULL, &msgid );
1745                 rc = ldap_back_op_result( lc, op, rs, msgid,
1746                         -1, (sendok|LDAP_BACK_BINDING) );
1747                 break;
1748
1749         default:
1750                 /* unsupported! */
1751                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1752                 rs->sr_err = LDAP_AUTH_METHOD_NOT_SUPPORTED;
1753                 if ( sendok & LDAP_BACK_SENDERR ) {
1754                         send_ldap_result( op, rs );
1755                 }
1756                 goto done;
1757         }
1758
1759         if ( rc == LDAP_SUCCESS ) {
1760                 /* set rebind stuff in case of successful proxyAuthz bind,
1761                  * so that referral chasing is attempted using the right
1762                  * identity */
1763                 LDAP_BACK_CONN_ISBOUND_SET( lc );
1764                 ber_bvreplace( &lc->lc_bound_ndn, &binddn );
1765
1766                 if ( LDAP_BACK_SAVECRED( li ) ) {
1767                         if ( !BER_BVISNULL( &lc->lc_cred ) ) {
1768                                 memset( lc->lc_cred.bv_val, 0,
1769                                                 lc->lc_cred.bv_len );
1770                         }
1771                         ber_bvreplace( &lc->lc_cred, &bindcred );
1772                         ldap_set_rebind_proc( lc->lc_ld, li->li_rebind_f, lc );
1773                 }
1774         }
1775 done:;
1776         return LDAP_BACK_CONN_ISBOUND( lc );
1777 }
1778
1779 /*
1780  * ldap_back_proxy_authz_ctrl() prepends a proxyAuthz control
1781  * to existing server-side controls if required; if not,
1782  * the existing server-side controls are placed in *pctrls.
1783  * The caller, after using the controls in client API 
1784  * operations, if ( *pctrls != op->o_ctrls ), should
1785  * free( (*pctrls)[ 0 ] ) and free( *pctrls ).
1786  * The function returns success if the control could
1787  * be added if required, or if it did nothing; in the future,
1788  * it might return some error if it failed.
1789  * 
1790  * if no bind took place yet, but the connection is bound
1791  * and the "proxyauthzdn" is set, then bind as "proxyauthzdn" 
1792  * and explicitly add proxyAuthz the control to every operation
1793  * with the dn bound to the connection as control value.
1794  *
1795  * If no server-side controls are defined for the operation,
1796  * simply add the proxyAuthz control; otherwise, if the
1797  * proxyAuthz control is not already set, add it as
1798  * the first one
1799  *
1800  * FIXME: is controls order significant for security?
1801  * ANSWER: controls ordering and interoperability
1802  * must be indicated by the specs of each control; if none
1803  * is specified, the order is irrelevant.
1804  */
1805 int
1806 ldap_back_proxy_authz_ctrl(
1807                 struct berval   *bound_ndn,
1808                 int             version,
1809                 slap_idassert_t *si,
1810                 Operation       *op,
1811                 SlapReply       *rs,
1812                 LDAPControl     ***pctrls )
1813 {
1814         LDAPControl             **ctrls = NULL;
1815         int                     i = 0;
1816         slap_idassert_mode_t    mode;
1817         struct berval           assertedID,
1818                                 ndn;
1819
1820         *pctrls = NULL;
1821
1822         rs->sr_err = LDAP_SUCCESS;
1823
1824         /* don't proxyAuthz if protocol is not LDAPv3 */
1825         switch ( version ) {
1826         case LDAP_VERSION3:
1827                 break;
1828
1829         case 0:
1830                 if ( op->o_protocol == 0 || op->o_protocol == LDAP_VERSION3 ) {
1831                         break;
1832                 }
1833                 /* fall thru */
1834
1835         default:
1836                 goto done;
1837         }
1838
1839         /* FIXME: SASL/EXTERNAL over ldapi:// doesn't honor the authcID,
1840          * but if it is not set this test fails.  We need a different
1841          * means to detect if idassert is enabled */
1842         if ( ( BER_BVISNULL( &si->si_bc.sb_authcId ) || BER_BVISEMPTY( &si->si_bc.sb_authcId ) )
1843                         && ( BER_BVISNULL( &si->si_bc.sb_binddn ) || BER_BVISEMPTY( &si->si_bc.sb_binddn ) ) )
1844         {
1845                 goto done;
1846         }
1847
1848         if ( !op->o_conn || op->o_do_not_cache || be_isroot( op ) ) {
1849                 goto done;
1850         }
1851
1852         if ( op->o_tag == LDAP_REQ_BIND ) {
1853                 ndn = op->o_req_ndn;
1854
1855         } else if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1856                 ndn = op->o_conn->c_ndn;
1857
1858         } else {
1859                 ndn = op->o_ndn;
1860         }
1861
1862         if ( si->si_mode == LDAP_BACK_IDASSERT_LEGACY ) {
1863                 if ( op->o_proxy_authz ) {
1864                         /*
1865                          * FIXME: we do not want to perform proxyAuthz
1866                          * on behalf of the client, because this would
1867                          * be performed with "proxyauthzdn" privileges.
1868                          *
1869                          * This might actually be too strict, since
1870                          * the "proxyauthzdn" authzTo, and each entry's
1871                          * authzFrom attributes may be crafted
1872                          * to avoid unwanted proxyAuthz to take place.
1873                          */
1874 #if 0
1875                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1876                         rs->sr_text = "proxyAuthz not allowed within namingContext";
1877 #endif
1878                         goto done;
1879                 }
1880
1881                 if ( !BER_BVISNULL( bound_ndn ) ) {
1882                         goto done;
1883                 }
1884
1885                 if ( BER_BVISNULL( &ndn ) ) {
1886                         goto done;
1887                 }
1888
1889                 if ( BER_BVISNULL( &si->si_bc.sb_binddn ) ) {
1890                         goto done;
1891                 }
1892
1893         } else if ( si->si_bc.sb_method == LDAP_AUTH_SASL ) {
1894                 if ( ( si->si_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
1895                 {
1896                         /* already asserted in SASL via native authz */
1897                         goto done;
1898                 }
1899
1900         } else if ( si->si_authz && !be_isroot( op ) ) {
1901                 int             rc;
1902                 struct berval authcDN;
1903
1904                 if ( BER_BVISNULL( &ndn ) ) {
1905                         authcDN = slap_empty_bv;
1906                 } else {
1907                         authcDN = ndn;
1908                 }
1909                 rc = slap_sasl_matches( op, si->si_authz,
1910                                 &authcDN, & authcDN );
1911                 if ( rc != LDAP_SUCCESS ) {
1912                         if ( si->si_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1913                                 /* ndn is not authorized
1914                                  * to use idassert */
1915                                 rs->sr_err = rc;
1916                         }
1917                         goto done;
1918                 }
1919         }
1920
1921         if ( op->o_proxy_authz ) {
1922                 /*
1923                  * FIXME: we can:
1924                  * 1) ignore the already set proxyAuthz control
1925                  * 2) leave it in place, and don't set ours
1926                  * 3) add both
1927                  * 4) reject the operation
1928                  *
1929                  * option (4) is very drastic
1930                  * option (3) will make the remote server reject
1931                  * the operation, thus being equivalent to (4)
1932                  * option (2) will likely break the idassert
1933                  * assumptions, so we cannot accept it;
1934                  * option (1) means that we are contradicting
1935                  * the client's reques.
1936                  *
1937                  * I think (4) is the only correct choice.
1938                  */
1939                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1940                 rs->sr_text = "proxyAuthz not allowed within namingContext";
1941         }
1942
1943         if ( op->o_is_auth_check ) {
1944                 mode = LDAP_BACK_IDASSERT_NOASSERT;
1945
1946         } else {
1947                 mode = si->si_mode;
1948         }
1949
1950         switch ( mode ) {
1951         case LDAP_BACK_IDASSERT_SELF:
1952                 if ( BER_BVISNULL( &ndn ) ) {
1953                         goto done;
1954                 }
1955                 assertedID = ndn;
1956                 break;
1957
1958         case LDAP_BACK_IDASSERT_LEGACY:
1959                 /* original behavior:
1960                  * assert the client's identity */
1961                 if ( BER_BVISNULL( &ndn ) ) {
1962                         assertedID = slap_empty_bv;
1963                 } else {
1964                         assertedID = ndn;
1965                 }
1966                 break;
1967
1968         case LDAP_BACK_IDASSERT_ANONYMOUS:
1969                 /* assert "anonymous" */
1970                 assertedID = slap_empty_bv;
1971                 break;
1972
1973         case LDAP_BACK_IDASSERT_NOASSERT:
1974                 /* don't assert; bind as proxyauthzdn */
1975                 goto done;
1976
1977         case LDAP_BACK_IDASSERT_OTHERID:
1978         case LDAP_BACK_IDASSERT_OTHERDN:
1979                 /* assert idassert DN */
1980                 assertedID = si->si_bc.sb_authzId;
1981                 break;
1982
1983         default:
1984                 assert( 0 );
1985         }
1986
1987         if ( BER_BVISNULL( &assertedID ) ) {
1988                 assertedID = slap_empty_bv;
1989         }
1990
1991         /* don't idassert the bound DN (ITS#4497) */
1992         if ( dn_match( &assertedID, bound_ndn ) ) {
1993                 goto done;
1994         }
1995
1996         if ( op->o_ctrls ) {
1997                 for ( i = 0; op->o_ctrls[ i ]; i++ )
1998                         /* just count ctrls */ ;
1999         }
2000
2001         ctrls = op->o_tmpalloc( sizeof( LDAPControl * ) * (i + 2) + sizeof( LDAPControl ),
2002                         op->o_tmpmemctx );
2003         ctrls[ 0 ] = (LDAPControl *)&ctrls[ i + 2 ];
2004         
2005         ctrls[ 0 ]->ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
2006         ctrls[ 0 ]->ldctl_iscritical = 1;
2007
2008         switch ( si->si_mode ) {
2009         /* already in u:ID or dn:DN form */
2010         case LDAP_BACK_IDASSERT_OTHERID:
2011         case LDAP_BACK_IDASSERT_OTHERDN:
2012                 ber_dupbv_x( &ctrls[ 0 ]->ldctl_value, &assertedID, op->o_tmpmemctx );
2013                 break;
2014
2015         /* needs the dn: prefix */
2016         default:
2017                 ctrls[ 0 ]->ldctl_value.bv_len = assertedID.bv_len + STRLENOF( "dn:" );
2018                 ctrls[ 0 ]->ldctl_value.bv_val = op->o_tmpalloc( ctrls[ 0 ]->ldctl_value.bv_len + 1,
2019                                 op->o_tmpmemctx );
2020                 AC_MEMCPY( ctrls[ 0 ]->ldctl_value.bv_val, "dn:", STRLENOF( "dn:" ) );
2021                 AC_MEMCPY( &ctrls[ 0 ]->ldctl_value.bv_val[ STRLENOF( "dn:" ) ],
2022                                 assertedID.bv_val, assertedID.bv_len + 1 );
2023                 break;
2024         }
2025
2026         /* Older versions of <draft-weltman-ldapv3-proxy> required
2027          * to encode the value of the authzID (and called it proxyDN);
2028          * this hack provides compatibility with those DSAs that
2029          * implement it this way */
2030         if ( si->si_flags & LDAP_BACK_AUTH_OBSOLETE_ENCODING_WORKAROUND ) {
2031                 struct berval           authzID = ctrls[ 0 ]->ldctl_value;
2032                 BerElementBuffer        berbuf;
2033                 BerElement              *ber = (BerElement *)&berbuf;
2034                 ber_tag_t               tag;
2035
2036                 ber_init2( ber, 0, LBER_USE_DER );
2037                 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
2038
2039                 tag = ber_printf( ber, "O", &authzID );
2040                 if ( tag == LBER_ERROR ) {
2041                         rs->sr_err = LDAP_OTHER;
2042                         goto free_ber;
2043                 }
2044
2045                 if ( ber_flatten2( ber, &ctrls[ 0 ]->ldctl_value, 1 ) == -1 ) {
2046                         rs->sr_err = LDAP_OTHER;
2047                         goto free_ber;
2048                 }
2049
2050 free_ber:;
2051                 op->o_tmpfree( authzID.bv_val, op->o_tmpmemctx );
2052                 ber_free_buf( ber );
2053
2054                 if ( rs->sr_err != LDAP_SUCCESS ) {
2055                         op->o_tmpfree( ctrls, op->o_tmpmemctx );
2056                         ctrls = NULL;
2057                         goto done;
2058                 }
2059
2060         } else if ( si->si_flags & LDAP_BACK_AUTH_OBSOLETE_PROXY_AUTHZ ) {
2061                 struct berval           authzID = ctrls[ 0 ]->ldctl_value,
2062                                         tmp;
2063                 BerElementBuffer        berbuf;
2064                 BerElement              *ber = (BerElement *)&berbuf;
2065                 ber_tag_t               tag;
2066
2067                 if ( strncasecmp( authzID.bv_val, "dn:", STRLENOF( "dn:" ) ) != 0 ) {
2068                         op->o_tmpfree( ctrls[ 0 ]->ldctl_value.bv_val, op->o_tmpmemctx );
2069                         op->o_tmpfree( ctrls, op->o_tmpmemctx );
2070                         ctrls = NULL;
2071                         rs->sr_err = LDAP_PROTOCOL_ERROR;
2072                         goto done;
2073                 }
2074
2075                 tmp = authzID;
2076                 tmp.bv_val += STRLENOF( "dn:" );
2077                 tmp.bv_len -= STRLENOF( "dn:" );
2078
2079                 ber_init2( ber, 0, LBER_USE_DER );
2080                 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
2081
2082                 /* apparently, Mozilla API encodes this
2083                  * as "SEQUENCE { LDAPDN }" */
2084                 tag = ber_printf( ber, "{O}", &tmp );
2085                 if ( tag == LBER_ERROR ) {
2086                         rs->sr_err = LDAP_OTHER;
2087                         goto free_ber2;
2088                 }
2089
2090                 if ( ber_flatten2( ber, &ctrls[ 0 ]->ldctl_value, 1 ) == -1 ) {
2091                         rs->sr_err = LDAP_OTHER;
2092                         goto free_ber2;
2093                 }
2094
2095 free_ber2:;
2096                 op->o_tmpfree( authzID.bv_val, op->o_tmpmemctx );
2097                 ber_free_buf( ber );
2098
2099                 if ( rs->sr_err != LDAP_SUCCESS ) {
2100                         op->o_tmpfree( ctrls, op->o_tmpmemctx );
2101                         ctrls = NULL;
2102                         goto done;
2103                 }
2104
2105                 ctrls[ 0 ]->ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
2106         }
2107
2108         if ( op->o_ctrls ) {
2109                 for ( i = 0; op->o_ctrls[ i ]; i++ ) {
2110                         ctrls[ i + 1 ] = op->o_ctrls[ i ];
2111                 }
2112         }
2113         ctrls[ i + 1 ] = NULL;
2114
2115 done:;
2116         if ( ctrls == NULL ) {
2117                 ctrls = op->o_ctrls;
2118         }
2119
2120         *pctrls = ctrls;
2121         
2122         return rs->sr_err;
2123 }
2124
2125 int
2126 ldap_back_proxy_authz_ctrl_free( Operation *op, LDAPControl ***pctrls )
2127 {
2128         LDAPControl     **ctrls = *pctrls;
2129
2130         /* we assume that the first control is the proxyAuthz
2131          * added by back-ldap, so it's the only one we explicitly 
2132          * free */
2133         if ( ctrls && ctrls != op->o_ctrls ) {
2134                 assert( ctrls[ 0 ] != NULL );
2135
2136                 if ( !BER_BVISNULL( &ctrls[ 0 ]->ldctl_value ) ) {
2137                         op->o_tmpfree( ctrls[ 0 ]->ldctl_value.bv_val, op->o_tmpmemctx );
2138                 }
2139
2140                 op->o_tmpfree( ctrls, op->o_tmpmemctx );
2141         } 
2142
2143         *pctrls = NULL;
2144
2145         return 0;
2146 }