]> git.sur5r.net Git - openldap/blob - servers/slapd/back-ldap/bind.c
further cleanup
[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-2007 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         slap_bindconf *sb;
605 #endif /* HAVE_TLS */
606
607         ldap_pvt_thread_mutex_lock( &li->li_uri_mutex );
608         rs->sr_err = ldap_initialize( &ld, li->li_uri );
609         ldap_pvt_thread_mutex_unlock( &li->li_uri_mutex );
610         if ( rs->sr_err != LDAP_SUCCESS ) {
611                 goto error_return;
612         }
613
614         if ( li->li_urllist_f ) {
615                 ldap_set_urllist_proc( ld, li->li_urllist_f, li->li_urllist_p );
616         }
617
618         /* Set LDAP version. This will always succeed: If the client
619          * bound with a particular version, then so can we.
620          */
621         if ( li->li_version != 0 ) {
622                 version = li->li_version;
623
624         } else if ( op->o_protocol != 0 ) {
625                 version = op->o_protocol;
626
627         } else {
628                 /* assume it's an internal op; set to LDAPv3 */
629                 version = LDAP_VERSION3;
630         }
631         ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, (const void *)&version );
632
633         /* automatically chase referrals ("chase-referrals [{yes|no}]" statement) */
634         ldap_set_option( ld, LDAP_OPT_REFERRALS,
635                 LDAP_BACK_CHASE_REFERRALS( li ) ? LDAP_OPT_ON : LDAP_OPT_OFF );
636
637         if ( li->li_network_timeout > 0 ) {
638                 struct timeval          tv;
639
640                 tv.tv_sec = li->li_network_timeout;
641                 tv.tv_usec = 0;
642                 ldap_set_option( ld, LDAP_OPT_NETWORK_TIMEOUT, (const void *)&tv );
643         }
644
645 #ifdef HAVE_TLS
646         if ( LDAP_BACK_CONN_ISPRIV( lc ) ) {
647                 sb = &li->li_acl;
648
649         } else if ( LDAP_BACK_CONN_ISIDASSERT( lc ) ) {
650                 sb = &li->li_idassert.si_bc;
651
652         } else {
653                 sb = &li->li_tls;
654         }
655
656         if ( sb->sb_tls_do_init ) {
657                 bindconf_tls_set( sb, ld );
658         } else if ( sb->sb_tls_ctx ) {
659                 ldap_set_option( ld, LDAP_OPT_X_TLS_CTX, sb->sb_tls_ctx );
660         }
661
662         ldap_pvt_thread_mutex_lock( &li->li_uri_mutex );
663         rs->sr_err = ldap_back_start_tls( ld, op->o_protocol, &is_tls,
664                         li->li_uri, li->li_flags, li->li_nretries, &rs->sr_text );
665         ldap_pvt_thread_mutex_unlock( &li->li_uri_mutex );
666         if ( rs->sr_err != LDAP_SUCCESS ) {
667                 ldap_unbind_ext( ld, NULL, NULL );
668                 goto error_return;
669
670         } else if ( li->li_idle_timeout ) {
671                 /* only touch when activity actually took place... */
672                 lc_time = op->o_time;
673         }
674 #endif /* HAVE_TLS */
675
676         lc->lc_ld = ld;
677         lc->lc_refcnt = 1;
678 #ifdef HAVE_TLS
679         if ( is_tls ) {
680                 LDAP_BACK_CONN_ISTLS_SET( lc );
681         } else {
682                 LDAP_BACK_CONN_ISTLS_CLEAR( lc );
683         }
684         if ( lc_time != (time_t)(-1) ) {
685                 lc->lc_time = lc_time;
686         }
687 #endif /* HAVE_TLS */
688
689 error_return:;
690         if ( rs->sr_err != LDAP_SUCCESS ) {
691                 rs->sr_err = slap_map_api2result( rs );
692                 if ( sendok & LDAP_BACK_SENDERR ) {
693                         if ( rs->sr_text == NULL ) {
694                                 rs->sr_text = "ldap_initialize() failed";
695                         }
696                         send_ldap_result( op, rs );
697                         rs->sr_text = NULL;
698                 }
699
700         } else {
701                 if ( li->li_conn_ttl > 0 ) {
702                         lc->lc_create_time = op->o_time;
703                 }
704         }
705
706         return rs->sr_err;
707 }
708
709 static ldapconn_t *
710 ldap_back_getconn(
711         Operation               *op,
712         SlapReply               *rs,
713         ldap_back_send_t        sendok,
714         struct berval           *binddn,
715         struct berval           *bindcred )
716 {
717         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
718         ldapconn_t      *lc = NULL,
719                         lc_curr = { 0 };
720         int             refcnt = 1,
721                         lookupconn = !( sendok & LDAP_BACK_BINDING );
722
723         /* if the server is quarantined, and
724          * - the current interval did not expire yet, or
725          * - no more retries should occur,
726          * don't return the connection */
727         if ( li->li_isquarantined ) {
728                 slap_retry_info_t       *ri = &li->li_quarantine;
729                 int                     dont_retry = 1;
730
731                 if ( li->li_quarantine.ri_interval ) {
732                         ldap_pvt_thread_mutex_lock( &li->li_quarantine_mutex );
733                         if ( li->li_isquarantined == LDAP_BACK_FQ_YES ) {
734                                 dont_retry = ( ri->ri_num[ ri->ri_idx ] == SLAP_RETRYNUM_TAIL
735                                         || slap_get_time() < ri->ri_last + ri->ri_interval[ ri->ri_idx ] );
736                                 if ( !dont_retry ) {
737                                         Debug( LDAP_DEBUG_ANY,
738                                                 "%s: ldap_back_getconn quarantine "
739                                                 "retry block #%d try #%d.\n",
740                                                 op->o_log_prefix, ri->ri_idx, ri->ri_count );
741                                         li->li_isquarantined = LDAP_BACK_FQ_RETRYING;
742                                 }
743                         }
744                         ldap_pvt_thread_mutex_unlock( &li->li_quarantine_mutex );
745                 }
746
747                 if ( dont_retry ) {
748                         rs->sr_err = LDAP_UNAVAILABLE;
749                         if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
750                                 send_ldap_result( op, rs );
751                         }
752                         return NULL;
753                 }
754         }
755
756         /* Internal searches are privileged and shared. So is root. */
757         if ( op->o_do_not_cache || be_isroot( op ) ) {
758                 LDAP_BACK_CONN_ISPRIV_SET( &lc_curr );
759                 lc_curr.lc_local_ndn = op->o_bd->be_rootndn;
760                 LDAP_BACK_PCONN_ROOTDN_SET( &lc_curr, op );
761
762         } else {
763                 struct berval   tmpbinddn,
764                                 tmpbindcred,
765                                 save_o_dn,
766                                 save_o_ndn;
767                 int             isproxyauthz;
768
769                 /* need cleanup */
770                 if ( binddn == NULL ) {
771                         binddn = &tmpbinddn;
772                 }       
773                 if ( bindcred == NULL ) {
774                         bindcred = &tmpbindcred;
775                 }
776                 if ( op->o_tag == LDAP_REQ_BIND ) {
777                         save_o_dn = op->o_dn;
778                         save_o_ndn = op->o_ndn;
779                         op->o_dn = op->o_req_dn;
780                         op->o_ndn = op->o_req_ndn;
781                 }
782                 isproxyauthz = ldap_back_is_proxy_authz( op, rs, sendok, binddn, bindcred );
783                 if ( isproxyauthz == -1 ) {
784                         return NULL;
785                 }
786                 if ( op->o_tag == LDAP_REQ_BIND ) {
787                         op->o_dn = save_o_dn;
788                         op->o_ndn = save_o_ndn;
789                 }
790
791                 lc_curr.lc_local_ndn = op->o_ndn;
792                 /* Explicit binds must not be shared;
793                  * however, explicit binds are piped in a special connection
794                  * when idassert is to occur with "override" set */
795                 if ( op->o_tag == LDAP_REQ_BIND && !isproxyauthz ) {
796                         lc_curr.lc_conn = op->o_conn;
797
798                 } else {
799                         if ( isproxyauthz && !( sendok & LDAP_BACK_BINDING ) ) {
800                                 lc_curr.lc_local_ndn = *binddn;
801                                 LDAP_BACK_PCONN_ROOTDN_SET( &lc_curr, op );
802                                 LDAP_BACK_CONN_ISIDASSERT_SET( &lc_curr );
803
804                         } else if ( isproxyauthz && ( li->li_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) ) {
805                                 lc_curr.lc_local_ndn = slap_empty_bv;
806                                 LDAP_BACK_PCONN_BIND_SET( &lc_curr, op );
807                                 LDAP_BACK_CONN_ISIDASSERT_SET( &lc_curr );
808                                 lookupconn = 1;
809
810                         } else if ( SLAP_IS_AUTHZ_BACKEND( op ) ) {
811                                 lc_curr.lc_conn = op->o_conn;
812
813                         } else {
814                                 LDAP_BACK_PCONN_ANON_SET( &lc_curr, op );
815                         }
816                 }
817         }
818
819         /* Explicit Bind requests always get their own conn */
820         if ( lookupconn ) {
821 retry_lock:
822                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
823                 if ( LDAP_BACK_PCONN_ISPRIV( &lc_curr ) ) {
824                         /* lookup a conn that's not binding */
825                         LDAP_TAILQ_FOREACH( lc,
826                                 &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( &lc_curr ) ].lic_priv,
827                                 lc_q )
828                         {
829                                 if ( !LDAP_BACK_CONN_BINDING( lc ) && lc->lc_refcnt == 0 ) {
830                                         break;
831                                 }
832                         }
833
834                         if ( lc != NULL ) {
835                                 if ( lc != LDAP_TAILQ_LAST( &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_priv,
836                                         ldapconn_t, lc_q ) )
837                                 {
838                                         LDAP_TAILQ_REMOVE( &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_priv,
839                                                 lc, lc_q );
840                                         LDAP_TAILQ_ENTRY_INIT( lc, lc_q );
841                                         LDAP_TAILQ_INSERT_TAIL( &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_priv,
842                                                 lc, lc_q );
843                                 }
844
845                         } else if ( !LDAP_BACK_USE_TEMPORARIES( li )
846                                 && li->li_conn_priv[ LDAP_BACK_CONN2PRIV( &lc_curr ) ].lic_num == li->li_conn_priv_max )
847                         {
848                                 lc = LDAP_TAILQ_FIRST( &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( &lc_curr ) ].lic_priv );
849                         }
850                         
851                 } else {
852
853                         /* Searches for a ldapconn in the avl tree */
854                         lc = (ldapconn_t *)avl_find( li->li_conninfo.lai_tree, 
855                                         (caddr_t)&lc_curr, ldap_back_conndn_cmp );
856                 }
857
858                 if ( lc != NULL ) {
859                         /* Don't reuse connections while they're still binding */
860                         if ( LDAP_BACK_CONN_BINDING( lc ) ) {
861                                 if ( !LDAP_BACK_USE_TEMPORARIES( li ) ) {
862                                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
863
864                                         ldap_pvt_thread_yield();
865                                         goto retry_lock;
866                                 }
867                                 lc = NULL;
868                         }
869
870                         if ( lc != NULL ) {
871                                 if ( op->o_tag == LDAP_REQ_BIND ) {
872                                         /* right now, this is the only possible case */
873                                         assert( ( li->li_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) );
874                                         LDAP_BACK_CONN_BINDING_SET( lc );
875                                 }
876
877                                 refcnt = ++lc->lc_refcnt;
878                         }
879                 }
880                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
881         }
882
883         /* Looks like we didn't get a bind. Open a new session... */
884         if ( lc == NULL ) {
885                 lc = (ldapconn_t *)ch_calloc( 1, sizeof( ldapconn_t ) );
886                 lc->lc_flags = li->li_flags;
887                 lc->lc_lcflags = lc_curr.lc_lcflags;
888                 if ( ldap_back_prepare_conn( lc, op, rs, sendok ) != LDAP_SUCCESS ) {
889                         ch_free( lc );
890                         return NULL;
891                 }
892
893                 if ( sendok & LDAP_BACK_BINDING ) {
894                         LDAP_BACK_CONN_BINDING_SET( lc );
895                 }
896
897                 lc->lc_conn = lc_curr.lc_conn;
898                 ber_dupbv( &lc->lc_local_ndn, &lc_curr.lc_local_ndn );
899
900                 /*
901                  * the rationale is: connections as the rootdn are privileged,
902                  * so acl_authcDN is to be used; however, in some cases
903                  * one already configured identity assertion with a highly
904                  * privileged idassert_authcDN, so if acl_authcDN is NULL
905                  * and idassert_authcDN is not, use the second instead.
906                  *
907                  * might change in the future, because it's preferable
908                  * to make clear what identity is being used, since
909                  * the only drawback is that one risks to configure
910                  * the same identity twice...
911                  */
912                 if ( LDAP_BACK_CONN_ISPRIV( &lc_curr ) ) {
913                         if ( BER_BVISNULL( &li->li_acl_authcDN ) && !BER_BVISNULL( &li->li_idassert_authcDN ) ) {
914                                 ber_dupbv( &lc->lc_bound_ndn, &li->li_idassert_authcDN );
915                                 ber_dupbv( &lc->lc_cred, &li->li_idassert_passwd );
916
917                         } else {
918                                 ber_dupbv( &lc->lc_bound_ndn, &li->li_acl_authcDN );
919                                 ber_dupbv( &lc->lc_cred, &li->li_acl_passwd );
920                         }
921                         LDAP_BACK_CONN_ISPRIV_SET( lc );
922
923                 } else if ( LDAP_BACK_CONN_ISIDASSERT( &lc_curr ) ) {
924                         if ( !LDAP_BACK_PCONN_ISBIND( &lc_curr ) ) {
925                                 ber_dupbv( &lc->lc_bound_ndn, &li->li_idassert_authcDN );
926                                 ber_dupbv( &lc->lc_cred, &li->li_idassert_passwd );
927                         }
928                         LDAP_BACK_CONN_ISIDASSERT_SET( lc );
929
930                 } else {
931                         BER_BVZERO( &lc->lc_cred );
932                         BER_BVZERO( &lc->lc_bound_ndn );
933                         if ( !BER_BVISEMPTY( &op->o_ndn )
934                                 && SLAP_IS_AUTHZ_BACKEND( op ) )
935                         {
936                                 ber_dupbv( &lc->lc_bound_ndn, &op->o_ndn );
937                         }
938                 }
939
940 #ifdef HAVE_TLS
941                 /* if start TLS failed but it was not mandatory,
942                  * check if the non-TLS connection was already
943                  * in cache; in case, destroy the newly created
944                  * connection and use the existing one */
945                 if ( LDAP_BACK_PCONN_ISTLS( lc ) 
946                                 && !ldap_tls_inplace( lc->lc_ld ) )
947                 {
948                         ldapconn_t      *tmplc = NULL;
949                         int             idx = LDAP_BACK_CONN2PRIV( &lc_curr ) - 1;
950                         
951                         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
952                         LDAP_TAILQ_FOREACH( tmplc,
953                                 &li->li_conn_priv[ idx ].lic_priv,
954                                 lc_q )
955                         {
956                                 if ( !LDAP_BACK_CONN_BINDING( tmplc ) ) {
957                                         break;
958                                 }
959                         }
960
961                         if ( tmplc != NULL ) {
962                                 refcnt = ++tmplc->lc_refcnt;
963                                 ldap_back_conn_free( lc );
964                                 lc = tmplc;
965                         }
966                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
967
968                         if ( tmplc != NULL ) {
969                                 goto done;
970                         }
971                 }
972 #endif /* HAVE_TLS */
973
974                 /* Inserts the newly created ldapconn in the avl tree */
975                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
976
977                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
978
979                 assert( lc->lc_refcnt == 1 );
980
981 #if LDAP_BACK_PRINT_CONNTREE > 0
982                 ldap_back_print_conntree( li, ">>> ldap_back_getconn(insert)" );
983 #endif /* LDAP_BACK_PRINT_CONNTREE */
984         
985                 if ( LDAP_BACK_PCONN_ISPRIV( lc ) ) {
986                         if ( li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_num < li->li_conn_priv_max ) {
987                                 LDAP_TAILQ_INSERT_TAIL( &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_priv, lc, lc_q );
988                                 li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_num++;
989                                 LDAP_BACK_CONN_CACHED_SET( lc );
990
991                         } else {
992                                 LDAP_BACK_CONN_TAINTED_SET( lc );
993                         }
994                         rs->sr_err = 0;
995
996                 } else {
997                         rs->sr_err = avl_insert( &li->li_conninfo.lai_tree, (caddr_t)lc,
998                                 ldap_back_conndn_cmp, ldap_back_conndn_dup );
999                         LDAP_BACK_CONN_CACHED_SET( lc );
1000                 }
1001
1002 #if LDAP_BACK_PRINT_CONNTREE > 0
1003                 ldap_back_print_conntree( li, "<<< ldap_back_getconn(insert)" );
1004 #endif /* LDAP_BACK_PRINT_CONNTREE */
1005         
1006                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1007
1008                 if ( LogTest( LDAP_DEBUG_TRACE ) ) {
1009                         char    buf[ SLAP_TEXT_BUFLEN ];
1010
1011                         snprintf( buf, sizeof( buf ),
1012                                 "lc=%p inserted refcnt=%u rc=%d",
1013                                 (void *)lc, refcnt, rs->sr_err );
1014                                 
1015                         Debug( LDAP_DEBUG_TRACE,
1016                                 "=>ldap_back_getconn: %s: %s\n",
1017                                 op->o_log_prefix, buf, 0 );
1018                 }
1019         
1020                 if ( !LDAP_BACK_PCONN_ISPRIV( lc ) ) {
1021                         /* Err could be -1 in case a duplicate ldapconn is inserted */
1022                         switch ( rs->sr_err ) {
1023                         case 0:
1024                                 break;
1025
1026                         case -1:
1027                                 LDAP_BACK_CONN_CACHED_CLEAR( lc );
1028                                 if ( !( sendok & LDAP_BACK_BINDING ) && !LDAP_BACK_USE_TEMPORARIES( li ) ) {
1029                                         /* duplicate: free and try to get the newly created one */
1030                                         ldap_back_conn_free( lc );
1031                                         lc = NULL;
1032                                         goto retry_lock;
1033                                 }
1034
1035                                 /* taint connection, so that it'll be freed when released */
1036                                 LDAP_BACK_CONN_TAINTED_SET( lc );
1037                                 break;
1038
1039                         default:
1040                                 LDAP_BACK_CONN_CACHED_CLEAR( lc );
1041                                 ldap_back_conn_free( lc );
1042                                 rs->sr_err = LDAP_OTHER;
1043                                 rs->sr_text = "proxy bind collision";
1044                                 if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
1045                                         send_ldap_result( op, rs );
1046                                         rs->sr_text = NULL;
1047                                 }
1048                                 return NULL;
1049                         }
1050                 }
1051
1052         } else {
1053                 int     expiring = 0;
1054
1055                 if ( ( li->li_idle_timeout != 0 && op->o_time > lc->lc_time + li->li_idle_timeout )
1056                         || ( li->li_conn_ttl != 0 && op->o_time > lc->lc_create_time + li->li_conn_ttl ) )
1057                 {
1058                         expiring = 1;
1059
1060                         /* let it be used, but taint/delete it so that 
1061                          * no-one else can look it up any further */
1062                         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1063
1064 #if LDAP_BACK_PRINT_CONNTREE > 0
1065                         ldap_back_print_conntree( li, ">>> ldap_back_getconn(timeout)" );
1066 #endif /* LDAP_BACK_PRINT_CONNTREE */
1067
1068                         (void)ldap_back_conn_delete( li, lc );
1069                         LDAP_BACK_CONN_TAINTED_SET( lc );
1070
1071 #if LDAP_BACK_PRINT_CONNTREE > 0
1072                         ldap_back_print_conntree( li, "<<< ldap_back_getconn(timeout)" );
1073 #endif /* LDAP_BACK_PRINT_CONNTREE */
1074
1075                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1076                 }
1077
1078                 if ( LogTest( LDAP_DEBUG_TRACE ) ) {
1079                         char    buf[ SLAP_TEXT_BUFLEN ];
1080
1081                         snprintf( buf, sizeof( buf ),
1082                                 "conn %p fetched refcnt=%u%s",
1083                                 (void *)lc, refcnt, expiring ? " expiring" : "" );
1084                         Debug( LDAP_DEBUG_TRACE,
1085                                 "=>ldap_back_getconn: %s.\n", buf, 0, 0 );
1086                 }
1087         }
1088
1089 #ifdef HAVE_TLS
1090 done:;
1091 #endif /* HAVE_TLS */
1092
1093         return lc;
1094 }
1095
1096 void
1097 ldap_back_release_conn_lock(
1098         ldapinfo_t              *li,
1099         ldapconn_t              **lcp,
1100         int                     dolock )
1101 {
1102
1103         ldapconn_t      *lc = *lcp;
1104
1105         if ( dolock ) {
1106                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1107         }
1108         assert( lc->lc_refcnt > 0 );
1109         LDAP_BACK_CONN_BINDING_CLEAR( lc );
1110         lc->lc_refcnt--;
1111         if ( LDAP_BACK_CONN_TAINTED( lc ) ) {
1112                 ldap_back_freeconn( li, lc, 0 );
1113                 *lcp = NULL;
1114         }
1115         if ( dolock ) {
1116                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1117         }
1118 }
1119
1120 void
1121 ldap_back_quarantine(
1122         Operation       *op,
1123         SlapReply       *rs )
1124 {
1125         ldapinfo_t              *li = (ldapinfo_t *)op->o_bd->be_private;
1126
1127         slap_retry_info_t       *ri = &li->li_quarantine;
1128
1129         ldap_pvt_thread_mutex_lock( &li->li_quarantine_mutex );
1130
1131         if ( rs->sr_err == LDAP_UNAVAILABLE ) {
1132                 time_t          new_last = slap_get_time();
1133
1134                 switch ( li->li_isquarantined ) {
1135                 case LDAP_BACK_FQ_NO:
1136                         if ( ri->ri_last == new_last ) {
1137                                 goto done;
1138                         }
1139
1140                         Debug( LDAP_DEBUG_ANY,
1141                                 "%s: ldap_back_quarantine enter.\n",
1142                                 op->o_log_prefix, 0, 0 );
1143
1144                         ri->ri_idx = 0;
1145                         ri->ri_count = 0;
1146                         break;
1147
1148                 case LDAP_BACK_FQ_RETRYING:
1149                         Debug( LDAP_DEBUG_ANY,
1150                                 "%s: ldap_back_quarantine block #%d try #%d failed.\n",
1151                                 op->o_log_prefix, ri->ri_idx, ri->ri_count );
1152
1153                         ++ri->ri_count;
1154                         if ( ri->ri_num[ ri->ri_idx ] != SLAP_RETRYNUM_FOREVER
1155                                 && ri->ri_count == ri->ri_num[ ri->ri_idx ] )
1156                         {
1157                                 ri->ri_count = 0;
1158                                 ++ri->ri_idx;
1159                         }
1160                         break;
1161
1162                 default:
1163                         break;
1164                 }
1165
1166                 li->li_isquarantined = LDAP_BACK_FQ_YES;
1167                 ri->ri_last = new_last;
1168
1169         } else if ( li->li_isquarantined != LDAP_BACK_FQ_NO ) {
1170                 if ( ri->ri_last == slap_get_time() ) {
1171                         goto done;
1172                 }
1173
1174                 Debug( LDAP_DEBUG_ANY,
1175                         "%s: ldap_back_quarantine exit (%d) err=%d.\n",
1176                         op->o_log_prefix, li->li_isquarantined, rs->sr_err );
1177
1178                 if ( li->li_quarantine_f ) {
1179                         (void)li->li_quarantine_f( li, li->li_quarantine_p );
1180                 }
1181
1182                 ri->ri_count = 0;
1183                 ri->ri_idx = 0;
1184                 li->li_isquarantined = LDAP_BACK_FQ_NO;
1185         }
1186
1187 done:;
1188         ldap_pvt_thread_mutex_unlock( &li->li_quarantine_mutex );
1189 }
1190
1191 /*
1192  * ldap_back_dobind_int
1193  *
1194  * Note: dolock indicates whether li->li_conninfo.lai_mutex must be locked or not
1195  */
1196 static int
1197 ldap_back_dobind_int(
1198         ldapconn_t              **lcp,
1199         Operation               *op,
1200         SlapReply               *rs,
1201         ldap_back_send_t        sendok,
1202         int                     retries,
1203         int                     dolock )
1204 {       
1205         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1206
1207         ldapconn_t      *lc;
1208         struct berval   binddn = slap_empty_bv,
1209                         bindcred = slap_empty_bv;
1210
1211         int             rc = 0,
1212                         isbound,
1213                         binding = 0;
1214         ber_int_t       msgid;
1215
1216         assert( lcp != NULL );
1217         assert( retries >= 0 );
1218
1219         if ( sendok & LDAP_BACK_GETCONN ) {
1220                 assert( *lcp == NULL );
1221
1222                 lc = ldap_back_getconn( op, rs, sendok, &binddn, &bindcred );
1223                 if ( lc == NULL ) {
1224                         return 0;
1225                 }
1226                 *lcp = lc;
1227
1228         } else {
1229                 lc = *lcp;
1230         }
1231
1232         assert( lc != NULL );
1233
1234 retry_lock:;
1235         if ( dolock ) {
1236                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1237         }
1238
1239         if ( binding == 0 ) {
1240                 /* check if already bound */
1241                 rc = isbound = LDAP_BACK_CONN_ISBOUND( lc );
1242                 if ( isbound ) {
1243                         if ( dolock ) {
1244                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1245                         }
1246                         return rc;
1247                 }
1248
1249                 if ( LDAP_BACK_CONN_BINDING( lc ) ) {
1250                         /* if someone else is about to bind it, give up and retry */
1251                         if ( dolock ) {
1252                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1253                         }
1254                         ldap_pvt_thread_yield();
1255                         goto retry_lock;
1256
1257                 } else {
1258                         /* otherwise this thread will bind it */
1259                         LDAP_BACK_CONN_BINDING_SET( lc );
1260                         binding = 1;
1261                 }
1262         }
1263
1264         if ( dolock ) {
1265                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1266         }
1267
1268         /*
1269          * FIXME: we need to let clients use proxyAuthz
1270          * otherwise we cannot do symmetric pools of servers;
1271          * we have to live with the fact that a user can
1272          * authorize itself as any ID that is allowed
1273          * by the authzTo directive of the "proxyauthzdn".
1274          */
1275         /*
1276          * NOTE: current Proxy Authorization specification
1277          * and implementation do not allow proxy authorization
1278          * control to be provided with Bind requests
1279          */
1280         /*
1281          * if no bind took place yet, but the connection is bound
1282          * and the "idassert-authcDN" (or other ID) is set, 
1283          * then bind as the asserting identity and explicitly 
1284          * add the proxyAuthz control to every operation with the
1285          * dn bound to the connection as control value.
1286          * This is done also if this is the authrizing backend,
1287          * but the "override" flag is given to idassert.
1288          * It allows to use SASL bind and yet proxyAuthz users
1289          */
1290         if ( LDAP_BACK_CONN_ISIDASSERT( lc ) ) {
1291                 if ( BER_BVISEMPTY( &binddn ) && BER_BVISEMPTY( &bindcred ) ) {
1292                         /* if we got here, it shouldn't return result */
1293                         rc = ldap_back_is_proxy_authz( op, rs,
1294                                 LDAP_BACK_DONTSEND, &binddn, &bindcred );
1295                         assert( rc == 1 );
1296                 }
1297                 rc = ldap_back_proxy_authz_bind( lc, op, rs, sendok, &binddn, &bindcred );
1298                 goto done;
1299         }
1300
1301 #ifdef HAVE_CYRUS_SASL
1302         if ( LDAP_BACK_CONN_ISPRIV( lc )
1303                 && li->li_acl_authmethod == LDAP_AUTH_SASL )
1304         {
1305                 void            *defaults = NULL;
1306
1307                 if ( li->li_acl_secprops != NULL ) {
1308                         rc = ldap_set_option( lc->lc_ld,
1309                                 LDAP_OPT_X_SASL_SECPROPS, li->li_acl_secprops );
1310
1311                         if ( rc != LDAP_OPT_SUCCESS ) {
1312                                 Debug( LDAP_DEBUG_ANY, "Error: ldap_set_option "
1313                                         "(SECPROPS,\"%s\") failed!\n",
1314                                         li->li_acl_secprops, 0, 0 );
1315                                 goto done;
1316                         }
1317                 }
1318
1319                 defaults = lutil_sasl_defaults( lc->lc_ld,
1320                                 li->li_acl_sasl_mech.bv_val,
1321                                 li->li_acl_sasl_realm.bv_val,
1322                                 li->li_acl_authcID.bv_val,
1323                                 li->li_acl_passwd.bv_val,
1324                                 NULL );
1325
1326                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld,
1327                                 li->li_acl_authcDN.bv_val,
1328                                 li->li_acl_sasl_mech.bv_val, NULL, NULL,
1329                                 LDAP_SASL_QUIET, lutil_sasl_interact,
1330                                 defaults );
1331
1332                 lutil_sasl_freedefs( defaults );
1333
1334                 rs->sr_err = slap_map_api2result( rs );
1335                 if ( rs->sr_err != LDAP_SUCCESS ) {
1336                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1337                         if ( sendok & LDAP_BACK_SENDERR ) {
1338                                 send_ldap_result( op, rs );
1339                         }
1340
1341                 } else {
1342                         LDAP_BACK_CONN_ISBOUND_SET( lc );
1343                 }
1344
1345                 if ( LDAP_BACK_QUARANTINE( li ) ) {
1346                         ldap_back_quarantine( op, rs );
1347                 }
1348
1349                 goto done;
1350         }
1351 #endif /* HAVE_CYRUS_SASL */
1352
1353 retry:;
1354         rs->sr_err = ldap_sasl_bind( lc->lc_ld,
1355                         BER_BVISNULL( &lc->lc_cred ) ? "" : lc->lc_bound_ndn.bv_val,
1356                         LDAP_SASL_SIMPLE, &lc->lc_cred,
1357                         NULL, NULL, &msgid );
1358
1359         if ( rs->sr_err == LDAP_SERVER_DOWN ) {
1360                 if ( retries != LDAP_BACK_RETRY_NEVER ) {
1361                         if ( dolock ) {
1362                                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1363                         }
1364
1365                         assert( lc->lc_refcnt > 0 );
1366                         if ( lc->lc_refcnt == 1 ) {
1367                                 ldap_unbind_ext( lc->lc_ld, NULL, NULL );
1368                                 lc->lc_ld = NULL;
1369
1370                                 /* lc here must be the regular lc, reset and ready for init */
1371                                 rs->sr_err = ldap_back_prepare_conn( lc, op, rs, sendok );
1372                                 if ( rs->sr_err != LDAP_SUCCESS ) {
1373                                         lc->lc_refcnt = 0;
1374                                 }
1375                         }
1376
1377                         if ( dolock ) {
1378                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1379                         }
1380
1381                         if ( rs->sr_err == LDAP_SUCCESS ) {
1382                                 if ( retries > 0 ) {
1383                                         retries--;
1384                                 }
1385                                 goto retry;
1386                         }
1387                 }
1388
1389                 assert( lc->lc_refcnt == 1 );
1390                 lc->lc_refcnt = 0;
1391                 ldap_back_freeconn( li, lc, dolock );
1392                 *lcp = NULL;
1393                 rs->sr_err = slap_map_api2result( rs );
1394
1395                 if ( LDAP_BACK_QUARANTINE( li ) ) {
1396                         ldap_back_quarantine( op, rs );
1397                 }
1398
1399                 if ( rs->sr_err != LDAP_SUCCESS &&
1400                         ( sendok & LDAP_BACK_SENDERR ) )
1401                 {
1402                         send_ldap_result( op, rs );
1403                 }
1404
1405                 return 0;
1406         }
1407
1408         rc = ldap_back_op_result( lc, op, rs, msgid,
1409                 -1, (sendok|LDAP_BACK_BINDING) );
1410         if ( rc == LDAP_SUCCESS ) {
1411                 LDAP_BACK_CONN_ISBOUND_SET( lc );
1412         }
1413
1414 done:;
1415         LDAP_BACK_CONN_BINDING_CLEAR( lc );
1416         rc = LDAP_BACK_CONN_ISBOUND( lc );
1417         if ( !rc ) {
1418                 ldap_back_release_conn_lock( li, lcp, dolock );
1419
1420         } else if ( LDAP_BACK_SAVECRED( li ) ) {
1421                 ldap_set_rebind_proc( lc->lc_ld, li->li_rebind_f, lc );
1422         }
1423
1424         return rc;
1425 }
1426
1427 /*
1428  * ldap_back_dobind
1429  *
1430  * Note: dolock indicates whether li->li_conninfo.lai_mutex must be locked or not
1431  */
1432 int
1433 ldap_back_dobind( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1434 {
1435         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1436
1437         return ldap_back_dobind_int( lcp, op, rs,
1438                 ( sendok | LDAP_BACK_GETCONN ), li->li_nretries, 1 );
1439 }
1440
1441 /*
1442  * ldap_back_default_rebind
1443  *
1444  * This is a callback used for chasing referrals using the same
1445  * credentials as the original user on this session.
1446  */
1447 int 
1448 ldap_back_default_rebind( LDAP *ld, LDAP_CONST char *url, ber_tag_t request,
1449         ber_int_t msgid, void *params )
1450 {
1451         ldapconn_t      *lc = (ldapconn_t *)params;
1452
1453 #ifdef HAVE_TLS
1454         /* ... otherwise we couldn't get here */
1455         assert( lc != NULL );
1456
1457         if ( !ldap_tls_inplace( ld ) ) {
1458                 int             is_tls = LDAP_BACK_CONN_ISTLS( lc ),
1459                                 rc;
1460                 const char      *text = NULL;
1461
1462                 rc = ldap_back_start_tls( ld, 0, &is_tls, url, lc->lc_flags,
1463                         LDAP_BACK_RETRY_DEFAULT, &text );
1464                 if ( rc != LDAP_SUCCESS ) {
1465                         return rc;
1466                 }
1467         }
1468 #endif /* HAVE_TLS */
1469
1470         /* FIXME: add checks on the URL/identity? */
1471
1472         return ldap_sasl_bind_s( ld,
1473                         BER_BVISNULL( &lc->lc_cred ) ? "" : lc->lc_bound_ndn.bv_val,
1474                         LDAP_SASL_SIMPLE, &lc->lc_cred, NULL, NULL, NULL );
1475 }
1476
1477 /*
1478  * ldap_back_default_urllist
1479  */
1480 int 
1481 ldap_back_default_urllist(
1482         LDAP            *ld,
1483         LDAPURLDesc     **urllist,
1484         LDAPURLDesc     **url,
1485         void            *params )
1486 {
1487         ldapinfo_t      *li = (ldapinfo_t *)params;
1488         LDAPURLDesc     **urltail;
1489
1490         if ( urllist == url ) {
1491                 return LDAP_SUCCESS;
1492         }
1493
1494         for ( urltail = &(*url)->lud_next; *urltail; urltail = &(*urltail)->lud_next )
1495                 /* count */ ;
1496
1497         *urltail = *urllist;
1498         *urllist = *url;
1499         *url = NULL;
1500
1501         ldap_pvt_thread_mutex_lock( &li->li_uri_mutex );
1502         if ( li->li_uri ) {
1503                 ch_free( li->li_uri );
1504         }
1505
1506         ldap_get_option( ld, LDAP_OPT_URI, (void *)&li->li_uri );
1507         ldap_pvt_thread_mutex_unlock( &li->li_uri_mutex );
1508
1509         return LDAP_SUCCESS;
1510 }
1511
1512 int
1513 ldap_back_cancel(
1514                 ldapconn_t              *lc,
1515                 Operation               *op,
1516                 SlapReply               *rs,
1517                 ber_int_t               msgid,
1518                 ldap_back_send_t        sendok )
1519 {
1520         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1521
1522         /* default behavior */
1523         if ( LDAP_BACK_ABANDON( li ) ) {
1524                 return ldap_abandon_ext( lc->lc_ld, msgid, NULL, NULL );
1525         }
1526
1527         if ( LDAP_BACK_IGNORE( li ) ) {
1528                 return ldap_pvt_discard( lc->lc_ld, msgid );
1529         }
1530
1531         if ( LDAP_BACK_CANCEL( li ) ) {
1532                 /* FIXME: asynchronous? */
1533                 return ldap_cancel_s( lc->lc_ld, msgid, NULL, NULL );
1534         }
1535
1536         assert( 0 );
1537
1538         return LDAP_OTHER;
1539 }
1540
1541 int
1542 ldap_back_op_result(
1543                 ldapconn_t              *lc,
1544                 Operation               *op,
1545                 SlapReply               *rs,
1546                 ber_int_t               msgid,
1547                 time_t                  timeout,
1548                 ldap_back_send_t        sendok )
1549 {
1550         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1551
1552         char            *match = NULL;
1553         char            *text = NULL;
1554         char            **refs = NULL;
1555         LDAPControl     **ctrls = NULL;
1556
1557 #define ERR_OK(err) ((err) == LDAP_SUCCESS || (err) == LDAP_COMPARE_FALSE || (err) == LDAP_COMPARE_TRUE)
1558
1559         rs->sr_text = NULL;
1560         rs->sr_matched = NULL;
1561         rs->sr_ref = NULL;
1562         rs->sr_ctrls = NULL;
1563
1564         /* if the error recorded in the reply corresponds
1565          * to a successful state, get the error from the
1566          * remote server response */
1567         if ( ERR_OK( rs->sr_err ) ) {
1568                 int             rc;
1569                 struct timeval  tv;
1570                 LDAPMessage     *res = NULL;
1571                 time_t          stoptime = (time_t)(-1);
1572                 int             timeout_err = op->o_protocol >= LDAP_VERSION3 ?
1573                                         LDAP_ADMINLIMIT_EXCEEDED : LDAP_OTHER;
1574                 const char      *timeout_text = "Operation timed out";
1575
1576                 /* if timeout is not specified, compute and use
1577                  * the one specific to the ongoing operation */
1578                 if ( timeout == (time_t)(-1) ) {
1579                         slap_op_t       opidx = slap_req2op( op->o_tag );
1580
1581                         if ( opidx == SLAP_OP_SEARCH ) {
1582                                 if ( op->ors_tlimit <= 0 ) {
1583                                         timeout = 0;
1584
1585                                 } else {
1586                                         timeout = op->ors_tlimit;
1587                                         timeout_err = LDAP_TIMELIMIT_EXCEEDED;
1588                                         timeout_text = NULL;
1589                                 }
1590
1591                         } else {
1592                                 timeout = li->li_timeout[ opidx ];
1593                         }
1594                 }
1595
1596                 /* better than nothing :) */
1597                 if ( timeout == 0 ) {
1598                         if ( li->li_idle_timeout ) {
1599                                 timeout = li->li_idle_timeout;
1600
1601                         } else if ( li->li_conn_ttl ) {
1602                                 timeout = li->li_conn_ttl;
1603                         }
1604                 }
1605
1606                 if ( timeout ) {
1607                         stoptime = op->o_time + timeout;
1608                 }
1609
1610                 LDAP_BACK_TV_SET( &tv );
1611
1612 retry:;
1613                 /* if result parsing fails, note the failure reason */
1614                 rc = ldap_result( lc->lc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
1615                 switch ( rc ) {
1616                 case 0:
1617                         if ( timeout && slap_get_time() > stoptime ) {
1618                                 if ( sendok & LDAP_BACK_BINDING ) {
1619                                         ldap_unbind_ext( lc->lc_ld, NULL, NULL );
1620                                         lc->lc_ld = NULL;
1621                                         LDAP_BACK_CONN_TAINTED_SET( lc );
1622
1623                                 } else {
1624                                         (void)ldap_back_cancel( lc, op, rs, msgid, sendok );
1625                                 }
1626                                 rs->sr_err = timeout_err;
1627                                 rs->sr_text = timeout_text;
1628                                 break;
1629                         }
1630
1631                         /* timeout == 0 */
1632                         LDAP_BACK_TV_SET( &tv );
1633                         ldap_pvt_thread_yield();
1634                         goto retry;
1635
1636                 case -1:
1637                         ldap_get_option( lc->lc_ld, LDAP_OPT_ERROR_NUMBER,
1638                                         &rs->sr_err );
1639                         break;
1640
1641
1642                 /* otherwise get the result; if it is not
1643                  * LDAP_SUCCESS, record it in the reply
1644                  * structure (this includes 
1645                  * LDAP_COMPARE_{TRUE|FALSE}) */
1646                 default:
1647                         /* only touch when activity actually took place... */
1648                         if ( li->li_idle_timeout && lc ) {
1649                                 lc->lc_time = op->o_time;
1650                         }
1651
1652                         rc = ldap_parse_result( lc->lc_ld, res, &rs->sr_err,
1653                                         &match, &text, &refs, &ctrls, 1 );
1654                         rs->sr_text = text;
1655                         if ( rc != LDAP_SUCCESS ) {
1656                                 rs->sr_err = rc;
1657                         }
1658                         if ( refs != NULL ) {
1659                                 int     i;
1660
1661                                 for ( i = 0; refs[ i ] != NULL; i++ )
1662                                         /* count */ ;
1663                                 rs->sr_ref = op->o_tmpalloc( sizeof( struct berval ) * ( i + 1 ),
1664                                         op->o_tmpmemctx );
1665                                 for ( i = 0; refs[ i ] != NULL; i++ ) {
1666                                         ber_str2bv( refs[ i ], 0, 0, &rs->sr_ref[ i ] );
1667                                 }
1668                                 BER_BVZERO( &rs->sr_ref[ i ] );
1669                         }
1670                         if ( ctrls != NULL ) {
1671                                 rs->sr_ctrls = ctrls;
1672                         }
1673                 }
1674         }
1675
1676         /* if the error in the reply structure is not
1677          * LDAP_SUCCESS, try to map it from client 
1678          * to server error */
1679         if ( !ERR_OK( rs->sr_err ) ) {
1680                 rs->sr_err = slap_map_api2result( rs );
1681
1682                 /* internal ops ( op->o_conn == NULL ) 
1683                  * must not reply to client */
1684                 if ( op->o_conn && !op->o_do_not_cache && match ) {
1685
1686                         /* record the (massaged) matched
1687                          * DN into the reply structure */
1688                         rs->sr_matched = match;
1689                 }
1690         }
1691
1692         if ( rs->sr_err == LDAP_UNAVAILABLE ) {
1693                 if ( !( sendok & LDAP_BACK_RETRYING ) ) {
1694                         if ( LDAP_BACK_QUARANTINE( li ) ) {
1695                                 ldap_back_quarantine( op, rs );
1696                         }
1697                         if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
1698                                 send_ldap_result( op, rs );
1699                         }
1700                 }
1701
1702         } else if ( op->o_conn &&
1703                 ( ( ( sendok & LDAP_BACK_SENDOK ) && ERR_OK( rs->sr_err ) )
1704                         || ( ( sendok & LDAP_BACK_SENDERR ) && rs->sr_err != LDAP_SUCCESS ) ) )
1705         {
1706                 send_ldap_result( op, rs );
1707         }
1708
1709         if ( match ) {
1710                 if ( rs->sr_matched != match ) {
1711                         free( (char *)rs->sr_matched );
1712                 }
1713                 rs->sr_matched = NULL;
1714                 ldap_memfree( match );
1715         }
1716
1717         if ( text ) {
1718                 ldap_memfree( text );
1719         }
1720         rs->sr_text = NULL;
1721
1722         if ( rs->sr_ref ) {
1723                 assert( refs != NULL );
1724                 ber_memvfree( (void **)refs );
1725                 op->o_tmpfree( rs->sr_ref, op->o_tmpmemctx );
1726                 rs->sr_ref = NULL;
1727         }
1728
1729         if ( ctrls ) {
1730                 assert( rs->sr_ctrls != NULL );
1731                 ldap_controls_free( ctrls );
1732                 rs->sr_ctrls = NULL;
1733         }
1734
1735         return( ERR_OK( rs->sr_err ) ? LDAP_SUCCESS : rs->sr_err );
1736 }
1737
1738 /* return true if bound, false if failed */
1739 int
1740 ldap_back_retry( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1741 {
1742         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1743         int             rc = 0,
1744                         binding;
1745
1746         assert( lcp != NULL );
1747         assert( *lcp != NULL );
1748
1749         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1750
1751         if ( (*lcp)->lc_refcnt == 1 ) {
1752                 binding = LDAP_BACK_CONN_BINDING( *lcp );
1753
1754                 ldap_pvt_thread_mutex_lock( &li->li_uri_mutex );
1755                 Debug( LDAP_DEBUG_ANY,
1756                         "%s ldap_back_retry: retrying URI=\"%s\" DN=\"%s\"\n",
1757                         op->o_log_prefix, li->li_uri,
1758                         BER_BVISNULL( &(*lcp)->lc_bound_ndn ) ?
1759                                 "" : (*lcp)->lc_bound_ndn.bv_val );
1760                 ldap_pvt_thread_mutex_unlock( &li->li_uri_mutex );
1761
1762                 ldap_unbind_ext( (*lcp)->lc_ld, NULL, NULL );
1763                 (*lcp)->lc_ld = NULL;
1764                 LDAP_BACK_CONN_ISBOUND_CLEAR( (*lcp) );
1765
1766                 /* lc here must be the regular lc, reset and ready for init */
1767                 rc = ldap_back_prepare_conn( *lcp, op, rs, sendok );
1768                 if ( rc != LDAP_SUCCESS ) {
1769                         /* freeit, because lc_refcnt == 1 */
1770                         (*lcp)->lc_refcnt = 0;
1771                         (void)ldap_back_freeconn( li, *lcp, 0 );
1772                         *lcp = NULL;
1773                         rc = 0;
1774
1775                 } else if ( ( sendok & LDAP_BACK_BINDING ) ) {
1776                         if ( binding ) {
1777                                 LDAP_BACK_CONN_BINDING_SET( *lcp );
1778                         }
1779                         rc = 1;
1780
1781                 } else {
1782                         rc = ldap_back_dobind_int( lcp, op, rs, sendok, 0, 0 );
1783                         if ( rc == 0 && *lcp != NULL ) {
1784                                 /* freeit, because lc_refcnt == 1 */
1785                                 (*lcp)->lc_refcnt = 0;
1786                                 LDAP_BACK_CONN_TAINTED_SET( *lcp );
1787                                 (void)ldap_back_freeconn( li, *lcp, 0 );
1788                                 *lcp = NULL;
1789                         }
1790                 }
1791
1792         } else {
1793                 Debug( LDAP_DEBUG_TRACE,
1794                         "ldap_back_retry: conn %p refcnt=%u unable to retry.\n",
1795                         (void *)(*lcp), (*lcp)->lc_refcnt, 0 );
1796
1797                 LDAP_BACK_CONN_TAINTED_SET( *lcp );
1798                 ldap_back_release_conn_lock( li, lcp, 0 );
1799                 assert( *lcp == NULL );
1800
1801                 if ( sendok ) {
1802                         rs->sr_err = LDAP_UNAVAILABLE;
1803                         rs->sr_text = "unable to retry";
1804                         send_ldap_result( op, rs );
1805                 }
1806         }
1807
1808         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1809
1810         return rc;
1811 }
1812
1813 static int
1814 ldap_back_is_proxy_authz( Operation *op, SlapReply *rs, ldap_back_send_t sendok,
1815         struct berval *binddn, struct berval *bindcred )
1816 {
1817         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1818         struct berval   ndn;
1819         int             dobind = 0;
1820
1821         if ( op->o_conn == NULL || op->o_do_not_cache ) {
1822                 goto done;
1823         }
1824
1825         /* don't proxyAuthz if protocol is not LDAPv3 */
1826         switch ( li->li_version ) {
1827         case LDAP_VERSION3:
1828                 break;
1829
1830         case 0:
1831                 if ( op->o_protocol == 0 || op->o_protocol == LDAP_VERSION3 ) {
1832                         break;
1833                 }
1834                 /* fall thru */
1835
1836         default:
1837                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1838                 if ( sendok & LDAP_BACK_SENDERR ) {
1839                         send_ldap_result( op, rs );
1840                         dobind = -1;
1841                 }
1842                 goto done;
1843         }
1844
1845         /* safe default */
1846         *binddn = slap_empty_bv;
1847         *bindcred = slap_empty_bv;
1848
1849         if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1850                 ndn = op->o_conn->c_ndn;
1851
1852         } else {
1853                 ndn = op->o_ndn;
1854         }
1855
1856         switch ( li->li_idassert_mode ) {
1857         case LDAP_BACK_IDASSERT_LEGACY:
1858                 if ( !BER_BVISNULL( &ndn ) && !BER_BVISEMPTY( &ndn ) ) {
1859                         if ( !BER_BVISNULL( &li->li_idassert_authcDN ) && !BER_BVISEMPTY( &li->li_idassert_authcDN ) )
1860                         {
1861                                 *binddn = li->li_idassert_authcDN;
1862                                 *bindcred = li->li_idassert_passwd;
1863                                 dobind = 1;
1864                         }
1865                 }
1866                 break;
1867
1868         default:
1869                 /* NOTE: rootdn can always idassert */
1870                 if ( BER_BVISNULL( &ndn )
1871                         && li->li_idassert_authz == NULL
1872                         && !( li->li_idassert_flags & LDAP_BACK_AUTH_AUTHZ_ALL ) )
1873                 {
1874                         if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1875                                 rs->sr_err = LDAP_INAPPROPRIATE_AUTH;
1876                                 if ( sendok & LDAP_BACK_SENDERR ) {
1877                                         send_ldap_result( op, rs );
1878                                         dobind = -1;
1879                                 }
1880
1881                         } else {
1882                                 rs->sr_err = LDAP_SUCCESS;
1883                                 *binddn = slap_empty_bv;
1884                                 *bindcred = slap_empty_bv;
1885                                 break;
1886                         }
1887
1888                         goto done;
1889
1890                 } else if ( li->li_idassert_authz && !be_isroot( op ) ) {
1891                         struct berval authcDN;
1892
1893                         if ( BER_BVISNULL( &ndn ) ) {
1894                                 authcDN = slap_empty_bv;
1895
1896                         } else {
1897                                 authcDN = ndn;
1898                         }       
1899                         rs->sr_err = slap_sasl_matches( op, li->li_idassert_authz,
1900                                         &authcDN, &authcDN );
1901                         if ( rs->sr_err != LDAP_SUCCESS ) {
1902                                 if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1903                                         if ( sendok & LDAP_BACK_SENDERR ) {
1904                                                 send_ldap_result( op, rs );
1905                                                 dobind = -1;
1906                                         }
1907
1908                                 } else {
1909                                         rs->sr_err = LDAP_SUCCESS;
1910                                         *binddn = slap_empty_bv;
1911                                         *bindcred = slap_empty_bv;
1912                                         break;
1913                                 }
1914
1915                                 goto done;
1916                         }
1917                 }
1918
1919                 *binddn = li->li_idassert_authcDN;
1920                 *bindcred = li->li_idassert_passwd;
1921                 dobind = 1;
1922                 break;
1923         }
1924
1925 done:;
1926         return dobind;
1927 }
1928
1929 static int
1930 ldap_back_proxy_authz_bind(
1931         ldapconn_t              *lc,
1932         Operation               *op,
1933         SlapReply               *rs,
1934         ldap_back_send_t        sendok,
1935         struct berval           *binddn,
1936         struct berval           *bindcred )
1937 {
1938         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1939         struct berval   ndn;
1940         int             msgid;
1941         int             rc;
1942
1943         if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1944                 ndn = op->o_conn->c_ndn;
1945
1946         } else {
1947                 ndn = op->o_ndn;
1948         }
1949
1950         if ( li->li_idassert_authmethod == LDAP_AUTH_SASL ) {
1951 #ifdef HAVE_CYRUS_SASL
1952                 void            *defaults = NULL;
1953                 struct berval   authzID = BER_BVNULL;
1954                 int             freeauthz = 0;
1955
1956                 /* if SASL supports native authz, prepare for it */
1957                 if ( ( !op->o_do_not_cache || !op->o_is_auth_check ) &&
1958                                 ( li->li_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
1959                 {
1960                         switch ( li->li_idassert_mode ) {
1961                         case LDAP_BACK_IDASSERT_OTHERID:
1962                         case LDAP_BACK_IDASSERT_OTHERDN:
1963                                 authzID = li->li_idassert_authzID;
1964                                 break;
1965
1966                         case LDAP_BACK_IDASSERT_ANONYMOUS:
1967                                 BER_BVSTR( &authzID, "dn:" );
1968                                 break;
1969
1970                         case LDAP_BACK_IDASSERT_SELF:
1971                                 if ( BER_BVISNULL( &ndn ) ) {
1972                                         /* connection is not authc'd, so don't idassert */
1973                                         BER_BVSTR( &authzID, "dn:" );
1974                                         break;
1975                                 }
1976                                 authzID.bv_len = STRLENOF( "dn:" ) + ndn.bv_len;
1977                                 authzID.bv_val = slap_sl_malloc( authzID.bv_len + 1, op->o_tmpmemctx );
1978                                 AC_MEMCPY( authzID.bv_val, "dn:", STRLENOF( "dn:" ) );
1979                                 AC_MEMCPY( authzID.bv_val + STRLENOF( "dn:" ),
1980                                                 ndn.bv_val, ndn.bv_len + 1 );
1981                                 freeauthz = 1;
1982                                 break;
1983
1984                         default:
1985                                 break;
1986                         }
1987                 }
1988
1989                 if ( li->li_idassert_secprops != NULL ) {
1990                         rs->sr_err = ldap_set_option( lc->lc_ld,
1991                                 LDAP_OPT_X_SASL_SECPROPS,
1992                                 (void *)li->li_idassert_secprops );
1993
1994                         if ( rs->sr_err != LDAP_OPT_SUCCESS ) {
1995                                 rs->sr_err = LDAP_OTHER;
1996                                 if ( sendok & LDAP_BACK_SENDERR ) {
1997                                         send_ldap_result( op, rs );
1998                                 }
1999                                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
2000                                 goto done;
2001                         }
2002                 }
2003
2004                 defaults = lutil_sasl_defaults( lc->lc_ld,
2005                                 li->li_idassert_sasl_mech.bv_val,
2006                                 li->li_idassert_sasl_realm.bv_val,
2007                                 li->li_idassert_authcID.bv_val,
2008                                 li->li_idassert_passwd.bv_val,
2009                                 authzID.bv_val );
2010
2011                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld, binddn->bv_val,
2012                                 li->li_idassert_sasl_mech.bv_val, NULL, NULL,
2013                                 LDAP_SASL_QUIET, lutil_sasl_interact,
2014                                 defaults );
2015
2016                 rs->sr_err = slap_map_api2result( rs );
2017                 if ( rs->sr_err != LDAP_SUCCESS ) {
2018                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
2019                         if ( sendok & LDAP_BACK_SENDERR ) {
2020                                 send_ldap_result( op, rs );
2021                         }
2022
2023                 } else {
2024                         LDAP_BACK_CONN_ISBOUND_SET( lc );
2025                 }
2026
2027                 lutil_sasl_freedefs( defaults );
2028                 if ( freeauthz ) {
2029                         slap_sl_free( authzID.bv_val, op->o_tmpmemctx );
2030                 }
2031
2032                 goto done;
2033 #endif /* HAVE_CYRUS_SASL */
2034         }
2035
2036         switch ( li->li_idassert_authmethod ) {
2037         case LDAP_AUTH_NONE:
2038                 /* FIXME: do we really need this? */
2039                 BER_BVSTR( binddn, "" );
2040                 BER_BVSTR( bindcred, "" );
2041                 /* fallthru */
2042
2043         case LDAP_AUTH_SIMPLE:
2044                 rs->sr_err = ldap_sasl_bind( lc->lc_ld,
2045                                 binddn->bv_val, LDAP_SASL_SIMPLE,
2046                                 bindcred, NULL, NULL, &msgid );
2047                 rc = ldap_back_op_result( lc, op, rs, msgid,
2048                         -1, (sendok|LDAP_BACK_BINDING) );
2049                 break;
2050
2051         default:
2052                 /* unsupported! */
2053                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
2054                 rs->sr_err = LDAP_AUTH_METHOD_NOT_SUPPORTED;
2055                 if ( sendok & LDAP_BACK_SENDERR ) {
2056                         send_ldap_result( op, rs );
2057                 }
2058                 goto done;
2059         }
2060
2061         if ( rc == LDAP_SUCCESS ) {
2062                 /* set rebind stuff in case of successful proxyAuthz bind,
2063                  * so that referral chasing is attempted using the right
2064                  * identity */
2065                 LDAP_BACK_CONN_ISBOUND_SET( lc );
2066                 ber_bvreplace( &lc->lc_bound_ndn, binddn );
2067
2068                 if ( !BER_BVISNULL( &lc->lc_cred ) ) {
2069                         memset( lc->lc_cred.bv_val, 0,
2070                                         lc->lc_cred.bv_len );
2071                 }
2072
2073                 if ( LDAP_BACK_SAVECRED( li ) ) {
2074                         ber_bvreplace( &lc->lc_cred, bindcred );
2075                         ldap_set_rebind_proc( lc->lc_ld, li->li_rebind_f, lc );
2076
2077                 } else {
2078                         lc->lc_cred.bv_len = 0;
2079                 }
2080         }
2081 done:;
2082         return LDAP_BACK_CONN_ISBOUND( lc );
2083 }
2084
2085 /*
2086  * ldap_back_proxy_authz_ctrl() prepends a proxyAuthz control
2087  * to existing server-side controls if required; if not,
2088  * the existing server-side controls are placed in *pctrls.
2089  * The caller, after using the controls in client API 
2090  * operations, if ( *pctrls != op->o_ctrls ), should
2091  * free( (*pctrls)[ 0 ] ) and free( *pctrls ).
2092  * The function returns success if the control could
2093  * be added if required, or if it did nothing; in the future,
2094  * it might return some error if it failed.
2095  * 
2096  * if no bind took place yet, but the connection is bound
2097  * and the "proxyauthzdn" is set, then bind as "proxyauthzdn" 
2098  * and explicitly add proxyAuthz the control to every operation
2099  * with the dn bound to the connection as control value.
2100  *
2101  * If no server-side controls are defined for the operation,
2102  * simply add the proxyAuthz control; otherwise, if the
2103  * proxyAuthz control is not already set, add it as
2104  * the first one
2105  *
2106  * FIXME: is controls order significant for security?
2107  * ANSWER: controls ordering and interoperability
2108  * must be indicated by the specs of each control; if none
2109  * is specified, the order is irrelevant.
2110  */
2111 int
2112 ldap_back_proxy_authz_ctrl(
2113                 struct berval   *bound_ndn,
2114                 int             version,
2115                 slap_idassert_t *si,
2116                 Operation       *op,
2117                 SlapReply       *rs,
2118                 LDAPControl     ***pctrls )
2119 {
2120         LDAPControl             **ctrls = NULL;
2121         int                     i = 0;
2122         slap_idassert_mode_t    mode;
2123         struct berval           assertedID,
2124                                 ndn;
2125         int                     isroot = 0;
2126
2127         *pctrls = NULL;
2128
2129         rs->sr_err = LDAP_SUCCESS;
2130
2131         /* don't proxyAuthz if protocol is not LDAPv3 */
2132         switch ( version ) {
2133         case LDAP_VERSION3:
2134                 break;
2135
2136         case 0:
2137                 if ( op->o_protocol == 0 || op->o_protocol == LDAP_VERSION3 ) {
2138                         break;
2139                 }
2140                 /* fall thru */
2141
2142         default:
2143                 goto done;
2144         }
2145
2146         /* FIXME: SASL/EXTERNAL over ldapi:// doesn't honor the authcID,
2147          * but if it is not set this test fails.  We need a different
2148          * means to detect if idassert is enabled */
2149         if ( ( BER_BVISNULL( &si->si_bc.sb_authcId ) || BER_BVISEMPTY( &si->si_bc.sb_authcId ) )
2150                         && ( BER_BVISNULL( &si->si_bc.sb_binddn ) || BER_BVISEMPTY( &si->si_bc.sb_binddn ) ) )
2151         {
2152                 goto done;
2153         }
2154
2155         if ( !op->o_conn || op->o_do_not_cache || ( isroot = be_isroot( op ) ) ) {
2156                 goto done;
2157         }
2158
2159         if ( op->o_tag == LDAP_REQ_BIND ) {
2160                 ndn = op->o_req_ndn;
2161
2162         } else if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
2163                 ndn = op->o_conn->c_ndn;
2164
2165         } else {
2166                 ndn = op->o_ndn;
2167         }
2168
2169         if ( si->si_mode == LDAP_BACK_IDASSERT_LEGACY ) {
2170                 if ( op->o_proxy_authz ) {
2171                         /*
2172                          * FIXME: we do not want to perform proxyAuthz
2173                          * on behalf of the client, because this would
2174                          * be performed with "proxyauthzdn" privileges.
2175                          *
2176                          * This might actually be too strict, since
2177                          * the "proxyauthzdn" authzTo, and each entry's
2178                          * authzFrom attributes may be crafted
2179                          * to avoid unwanted proxyAuthz to take place.
2180                          */
2181 #if 0
2182                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
2183                         rs->sr_text = "proxyAuthz not allowed within namingContext";
2184 #endif
2185                         goto done;
2186                 }
2187
2188                 if ( !BER_BVISNULL( bound_ndn ) ) {
2189                         goto done;
2190                 }
2191
2192                 if ( BER_BVISNULL( &ndn ) ) {
2193                         goto done;
2194                 }
2195
2196                 if ( BER_BVISNULL( &si->si_bc.sb_binddn ) ) {
2197                         goto done;
2198                 }
2199
2200         } else if ( si->si_bc.sb_method == LDAP_AUTH_SASL ) {
2201                 if ( ( si->si_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
2202                 {
2203                         /* already asserted in SASL via native authz */
2204                         goto done;
2205                 }
2206
2207         } else if ( si->si_authz && !isroot ) {
2208                 int             rc;
2209                 struct berval authcDN;
2210
2211                 if ( BER_BVISNULL( &ndn ) ) {
2212                         authcDN = slap_empty_bv;
2213                 } else {
2214                         authcDN = ndn;
2215                 }
2216                 rc = slap_sasl_matches( op, si->si_authz,
2217                                 &authcDN, & authcDN );
2218                 if ( rc != LDAP_SUCCESS ) {
2219                         if ( si->si_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
2220                                 /* ndn is not authorized
2221                                  * to use idassert */
2222                                 rs->sr_err = rc;
2223                         }
2224                         goto done;
2225                 }
2226         }
2227
2228         if ( op->o_proxy_authz ) {
2229                 /*
2230                  * FIXME: we can:
2231                  * 1) ignore the already set proxyAuthz control
2232                  * 2) leave it in place, and don't set ours
2233                  * 3) add both
2234                  * 4) reject the operation
2235                  *
2236                  * option (4) is very drastic
2237                  * option (3) will make the remote server reject
2238                  * the operation, thus being equivalent to (4)
2239                  * option (2) will likely break the idassert
2240                  * assumptions, so we cannot accept it;
2241                  * option (1) means that we are contradicting
2242                  * the client's reques.
2243                  *
2244                  * I think (4) is the only correct choice.
2245                  */
2246                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
2247                 rs->sr_text = "proxyAuthz not allowed within namingContext";
2248         }
2249
2250         if ( op->o_is_auth_check ) {
2251                 mode = LDAP_BACK_IDASSERT_NOASSERT;
2252
2253         } else {
2254                 mode = si->si_mode;
2255         }
2256
2257         switch ( mode ) {
2258         case LDAP_BACK_IDASSERT_LEGACY:
2259                 /* original behavior:
2260                  * assert the client's identity */
2261         case LDAP_BACK_IDASSERT_SELF:
2262                 assertedID = ndn;
2263                 break;
2264
2265         case LDAP_BACK_IDASSERT_ANONYMOUS:
2266                 /* assert "anonymous" */
2267                 assertedID = slap_empty_bv;
2268                 break;
2269
2270         case LDAP_BACK_IDASSERT_NOASSERT:
2271                 /* don't assert; bind as proxyauthzdn */
2272                 goto done;
2273
2274         case LDAP_BACK_IDASSERT_OTHERID:
2275         case LDAP_BACK_IDASSERT_OTHERDN:
2276                 /* assert idassert DN */
2277                 assertedID = si->si_bc.sb_authzId;
2278                 break;
2279
2280         default:
2281                 assert( 0 );
2282         }
2283
2284         /* if we got here, "" is allowed to proxyAuthz */
2285         if ( BER_BVISNULL( &assertedID ) ) {
2286                 assertedID = slap_empty_bv;
2287         }
2288
2289         /* don't idassert the bound DN (ITS#4497) */
2290         if ( dn_match( &assertedID, bound_ndn ) ) {
2291                 goto done;
2292         }
2293
2294         if ( op->o_ctrls ) {
2295                 for ( i = 0; op->o_ctrls[ i ]; i++ )
2296                         /* just count ctrls */ ;
2297         }
2298
2299         ctrls = op->o_tmpalloc( sizeof( LDAPControl * ) * (i + 2) + sizeof( LDAPControl ),
2300                         op->o_tmpmemctx );
2301         ctrls[ 0 ] = (LDAPControl *)&ctrls[ i + 2 ];
2302         
2303         ctrls[ 0 ]->ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
2304         ctrls[ 0 ]->ldctl_iscritical = 1;
2305
2306         switch ( si->si_mode ) {
2307         /* already in u:ID or dn:DN form */
2308         case LDAP_BACK_IDASSERT_OTHERID:
2309         case LDAP_BACK_IDASSERT_OTHERDN:
2310                 ber_dupbv_x( &ctrls[ 0 ]->ldctl_value, &assertedID, op->o_tmpmemctx );
2311                 break;
2312
2313         /* needs the dn: prefix */
2314         default:
2315                 ctrls[ 0 ]->ldctl_value.bv_len = assertedID.bv_len + STRLENOF( "dn:" );
2316                 ctrls[ 0 ]->ldctl_value.bv_val = op->o_tmpalloc( ctrls[ 0 ]->ldctl_value.bv_len + 1,
2317                                 op->o_tmpmemctx );
2318                 AC_MEMCPY( ctrls[ 0 ]->ldctl_value.bv_val, "dn:", STRLENOF( "dn:" ) );
2319                 AC_MEMCPY( &ctrls[ 0 ]->ldctl_value.bv_val[ STRLENOF( "dn:" ) ],
2320                                 assertedID.bv_val, assertedID.bv_len + 1 );
2321                 break;
2322         }
2323
2324         /* Older versions of <draft-weltman-ldapv3-proxy> required
2325          * to encode the value of the authzID (and called it proxyDN);
2326          * this hack provides compatibility with those DSAs that
2327          * implement it this way */
2328         if ( si->si_flags & LDAP_BACK_AUTH_OBSOLETE_ENCODING_WORKAROUND ) {
2329                 struct berval           authzID = ctrls[ 0 ]->ldctl_value;
2330                 BerElementBuffer        berbuf;
2331                 BerElement              *ber = (BerElement *)&berbuf;
2332                 ber_tag_t               tag;
2333
2334                 ber_init2( ber, 0, LBER_USE_DER );
2335                 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
2336
2337                 tag = ber_printf( ber, "O", &authzID );
2338                 if ( tag == LBER_ERROR ) {
2339                         rs->sr_err = LDAP_OTHER;
2340                         goto free_ber;
2341                 }
2342
2343                 if ( ber_flatten2( ber, &ctrls[ 0 ]->ldctl_value, 1 ) == -1 ) {
2344                         rs->sr_err = LDAP_OTHER;
2345                         goto free_ber;
2346                 }
2347
2348 free_ber:;
2349                 op->o_tmpfree( authzID.bv_val, op->o_tmpmemctx );
2350                 ber_free_buf( ber );
2351
2352                 if ( rs->sr_err != LDAP_SUCCESS ) {
2353                         op->o_tmpfree( ctrls, op->o_tmpmemctx );
2354                         ctrls = NULL;
2355                         goto done;
2356                 }
2357
2358         } else if ( si->si_flags & LDAP_BACK_AUTH_OBSOLETE_PROXY_AUTHZ ) {
2359                 struct berval           authzID = ctrls[ 0 ]->ldctl_value,
2360                                         tmp;
2361                 BerElementBuffer        berbuf;
2362                 BerElement              *ber = (BerElement *)&berbuf;
2363                 ber_tag_t               tag;
2364
2365                 if ( strncasecmp( authzID.bv_val, "dn:", STRLENOF( "dn:" ) ) != 0 ) {
2366                         op->o_tmpfree( ctrls[ 0 ]->ldctl_value.bv_val, op->o_tmpmemctx );
2367                         op->o_tmpfree( ctrls, op->o_tmpmemctx );
2368                         ctrls = NULL;
2369                         rs->sr_err = LDAP_PROTOCOL_ERROR;
2370                         goto done;
2371                 }
2372
2373                 tmp = authzID;
2374                 tmp.bv_val += STRLENOF( "dn:" );
2375                 tmp.bv_len -= STRLENOF( "dn:" );
2376
2377                 ber_init2( ber, 0, LBER_USE_DER );
2378                 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
2379
2380                 /* apparently, Mozilla API encodes this
2381                  * as "SEQUENCE { LDAPDN }" */
2382                 tag = ber_printf( ber, "{O}", &tmp );
2383                 if ( tag == LBER_ERROR ) {
2384                         rs->sr_err = LDAP_OTHER;
2385                         goto free_ber2;
2386                 }
2387
2388                 if ( ber_flatten2( ber, &ctrls[ 0 ]->ldctl_value, 1 ) == -1 ) {
2389                         rs->sr_err = LDAP_OTHER;
2390                         goto free_ber2;
2391                 }
2392
2393 free_ber2:;
2394                 op->o_tmpfree( authzID.bv_val, op->o_tmpmemctx );
2395                 ber_free_buf( ber );
2396
2397                 if ( rs->sr_err != LDAP_SUCCESS ) {
2398                         op->o_tmpfree( ctrls, op->o_tmpmemctx );
2399                         ctrls = NULL;
2400                         goto done;
2401                 }
2402
2403                 ctrls[ 0 ]->ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
2404         }
2405
2406         if ( op->o_ctrls ) {
2407                 for ( i = 0; op->o_ctrls[ i ]; i++ ) {
2408                         ctrls[ i + 1 ] = op->o_ctrls[ i ];
2409                 }
2410         }
2411         ctrls[ i + 1 ] = NULL;
2412
2413 done:;
2414         if ( ctrls == NULL ) {
2415                 ctrls = op->o_ctrls;
2416         }
2417
2418         *pctrls = ctrls;
2419         
2420         return rs->sr_err;
2421 }
2422
2423 int
2424 ldap_back_proxy_authz_ctrl_free( Operation *op, LDAPControl ***pctrls )
2425 {
2426         LDAPControl     **ctrls = *pctrls;
2427
2428         /* we assume that the first control is the proxyAuthz
2429          * added by back-ldap, so it's the only one we explicitly 
2430          * free */
2431         if ( ctrls && ctrls != op->o_ctrls ) {
2432                 assert( ctrls[ 0 ] != NULL );
2433
2434                 if ( !BER_BVISNULL( &ctrls[ 0 ]->ldctl_value ) ) {
2435                         op->o_tmpfree( ctrls[ 0 ]->ldctl_value.bv_val, op->o_tmpmemctx );
2436                 }
2437
2438                 op->o_tmpfree( ctrls, op->o_tmpmemctx );
2439         } 
2440
2441         *pctrls = NULL;
2442
2443         return 0;
2444 }