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