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