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