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