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