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