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