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