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