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