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