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