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