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