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