]> git.sur5r.net Git - openldap/blob - servers/slapd/back-ldap/bind.c
ITS#5404
[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-2008 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 #undef ldap_debug       /* silence a warning in ldap-int.h */
36 #include "../../../libraries/libldap/ldap-int.h"
37
38 #include "lutil_ldap.h"
39
40 #define LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ       "2.16.840.1.113730.3.4.12"
41
42 #if LDAP_BACK_PRINT_CONNTREE > 0
43 static void
44 ldap_back_ravl_print( Avlnode *root, int depth )
45 {
46         int             i;
47         ldapconn_t      *lc;
48         
49         if ( root == 0 ) {
50                 return;
51         }
52         
53         ldap_back_ravl_print( root->avl_right, depth+1 );
54         
55         for ( i = 0; i < depth; i++ ) {
56                 fprintf( stderr, "-" );
57         }
58
59         lc = root->avl_data;
60         fprintf( stderr, "lc=%p local=\"%s\" conn=%p %s refcnt=%d flags=0x%08x\n",
61                 (void *)lc,
62                 lc->lc_local_ndn.bv_val ? lc->lc_local_ndn.bv_val : "",
63                 (void *)lc->lc_conn,
64                 avl_bf2str( root->avl_bf ), lc->lc_refcnt, lc->lc_lcflags );
65         
66         ldap_back_ravl_print( root->avl_left, depth+1 );
67 }
68
69 static char* priv2str[] = {
70         "privileged",
71         "privileged/TLS",
72         "anonymous",
73         "anonymous/TLS",
74         "bind",
75         "bind/TLS",
76         NULL
77 };
78
79 void
80 ldap_back_print_conntree( ldapinfo_t *li, char *msg )
81 {
82         int     c;
83
84         fprintf( stderr, "========> %s\n", msg );
85
86         for ( c = LDAP_BACK_PCONN_FIRST; c < LDAP_BACK_PCONN_LAST; c++ ) {
87                 int             i = 0;
88                 ldapconn_t      *lc;
89
90                 fprintf( stderr, "  %s[%d]\n", priv2str[ c ], li->li_conn_priv[ c ].lic_num );
91
92                 LDAP_TAILQ_FOREACH( lc, &li->li_conn_priv[ c ].lic_priv, lc_q )
93                 {
94                         fprintf( stderr, "    [%d] lc=%p local=\"%s\" conn=%p refcnt=%d flags=0x%08x\n",
95                                 i,
96                                 (void *)lc,
97                                 lc->lc_local_ndn.bv_val ? lc->lc_local_ndn.bv_val : "",
98                                 (void *)lc->lc_conn, lc->lc_refcnt, lc->lc_lcflags );
99                         i++;
100                 }
101         }
102         
103         if ( li->li_conninfo.lai_tree == 0 ) {
104                 fprintf( stderr, "\t(empty)\n" );
105
106         } else {
107                 ldap_back_ravl_print( li->li_conninfo.lai_tree, 0 );
108         }
109         
110         fprintf( stderr, "<======== %s\n", msg );
111 }
112 #endif /* LDAP_BACK_PRINT_CONNTREE */
113
114 static int
115 ldap_back_freeconn( ldapinfo_t *li, ldapconn_t *lc, int dolock );
116
117 static ldapconn_t *
118 ldap_back_getconn( Operation *op, SlapReply *rs, ldap_back_send_t sendok,
119         struct berval *binddn, struct berval *bindcred );
120
121 static int
122 ldap_back_is_proxy_authz( Operation *op, SlapReply *rs, ldap_back_send_t sendok,
123         struct berval *binddn, struct berval *bindcred );
124
125 static int
126 ldap_back_proxy_authz_bind( ldapconn_t *lc, Operation *op, SlapReply *rs,
127         ldap_back_send_t sendok, struct berval *binddn, struct berval *bindcred );
128
129 static int
130 ldap_back_prepare_conn( ldapconn_t *lc, Operation *op, SlapReply *rs,
131         ldap_back_send_t sendok );
132
133 static int
134 ldap_back_conndnlc_cmp( const void *c1, const void *c2 );
135
136 ldapconn_t *
137 ldap_back_conn_delete( ldapinfo_t *li, ldapconn_t *lc )
138 {
139         if ( LDAP_BACK_PCONN_ISPRIV( lc ) ) {
140                 if ( LDAP_BACK_CONN_CACHED( lc ) ) {
141                         assert( lc->lc_q.tqe_prev != NULL );
142                         assert( li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_num > 0 );
143                         li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_num--;
144                         LDAP_TAILQ_REMOVE( &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_priv, lc, lc_q );
145                         LDAP_TAILQ_ENTRY_INIT( lc, lc_q );
146                         LDAP_BACK_CONN_CACHED_CLEAR( lc );
147
148                 } else {
149                         assert( LDAP_BACK_CONN_TAINTED( lc ) );
150                         assert( lc->lc_q.tqe_prev == NULL );
151                 }
152
153         } else {
154                 ldapconn_t      *tmplc = NULL;
155
156                 if ( LDAP_BACK_CONN_CACHED( lc ) ) {
157                         assert( !LDAP_BACK_CONN_TAINTED( lc ) );
158                         tmplc = avl_delete( &li->li_conninfo.lai_tree, (caddr_t)lc,
159                                 ldap_back_conndnlc_cmp );
160                         assert( tmplc == lc );
161                         LDAP_BACK_CONN_CACHED_CLEAR( lc );
162                 }
163
164                 assert( LDAP_BACK_CONN_TAINTED( lc ) || tmplc == lc );
165         }
166
167         return lc;
168 }
169
170 int
171 ldap_back_bind( Operation *op, SlapReply *rs )
172 {
173         ldapinfo_t              *li = (ldapinfo_t *) op->o_bd->be_private;
174         ldapconn_t              *lc;
175
176         int                     rc = 0;
177         ber_int_t               msgid;
178         ldap_back_send_t        retrying = LDAP_BACK_RETRYING;
179
180         lc = ldap_back_getconn( op, rs, LDAP_BACK_BIND_SERR, NULL, NULL );
181         if ( !lc ) {
182                 return rs->sr_err;
183         }
184
185         /* we can do (almost) whatever we want with this conn,
186          * because either it's temporary, or it's marked as binding */
187         if ( !BER_BVISNULL( &lc->lc_bound_ndn ) ) {
188                 ch_free( lc->lc_bound_ndn.bv_val );
189                 BER_BVZERO( &lc->lc_bound_ndn );
190         }
191         if ( !BER_BVISNULL( &lc->lc_cred ) ) {
192                 memset( lc->lc_cred.bv_val, 0, lc->lc_cred.bv_len );
193                 ch_free( lc->lc_cred.bv_val );
194                 BER_BVZERO( &lc->lc_cred );
195         }
196         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
197
198 retry:;
199         /* method is always LDAP_AUTH_SIMPLE if we got here */
200         rs->sr_err = ldap_sasl_bind( lc->lc_ld, op->o_req_dn.bv_val,
201                         LDAP_SASL_SIMPLE,
202                         &op->orb_cred, op->o_ctrls, NULL, &msgid );
203         /* FIXME: should we always retry, or only when piping the bind
204          * in the "override" connection pool? */
205         rc = ldap_back_op_result( lc, op, rs, msgid,
206                 li->li_timeout[ SLAP_OP_BIND ],
207                 LDAP_BACK_BIND_SERR | retrying );
208         if ( rc == LDAP_UNAVAILABLE && retrying ) {
209                 retrying &= ~LDAP_BACK_RETRYING;
210                 if ( ldap_back_retry( &lc, op, rs, LDAP_BACK_BIND_SERR ) ) {
211                         goto retry;
212                 }
213         }
214
215         if ( rc == LDAP_SUCCESS ) {
216                 /* If defined, proxyAuthz will be used also when
217                  * back-ldap is the authorizing backend; for this
218                  * purpose, after a successful bind the connection
219                  * is left for further binds, and further operations 
220                  * on this client connection will use a default
221                  * connection with identity assertion */
222                 /* NOTE: use with care */
223                 if ( li->li_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) {
224                         ldap_back_release_conn( li, lc );
225                         return( rc );
226                 }
227
228                 /* rebind is now done inside ldap_back_proxy_authz_bind()
229                  * in case of success */
230                 LDAP_BACK_CONN_ISBOUND_SET( lc );
231                 ber_dupbv( &lc->lc_bound_ndn, &op->o_req_ndn );
232
233                 if ( !BER_BVISNULL( &lc->lc_cred ) ) {
234                         memset( lc->lc_cred.bv_val, 0,
235                                         lc->lc_cred.bv_len );
236                 }
237
238                 if ( LDAP_BACK_SAVECRED( li ) ) {
239                         ber_bvreplace( &lc->lc_cred, &op->orb_cred );
240                         ldap_set_rebind_proc( lc->lc_ld, li->li_rebind_f, lc );
241
242                 } else {
243                         lc->lc_cred.bv_len = 0;
244                 }
245         }
246
247         /* must re-insert if local DN changed as result of bind */
248         if ( !LDAP_BACK_CONN_ISBOUND( lc )
249                 || ( !dn_match( &op->o_req_ndn, &lc->lc_local_ndn )
250                         && !LDAP_BACK_PCONN_ISPRIV( lc ) ) )
251         {
252                 int             lerr = -1;
253                 ldapconn_t      *tmplc;
254
255                 /* wait for all other ops to release the connection */
256 retry_lock:;
257                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
258                 if ( lc->lc_refcnt > 1 ) {
259                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
260                         ldap_pvt_thread_yield();
261                         goto retry_lock;
262                 }
263
264 #if LDAP_BACK_PRINT_CONNTREE > 0
265                 ldap_back_print_conntree( li, ">>> ldap_back_bind" );
266 #endif /* LDAP_BACK_PRINT_CONNTREE */
267
268                 assert( lc->lc_refcnt == 1 );
269                 ldap_back_conn_delete( li, lc );
270
271                 /* delete all cached connections with the current connection */
272                 if ( LDAP_BACK_SINGLECONN( li ) ) {
273                         while ( ( tmplc = avl_delete( &li->li_conninfo.lai_tree, (caddr_t)lc, ldap_back_conn_cmp ) ) != NULL )
274                         {
275                                 Debug( LDAP_DEBUG_TRACE,
276                                         "=>ldap_back_bind: destroying conn %ld (refcnt=%u)\n",
277                                         LDAP_BACK_PCONN_ID( lc ), lc->lc_refcnt, 0 );
278
279                                 if ( tmplc->lc_refcnt != 0 ) {
280                                         /* taint it */
281                                         LDAP_BACK_CONN_TAINTED_SET( tmplc );
282                                         LDAP_BACK_CONN_CACHED_CLEAR( tmplc );
283
284                                 } else {
285                                         /*
286                                          * Needs a test because the handler may be corrupted,
287                                          * and calling ldap_unbind on a corrupted header results
288                                          * in a segmentation fault
289                                          */
290                                         ldap_back_conn_free( tmplc );
291                                 }
292                         }
293                 }
294
295                 if ( LDAP_BACK_CONN_ISBOUND( lc ) ) {
296                         ber_bvreplace( &lc->lc_local_ndn, &op->o_req_ndn );
297                         if ( be_isroot_dn( op->o_bd, &op->o_req_ndn ) ) {
298                                 LDAP_BACK_PCONN_ROOTDN_SET( lc, op );
299                         }
300                         lerr = avl_insert( &li->li_conninfo.lai_tree, (caddr_t)lc,
301                                 ldap_back_conndn_cmp, ldap_back_conndn_dup );
302                 }
303
304 #if LDAP_BACK_PRINT_CONNTREE > 0
305                 ldap_back_print_conntree( li, "<<< ldap_back_bind" );
306 #endif /* LDAP_BACK_PRINT_CONNTREE */
307         
308                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
309                 switch ( lerr ) {
310                 case 0:
311                         LDAP_BACK_CONN_CACHED_SET( lc );
312                         break;
313
314                 case -1:
315                         /* duplicate; someone else successfully bound
316                          * on the same connection with the same identity;
317                          * we can do this because lc_refcnt == 1 */
318                         ldap_back_conn_free( lc );
319                         lc = NULL;
320                 }
321         }
322
323         if ( lc != NULL ) {
324                 ldap_back_release_conn( li, lc );
325         }
326
327         return( rc );
328 }
329
330 /*
331  * ldap_back_conndn_cmp
332  *
333  * compares two ldapconn_t based on the value of the conn pointer
334  * and of the local DN; used by avl stuff for insert, lookup
335  * and direct delete
336  */
337 int
338 ldap_back_conndn_cmp( const void *c1, const void *c2 )
339 {
340         const ldapconn_t        *lc1 = (const ldapconn_t *)c1;
341         const ldapconn_t        *lc2 = (const ldapconn_t *)c2;
342         int rc;
343
344         /* If local DNs don't match, it is definitely not a match */
345         /* For shared sessions, conn is NULL. Only explicitly
346          * bound sessions will have non-NULL conn.
347          */
348         rc = SLAP_PTRCMP( lc1->lc_conn, lc2->lc_conn );
349         if ( rc == 0 ) {
350                 rc = ber_bvcmp( &lc1->lc_local_ndn, &lc2->lc_local_ndn );
351         }
352
353         return rc;
354 }
355
356 /*
357  * ldap_back_conndnlc_cmp
358  *
359  * compares two ldapconn_t based on the value of the conn pointer,
360  * the local DN and the lc pointer; used by avl stuff for insert, lookup
361  * and direct delete
362  */
363 static int
364 ldap_back_conndnlc_cmp( const void *c1, const void *c2 )
365 {
366         const ldapconn_t        *lc1 = (const ldapconn_t *)c1;
367         const ldapconn_t        *lc2 = (const ldapconn_t *)c2;
368         int rc;
369
370         /* If local DNs don't match, it is definitely not a match */
371         /* For shared sessions, conn is NULL. Only explicitly
372          * bound sessions will have non-NULL conn.
373          */
374         rc = SLAP_PTRCMP( lc1->lc_conn, lc2->lc_conn );
375         if ( rc == 0 ) {
376                 rc = ber_bvcmp( &lc1->lc_local_ndn, &lc2->lc_local_ndn );
377                 if ( rc == 0 ) {
378                         rc = SLAP_PTRCMP( lc1, lc2 );
379                 }
380         }
381
382         return rc;
383 }
384
385 /*
386  * ldap_back_conn_cmp
387  *
388  * compares two ldapconn_t based on the value of the conn pointer;
389  * used by avl stuff for delete of all conns with the same connid
390  */
391 int
392 ldap_back_conn_cmp( const void *c1, const void *c2 )
393 {
394         const ldapconn_t        *lc1 = (const ldapconn_t *)c1;
395         const ldapconn_t        *lc2 = (const ldapconn_t *)c2;
396
397         /* For shared sessions, conn is NULL. Only explicitly
398          * bound sessions will have non-NULL conn.
399          */
400         return SLAP_PTRCMP( lc1->lc_conn, lc2->lc_conn );
401 }
402
403 /*
404  * ldap_back_conndn_dup
405  *
406  * returns -1 in case a duplicate ldapconn_t has been inserted;
407  * used by avl stuff
408  */
409 int
410 ldap_back_conndn_dup( void *c1, void *c2 )
411 {
412         ldapconn_t      *lc1 = (ldapconn_t *)c1;
413         ldapconn_t      *lc2 = (ldapconn_t *)c2;
414
415         /* Cannot have more than one shared session with same DN */
416         if ( lc1->lc_conn == lc2->lc_conn &&
417                 dn_match( &lc1->lc_local_ndn, &lc2->lc_local_ndn ) )
418         {
419                 return -1;
420         }
421                 
422         return 0;
423 }
424
425 static int
426 ldap_back_freeconn( ldapinfo_t *li, ldapconn_t *lc, int dolock )
427 {
428         if ( dolock ) {
429                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
430         }
431
432 #if LDAP_BACK_PRINT_CONNTREE > 0
433         ldap_back_print_conntree( li, ">>> ldap_back_freeconn" );
434 #endif /* LDAP_BACK_PRINT_CONNTREE */
435
436         (void)ldap_back_conn_delete( li, lc );
437
438         if ( lc->lc_refcnt == 0 ) {
439                 ldap_back_conn_free( (void *)lc );
440         }
441
442 #if LDAP_BACK_PRINT_CONNTREE > 0
443         ldap_back_print_conntree( li, "<<< ldap_back_freeconn" );
444 #endif /* LDAP_BACK_PRINT_CONNTREE */
445
446         if ( dolock ) {
447                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
448         }
449
450         return 0;
451 }
452
453 #ifdef HAVE_TLS
454 static int
455 ldap_back_start_tls(
456         LDAP            *ld,
457         int             protocol,
458         int             *is_tls,
459         const char      *url,
460         unsigned        flags,
461         int             retries,
462         const char      **text )
463 {
464         int             rc = LDAP_SUCCESS;
465
466         /* start TLS ("tls-[try-]{start,propagate}" statements) */
467         if ( ( LDAP_BACK_USE_TLS_F( flags ) || ( *is_tls && LDAP_BACK_PROPAGATE_TLS_F( flags ) ) )
468                                 && !ldap_is_ldaps_url( url ) )
469         {
470 #ifdef SLAP_STARTTLS_ASYNCHRONOUS
471                 /*
472                  * use asynchronous StartTLS
473                  * in case, chase referral (not implemented yet)
474                  */
475                 int             msgid;
476
477                 if ( protocol == 0 ) {
478                         ldap_get_option( ld, LDAP_OPT_PROTOCOL_VERSION,
479                                         (void *)&protocol );
480                 }
481
482                 if ( protocol < LDAP_VERSION3 ) {
483                         /* we should rather bail out... */
484                         rc = LDAP_UNWILLING_TO_PERFORM;
485                         *text = "invalid protocol version";
486                 }
487
488                 if ( rc == LDAP_SUCCESS ) {
489                         rc = ldap_start_tls( ld, NULL, NULL, &msgid );
490                 }
491
492                 if ( rc == LDAP_SUCCESS ) {
493                         LDAPMessage     *res = NULL;
494                         struct timeval  tv;
495
496                         LDAP_BACK_TV_SET( &tv );
497
498 retry:;
499                         rc = ldap_result( ld, msgid, LDAP_MSG_ALL, &tv, &res );
500                         if ( rc < 0 ) {
501                                 rc = LDAP_UNAVAILABLE;
502
503                         } else if ( rc == 0 ) {
504                                 if ( retries != LDAP_BACK_RETRY_NEVER ) {
505                                         ldap_pvt_thread_yield();
506                                         if ( retries > 0 ) {
507                                                 retries--;
508                                         }
509                                         LDAP_BACK_TV_SET( &tv );
510                                         goto retry;
511                                 }
512                                 rc = LDAP_UNAVAILABLE;
513
514                         } else if ( rc == LDAP_RES_EXTENDED ) {
515                                 struct berval   *data = NULL;
516
517                                 rc = ldap_parse_extended_result( ld, res,
518                                                 NULL, &data, 0 );
519                                 if ( rc == LDAP_SUCCESS ) {
520                                         int err;
521                                         rc = ldap_parse_result( ld, res, &err,
522                                                 NULL, NULL, NULL, NULL, 1 );
523                                         if ( rc == LDAP_SUCCESS ) {
524                                                 rc = err;
525                                         }
526                                         res = NULL;
527                                         
528                                         /* FIXME: in case a referral 
529                                          * is returned, should we try
530                                          * using it instead of the 
531                                          * configured URI? */
532                                         if ( rc == LDAP_SUCCESS ) {
533                                                 rc = ldap_install_tls( ld );
534
535                                         } else if ( rc == LDAP_REFERRAL ) {
536                                                 rc = LDAP_UNWILLING_TO_PERFORM;
537                                                 *text = "unwilling to chase referral returned by Start TLS exop";
538                                         }
539
540                                         if ( data ) {
541                                                 if ( data->bv_val ) {
542                                                         ber_memfree( data->bv_val );
543                                                 }
544                                                 ber_memfree( data );
545                                         }
546                                 }
547
548                         } else {
549                                 rc = LDAP_OTHER;
550                         }
551
552                         if ( res != NULL ) {
553                                 ldap_msgfree( res );
554                         }
555                 }
556 #else /* ! SLAP_STARTTLS_ASYNCHRONOUS */
557                 /*
558                  * use synchronous StartTLS
559                  */
560                 rc = ldap_start_tls_s( ld, NULL, NULL );
561 #endif /* ! SLAP_STARTTLS_ASYNCHRONOUS */
562
563                 /* if StartTLS is requested, only attempt it if the URL
564                  * is not "ldaps://"; this may occur not only in case
565                  * of misconfiguration, but also when used in the chain 
566                  * overlay, where the "uri" can be parsed out of a referral */
567                 switch ( rc ) {
568                 case LDAP_SUCCESS:
569                         *is_tls = 1;
570                         break;
571
572                 case LDAP_SERVER_DOWN:
573                         break;
574
575                 default:
576                         if ( LDAP_BACK_TLS_CRITICAL_F( flags ) ) {
577                                 *text = "could not start TLS";
578                                 break;
579                         }
580
581                         /* in case Start TLS is not critical */
582                         *is_tls = 0;
583                         rc = LDAP_SUCCESS;
584                         break;
585                 }
586
587         } else {
588                 *is_tls = 0;
589         }
590
591         return rc;
592 }
593 #endif /* HAVE_TLS */
594
595 static int
596 ldap_back_prepare_conn( ldapconn_t *lc, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
597 {
598         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
599         int             version;
600         LDAP            *ld = NULL;
601 #ifdef HAVE_TLS
602         int             is_tls = op->o_conn->c_is_tls;
603         time_t          lc_time = (time_t)(-1);
604 #endif /* HAVE_TLS */
605
606         ldap_pvt_thread_mutex_lock( &li->li_uri_mutex );
607         rs->sr_err = ldap_initialize( &ld, li->li_uri );
608         ldap_pvt_thread_mutex_unlock( &li->li_uri_mutex );
609         if ( rs->sr_err != LDAP_SUCCESS ) {
610                 goto error_return;
611         }
612
613         /* Set LDAP version. This will always succeed: If the client
614          * bound with a particular version, then so can we.
615          */
616         if ( li->li_version != 0 ) {
617                 version = li->li_version;
618
619         } else if ( op->o_protocol != 0 ) {
620                 version = op->o_protocol;
621
622         } else {
623                 /* assume it's an internal op; set to LDAPv3 */
624                 version = LDAP_VERSION3;
625         }
626         ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, (const void *)&version );
627
628         /* automatically chase referrals ("chase-referrals [{yes|no}]" statement) */
629         ldap_set_option( ld, LDAP_OPT_REFERRALS,
630                 LDAP_BACK_CHASE_REFERRALS( li ) ? LDAP_OPT_ON : LDAP_OPT_OFF );
631
632         if ( li->li_network_timeout > 0 ) {
633                 struct timeval          tv;
634
635                 tv.tv_sec = li->li_network_timeout;
636                 tv.tv_usec = 0;
637                 ldap_set_option( ld, LDAP_OPT_NETWORK_TIMEOUT, (const void *)&tv );
638         }
639
640 #ifdef HAVE_TLS
641         ldap_pvt_thread_mutex_lock( &li->li_uri_mutex );
642         rs->sr_err = ldap_back_start_tls( ld, op->o_protocol, &is_tls,
643                         li->li_uri, li->li_flags, li->li_nretries, &rs->sr_text );
644         ldap_pvt_thread_mutex_unlock( &li->li_uri_mutex );
645         if ( rs->sr_err != LDAP_SUCCESS ) {
646                 ldap_unbind_ext( ld, NULL, NULL );
647                 rs->sr_text = "Start TLS failed";
648                 goto error_return;
649
650         } else if ( li->li_idle_timeout ) {
651                 /* only touch when activity actually took place... */
652                 lc_time = op->o_time;
653         }
654 #endif /* HAVE_TLS */
655
656         lc->lc_ld = ld;
657         lc->lc_refcnt = 1;
658 #ifdef HAVE_TLS
659         if ( is_tls ) {
660                 LDAP_BACK_CONN_ISTLS_SET( lc );
661         } else {
662                 LDAP_BACK_CONN_ISTLS_CLEAR( lc );
663         }
664         if ( lc_time != (time_t)(-1) ) {
665                 lc->lc_time = lc_time;
666         }
667 #endif /* HAVE_TLS */
668
669 error_return:;
670         if ( rs->sr_err != LDAP_SUCCESS ) {
671                 rs->sr_err = slap_map_api2result( rs );
672                 if ( sendok & LDAP_BACK_SENDERR ) {
673                         if ( rs->sr_text == NULL ) {
674                                 rs->sr_text = "Proxy connection initialization failed";
675                         }
676                         send_ldap_result( op, rs );
677                 }
678
679         } else {
680                 if ( li->li_conn_ttl > 0 ) {
681                         lc->lc_create_time = op->o_time;
682                 }
683         }
684
685         return rs->sr_err;
686 }
687
688 static ldapconn_t *
689 ldap_back_getconn(
690         Operation               *op,
691         SlapReply               *rs,
692         ldap_back_send_t        sendok,
693         struct berval           *binddn,
694         struct berval           *bindcred )
695 {
696         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
697         ldapconn_t      *lc = NULL,
698                         lc_curr = { 0 };
699         int             refcnt = 1,
700                         lookupconn = !( sendok & LDAP_BACK_BINDING );
701
702         /* if the server is quarantined, and
703          * - the current interval did not expire yet, or
704          * - no more retries should occur,
705          * don't return the connection */
706         if ( li->li_isquarantined ) {
707                 slap_retry_info_t       *ri = &li->li_quarantine;
708                 int                     dont_retry = 1;
709
710                 if ( li->li_quarantine.ri_interval ) {
711                         ldap_pvt_thread_mutex_lock( &li->li_quarantine_mutex );
712                         if ( li->li_isquarantined == LDAP_BACK_FQ_YES ) {
713                                 dont_retry = ( ri->ri_num[ ri->ri_idx ] == SLAP_RETRYNUM_TAIL
714                                         || slap_get_time() < ri->ri_last + ri->ri_interval[ ri->ri_idx ] );
715                                 if ( !dont_retry ) {
716                                         Debug( LDAP_DEBUG_ANY,
717                                                 "%s: ldap_back_getconn quarantine "
718                                                 "retry block #%d try #%d.\n",
719                                                 op->o_log_prefix, ri->ri_idx, ri->ri_count );
720                                         li->li_isquarantined = LDAP_BACK_FQ_RETRYING;
721                                 }
722                         }
723                         ldap_pvt_thread_mutex_unlock( &li->li_quarantine_mutex );
724                 }
725
726                 if ( dont_retry ) {
727                         rs->sr_err = LDAP_UNAVAILABLE;
728                         if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
729                                 rs->sr_text = "Target is quarantined";
730                                 send_ldap_result( op, rs );
731                         }
732                         return NULL;
733                 }
734         }
735
736         /* Internal searches are privileged and shared. So is root. */
737         if ( op->o_do_not_cache || be_isroot( op ) ) {
738                 LDAP_BACK_CONN_ISPRIV_SET( &lc_curr );
739                 lc_curr.lc_local_ndn = op->o_bd->be_rootndn;
740                 LDAP_BACK_PCONN_ROOTDN_SET( &lc_curr, op );
741
742         } else {
743                 struct berval   tmpbinddn,
744                                 tmpbindcred,
745                                 save_o_dn,
746                                 save_o_ndn;
747                 int             isproxyauthz;
748
749                 /* need cleanup */
750                 if ( binddn == NULL ) {
751                         binddn = &tmpbinddn;
752                 }       
753                 if ( bindcred == NULL ) {
754                         bindcred = &tmpbindcred;
755                 }
756                 if ( op->o_tag == LDAP_REQ_BIND ) {
757                         save_o_dn = op->o_dn;
758                         save_o_ndn = op->o_ndn;
759                         op->o_dn = op->o_req_dn;
760                         op->o_ndn = op->o_req_ndn;
761                 }
762                 isproxyauthz = ldap_back_is_proxy_authz( op, rs, sendok, binddn, bindcred );
763                 if ( op->o_tag == LDAP_REQ_BIND ) {
764                         op->o_dn = save_o_dn;
765                         op->o_ndn = save_o_ndn;
766                 }
767                 if ( isproxyauthz == -1 ) {
768                         return NULL;
769                 }
770
771                 lc_curr.lc_local_ndn = op->o_ndn;
772                 /* Explicit binds must not be shared;
773                  * however, explicit binds are piped in a special connection
774                  * when idassert is to occur with "override" set */
775                 if ( op->o_tag == LDAP_REQ_BIND && !isproxyauthz ) {
776                         lc_curr.lc_conn = op->o_conn;
777
778                 } else {
779                         if ( isproxyauthz && !( sendok & LDAP_BACK_BINDING ) ) {
780                                 lc_curr.lc_local_ndn = *binddn;
781                                 LDAP_BACK_PCONN_ROOTDN_SET( &lc_curr, op );
782                                 LDAP_BACK_CONN_ISIDASSERT_SET( &lc_curr );
783
784                         } else if ( isproxyauthz && ( li->li_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) ) {
785                                 lc_curr.lc_local_ndn = slap_empty_bv;
786                                 LDAP_BACK_PCONN_BIND_SET( &lc_curr, op );
787                                 LDAP_BACK_CONN_ISIDASSERT_SET( &lc_curr );
788                                 lookupconn = 1;
789
790                         } else if ( SLAP_IS_AUTHZ_BACKEND( op ) ) {
791                                 lc_curr.lc_conn = op->o_conn;
792
793                         } else {
794                                 LDAP_BACK_PCONN_ANON_SET( &lc_curr, op );
795                         }
796                 }
797         }
798
799         /* Explicit Bind requests always get their own conn */
800         if ( lookupconn ) {
801 retry_lock:
802                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
803                 if ( LDAP_BACK_PCONN_ISPRIV( &lc_curr ) ) {
804                         /* lookup a conn that's not binding */
805                         LDAP_TAILQ_FOREACH( lc,
806                                 &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( &lc_curr ) ].lic_priv,
807                                 lc_q )
808                         {
809                                 if ( !LDAP_BACK_CONN_BINDING( lc ) && lc->lc_refcnt == 0 ) {
810                                         break;
811                                 }
812                         }
813
814                         if ( lc != NULL ) {
815                                 if ( lc != LDAP_TAILQ_LAST( &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_priv,
816                                         ldapconn_t, lc_q ) )
817                                 {
818                                         LDAP_TAILQ_REMOVE( &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_priv,
819                                                 lc, lc_q );
820                                         LDAP_TAILQ_ENTRY_INIT( lc, lc_q );
821                                         LDAP_TAILQ_INSERT_TAIL( &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_priv,
822                                                 lc, lc_q );
823                                 }
824
825                         } else if ( !LDAP_BACK_USE_TEMPORARIES( li )
826                                 && li->li_conn_priv[ LDAP_BACK_CONN2PRIV( &lc_curr ) ].lic_num == li->li_conn_priv_max )
827                         {
828                                 lc = LDAP_TAILQ_FIRST( &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( &lc_curr ) ].lic_priv );
829                         }
830                         
831                 } else {
832
833                         /* Searches for a ldapconn in the avl tree */
834                         lc = (ldapconn_t *)avl_find( li->li_conninfo.lai_tree, 
835                                         (caddr_t)&lc_curr, ldap_back_conndn_cmp );
836                 }
837
838                 if ( lc != NULL ) {
839                         /* Don't reuse connections while they're still binding */
840                         if ( LDAP_BACK_CONN_BINDING( lc ) ) {
841                                 if ( !LDAP_BACK_USE_TEMPORARIES( li ) ) {
842                                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
843
844                                         ldap_pvt_thread_yield();
845                                         goto retry_lock;
846                                 }
847                                 lc = NULL;
848                         }
849
850                         if ( lc != NULL ) {
851                                 if ( op->o_tag == LDAP_REQ_BIND ) {
852                                         /* right now, this is the only possible case */
853                                         assert( ( li->li_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) );
854                                         LDAP_BACK_CONN_BINDING_SET( lc );
855                                 }
856
857                                 refcnt = ++lc->lc_refcnt;
858                         }
859                 }
860                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
861         }
862
863         /* Looks like we didn't get a bind. Open a new session... */
864         if ( lc == NULL ) {
865                 lc = (ldapconn_t *)ch_calloc( 1, sizeof( ldapconn_t ) );
866                 lc->lc_flags = li->li_flags;
867                 lc->lc_lcflags = lc_curr.lc_lcflags;
868                 if ( ldap_back_prepare_conn( lc, op, rs, sendok ) != LDAP_SUCCESS ) {
869                         ch_free( lc );
870                         return NULL;
871                 }
872
873                 if ( sendok & LDAP_BACK_BINDING ) {
874                         LDAP_BACK_CONN_BINDING_SET( lc );
875                 }
876
877                 lc->lc_conn = lc_curr.lc_conn;
878                 ber_dupbv( &lc->lc_local_ndn, &lc_curr.lc_local_ndn );
879
880                 /*
881                  * the rationale is: connections as the rootdn are privileged,
882                  * so acl_authcDN is to be used; however, in some cases
883                  * one already configured identity assertion with a highly
884                  * privileged idassert_authcDN, so if acl_authcDN is NULL
885                  * and idassert_authcDN is not, use the second instead.
886                  *
887                  * might change in the future, because it's preferable
888                  * to make clear what identity is being used, since
889                  * the only drawback is that one risks to configure
890                  * the same identity twice...
891                  */
892                 if ( LDAP_BACK_CONN_ISPRIV( &lc_curr ) ) {
893                         if ( BER_BVISNULL( &li->li_acl_authcDN ) && !BER_BVISNULL( &li->li_idassert_authcDN ) ) {
894                                 ber_dupbv( &lc->lc_bound_ndn, &li->li_idassert_authcDN );
895                                 ber_dupbv( &lc->lc_cred, &li->li_idassert_passwd );
896
897                         } else {
898                                 ber_dupbv( &lc->lc_bound_ndn, &li->li_acl_authcDN );
899                                 ber_dupbv( &lc->lc_cred, &li->li_acl_passwd );
900                         }
901                         LDAP_BACK_CONN_ISPRIV_SET( lc );
902
903                 } else if ( LDAP_BACK_CONN_ISIDASSERT( &lc_curr ) ) {
904                         if ( !LDAP_BACK_PCONN_ISBIND( &lc_curr ) ) {
905                                 ber_dupbv( &lc->lc_bound_ndn, &li->li_idassert_authcDN );
906                                 ber_dupbv( &lc->lc_cred, &li->li_idassert_passwd );
907                         }
908                         LDAP_BACK_CONN_ISIDASSERT_SET( lc );
909
910                 } else {
911                         BER_BVZERO( &lc->lc_cred );
912                         BER_BVZERO( &lc->lc_bound_ndn );
913                         if ( !BER_BVISEMPTY( &op->o_ndn )
914                                 && SLAP_IS_AUTHZ_BACKEND( op ) )
915                         {
916                                 ber_dupbv( &lc->lc_bound_ndn, &op->o_ndn );
917                         }
918                 }
919
920 #ifdef HAVE_TLS
921                 /* if start TLS failed but it was not mandatory,
922                  * check if the non-TLS connection was already
923                  * in cache; in case, destroy the newly created
924                  * connection and use the existing one */
925                 if ( LDAP_BACK_PCONN_ISTLS( lc ) 
926                                 && !ldap_tls_inplace( lc->lc_ld ) )
927                 {
928                         ldapconn_t      *tmplc = NULL;
929                         int             idx = LDAP_BACK_CONN2PRIV( &lc_curr ) - 1;
930                         
931                         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
932                         LDAP_TAILQ_FOREACH( tmplc,
933                                 &li->li_conn_priv[ idx ].lic_priv,
934                                 lc_q )
935                         {
936                                 if ( !LDAP_BACK_CONN_BINDING( tmplc ) ) {
937                                         break;
938                                 }
939                         }
940
941                         if ( tmplc != NULL ) {
942                                 refcnt = ++tmplc->lc_refcnt;
943                                 ldap_back_conn_free( lc );
944                                 lc = tmplc;
945                         }
946                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
947
948                         if ( tmplc != NULL ) {
949                                 goto done;
950                         }
951                 }
952 #endif /* HAVE_TLS */
953
954                 /* Inserts the newly created ldapconn in the avl tree */
955                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
956
957                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
958
959                 assert( lc->lc_refcnt == 1 );
960
961 #if LDAP_BACK_PRINT_CONNTREE > 0
962                 ldap_back_print_conntree( li, ">>> ldap_back_getconn(insert)" );
963 #endif /* LDAP_BACK_PRINT_CONNTREE */
964         
965                 if ( LDAP_BACK_PCONN_ISPRIV( lc ) ) {
966                         if ( li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_num < li->li_conn_priv_max ) {
967                                 LDAP_TAILQ_INSERT_TAIL( &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_priv, lc, lc_q );
968                                 li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_num++;
969                                 LDAP_BACK_CONN_CACHED_SET( lc );
970
971                         } else {
972                                 LDAP_BACK_CONN_TAINTED_SET( lc );
973                         }
974                         rs->sr_err = 0;
975
976                 } else {
977                         rs->sr_err = avl_insert( &li->li_conninfo.lai_tree, (caddr_t)lc,
978                                 ldap_back_conndn_cmp, ldap_back_conndn_dup );
979                         LDAP_BACK_CONN_CACHED_SET( lc );
980                 }
981
982 #if LDAP_BACK_PRINT_CONNTREE > 0
983                 ldap_back_print_conntree( li, "<<< ldap_back_getconn(insert)" );
984 #endif /* LDAP_BACK_PRINT_CONNTREE */
985         
986                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
987
988                 if ( StatslogTest( LDAP_DEBUG_TRACE ) ) {
989                         char    buf[ SLAP_TEXT_BUFLEN ];
990
991                         snprintf( buf, sizeof( buf ),
992                                 "lc=%p inserted refcnt=%u rc=%d",
993                                 (void *)lc, refcnt, rs->sr_err );
994                                 
995                         Debug( LDAP_DEBUG_TRACE,
996                                 "=>ldap_back_getconn: %s: %s\n",
997                                 op->o_log_prefix, buf, 0 );
998                 }
999         
1000                 if ( !LDAP_BACK_PCONN_ISPRIV( lc ) ) {
1001                         /* Err could be -1 in case a duplicate ldapconn is inserted */
1002                         switch ( rs->sr_err ) {
1003                         case 0:
1004                                 break;
1005
1006                         case -1:
1007                                 LDAP_BACK_CONN_CACHED_CLEAR( lc );
1008                                 if ( !( sendok & LDAP_BACK_BINDING ) && !LDAP_BACK_USE_TEMPORARIES( li ) ) {
1009                                         /* duplicate: free and try to get the newly created one */
1010                                         ldap_back_conn_free( lc );
1011                                         lc = NULL;
1012                                         goto retry_lock;
1013                                 }
1014
1015                                 /* taint connection, so that it'll be freed when released */
1016                                 LDAP_BACK_CONN_TAINTED_SET( lc );
1017                                 break;
1018
1019                         default:
1020                                 LDAP_BACK_CONN_CACHED_CLEAR( lc );
1021                                 ldap_back_conn_free( lc );
1022                                 rs->sr_err = LDAP_OTHER;
1023                                 rs->sr_text = "Proxy bind collision";
1024                                 if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
1025                                         send_ldap_result( op, rs );
1026                                 }
1027                                 return NULL;
1028                         }
1029                 }
1030
1031         } else {
1032                 int     expiring = 0;
1033
1034                 if ( ( li->li_idle_timeout != 0 && op->o_time > lc->lc_time + li->li_idle_timeout )
1035                         || ( li->li_conn_ttl != 0 && op->o_time > lc->lc_create_time + li->li_conn_ttl ) )
1036                 {
1037                         expiring = 1;
1038
1039                         /* let it be used, but taint/delete it so that 
1040                          * no-one else can look it up any further */
1041                         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1042
1043 #if LDAP_BACK_PRINT_CONNTREE > 0
1044                         ldap_back_print_conntree( li, ">>> ldap_back_getconn(timeout)" );
1045 #endif /* LDAP_BACK_PRINT_CONNTREE */
1046
1047                         (void)ldap_back_conn_delete( li, lc );
1048                         LDAP_BACK_CONN_TAINTED_SET( lc );
1049
1050 #if LDAP_BACK_PRINT_CONNTREE > 0
1051                         ldap_back_print_conntree( li, "<<< ldap_back_getconn(timeout)" );
1052 #endif /* LDAP_BACK_PRINT_CONNTREE */
1053
1054                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1055                 }
1056
1057                 if ( StatslogTest( LDAP_DEBUG_TRACE ) ) {
1058                         char    buf[ SLAP_TEXT_BUFLEN ];
1059
1060                         snprintf( buf, sizeof( buf ),
1061                                 "conn %p fetched refcnt=%u%s",
1062                                 (void *)lc, refcnt,
1063                                 expiring ? " expiring" : "" );
1064                         Debug( LDAP_DEBUG_TRACE,
1065                                 "=>ldap_back_getconn: %s.\n", buf, 0, 0 );
1066                 }
1067         }
1068
1069 #ifdef HAVE_TLS
1070 done:;
1071 #endif /* HAVE_TLS */
1072
1073         return lc;
1074 }
1075
1076 void
1077 ldap_back_release_conn_lock(
1078         ldapinfo_t              *li,
1079         ldapconn_t              **lcp,
1080         int                     dolock )
1081 {
1082
1083         ldapconn_t      *lc = *lcp;
1084
1085         if ( dolock ) {
1086                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1087         }
1088         assert( lc->lc_refcnt > 0 );
1089         LDAP_BACK_CONN_BINDING_CLEAR( lc );
1090         lc->lc_refcnt--;
1091         if ( LDAP_BACK_CONN_TAINTED( lc ) ) {
1092                 ldap_back_freeconn( li, lc, 0 );
1093                 *lcp = NULL;
1094         }
1095         if ( dolock ) {
1096                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1097         }
1098 }
1099
1100 void
1101 ldap_back_quarantine(
1102         Operation       *op,
1103         SlapReply       *rs )
1104 {
1105         ldapinfo_t              *li = (ldapinfo_t *)op->o_bd->be_private;
1106
1107         slap_retry_info_t       *ri = &li->li_quarantine;
1108
1109         ldap_pvt_thread_mutex_lock( &li->li_quarantine_mutex );
1110
1111         if ( rs->sr_err == LDAP_UNAVAILABLE ) {
1112                 time_t          new_last = slap_get_time();
1113
1114                 switch ( li->li_isquarantined ) {
1115                 case LDAP_BACK_FQ_NO:
1116                         if ( ri->ri_last == new_last ) {
1117                                 goto done;
1118                         }
1119
1120                         Debug( LDAP_DEBUG_ANY,
1121                                 "%s: ldap_back_quarantine enter.\n",
1122                                 op->o_log_prefix, 0, 0 );
1123
1124                         ri->ri_idx = 0;
1125                         ri->ri_count = 0;
1126                         break;
1127
1128                 case LDAP_BACK_FQ_RETRYING:
1129                         Debug( LDAP_DEBUG_ANY,
1130                                 "%s: ldap_back_quarantine block #%d try #%d failed.\n",
1131                                 op->o_log_prefix, ri->ri_idx, ri->ri_count );
1132
1133                         ++ri->ri_count;
1134                         if ( ri->ri_num[ ri->ri_idx ] != SLAP_RETRYNUM_FOREVER
1135                                 && ri->ri_count == ri->ri_num[ ri->ri_idx ] )
1136                         {
1137                                 ri->ri_count = 0;
1138                                 ++ri->ri_idx;
1139                         }
1140                         break;
1141
1142                 default:
1143                         break;
1144                 }
1145
1146                 li->li_isquarantined = LDAP_BACK_FQ_YES;
1147                 ri->ri_last = new_last;
1148
1149         } else if ( li->li_isquarantined != LDAP_BACK_FQ_NO ) {
1150                 if ( ri->ri_last == slap_get_time() ) {
1151                         goto done;
1152                 }
1153
1154                 Debug( LDAP_DEBUG_ANY,
1155                         "%s: ldap_back_quarantine exit (%d) err=%d.\n",
1156                         op->o_log_prefix, li->li_isquarantined, rs->sr_err );
1157
1158                 if ( li->li_quarantine_f ) {
1159                         (void)li->li_quarantine_f( li, li->li_quarantine_p );
1160                 }
1161
1162                 ri->ri_count = 0;
1163                 ri->ri_idx = 0;
1164                 li->li_isquarantined = LDAP_BACK_FQ_NO;
1165         }
1166
1167 done:;
1168         ldap_pvt_thread_mutex_unlock( &li->li_quarantine_mutex );
1169 }
1170
1171 /*
1172  * ldap_back_dobind_int
1173  *
1174  * Note: dolock indicates whether li->li_conninfo.lai_mutex must be locked or not
1175  */
1176 static int
1177 ldap_back_dobind_int(
1178         ldapconn_t              **lcp,
1179         Operation               *op,
1180         SlapReply               *rs,
1181         ldap_back_send_t        sendok,
1182         int                     retries,
1183         int                     dolock )
1184 {       
1185         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1186
1187         ldapconn_t      *lc;
1188         struct berval   binddn = slap_empty_bv,
1189                         bindcred = slap_empty_bv;
1190
1191         int             rc = 0,
1192                         isbound,
1193                         binding = 0;
1194         ber_int_t       msgid;
1195
1196         assert( lcp != NULL );
1197         assert( retries >= 0 );
1198
1199         if ( sendok & LDAP_BACK_GETCONN ) {
1200                 assert( *lcp == NULL );
1201
1202                 lc = ldap_back_getconn( op, rs, sendok, &binddn, &bindcred );
1203                 if ( lc == NULL ) {
1204                         return 0;
1205                 }
1206                 *lcp = lc;
1207
1208         } else {
1209                 lc = *lcp;
1210         }
1211
1212         assert( lc != NULL );
1213
1214 retry_lock:;
1215         if ( dolock ) {
1216                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1217         }
1218
1219         if ( binding == 0 ) {
1220                 /* check if already bound */
1221                 rc = isbound = LDAP_BACK_CONN_ISBOUND( lc );
1222                 if ( isbound ) {
1223                         if ( dolock ) {
1224                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1225                         }
1226                         return rc;
1227                 }
1228
1229                 if ( LDAP_BACK_CONN_BINDING( lc ) ) {
1230                         /* if someone else is about to bind it, give up and retry */
1231                         if ( dolock ) {
1232                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1233                         }
1234                         ldap_pvt_thread_yield();
1235                         goto retry_lock;
1236
1237                 } else {
1238                         /* otherwise this thread will bind it */
1239                         LDAP_BACK_CONN_BINDING_SET( lc );
1240                         binding = 1;
1241                 }
1242         }
1243
1244         if ( dolock ) {
1245                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1246         }
1247
1248         /*
1249          * FIXME: we need to let clients use proxyAuthz
1250          * otherwise we cannot do symmetric pools of servers;
1251          * we have to live with the fact that a user can
1252          * authorize itself as any ID that is allowed
1253          * by the authzTo directive of the "proxyauthzdn".
1254          */
1255         /*
1256          * NOTE: current Proxy Authorization specification
1257          * and implementation do not allow proxy authorization
1258          * control to be provided with Bind requests
1259          */
1260         /*
1261          * if no bind took place yet, but the connection is bound
1262          * and the "idassert-authcDN" (or other ID) is set, 
1263          * then bind as the asserting identity and explicitly 
1264          * add the proxyAuthz control to every operation with the
1265          * dn bound to the connection as control value.
1266          * This is done also if this is the authrizing backend,
1267          * but the "override" flag is given to idassert.
1268          * It allows to use SASL bind and yet proxyAuthz users
1269          */
1270         if ( LDAP_BACK_CONN_ISIDASSERT( lc ) ) {
1271                 if ( BER_BVISEMPTY( &binddn ) && BER_BVISEMPTY( &bindcred ) ) {
1272                         /* if we got here, it shouldn't return result */
1273                         rc = ldap_back_is_proxy_authz( op, rs,
1274                                 LDAP_BACK_DONTSEND, &binddn, &bindcred );
1275                         assert( rc == 1 );
1276                 }
1277                 rc = ldap_back_proxy_authz_bind( lc, op, rs, sendok, &binddn, &bindcred );
1278                 goto done;
1279         }
1280
1281 #ifdef HAVE_CYRUS_SASL
1282         if ( LDAP_BACK_CONN_ISPRIV( lc )
1283                 && li->li_acl_authmethod == LDAP_AUTH_SASL )
1284         {
1285                 void            *defaults = NULL;
1286
1287                 if ( li->li_acl_secprops != NULL ) {
1288                         rc = ldap_set_option( lc->lc_ld,
1289                                 LDAP_OPT_X_SASL_SECPROPS, li->li_acl_secprops );
1290
1291                         if ( rc != LDAP_OPT_SUCCESS ) {
1292                                 Debug( LDAP_DEBUG_ANY, "Error: ldap_set_option "
1293                                         "(SECPROPS,\"%s\") failed!\n",
1294                                         li->li_acl_secprops, 0, 0 );
1295                                 goto done;
1296                         }
1297                 }
1298
1299                 defaults = lutil_sasl_defaults( lc->lc_ld,
1300                                 li->li_acl_sasl_mech.bv_val,
1301                                 li->li_acl_sasl_realm.bv_val,
1302                                 li->li_acl_authcID.bv_val,
1303                                 li->li_acl_passwd.bv_val,
1304                                 NULL );
1305
1306                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld,
1307                                 li->li_acl_authcDN.bv_val,
1308                                 li->li_acl_sasl_mech.bv_val, NULL, NULL,
1309                                 LDAP_SASL_QUIET, lutil_sasl_interact,
1310                                 defaults );
1311
1312                 lutil_sasl_freedefs( defaults );
1313
1314                 switch ( rs->sr_err ) {
1315                 case LDAP_SUCCESS:
1316                         LDAP_BACK_CONN_ISBOUND_SET( lc );
1317                         break;
1318
1319                 case LDAP_LOCAL_ERROR:
1320                         /* list client API error codes that require
1321                          * to taint the connection */
1322                         /* FIXME: should actually retry? */
1323                         LDAP_BACK_CONN_TAINTED_SET( lc );
1324
1325                         /* fallthru */
1326
1327                 default:
1328                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1329                         rs->sr_err = slap_map_api2result( rs );
1330                         if ( sendok & LDAP_BACK_SENDERR ) {
1331                                 send_ldap_result( op, rs );
1332                         }
1333                         break;
1334                 }
1335
1336                 if ( LDAP_BACK_QUARANTINE( li ) ) {
1337                         ldap_back_quarantine( op, rs );
1338                 }
1339
1340                 goto done;
1341         }
1342 #endif /* HAVE_CYRUS_SASL */
1343
1344 retry:;
1345         rs->sr_err = ldap_sasl_bind( lc->lc_ld,
1346                         BER_BVISNULL( &lc->lc_cred ) ? "" : lc->lc_bound_ndn.bv_val,
1347                         LDAP_SASL_SIMPLE, &lc->lc_cred,
1348                         NULL, NULL, &msgid );
1349
1350         if ( rs->sr_err == LDAP_SERVER_DOWN ) {
1351                 if ( retries != LDAP_BACK_RETRY_NEVER ) {
1352                         if ( dolock ) {
1353                                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1354                         }
1355
1356                         assert( lc->lc_refcnt > 0 );
1357                         if ( lc->lc_refcnt == 1 ) {
1358                                 ldap_unbind_ext( lc->lc_ld, NULL, NULL );
1359                                 lc->lc_ld = NULL;
1360
1361                                 /* lc here must be the regular lc, reset and ready for init */
1362                                 rs->sr_err = ldap_back_prepare_conn( lc, op, rs, sendok );
1363                                 if ( rs->sr_err != LDAP_SUCCESS ) {
1364                                         sendok &= ~LDAP_BACK_SENDERR;
1365                                         lc->lc_refcnt = 0;
1366                                 }
1367                         }
1368
1369                         if ( dolock ) {
1370                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1371                         }
1372
1373                         if ( rs->sr_err == LDAP_SUCCESS ) {
1374                                 if ( retries > 0 ) {
1375                                         retries--;
1376                                 }
1377                                 goto retry;
1378                         }
1379                 }
1380
1381                 assert( lc->lc_refcnt == 1 );
1382                 lc->lc_refcnt = 0;
1383                 ldap_back_freeconn( li, lc, dolock );
1384                 *lcp = NULL;
1385                 rs->sr_err = slap_map_api2result( rs );
1386
1387                 if ( LDAP_BACK_QUARANTINE( li ) ) {
1388                         ldap_back_quarantine( op, rs );
1389                 }
1390
1391                 if ( rs->sr_err != LDAP_SUCCESS &&
1392                         ( sendok & LDAP_BACK_SENDERR ) )
1393                 {
1394                         rs->sr_text = "Internal proxy bind failure";
1395                         send_ldap_result( op, rs );
1396                 }
1397
1398                 return 0;
1399         }
1400
1401         rc = ldap_back_op_result( lc, op, rs, msgid,
1402                 -1, ( sendok | LDAP_BACK_BINDING ) );
1403         if ( rc == LDAP_SUCCESS ) {
1404                 LDAP_BACK_CONN_ISBOUND_SET( lc );
1405         }
1406
1407 done:;
1408         LDAP_BACK_CONN_BINDING_CLEAR( lc );
1409         rc = LDAP_BACK_CONN_ISBOUND( lc );
1410         if ( !rc ) {
1411                 ldap_back_release_conn_lock( li, lcp, dolock );
1412
1413         } else if ( LDAP_BACK_SAVECRED( li ) ) {
1414                 ldap_set_rebind_proc( lc->lc_ld, li->li_rebind_f, lc );
1415         }
1416
1417         return rc;
1418 }
1419
1420 /*
1421  * ldap_back_dobind
1422  *
1423  * Note: dolock indicates whether li->li_conninfo.lai_mutex must be locked or not
1424  */
1425 int
1426 ldap_back_dobind( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1427 {
1428         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1429
1430         return ldap_back_dobind_int( lcp, op, rs,
1431                 ( sendok | LDAP_BACK_GETCONN ), li->li_nretries, 1 );
1432 }
1433
1434 /*
1435  * ldap_back_default_rebind
1436  *
1437  * This is a callback used for chasing referrals using the same
1438  * credentials as the original user on this session.
1439  */
1440 int 
1441 ldap_back_default_rebind( LDAP *ld, LDAP_CONST char *url, ber_tag_t request,
1442         ber_int_t msgid, void *params )
1443 {
1444         ldapconn_t      *lc = (ldapconn_t *)params;
1445
1446 #ifdef HAVE_TLS
1447         /* ... otherwise we couldn't get here */
1448         assert( lc != NULL );
1449
1450         if ( !ldap_tls_inplace( ld ) ) {
1451                 int             is_tls = LDAP_BACK_CONN_ISTLS( lc ),
1452                                 rc;
1453                 const char      *text = NULL;
1454
1455                 rc = ldap_back_start_tls( ld, 0, &is_tls, url, lc->lc_flags,
1456                         LDAP_BACK_RETRY_DEFAULT, &text );
1457                 if ( rc != LDAP_SUCCESS ) {
1458                         return rc;
1459                 }
1460         }
1461 #endif /* HAVE_TLS */
1462
1463         /* FIXME: add checks on the URL/identity? */
1464
1465         return ldap_sasl_bind_s( ld,
1466                         BER_BVISNULL( &lc->lc_cred ) ? "" : lc->lc_bound_ndn.bv_val,
1467                         LDAP_SASL_SIMPLE, &lc->lc_cred, NULL, NULL, NULL );
1468 }
1469
1470 int
1471 ldap_back_cancel(
1472                 ldapconn_t              *lc,
1473                 Operation               *op,
1474                 SlapReply               *rs,
1475                 ber_int_t               msgid,
1476                 ldap_back_send_t        sendok )
1477 {
1478         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1479
1480         /* default behavior */
1481         if ( LDAP_BACK_ABANDON( li ) ) {
1482                 return ldap_abandon_ext( lc->lc_ld, msgid, NULL, NULL );
1483         }
1484
1485         if ( LDAP_BACK_CANCEL( li ) ) {
1486                 /* FIXME: asynchronous? */
1487                 return ldap_cancel_s( lc->lc_ld, msgid, NULL, NULL );
1488         }
1489
1490         assert( 0 );
1491
1492         return LDAP_OTHER;
1493 }
1494
1495 int
1496 ldap_back_op_result(
1497                 ldapconn_t              *lc,
1498                 Operation               *op,
1499                 SlapReply               *rs,
1500                 ber_int_t               msgid,
1501                 time_t                  timeout,
1502                 ldap_back_send_t        sendok )
1503 {
1504         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1505
1506         char            *match = NULL;
1507         char            *text = NULL;
1508         char            **refs = NULL;
1509         LDAPControl     **ctrls = NULL;
1510
1511 #define ERR_OK(err) ((err) == LDAP_SUCCESS || (err) == LDAP_COMPARE_FALSE || (err) == LDAP_COMPARE_TRUE)
1512
1513         rs->sr_text = NULL;
1514         rs->sr_matched = NULL;
1515         rs->sr_ref = NULL;
1516         rs->sr_ctrls = NULL;
1517
1518         /* if the error recorded in the reply corresponds
1519          * to a successful state, get the error from the
1520          * remote server response */
1521         if ( ERR_OK( rs->sr_err ) ) {
1522                 int             rc;
1523                 struct timeval  tv;
1524                 LDAPMessage     *res = NULL;
1525                 time_t          stoptime = (time_t)(-1);
1526                 int             timeout_err = op->o_protocol >= LDAP_VERSION3 ?
1527                                         LDAP_ADMINLIMIT_EXCEEDED : LDAP_OTHER;
1528                 const char      *timeout_text = "Operation timed out";
1529
1530                 /* if timeout is not specified, compute and use
1531                  * the one specific to the ongoing operation */
1532                 if ( timeout == (time_t)(-1) ) {
1533                         slap_op_t       opidx = slap_req2op( op->o_tag );
1534
1535                         if ( opidx == SLAP_OP_SEARCH ) {
1536                                 if ( op->ors_tlimit <= 0 ) {
1537                                         timeout = 0;
1538
1539                                 } else {
1540                                         timeout = op->ors_tlimit;
1541                                         timeout_err = LDAP_TIMELIMIT_EXCEEDED;
1542                                         timeout_text = NULL;
1543                                 }
1544
1545                         } else {
1546                                 timeout = li->li_timeout[ opidx ];
1547                         }
1548                 }
1549
1550                 /* better than nothing :) */
1551                 if ( timeout == 0 ) {
1552                         if ( li->li_idle_timeout ) {
1553                                 timeout = li->li_idle_timeout;
1554
1555                         } else if ( li->li_conn_ttl ) {
1556                                 timeout = li->li_conn_ttl;
1557                         }
1558                 }
1559
1560                 if ( timeout ) {
1561                         stoptime = op->o_time + timeout;
1562                 }
1563
1564                 LDAP_BACK_TV_SET( &tv );
1565
1566 retry:;
1567                 /* if result parsing fails, note the failure reason */
1568                 rc = ldap_result( lc->lc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
1569                 switch ( rc ) {
1570                 case 0:
1571                         if ( timeout && slap_get_time() > stoptime ) {
1572                                 if ( sendok & LDAP_BACK_BINDING ) {
1573                                         ldap_unbind_ext( lc->lc_ld, NULL, NULL );
1574                                         lc->lc_ld = NULL;
1575
1576                                         /* let it be used, but taint/delete it so that 
1577                                          * no-one else can look it up any further */
1578                                         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1579
1580 #if LDAP_BACK_PRINT_CONNTREE > 0
1581                                         ldap_back_print_conntree( li, ">>> ldap_back_getconn(timeout)" );
1582 #endif /* LDAP_BACK_PRINT_CONNTREE */
1583
1584                                         (void)ldap_back_conn_delete( li, lc );
1585                                         LDAP_BACK_CONN_TAINTED_SET( lc );
1586
1587 #if LDAP_BACK_PRINT_CONNTREE > 0
1588                                         ldap_back_print_conntree( li, "<<< ldap_back_getconn(timeout)" );
1589 #endif /* LDAP_BACK_PRINT_CONNTREE */
1590                                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1591
1592                                 } else {
1593                                         (void)ldap_back_cancel( lc, op, rs, msgid, sendok );
1594                                 }
1595                                 rs->sr_err = timeout_err;
1596                                 rs->sr_text = timeout_text;
1597                                 break;
1598                         }
1599
1600                         /* timeout == 0 */
1601                         LDAP_BACK_TV_SET( &tv );
1602                         ldap_pvt_thread_yield();
1603                         goto retry;
1604
1605                 case -1:
1606                         ldap_get_option( lc->lc_ld, LDAP_OPT_ERROR_NUMBER,
1607                                         &rs->sr_err );
1608                         break;
1609
1610
1611                 /* otherwise get the result; if it is not
1612                  * LDAP_SUCCESS, record it in the reply
1613                  * structure (this includes 
1614                  * LDAP_COMPARE_{TRUE|FALSE}) */
1615                 default:
1616                         /* only touch when activity actually took place... */
1617                         if ( li->li_idle_timeout && lc ) {
1618                                 lc->lc_time = op->o_time;
1619                         }
1620
1621                         rc = ldap_parse_result( lc->lc_ld, res, &rs->sr_err,
1622                                         &match, &text, &refs, &ctrls, 1 );
1623                         rs->sr_text = text;
1624                         if ( rc != LDAP_SUCCESS ) {
1625                                 rs->sr_err = rc;
1626                         }
1627
1628                         /* RFC 4511: referrals can only appear
1629                          * if result code is LDAP_REFERRAL */
1630                         if ( refs != NULL
1631                                 && refs[ 0 ] != NULL
1632                                 && refs[ 0 ][ 0 ] != '\0' )
1633                         {
1634                                 if ( rs->sr_err != LDAP_REFERRAL ) {
1635                                         Debug( LDAP_DEBUG_ANY,
1636                                                 "%s ldap_back_op_result: "
1637                                                 "got referrals with err=%d\n",
1638                                                 op->o_log_prefix,
1639                                                 rs->sr_err, 0 );
1640
1641                                 } else {
1642                                         int     i;
1643
1644                                         for ( i = 0; refs[ i ] != NULL; i++ )
1645                                                 /* count */ ;
1646                                         rs->sr_ref = op->o_tmpalloc( sizeof( struct berval ) * ( i + 1 ),
1647                                                 op->o_tmpmemctx );
1648                                         for ( i = 0; refs[ i ] != NULL; i++ ) {
1649                                                 ber_str2bv( refs[ i ], 0, 0, &rs->sr_ref[ i ] );
1650                                         }
1651                                         BER_BVZERO( &rs->sr_ref[ i ] );
1652                                 }
1653
1654                         } else if ( rs->sr_err == LDAP_REFERRAL ) {
1655                                 Debug( LDAP_DEBUG_ANY,
1656                                         "%s ldap_back_op_result: "
1657                                         "got err=%d with null "
1658                                         "or empty referrals\n",
1659                                         op->o_log_prefix,
1660                                         rs->sr_err, 0 );
1661
1662                                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
1663                         }
1664
1665                         if ( ctrls != NULL ) {
1666                                 rs->sr_ctrls = ctrls;
1667                         }
1668                 }
1669         }
1670
1671         /* if the error in the reply structure is not
1672          * LDAP_SUCCESS, try to map it from client 
1673          * to server error */
1674         if ( !ERR_OK( rs->sr_err ) ) {
1675                 rs->sr_err = slap_map_api2result( rs );
1676
1677                 /* internal ops ( op->o_conn == NULL ) 
1678                  * must not reply to client */
1679                 if ( op->o_conn && !op->o_do_not_cache && match ) {
1680
1681                         /* record the (massaged) matched
1682                          * DN into the reply structure */
1683                         rs->sr_matched = match;
1684                 }
1685         }
1686
1687         if ( rs->sr_err == LDAP_UNAVAILABLE ) {
1688                 if ( !( sendok & LDAP_BACK_RETRYING ) ) {
1689                         if ( LDAP_BACK_QUARANTINE( li ) ) {
1690                                 ldap_back_quarantine( op, rs );
1691                         }
1692                         if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
1693                                 if ( rs->sr_text == NULL ) rs->sr_text = "Proxy operation retry failed";
1694                                 send_ldap_result( op, rs );
1695                         }
1696                 }
1697
1698         } else if ( op->o_conn &&
1699                 ( ( ( sendok & LDAP_BACK_SENDOK ) && ERR_OK( rs->sr_err ) )
1700                         || ( ( sendok & LDAP_BACK_SENDERR ) && rs->sr_err != LDAP_SUCCESS ) ) )
1701         {
1702                 send_ldap_result( op, rs );
1703         }
1704
1705         if ( match ) {
1706                 if ( rs->sr_matched != match ) {
1707                         free( (char *)rs->sr_matched );
1708                 }
1709                 rs->sr_matched = NULL;
1710                 ldap_memfree( match );
1711         }
1712
1713         if ( text ) {
1714                 ldap_memfree( text );
1715         }
1716         rs->sr_text = NULL;
1717
1718         if ( rs->sr_ref ) {
1719                 op->o_tmpfree( rs->sr_ref, op->o_tmpmemctx );
1720                 rs->sr_ref = NULL;
1721         }
1722
1723         if ( refs ) {
1724                 ber_memvfree( (void **)refs );
1725         }
1726
1727         if ( ctrls ) {
1728                 assert( rs->sr_ctrls != NULL );
1729                 ldap_controls_free( ctrls );
1730                 rs->sr_ctrls = NULL;
1731         }
1732
1733         return( ERR_OK( rs->sr_err ) ? LDAP_SUCCESS : rs->sr_err );
1734 }
1735
1736 /* return true if bound, false if failed */
1737 int
1738 ldap_back_retry( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1739 {
1740         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1741         int             rc = 0;
1742
1743         assert( lcp != NULL );
1744         assert( *lcp != NULL );
1745
1746         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1747
1748         if ( (*lcp)->lc_refcnt == 1 ) {
1749                 int binding = LDAP_BACK_CONN_BINDING( *lcp );
1750
1751                 ldap_pvt_thread_mutex_lock( &li->li_uri_mutex );
1752                 Debug( LDAP_DEBUG_ANY,
1753                         "%s ldap_back_retry: retrying URI=\"%s\" DN=\"%s\"\n",
1754                         op->o_log_prefix, li->li_uri,
1755                         BER_BVISNULL( &(*lcp)->lc_bound_ndn ) ?
1756                                 "" : (*lcp)->lc_bound_ndn.bv_val );
1757                 ldap_pvt_thread_mutex_unlock( &li->li_uri_mutex );
1758
1759                 ldap_unbind_ext( (*lcp)->lc_ld, NULL, NULL );
1760                 (*lcp)->lc_ld = NULL;
1761                 LDAP_BACK_CONN_ISBOUND_CLEAR( (*lcp) );
1762
1763                 /* lc here must be the regular lc, reset and ready for init */
1764                 rc = ldap_back_prepare_conn( *lcp, op, rs, sendok );
1765                 if ( rc != LDAP_SUCCESS ) {
1766                         /* freeit, because lc_refcnt == 1 */
1767                         (*lcp)->lc_refcnt = 0;
1768                         (void)ldap_back_freeconn( li, *lcp, 0 );
1769                         *lcp = NULL;
1770                         rc = 0;
1771
1772                 } else if ( ( sendok & LDAP_BACK_BINDING ) ) {
1773                         if ( binding ) {
1774                                 LDAP_BACK_CONN_BINDING_SET( *lcp );
1775                         }
1776                         rc = 1;
1777
1778                 } else {
1779                         rc = ldap_back_dobind_int( lcp, op, rs, sendok, 0, 0 );
1780                         if ( rc == 0 && *lcp != NULL ) {
1781                                 /* freeit, because lc_refcnt == 1 */
1782                                 (*lcp)->lc_refcnt = 0;
1783                                 LDAP_BACK_CONN_TAINTED_SET( *lcp );
1784                                 (void)ldap_back_freeconn( li, *lcp, 0 );
1785                                 *lcp = NULL;
1786                         }
1787                 }
1788
1789         } else {
1790                 Debug( LDAP_DEBUG_TRACE,
1791                         "ldap_back_retry: conn %p refcnt=%u unable to retry.\n",
1792                         (void *)(*lcp), (*lcp)->lc_refcnt, 0 );
1793
1794                 LDAP_BACK_CONN_TAINTED_SET( *lcp );
1795                 ldap_back_release_conn_lock( li, lcp, 0 );
1796                 assert( *lcp == NULL );
1797
1798                 if ( sendok & LDAP_BACK_SENDERR ) {
1799                         rs->sr_err = LDAP_UNAVAILABLE;
1800                         rs->sr_text = "Unable to retry";
1801                         send_ldap_result( op, rs );
1802                 }
1803         }
1804
1805         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1806
1807         return rc;
1808 }
1809
1810 static int
1811 ldap_back_is_proxy_authz( Operation *op, SlapReply *rs, ldap_back_send_t sendok,
1812         struct berval *binddn, struct berval *bindcred )
1813 {
1814         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1815         struct berval   ndn;
1816         int             dobind = 0;
1817
1818         if ( op->o_conn == NULL || op->o_do_not_cache ) {
1819                 goto done;
1820         }
1821
1822         /* don't proxyAuthz if protocol is not LDAPv3 */
1823         switch ( li->li_version ) {
1824         case LDAP_VERSION3:
1825                 break;
1826
1827         case 0:
1828                 if ( op->o_protocol == 0 || op->o_protocol == LDAP_VERSION3 ) {
1829                         break;
1830                 }
1831                 /* fall thru */
1832
1833         default:
1834                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1835                 if ( sendok & LDAP_BACK_SENDERR ) {
1836                         send_ldap_result( op, rs );
1837                         dobind = -1;
1838                 }
1839                 goto done;
1840         }
1841
1842         /* safe default */
1843         *binddn = slap_empty_bv;
1844         *bindcred = slap_empty_bv;
1845
1846         if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1847                 ndn = op->o_conn->c_ndn;
1848
1849         } else {
1850                 ndn = op->o_ndn;
1851         }
1852
1853         switch ( li->li_idassert_mode ) {
1854         case LDAP_BACK_IDASSERT_LEGACY:
1855                 if ( !BER_BVISNULL( &ndn ) && !BER_BVISEMPTY( &ndn ) ) {
1856                         if ( !BER_BVISNULL( &li->li_idassert_authcDN ) && !BER_BVISEMPTY( &li->li_idassert_authcDN ) )
1857                         {
1858                                 *binddn = li->li_idassert_authcDN;
1859                                 *bindcred = li->li_idassert_passwd;
1860                                 dobind = 1;
1861                         }
1862                 }
1863                 break;
1864
1865         default:
1866                 /* NOTE: rootdn can always idassert */
1867                 if ( BER_BVISNULL( &ndn )
1868                         && li->li_idassert_authz == NULL
1869                         && !( li->li_idassert_flags & LDAP_BACK_AUTH_AUTHZ_ALL ) )
1870                 {
1871                         if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1872                                 rs->sr_err = LDAP_INAPPROPRIATE_AUTH;
1873                                 if ( sendok & LDAP_BACK_SENDERR ) {
1874                                         send_ldap_result( op, rs );
1875                                         dobind = -1;
1876                                 }
1877
1878                         } else {
1879                                 rs->sr_err = LDAP_SUCCESS;
1880                                 *binddn = slap_empty_bv;
1881                                 *bindcred = slap_empty_bv;
1882                                 break;
1883                         }
1884
1885                         goto done;
1886
1887                 } else if ( li->li_idassert_authz && !be_isroot( op ) ) {
1888                         struct berval authcDN;
1889
1890                         if ( BER_BVISNULL( &ndn ) ) {
1891                                 authcDN = slap_empty_bv;
1892
1893                         } else {
1894                                 authcDN = ndn;
1895                         }       
1896                         rs->sr_err = slap_sasl_matches( op, li->li_idassert_authz,
1897                                         &authcDN, &authcDN );
1898                         if ( rs->sr_err != LDAP_SUCCESS ) {
1899                                 if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1900                                         if ( sendok & LDAP_BACK_SENDERR ) {
1901                                                 send_ldap_result( op, rs );
1902                                                 dobind = -1;
1903                                         }
1904
1905                                 } else {
1906                                         rs->sr_err = LDAP_SUCCESS;
1907                                         *binddn = slap_empty_bv;
1908                                         *bindcred = slap_empty_bv;
1909                                         break;
1910                                 }
1911
1912                                 goto done;
1913                         }
1914                 }
1915
1916                 *binddn = li->li_idassert_authcDN;
1917                 *bindcred = li->li_idassert_passwd;
1918                 dobind = 1;
1919                 break;
1920         }
1921
1922 done:;
1923         return dobind;
1924 }
1925
1926 static int
1927 ldap_back_proxy_authz_bind(
1928         ldapconn_t              *lc,
1929         Operation               *op,
1930         SlapReply               *rs,
1931         ldap_back_send_t        sendok,
1932         struct berval           *binddn,
1933         struct berval           *bindcred )
1934 {
1935         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1936         struct berval   ndn;
1937         int             msgid;
1938         int             rc;
1939
1940         if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1941                 ndn = op->o_conn->c_ndn;
1942
1943         } else {
1944                 ndn = op->o_ndn;
1945         }
1946
1947         if ( li->li_idassert_authmethod == LDAP_AUTH_SASL ) {
1948 #ifdef HAVE_CYRUS_SASL
1949                 void            *defaults = NULL;
1950                 struct berval   authzID = BER_BVNULL;
1951                 int             freeauthz = 0;
1952
1953                 /* if SASL supports native authz, prepare for it */
1954                 if ( ( !op->o_do_not_cache || !op->o_is_auth_check ) &&
1955                                 ( li->li_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
1956                 {
1957                         switch ( li->li_idassert_mode ) {
1958                         case LDAP_BACK_IDASSERT_OTHERID:
1959                         case LDAP_BACK_IDASSERT_OTHERDN:
1960                                 authzID = li->li_idassert_authzID;
1961                                 break;
1962
1963                         case LDAP_BACK_IDASSERT_ANONYMOUS:
1964                                 BER_BVSTR( &authzID, "dn:" );
1965                                 break;
1966
1967                         case LDAP_BACK_IDASSERT_SELF:
1968                                 if ( BER_BVISNULL( &ndn ) ) {
1969                                         /* connection is not authc'd, so don't idassert */
1970                                         BER_BVSTR( &authzID, "dn:" );
1971                                         break;
1972                                 }
1973                                 authzID.bv_len = STRLENOF( "dn:" ) + ndn.bv_len;
1974                                 authzID.bv_val = slap_sl_malloc( authzID.bv_len + 1, op->o_tmpmemctx );
1975                                 AC_MEMCPY( authzID.bv_val, "dn:", STRLENOF( "dn:" ) );
1976                                 AC_MEMCPY( authzID.bv_val + STRLENOF( "dn:" ),
1977                                                 ndn.bv_val, ndn.bv_len + 1 );
1978                                 freeauthz = 1;
1979                                 break;
1980
1981                         default:
1982                                 break;
1983                         }
1984                 }
1985
1986                 if ( li->li_idassert_secprops != NULL ) {
1987                         rs->sr_err = ldap_set_option( lc->lc_ld,
1988                                 LDAP_OPT_X_SASL_SECPROPS,
1989                                 (void *)li->li_idassert_secprops );
1990
1991                         if ( rs->sr_err != LDAP_OPT_SUCCESS ) {
1992                                 rs->sr_err = LDAP_OTHER;
1993                                 if ( sendok & LDAP_BACK_SENDERR ) {
1994                                         send_ldap_result( op, rs );
1995                                 }
1996                                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1997                                 goto done;
1998                         }
1999                 }
2000
2001                 defaults = lutil_sasl_defaults( lc->lc_ld,
2002                                 li->li_idassert_sasl_mech.bv_val,
2003                                 li->li_idassert_sasl_realm.bv_val,
2004                                 li->li_idassert_authcID.bv_val,
2005                                 li->li_idassert_passwd.bv_val,
2006                                 authzID.bv_val );
2007
2008                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld, binddn->bv_val,
2009                                 li->li_idassert_sasl_mech.bv_val, NULL, NULL,
2010                                 LDAP_SASL_QUIET, lutil_sasl_interact,
2011                                 defaults );
2012
2013                 switch ( rs->sr_err ) {
2014                 case LDAP_SUCCESS:
2015                         LDAP_BACK_CONN_ISBOUND_SET( lc );
2016                         break;
2017
2018                 case LDAP_LOCAL_ERROR:
2019                         /* list client API error codes that require
2020                          * to taint the connection */
2021                         /* FIXME: should actually retry? */
2022                         LDAP_BACK_CONN_TAINTED_SET( lc );
2023
2024                         /* fallthru */
2025
2026                 default:
2027                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
2028                         rs->sr_err = slap_map_api2result( rs );
2029                         if ( sendok & LDAP_BACK_SENDERR ) {
2030                                 send_ldap_result( op, rs );
2031                         }
2032                         break;
2033                 }
2034
2035                 lutil_sasl_freedefs( defaults );
2036                 if ( freeauthz ) {
2037                         slap_sl_free( authzID.bv_val, op->o_tmpmemctx );
2038                 }
2039
2040                 goto done;
2041 #endif /* HAVE_CYRUS_SASL */
2042         }
2043
2044         switch ( li->li_idassert_authmethod ) {
2045         case LDAP_AUTH_NONE:
2046                 /* FIXME: do we really need this? */
2047                 BER_BVSTR( binddn, "" );
2048                 BER_BVSTR( bindcred, "" );
2049                 /* fallthru */
2050
2051         case LDAP_AUTH_SIMPLE:
2052                 rs->sr_err = ldap_sasl_bind( lc->lc_ld,
2053                                 binddn->bv_val, LDAP_SASL_SIMPLE,
2054                                 bindcred, NULL, NULL, &msgid );
2055                 rc = ldap_back_op_result( lc, op, rs, msgid,
2056                         -1, ( sendok | LDAP_BACK_BINDING ) );
2057                 break;
2058
2059         default:
2060                 /* unsupported! */
2061                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
2062                 rs->sr_err = LDAP_AUTH_METHOD_NOT_SUPPORTED;
2063                 if ( sendok & LDAP_BACK_SENDERR ) {
2064                         send_ldap_result( op, rs );
2065                 }
2066                 goto done;
2067         }
2068
2069         if ( rc == LDAP_SUCCESS ) {
2070                 /* set rebind stuff in case of successful proxyAuthz bind,
2071                  * so that referral chasing is attempted using the right
2072                  * identity */
2073                 LDAP_BACK_CONN_ISBOUND_SET( lc );
2074                 ber_bvreplace( &lc->lc_bound_ndn, binddn );
2075
2076                 if ( !BER_BVISNULL( &lc->lc_cred ) ) {
2077                         memset( lc->lc_cred.bv_val, 0,
2078                                         lc->lc_cred.bv_len );
2079                 }
2080
2081                 if ( LDAP_BACK_SAVECRED( li ) ) {
2082                         ber_bvreplace( &lc->lc_cred, bindcred );
2083                         ldap_set_rebind_proc( lc->lc_ld, li->li_rebind_f, lc );
2084
2085                 } else {
2086                         lc->lc_cred.bv_len = 0;
2087                 }
2088         }
2089 done:;
2090         return LDAP_BACK_CONN_ISBOUND( lc );
2091 }
2092
2093 /*
2094  * ldap_back_proxy_authz_ctrl() prepends a proxyAuthz control
2095  * to existing server-side controls if required; if not,
2096  * the existing server-side controls are placed in *pctrls.
2097  * The caller, after using the controls in client API 
2098  * operations, if ( *pctrls != op->o_ctrls ), should
2099  * free( (*pctrls)[ 0 ] ) and free( *pctrls ).
2100  * The function returns success if the control could
2101  * be added if required, or if it did nothing; in the future,
2102  * it might return some error if it failed.
2103  * 
2104  * if no bind took place yet, but the connection is bound
2105  * and the "proxyauthzdn" is set, then bind as "proxyauthzdn" 
2106  * and explicitly add proxyAuthz the control to every operation
2107  * with the dn bound to the connection as control value.
2108  *
2109  * If no server-side controls are defined for the operation,
2110  * simply add the proxyAuthz control; otherwise, if the
2111  * proxyAuthz control is not already set, add it as
2112  * the first one
2113  *
2114  * FIXME: is controls order significant for security?
2115  * ANSWER: controls ordering and interoperability
2116  * must be indicated by the specs of each control; if none
2117  * is specified, the order is irrelevant.
2118  */
2119 int
2120 ldap_back_proxy_authz_ctrl(
2121                 struct berval   *bound_ndn,
2122                 int             version,
2123                 slap_idassert_t *si,
2124                 Operation       *op,
2125                 SlapReply       *rs,
2126                 LDAPControl     ***pctrls )
2127 {
2128         LDAPControl             **ctrls = NULL;
2129         int                     i = 0;
2130         slap_idassert_mode_t    mode;
2131         struct berval           assertedID,
2132                                 ndn;
2133         int                     isroot = 0;
2134
2135         *pctrls = NULL;
2136
2137         rs->sr_err = LDAP_SUCCESS;
2138
2139         /* don't proxyAuthz if protocol is not LDAPv3 */
2140         switch ( version ) {
2141         case LDAP_VERSION3:
2142                 break;
2143
2144         case 0:
2145                 if ( op->o_protocol == 0 || op->o_protocol == LDAP_VERSION3 ) {
2146                         break;
2147                 }
2148                 /* fall thru */
2149
2150         default:
2151                 goto done;
2152         }
2153
2154         /* FIXME: SASL/EXTERNAL over ldapi:// doesn't honor the authcID,
2155          * but if it is not set this test fails.  We need a different
2156          * means to detect if idassert is enabled */
2157         if ( ( BER_BVISNULL( &si->si_bc.sb_authcId ) || BER_BVISEMPTY( &si->si_bc.sb_authcId ) )
2158                 && ( BER_BVISNULL( &si->si_bc.sb_binddn ) || BER_BVISEMPTY( &si->si_bc.sb_binddn ) )
2159                 && BER_BVISNULL( &si->si_bc.sb_saslmech ) )
2160         {
2161                 goto done;
2162         }
2163
2164         if ( !op->o_conn || op->o_do_not_cache || ( isroot = be_isroot( op ) ) ) {
2165                 goto done;
2166         }
2167
2168         if ( op->o_tag == LDAP_REQ_BIND ) {
2169                 ndn = op->o_req_ndn;
2170
2171         } else if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
2172                 ndn = op->o_conn->c_ndn;
2173
2174         } else {
2175                 ndn = op->o_ndn;
2176         }
2177
2178         if ( si->si_mode == LDAP_BACK_IDASSERT_LEGACY ) {
2179                 if ( op->o_proxy_authz ) {
2180                         /*
2181                          * FIXME: we do not want to perform proxyAuthz
2182                          * on behalf of the client, because this would
2183                          * be performed with "proxyauthzdn" privileges.
2184                          *
2185                          * This might actually be too strict, since
2186                          * the "proxyauthzdn" authzTo, and each entry's
2187                          * authzFrom attributes may be crafted
2188                          * to avoid unwanted proxyAuthz to take place.
2189                          */
2190 #if 0
2191                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
2192                         rs->sr_text = "proxyAuthz not allowed within namingContext";
2193 #endif
2194                         goto done;
2195                 }
2196
2197                 if ( !BER_BVISNULL( bound_ndn ) ) {
2198                         goto done;
2199                 }
2200
2201                 if ( BER_BVISNULL( &ndn ) ) {
2202                         goto done;
2203                 }
2204
2205                 if ( BER_BVISNULL( &si->si_bc.sb_binddn ) ) {
2206                         goto done;
2207                 }
2208
2209         } else if ( si->si_bc.sb_method == LDAP_AUTH_SASL ) {
2210                 if ( ( si->si_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
2211                 {
2212                         /* already asserted in SASL via native authz */
2213                         goto done;
2214                 }
2215
2216         } else if ( si->si_authz && !isroot ) {
2217                 int             rc;
2218                 struct berval authcDN;
2219
2220                 if ( BER_BVISNULL( &ndn ) ) {
2221                         authcDN = slap_empty_bv;
2222                 } else {
2223                         authcDN = ndn;
2224                 }
2225                 rc = slap_sasl_matches( op, si->si_authz,
2226                                 &authcDN, & authcDN );
2227                 if ( rc != LDAP_SUCCESS ) {
2228                         if ( si->si_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
2229                                 /* ndn is not authorized
2230                                  * to use idassert */
2231                                 rs->sr_err = rc;
2232                         }
2233                         goto done;
2234                 }
2235         }
2236
2237         if ( op->o_proxy_authz ) {
2238                 /*
2239                  * FIXME: we can:
2240                  * 1) ignore the already set proxyAuthz control
2241                  * 2) leave it in place, and don't set ours
2242                  * 3) add both
2243                  * 4) reject the operation
2244                  *
2245                  * option (4) is very drastic
2246                  * option (3) will make the remote server reject
2247                  * the operation, thus being equivalent to (4)
2248                  * option (2) will likely break the idassert
2249                  * assumptions, so we cannot accept it;
2250                  * option (1) means that we are contradicting
2251                  * the client's reques.
2252                  *
2253                  * I think (4) is the only correct choice.
2254                  */
2255                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
2256                 rs->sr_text = "proxyAuthz not allowed within namingContext";
2257         }
2258
2259         if ( op->o_is_auth_check ) {
2260                 mode = LDAP_BACK_IDASSERT_NOASSERT;
2261
2262         } else {
2263                 mode = si->si_mode;
2264         }
2265
2266         switch ( mode ) {
2267         case LDAP_BACK_IDASSERT_LEGACY:
2268                 /* original behavior:
2269                  * assert the client's identity */
2270         case LDAP_BACK_IDASSERT_SELF:
2271                 assertedID = ndn;
2272                 break;
2273
2274         case LDAP_BACK_IDASSERT_ANONYMOUS:
2275                 /* assert "anonymous" */
2276                 assertedID = slap_empty_bv;
2277                 break;
2278
2279         case LDAP_BACK_IDASSERT_NOASSERT:
2280                 /* don't assert; bind as proxyauthzdn */
2281                 goto done;
2282
2283         case LDAP_BACK_IDASSERT_OTHERID:
2284         case LDAP_BACK_IDASSERT_OTHERDN:
2285                 /* assert idassert DN */
2286                 assertedID = si->si_bc.sb_authzId;
2287                 break;
2288
2289         default:
2290                 assert( 0 );
2291         }
2292
2293         /* if we got here, "" is allowed to proxyAuthz */
2294         if ( BER_BVISNULL( &assertedID ) ) {
2295                 assertedID = slap_empty_bv;
2296         }
2297
2298         /* don't idassert the bound DN (ITS#4497) */
2299         if ( dn_match( &assertedID, bound_ndn ) ) {
2300                 goto done;
2301         }
2302
2303         if ( op->o_ctrls ) {
2304                 for ( i = 0; op->o_ctrls[ i ]; i++ )
2305                         /* just count ctrls */ ;
2306         }
2307
2308         ctrls = op->o_tmpalloc( sizeof( LDAPControl * ) * (i + 2) + sizeof( LDAPControl ),
2309                         op->o_tmpmemctx );
2310         ctrls[ 0 ] = (LDAPControl *)&ctrls[ i + 2 ];
2311         
2312         ctrls[ 0 ]->ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
2313         ctrls[ 0 ]->ldctl_iscritical = 1;
2314
2315         switch ( si->si_mode ) {
2316         /* already in u:ID or dn:DN form */
2317         case LDAP_BACK_IDASSERT_OTHERID:
2318         case LDAP_BACK_IDASSERT_OTHERDN:
2319                 ber_dupbv_x( &ctrls[ 0 ]->ldctl_value, &assertedID, op->o_tmpmemctx );
2320                 break;
2321
2322         /* needs the dn: prefix */
2323         default:
2324                 ctrls[ 0 ]->ldctl_value.bv_len = assertedID.bv_len + STRLENOF( "dn:" );
2325                 ctrls[ 0 ]->ldctl_value.bv_val = op->o_tmpalloc( ctrls[ 0 ]->ldctl_value.bv_len + 1,
2326                                 op->o_tmpmemctx );
2327                 AC_MEMCPY( ctrls[ 0 ]->ldctl_value.bv_val, "dn:", STRLENOF( "dn:" ) );
2328                 AC_MEMCPY( &ctrls[ 0 ]->ldctl_value.bv_val[ STRLENOF( "dn:" ) ],
2329                                 assertedID.bv_val, assertedID.bv_len + 1 );
2330                 break;
2331         }
2332
2333         /* Older versions of <draft-weltman-ldapv3-proxy> required
2334          * to encode the value of the authzID (and called it proxyDN);
2335          * this hack provides compatibility with those DSAs that
2336          * implement it this way */
2337         if ( si->si_flags & LDAP_BACK_AUTH_OBSOLETE_ENCODING_WORKAROUND ) {
2338                 struct berval           authzID = ctrls[ 0 ]->ldctl_value;
2339                 BerElementBuffer        berbuf;
2340                 BerElement              *ber = (BerElement *)&berbuf;
2341                 ber_tag_t               tag;
2342
2343                 ber_init2( ber, 0, LBER_USE_DER );
2344                 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
2345
2346                 tag = ber_printf( ber, "O", &authzID );
2347                 if ( tag == LBER_ERROR ) {
2348                         rs->sr_err = LDAP_OTHER;
2349                         goto free_ber;
2350                 }
2351
2352                 if ( ber_flatten2( ber, &ctrls[ 0 ]->ldctl_value, 1 ) == -1 ) {
2353                         rs->sr_err = LDAP_OTHER;
2354                         goto free_ber;
2355                 }
2356
2357 free_ber:;
2358                 op->o_tmpfree( authzID.bv_val, op->o_tmpmemctx );
2359                 ber_free_buf( ber );
2360
2361                 if ( rs->sr_err != LDAP_SUCCESS ) {
2362                         op->o_tmpfree( ctrls, op->o_tmpmemctx );
2363                         ctrls = NULL;
2364                         goto done;
2365                 }
2366
2367         } else if ( si->si_flags & LDAP_BACK_AUTH_OBSOLETE_PROXY_AUTHZ ) {
2368                 struct berval           authzID = ctrls[ 0 ]->ldctl_value,
2369                                         tmp;
2370                 BerElementBuffer        berbuf;
2371                 BerElement              *ber = (BerElement *)&berbuf;
2372                 ber_tag_t               tag;
2373
2374                 if ( strncasecmp( authzID.bv_val, "dn:", STRLENOF( "dn:" ) ) != 0 ) {
2375                         op->o_tmpfree( ctrls[ 0 ]->ldctl_value.bv_val, op->o_tmpmemctx );
2376                         op->o_tmpfree( ctrls, op->o_tmpmemctx );
2377                         ctrls = NULL;
2378                         rs->sr_err = LDAP_PROTOCOL_ERROR;
2379                         goto done;
2380                 }
2381
2382                 tmp = authzID;
2383                 tmp.bv_val += STRLENOF( "dn:" );
2384                 tmp.bv_len -= STRLENOF( "dn:" );
2385
2386                 ber_init2( ber, 0, LBER_USE_DER );
2387                 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
2388
2389                 /* apparently, Mozilla API encodes this
2390                  * as "SEQUENCE { LDAPDN }" */
2391                 tag = ber_printf( ber, "{O}", &tmp );
2392                 if ( tag == LBER_ERROR ) {
2393                         rs->sr_err = LDAP_OTHER;
2394                         goto free_ber2;
2395                 }
2396
2397                 if ( ber_flatten2( ber, &ctrls[ 0 ]->ldctl_value, 1 ) == -1 ) {
2398                         rs->sr_err = LDAP_OTHER;
2399                         goto free_ber2;
2400                 }
2401
2402 free_ber2:;
2403                 op->o_tmpfree( authzID.bv_val, op->o_tmpmemctx );
2404                 ber_free_buf( ber );
2405
2406                 if ( rs->sr_err != LDAP_SUCCESS ) {
2407                         op->o_tmpfree( ctrls, op->o_tmpmemctx );
2408                         ctrls = NULL;
2409                         goto done;
2410                 }
2411
2412                 ctrls[ 0 ]->ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
2413         }
2414
2415         if ( op->o_ctrls ) {
2416                 for ( i = 0; op->o_ctrls[ i ]; i++ ) {
2417                         ctrls[ i + 1 ] = op->o_ctrls[ i ];
2418                 }
2419         }
2420         ctrls[ i + 1 ] = NULL;
2421
2422 done:;
2423         if ( ctrls == NULL ) {
2424                 ctrls = op->o_ctrls;
2425         }
2426
2427         *pctrls = ctrls;
2428         
2429         return rs->sr_err;
2430 }
2431
2432 int
2433 ldap_back_proxy_authz_ctrl_free( Operation *op, LDAPControl ***pctrls )
2434 {
2435         LDAPControl     **ctrls = *pctrls;
2436
2437         /* we assume that the first control is the proxyAuthz
2438          * added by back-ldap, so it's the only one we explicitly 
2439          * free */
2440         if ( ctrls && ctrls != op->o_ctrls ) {
2441                 assert( ctrls[ 0 ] != NULL );
2442
2443                 if ( !BER_BVISNULL( &ctrls[ 0 ]->ldctl_value ) ) {
2444                         op->o_tmpfree( ctrls[ 0 ]->ldctl_value.bv_val, op->o_tmpmemctx );
2445                 }
2446
2447                 op->o_tmpfree( ctrls, op->o_tmpmemctx );
2448         } 
2449
2450         *pctrls = NULL;
2451
2452         return 0;
2453 }