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