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