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