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