]> git.sur5r.net Git - openldap/blob - servers/slapd/back-ldap/bind.c
27888d19d03177afb135f1b1a37684e493199ad8
[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-2006 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
36 #include <lutil_ldap.h>
37
38 #ifndef PRINT_CONNTREE
39 #define PRINT_CONNTREE 0
40 #endif /* !PRINT_CONNTREE */
41
42 #define LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ       "2.16.840.1.113730.3.4.12"
43
44 static LDAP_REBIND_PROC ldap_back_default_rebind;
45
46 LDAP_REBIND_PROC        *ldap_back_rebind_f = ldap_back_default_rebind;
47
48 static int
49 ldap_back_proxy_authz_bind( ldapconn_t *lc, Operation *op, SlapReply *rs, ldap_back_send_t sendok );
50
51 static int
52 ldap_back_prepare_conn( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok );
53
54 int
55 ldap_back_bind( Operation *op, SlapReply *rs )
56 {
57         ldapinfo_t      *li = (ldapinfo_t *) op->o_bd->be_private;
58         ldapconn_t      *lc;
59
60         int rc = 0;
61         ber_int_t msgid;
62
63         lc = ldap_back_getconn( op, rs, LDAP_BACK_BIND_SERR );
64         if ( !lc ) {
65                 return rs->sr_err;
66         }
67
68         if ( !BER_BVISNULL( &lc->lc_bound_ndn ) ) {
69                 ch_free( lc->lc_bound_ndn.bv_val );
70                 BER_BVZERO( &lc->lc_bound_ndn );
71         }
72         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
73
74         /* method is always LDAP_AUTH_SIMPLE if we got here */
75         rs->sr_err = ldap_sasl_bind( lc->lc_ld, op->o_req_dn.bv_val,
76                         LDAP_SASL_SIMPLE,
77                         &op->orb_cred, op->o_ctrls, NULL, &msgid );
78         rc = ldap_back_op_result( lc, op, rs, msgid, 0, LDAP_BACK_SENDERR );
79
80         if ( rc == LDAP_SUCCESS ) {
81                 /* If defined, proxyAuthz will be used also when
82                  * back-ldap is the authorizing backend; for this
83                  * purpose, a successful bind is followed by a
84                  * bind with the configured identity assertion */
85                 /* NOTE: use with care */
86                 if ( li->li_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) {
87                         ldap_back_proxy_authz_bind( lc, op, rs, LDAP_BACK_SENDERR );
88                         if ( !LDAP_BACK_CONN_ISBOUND( lc ) ) {
89                                 rc = 1;
90                                 goto done;
91                         }
92                 }
93
94                 assert( lc->lc_binding == 1 );
95                 lc->lc_binding = 0;
96                 LDAP_BACK_CONN_ISBOUND_SET( lc );
97                 ber_dupbv( &lc->lc_bound_ndn, &op->o_req_ndn );
98
99                 if ( LDAP_BACK_SAVECRED( li ) ) {
100                         if ( !BER_BVISNULL( &lc->lc_cred ) ) {
101                                 memset( lc->lc_cred.bv_val, 0,
102                                                 lc->lc_cred.bv_len );
103                         }
104                         ber_bvreplace( &lc->lc_cred, &op->orb_cred );
105                         ldap_set_rebind_proc( lc->lc_ld, ldap_back_rebind_f, lc );
106                 }
107         }
108 done:;
109
110         /* must re-insert if local DN changed as result of bind */
111         if ( LDAP_BACK_CONN_ISBOUND( lc )
112                 && !dn_match( &op->o_req_ndn, &lc->lc_local_ndn ) )
113         {
114                 int             lerr;
115
116                 /* wait for all other ops to release the connection */
117 retry_lock:;
118                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
119                 if ( lc->lc_refcnt > 1 ) {
120                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
121                         ldap_pvt_thread_yield();
122                         goto retry_lock;
123                 }
124
125                 assert( lc->lc_refcnt == 1 );
126                 lc = avl_delete( &li->li_conninfo.lai_tree, (caddr_t)lc,
127                                 ldap_back_conndn_cmp );
128                 assert( lc != NULL );
129
130                 ber_bvreplace( &lc->lc_local_ndn, &op->o_req_ndn );
131                 lerr = avl_insert( &li->li_conninfo.lai_tree, (caddr_t)lc,
132                         ldap_back_conndn_cmp, ldap_back_conndn_dup );
133                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
134                 if ( lerr == -1 ) {
135                         /* we can do this because lc_refcnt == 1 */
136                         ldap_back_conn_free( lc );
137                         lc = NULL;
138                 }
139         }
140
141         if ( lc != NULL ) {
142                 ldap_back_release_conn( op, rs, lc );
143         }
144
145         return( rc );
146 }
147
148 /*
149  * ldap_back_conndn_cmp
150  *
151  * compares two ldapconn_t based on the value of the conn pointer
152  * and of the local DN; used by avl stuff for insert, lookup
153  * and direct delete
154  */
155 int
156 ldap_back_conndn_cmp( const void *c1, const void *c2 )
157 {
158         const ldapconn_t        *lc1 = (const ldapconn_t *)c1;
159         const ldapconn_t        *lc2 = (const ldapconn_t *)c2;
160         int rc;
161
162         /* If local DNs don't match, it is definitely not a match */
163         /* For shared sessions, conn is NULL. Only explicitly
164          * bound sessions will have non-NULL conn.
165          */
166         rc = SLAP_PTRCMP( lc1->lc_conn, lc2->lc_conn );
167         if ( rc == 0 ) {
168                 rc = ber_bvcmp( &lc1->lc_local_ndn, &lc2->lc_local_ndn );
169         }
170
171         return rc;
172 }
173
174 /*
175  * ldap_back_conn_cmp
176  *
177  * compares two ldapconn_t based on the value of the conn pointer;
178  * used by avl stuff for delete of all conns with the same connid
179  */
180 int
181 ldap_back_conn_cmp( const void *c1, const void *c2 )
182 {
183         const ldapconn_t        *lc1 = (const ldapconn_t *)c1;
184         const ldapconn_t        *lc2 = (const ldapconn_t *)c2;
185
186         /* For shared sessions, conn is NULL. Only explicitly
187          * bound sessions will have non-NULL conn.
188          */
189         return SLAP_PTRCMP( lc1->lc_conn, lc2->lc_conn );
190 }
191
192 /*
193  * ldap_back_conndn_dup
194  *
195  * returns -1 in case a duplicate ldapconn_t has been inserted;
196  * used by avl stuff
197  */
198 int
199 ldap_back_conndn_dup( void *c1, void *c2 )
200 {
201         ldapconn_t      *lc1 = (ldapconn_t *)c1;
202         ldapconn_t      *lc2 = (ldapconn_t *)c2;
203
204         /* Cannot have more than one shared session with same DN */
205         if ( lc1->lc_conn == lc2->lc_conn &&
206                 dn_match( &lc1->lc_local_ndn, &lc2->lc_local_ndn ) )
207         {
208                 return -1;
209         }
210                 
211         return 0;
212 }
213
214 #if PRINT_CONNTREE > 0
215 static void
216 ravl_print( Avlnode *root, int depth )
217 {
218         int             i;
219         ldapconn_t      *lc;
220         
221         if ( root == 0 ) {
222                 return;
223         }
224         
225         ravl_print( root->avl_right, depth+1 );
226         
227         for ( i = 0; i < depth; i++ ) {
228                 fprintf( stderr, "-" );
229         }
230
231         lc = root->avl_data;
232         fprintf( stderr, "lc=%p local=\"%s\" conn=%p %s refcnt=%d\n",
233                 (void *)lc, lc->lc_local_ndn.bv_val, (void *)lc->lc_conn,
234                 avl_bf2str( root->avl_bf ), lc->lc_refcnt );
235         
236         ravl_print( root->avl_left, depth+1 );
237 }
238
239 static void
240 myprint( Avlnode *root )
241 {
242         fprintf( stderr, "========>\n" );
243         
244         if ( root == 0 ) {
245                 fprintf( stderr, "\tNULL\n" );
246
247         } else {
248                 ravl_print( root, 0 );
249         }
250         
251         fprintf( stderr, "<========\n" );
252 }
253 #endif /* PRINT_CONNTREE */
254
255 int
256 ldap_back_freeconn( Operation *op, ldapconn_t *lc, int dolock )
257 {
258         ldapinfo_t      *li = (ldapinfo_t *) op->o_bd->be_private;
259
260         if ( dolock ) {
261                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
262         }
263
264         assert( lc->lc_refcnt > 0 );
265         if ( --lc->lc_refcnt == 0 ) {
266                 lc = avl_delete( &li->li_conninfo.lai_tree, (caddr_t)lc,
267                                 ldap_back_conndn_cmp );
268                 assert( lc != NULL );
269
270                 ldap_back_conn_free( (void *)lc );
271         }
272
273         if ( dolock ) {
274                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
275         }
276
277         return 0;
278 }
279
280 #ifdef HAVE_TLS
281 static int
282 ldap_back_start_tls(
283         LDAP            *ld,
284         int             protocol,
285         int             *is_tls,
286         const char      *url,
287         unsigned        flags,
288         int             retries,
289         const char      **text )
290 {
291         int             rc = LDAP_SUCCESS;
292         ldapinfo_t      dummy;
293
294         /* this is ridiculous... */
295         dummy.li_flags = flags;
296
297         /* start TLS ("tls-[try-]{start,propagate}" statements) */
298         if ( ( LDAP_BACK_USE_TLS( &dummy ) || ( *is_tls && LDAP_BACK_PROPAGATE_TLS( &dummy ) ) )
299                                 && !ldap_is_ldaps_url( url ) )
300         {
301 #ifdef SLAP_STARTTLS_ASYNCHRONOUS
302                 /*
303                  * use asynchronous StartTLS
304                  * in case, chase referral (not implemented yet)
305                  */
306                 int             msgid;
307
308                 if ( protocol == 0 ) {
309                         ldap_get_option( ld, LDAP_OPT_PROTOCOL_VERSION,
310                                         (void *)&protocol );
311                 }
312
313                 if ( protocol < LDAP_VERSION3 ) {
314                         protocol = LDAP_VERSION3;
315                         /* Set LDAP version */
316                         ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION,
317                                         (const void *)&protocol );
318                 }
319
320                 rc = ldap_start_tls( ld, NULL, NULL, &msgid );
321                 if ( rc == LDAP_SUCCESS ) {
322                         LDAPMessage     *res = NULL;
323                         struct timeval  tv;
324
325                         LDAP_BACK_TV_SET( &tv );
326
327 retry:;
328                         rc = ldap_result( ld, msgid, LDAP_MSG_ALL, &tv, &res );
329                         if ( rc < 0 ) {
330                                 rc = LDAP_UNAVAILABLE;
331
332                         } else if ( rc == 0 ) {
333                                 if ( retries != LDAP_BACK_RETRY_NEVER ) {
334                                         ldap_pvt_thread_yield();
335                                         if ( retries > 0 ) {
336                                                 retries--;
337                                         }
338                                         LDAP_BACK_TV_SET( &tv );
339                                         goto retry;
340                                 }
341                                 rc = LDAP_UNAVAILABLE;
342
343                         } else if ( rc == LDAP_RES_EXTENDED ) {
344                                 struct berval   *data = NULL;
345
346                                 rc = ldap_parse_extended_result( ld, res,
347                                                 NULL, &data, 0 );
348                                 if ( rc == LDAP_SUCCESS ) {
349                                         int err;
350                                         rc = ldap_parse_result( ld, res, &err,
351                                                 NULL, NULL, NULL, NULL, 1 );
352                                         if ( rc == LDAP_SUCCESS ) {
353                                                 rc = err;
354                                         }
355                                         res = NULL;
356                                         
357                                         /* FIXME: in case a referral 
358                                          * is returned, should we try
359                                          * using it instead of the 
360                                          * configured URI? */
361                                         if ( rc == LDAP_SUCCESS ) {
362                                                 rc = ldap_install_tls( ld );
363
364                                         } else if ( rc == LDAP_REFERRAL ) {
365                                                 rc = LDAP_UNWILLING_TO_PERFORM;
366                                                 *text = "unwilling to chase referral returned by Start TLS exop";
367                                         }
368
369                                         if ( data ) {
370                                                 if ( data->bv_val ) {
371                                                         ber_memfree( data->bv_val );
372                                                 }
373                                                 ber_memfree( data );
374                                         }
375                                 }
376
377                         } else {
378                                 rc = LDAP_OTHER;
379                         }
380
381                         if ( res != NULL ) {
382                                 ldap_msgfree( res );
383                         }
384                 }
385 #else /* ! SLAP_STARTTLS_ASYNCHRONOUS */
386                 /*
387                  * use synchronous StartTLS
388                  */
389                 rc = ldap_start_tls_s( ld, NULL, NULL );
390 #endif /* ! SLAP_STARTTLS_ASYNCHRONOUS */
391
392                 /* if StartTLS is requested, only attempt it if the URL
393                  * is not "ldaps://"; this may occur not only in case
394                  * of misconfiguration, but also when used in the chain 
395                  * overlay, where the "uri" can be parsed out of a referral */
396                 switch ( rc ) {
397                 case LDAP_SUCCESS:
398                         *is_tls = 1;
399                         break;
400
401                 case LDAP_SERVER_DOWN:
402                         break;
403
404                 default:
405                         if ( LDAP_BACK_TLS_CRITICAL( &dummy ) ) {
406                                 *text = "could not start TLS";
407                                 break;
408                         }
409
410                         /* in case Start TLS is not critical */
411                         *is_tls = 0;
412                         rc = LDAP_SUCCESS;
413                         break;
414                 }
415
416         } else {
417                 *is_tls = 0;
418         }
419
420         return rc;
421 }
422 #endif /* HAVE_TLS */
423
424 static int
425 ldap_back_prepare_conn( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
426 {
427         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
428         int             vers = op->o_protocol;
429         LDAP            *ld = NULL;
430 #ifdef HAVE_TLS
431         int             is_tls = op->o_conn->c_is_tls;
432 #endif /* HAVE_TLS */
433
434         assert( lcp != NULL );
435
436         rs->sr_err = ldap_initialize( &ld, li->li_uri );
437         if ( rs->sr_err != LDAP_SUCCESS ) {
438                 goto error_return;
439         }
440
441         /* Set LDAP version. This will always succeed: If the client
442          * bound with a particular version, then so can we.
443          */
444         if ( vers == 0 ) {
445                 /* assume it's an internal op; set to LDAPv3 */
446                 vers = LDAP_VERSION3;
447         }
448         ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, (const void *)&vers );
449
450         /* automatically chase referrals ("chase-referrals [{yes|no}]" statement) */
451         ldap_set_option( ld, LDAP_OPT_REFERRALS,
452                 LDAP_BACK_CHASE_REFERRALS( li ) ? LDAP_OPT_ON : LDAP_OPT_OFF );
453
454 #ifdef HAVE_TLS
455         rs->sr_err = ldap_back_start_tls( ld, op->o_protocol, &is_tls,
456                         li->li_uri, li->li_flags, li->li_nretries, &rs->sr_text );
457         if ( rs->sr_err != LDAP_SUCCESS ) {
458                 ldap_unbind_ext( ld, NULL, NULL );
459                 goto error_return;
460         }
461 #endif /* HAVE_TLS */
462
463         if ( *lcp == NULL ) {
464                 *lcp = (ldapconn_t *)ch_calloc( 1, sizeof( ldapconn_t ) );
465                 (*lcp)->lc_flags= li->li_flags;
466         }
467         (*lcp)->lc_ld = ld;
468         (*lcp)->lc_refcnt = 1;
469         (*lcp)->lc_binding = 1;
470 #ifdef HAVE_TLS
471         if ( is_tls ) {
472                 LDAP_BACK_CONN_ISTLS_SET( *lcp );
473         } else {
474                 LDAP_BACK_CONN_ISTLS_CLEAR( *lcp );
475         }
476 #endif /* HAVE_TLS */
477
478 error_return:;
479         if ( rs->sr_err != LDAP_SUCCESS ) {
480                 rs->sr_err = slap_map_api2result( rs );
481                 if ( sendok & LDAP_BACK_SENDERR ) {
482                         if ( rs->sr_text == NULL ) {
483                                 rs->sr_text = "ldap_initialize() failed";
484                         }
485                         send_ldap_result( op, rs );
486                         rs->sr_text = NULL;
487                 }
488
489         } else {
490                 if ( li->li_conn_ttl > 0 ) {
491                         (*lcp)->lc_create_time = op->o_time;
492                 }
493         }
494
495         return rs->sr_err;
496 }
497
498 ldapconn_t *
499 ldap_back_getconn( Operation *op, SlapReply *rs, ldap_back_send_t sendok )
500 {
501         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
502         ldapconn_t      *lc = NULL,
503                         lc_curr = { 0 };
504         int             refcnt = 1, binding = 1;
505
506         /* Internal searches are privileged and shared. So is root. */
507         if ( op->o_do_not_cache || be_isroot( op ) ) {
508                 LDAP_BACK_CONN_ISPRIV_SET( &lc_curr );
509                 lc_curr.lc_local_ndn = op->o_bd->be_rootndn;
510                 lc_curr.lc_conn = LDAP_BACK_PCONN_SET( op );
511
512         } else {
513                 lc_curr.lc_local_ndn = op->o_ndn;
514                 /* Explicit binds must not be shared */
515                 if ( op->o_tag == LDAP_REQ_BIND || SLAP_IS_AUTHZ_BACKEND( op ) ) {
516                         lc_curr.lc_conn = op->o_conn;
517         
518                 } else {
519                         lc_curr.lc_conn = LDAP_BACK_PCONN_SET( op );
520                 }
521         }
522
523         /* Explicit Bind requests always get their own conn */
524         if ( !( sendok & LDAP_BACK_BINDING ) ) {
525                 /* Searches for a ldapconn in the avl tree */
526 retry_lock:
527                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
528
529                 lc = (ldapconn_t *)avl_find( li->li_conninfo.lai_tree, 
530                                 (caddr_t)&lc_curr, ldap_back_conndn_cmp );
531                 if ( lc != NULL ) {
532                         /* Don't reuse connections while they're still binding */
533                         if ( LDAP_BACK_CONN_BINDING( lc ) ) {
534                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
535                                 ldap_pvt_thread_yield();
536                                 goto retry_lock;
537                         }
538                         refcnt = ++lc->lc_refcnt;
539                         binding = ++lc->lc_binding;
540                 }
541                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
542         }
543
544         /* Looks like we didn't get a bind. Open a new session... */
545         if ( lc == NULL ) {
546                 if ( ldap_back_prepare_conn( &lc, op, rs, sendok ) != LDAP_SUCCESS ) {
547                         return NULL;
548                 }
549                 if ( sendok & LDAP_BACK_BINDING ) {
550                         LDAP_BACK_CONN_BINDING_SET( lc );
551                 }
552                 lc->lc_conn = lc_curr.lc_conn;
553                 ber_dupbv( &lc->lc_local_ndn, &lc_curr.lc_local_ndn );
554
555                 if ( LDAP_BACK_CONN_ISPRIV( &lc_curr ) ) {
556                         ber_dupbv( &lc->lc_cred, &li->li_acl_passwd );
557                         ber_dupbv( &lc->lc_bound_ndn, &li->li_acl_authcDN );
558                         LDAP_BACK_CONN_ISPRIV_SET( lc );
559
560                 } else {
561                         BER_BVZERO( &lc->lc_cred );
562                         BER_BVZERO( &lc->lc_bound_ndn );
563 #if 0
564                         /* FIXME: if we set lc_bound_ndn = o_ndn
565                          * we end up with a bind with DN but no password! */
566                         if ( !BER_BVISEMPTY( &op->o_ndn )
567                                 && SLAP_IS_AUTHZ_BACKEND( op ) )
568                         {
569                                 ber_dupbv( &lc->lc_bound_ndn, &op->o_ndn );
570                         }
571 #endif
572                 }
573
574 #ifdef HAVE_TLS
575                 /* if start TLS failed but it was not mandatory,
576                  * check if the non-TLS connection was already
577                  * in cache; in case, destroy the newly created
578                  * connection and use the existing one */
579                 if ( lc->lc_conn == LDAP_BACK_PCONN_TLS
580                                 && !ldap_tls_inplace( lc->lc_ld ) )
581                 {
582                         ldapconn_t *tmplc;
583                         
584                         lc_curr.lc_conn = LDAP_BACK_PCONN;
585                         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
586                         tmplc = (ldapconn_t *)avl_find( li->li_conninfo.lai_tree, 
587                                         (caddr_t)&lc_curr, ldap_back_conndn_cmp );
588                         if ( tmplc != NULL ) {
589                                 refcnt = ++tmplc->lc_refcnt;
590                                 binding = ++tmplc->lc_binding;
591                                 ldap_back_conn_free( lc );
592                                 lc = tmplc;
593                         }
594                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
595
596                         if ( tmplc != NULL ) {
597                                 goto done;
598                         }
599                 }
600 #endif /* HAVE_TLS */
601
602                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
603
604                 /* Inserts the newly created ldapconn in the avl tree */
605                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
606
607                 assert( lc->lc_refcnt == 1 );
608                 assert( lc->lc_binding == 1 );
609                 rs->sr_err = avl_insert( &li->li_conninfo.lai_tree, (caddr_t)lc,
610                         ldap_back_conndn_cmp, ldap_back_conndn_dup );
611
612 #if PRINT_CONNTREE > 0
613                 myprint( li->li_conninfo.lai_tree );
614 #endif /* PRINT_CONNTREE */
615         
616                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
617
618                 Debug( LDAP_DEBUG_TRACE,
619                         "=>ldap_back_getconn: conn %p inserted refcnt=%u binding=%u\n",
620                         (void *)lc, refcnt, binding );
621         
622                 /* Err could be -1 in case a duplicate ldapconn is inserted */
623                 if ( rs->sr_err != 0 ) {
624                         ldap_back_conn_free( lc );
625                         rs->sr_err = LDAP_OTHER;
626                         if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
627                                 send_ldap_error( op, rs, LDAP_OTHER,
628                                         "internal server error" );
629                         }
630                         return NULL;
631                 }
632
633         } else {
634                 if ( ( li->li_idle_timeout != 0 && op->o_time > lc->lc_time + li->li_idle_timeout )
635                         || ( li->li_conn_ttl != 0 && op->o_time > lc->lc_create_time + li->li_conn_ttl ) )
636                 {
637                         /* in case of failure, it frees/taints lc and sets it to NULL */
638                         if ( !ldap_back_retry( &lc, op, rs, sendok ) ) {
639                                 lc = NULL;
640                         }
641                 }
642
643                 if ( lc ) {
644                         Debug( LDAP_DEBUG_TRACE,
645                                 "=>ldap_back_getconn: conn %p fetched refcnt=%u binding=%u\n",
646                                 (void *)lc, refcnt, binding );
647                 }
648         }
649
650         if ( li->li_idle_timeout && lc ) {
651                 lc->lc_time = op->o_time;
652         }
653
654 done:;
655         return lc;
656 }
657
658 void
659 ldap_back_release_conn_lock(
660         Operation               *op,
661         SlapReply               *rs,
662         ldapconn_t              *lc,
663         int                     dolock )
664 {
665         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
666
667         if ( dolock ) {
668                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
669         }
670         assert( lc->lc_refcnt > 0 );
671         lc->lc_refcnt--;
672         LDAP_BACK_CONN_BINDING_CLEAR( lc );
673         if ( dolock ) {
674                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
675         }
676 }
677
678 /*
679  * ldap_back_dobind
680  *
681  * Note: as the check for the value of lc->lc_bound was already here, I removed
682  * it from all the callers, and I made the function return the flag, so
683  * it can be used to simplify the check.
684  *
685  * Note: dolock indicates whether li->li_conninfo.lai_mutex must be locked or not
686  */
687 static int
688 ldap_back_dobind_int(
689         ldapconn_t              *lc,
690         Operation               *op,
691         SlapReply               *rs,
692         ldap_back_send_t        sendok,
693         int                     retries,
694         int                     dolock )
695 {       
696         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
697
698         int             rc, binding = 0;
699         ber_int_t       msgid;
700
701         assert( retries >= 0 );
702
703 retry_lock:;
704         if ( dolock ) {
705                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
706         }
707
708         if ( binding == 0 ) {
709                 /* check if already bound */
710                 rc = LDAP_BACK_CONN_ISBOUND( lc );
711                 if ( rc ) {
712                         lc->lc_binding--;
713                         if ( dolock ) {
714                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
715                         }
716                         return rc;
717                 }
718
719                 if ( LDAP_BACK_CONN_BINDING( lc ) ) {
720                         /* if someone else is about to bind it, give up and retry */
721                         if ( dolock ) {
722                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
723                         }
724                         ldap_pvt_thread_yield();
725                         goto retry_lock;
726
727                 } else {
728                         /* otherwise this thread will bind it */
729                         LDAP_BACK_CONN_BINDING_SET( lc );
730                         binding = 1;
731                 }
732         }
733
734         /* wait for pending operations to finish */
735         /* FIXME: may become a bottleneck! */
736         if ( lc->lc_refcnt != lc->lc_binding ) {
737                 if ( dolock ) {
738                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
739                 }
740                 ldap_pvt_thread_yield();
741                 goto retry_lock;
742         }
743
744         if ( dolock ) {
745                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
746         }
747
748 #if 0
749         while ( lc->lc_refcnt > 1 ) {
750                 ldap_pvt_thread_yield();
751                 rc = LDAP_BACK_CONN_ISBOUND( lc );
752                 if ( rc ) {
753                         return rc;
754                 }
755         }
756
757         if ( dolock ) {
758                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
759         }
760         LDAP_BACK_CONN_BINDING_SET( lc );
761         if ( dolock ) {
762                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
763         }
764 #endif
765
766         /*
767          * FIXME: we need to let clients use proxyAuthz
768          * otherwise we cannot do symmetric pools of servers;
769          * we have to live with the fact that a user can
770          * authorize itself as any ID that is allowed
771          * by the authzTo directive of the "proxyauthzdn".
772          */
773         /*
774          * NOTE: current Proxy Authorization specification
775          * and implementation do not allow proxy authorization
776          * control to be provided with Bind requests
777          */
778         /*
779          * if no bind took place yet, but the connection is bound
780          * and the "idassert-authcDN" (or other ID) is set, 
781          * then bind as the asserting identity and explicitly 
782          * add the proxyAuthz control to every operation with the
783          * dn bound to the connection as control value.
784          * This is done also if this is the authrizing backend,
785          * but the "override" flag is given to idassert.
786          * It allows to use SASL bind and yet proxyAuthz users
787          */
788         if ( op->o_conn != NULL &&
789                         !op->o_do_not_cache &&
790                         ( BER_BVISNULL( &lc->lc_bound_ndn ) ||
791                           ( li->li_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) ) )
792         {
793                 (void)ldap_back_proxy_authz_bind( lc, op, rs, sendok );
794                 goto done;
795         }
796
797 #ifdef HAVE_CYRUS_SASL
798         if ( LDAP_BACK_CONN_ISPRIV( lc )
799                 && li->li_acl_authmethod == LDAP_AUTH_SASL )
800         {
801                 void            *defaults = NULL;
802
803                 if ( li->li_acl_secprops != NULL ) {
804                         rc = ldap_set_option( lc->lc_ld,
805                                 LDAP_OPT_X_SASL_SECPROPS, li->li_acl_secprops);
806
807                         if ( rc != LDAP_OPT_SUCCESS ) {
808                                 Debug( LDAP_DEBUG_ANY, "Error: ldap_set_option "
809                                         "(%s,SECPROPS,\"%s\") failed!\n",
810                                         li->li_uri, li->li_acl_secprops, 0 );
811                                 goto done;
812                         }
813                 }
814
815                 defaults = lutil_sasl_defaults( lc->lc_ld,
816                                 li->li_acl_sasl_mech.bv_val,
817                                 li->li_acl_sasl_realm.bv_val,
818                                 li->li_acl_authcID.bv_val,
819                                 li->li_acl_passwd.bv_val,
820                                 NULL );
821
822                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld,
823                                 li->li_acl_authcDN.bv_val,
824                                 li->li_acl_sasl_mech.bv_val, NULL, NULL,
825                                 LDAP_SASL_QUIET, lutil_sasl_interact,
826                                 defaults );
827
828                 lutil_sasl_freedefs( defaults );
829
830                 rs->sr_err = slap_map_api2result( rs );
831                 if ( rs->sr_err != LDAP_SUCCESS ) {
832                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
833                         send_ldap_result( op, rs );
834
835                 } else {
836                         LDAP_BACK_CONN_ISBOUND_SET( lc );
837                 }
838                 goto done;
839         }
840 #endif /* HAVE_CYRUS_SASL */
841
842 retry:;
843         rs->sr_err = ldap_sasl_bind( lc->lc_ld,
844                         lc->lc_bound_ndn.bv_val,
845                         LDAP_SASL_SIMPLE, &lc->lc_cred,
846                         NULL, NULL, &msgid );
847
848         if ( rs->sr_err == LDAP_SERVER_DOWN ) {
849                 if ( retries != LDAP_BACK_RETRY_NEVER ) {
850                         if ( dolock ) {
851                                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
852                         }
853
854                         assert( lc->lc_refcnt > 0 );
855                         if ( lc->lc_refcnt == 1 ) {
856                                 ldap_unbind_ext( lc->lc_ld, NULL, NULL );
857                                 lc->lc_ld = NULL;
858
859                                 /* lc here must be the regular lc, reset and ready for init */
860                                 rs->sr_err = ldap_back_prepare_conn( &lc, op, rs, sendok );
861                         }
862                         if ( dolock ) {
863                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
864                         }
865                         if ( rs->sr_err == LDAP_SUCCESS ) {
866                                 if ( retries > 0 ) {
867                                         retries--;
868                                 }
869                                 goto retry;
870                         }
871                 }
872
873                 lc->lc_binding--;
874                 ldap_back_freeconn( op, lc, dolock );
875                 rs->sr_err = slap_map_api2result( rs );
876
877                 return 0;
878         }
879
880         rc = ldap_back_op_result( lc, op, rs, msgid, 0, sendok );
881         if ( rc == LDAP_SUCCESS ) {
882                 LDAP_BACK_CONN_ISBOUND_SET( lc );
883         }
884
885 done:;
886         lc->lc_binding--;
887         LDAP_BACK_CONN_BINDING_CLEAR( lc );
888         rc = LDAP_BACK_CONN_ISBOUND( lc );
889         if ( !rc ) {
890                 ldap_back_release_conn_lock( op, rs, lc, dolock );
891         }
892
893         return rc;
894 }
895
896 int
897 ldap_back_dobind( ldapconn_t *lc, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
898 {
899         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
900
901         return ldap_back_dobind_int( lc, op, rs, sendok, li->li_nretries, 1 );
902 }
903
904 /*
905  * ldap_back_default_rebind
906  *
907  * This is a callback used for chasing referrals using the same
908  * credentials as the original user on this session.
909  */
910 static int 
911 ldap_back_default_rebind( LDAP *ld, LDAP_CONST char *url, ber_tag_t request,
912         ber_int_t msgid, void *params )
913 {
914         ldapconn_t      *lc = (ldapconn_t *)params;
915
916 #ifdef HAVE_TLS
917         /* ... otherwise we couldn't get here */
918         assert( lc != NULL );
919
920         if ( !ldap_tls_inplace( ld ) ) {
921                 int             is_tls = LDAP_BACK_CONN_ISTLS( lc ),
922                                 rc;
923                 const char      *text = NULL;
924
925                 rc = ldap_back_start_tls( ld, 0, &is_tls, url, lc->lc_flags,
926                         LDAP_BACK_RETRY_DEFAULT, &text );
927                 if ( rc != LDAP_SUCCESS ) {
928                         return rc;
929                 }
930         }
931 #endif /* HAVE_TLS */
932
933         /* FIXME: add checks on the URL/identity? */
934
935         return ldap_sasl_bind_s( ld, lc->lc_bound_ndn.bv_val,
936                         LDAP_SASL_SIMPLE, &lc->lc_cred, NULL, NULL, NULL );
937 }
938
939 int
940 ldap_back_op_result(
941                 ldapconn_t              *lc,
942                 Operation               *op,
943                 SlapReply               *rs,
944                 ber_int_t               msgid,
945                 time_t                  timeout,
946                 ldap_back_send_t        sendok )
947 {
948         char            *match = NULL;
949         LDAPMessage     *res = NULL;
950         char            *text = NULL;
951
952 #define ERR_OK(err) ((err) == LDAP_SUCCESS || (err) == LDAP_COMPARE_FALSE || (err) == LDAP_COMPARE_TRUE)
953
954         rs->sr_text = NULL;
955         rs->sr_matched = NULL;
956
957         /* if the error recorded in the reply corresponds
958          * to a successful state, get the error from the
959          * remote server response */
960         if ( ERR_OK( rs->sr_err ) ) {
961                 int             rc;
962                 struct timeval  tv;
963
964                 if ( timeout ) {
965                         tv.tv_sec = timeout;
966                         tv.tv_usec = 0;
967
968                 } else {
969                         LDAP_BACK_TV_SET( &tv );
970                 }
971
972 retry:;
973                 /* if result parsing fails, note the failure reason */
974                 rc = ldap_result( lc->lc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
975                 switch ( rc ) {
976                 case 0:
977                         if ( timeout ) {
978                                 (void)ldap_abandon_ext( lc->lc_ld, msgid, NULL, NULL );
979                                 rs->sr_err = op->o_protocol >= LDAP_VERSION3 ?
980                                         LDAP_ADMINLIMIT_EXCEEDED : LDAP_OPERATIONS_ERROR;
981                                 rs->sr_text = "Operation timed out";
982                                 break;
983                         }
984
985                         LDAP_BACK_TV_SET( &tv );
986                         ldap_pvt_thread_yield();
987                         goto retry;
988
989                 case -1:
990                         ldap_get_option( lc->lc_ld, LDAP_OPT_ERROR_NUMBER,
991                                         &rs->sr_err );
992                         break;
993
994
995                 /* otherwise get the result; if it is not
996                  * LDAP_SUCCESS, record it in the reply
997                  * structure (this includes 
998                  * LDAP_COMPARE_{TRUE|FALSE}) */
999                 default:
1000                         rc = ldap_parse_result( lc->lc_ld, res, &rs->sr_err,
1001                                         &match, &text, NULL, NULL, 1 );
1002                         rs->sr_text = text;
1003                         if ( rc != LDAP_SUCCESS ) {
1004                                 rs->sr_err = rc;
1005                         }
1006                 }
1007         }
1008
1009         /* if the error in the reply structure is not
1010          * LDAP_SUCCESS, try to map it from client 
1011          * to server error */
1012         if ( !ERR_OK( rs->sr_err ) ) {
1013                 rs->sr_err = slap_map_api2result( rs );
1014
1015                 /* internal ops ( op->o_conn == NULL ) 
1016                  * must not reply to client */
1017                 if ( op->o_conn && !op->o_do_not_cache && match ) {
1018
1019                         /* record the (massaged) matched
1020                          * DN into the reply structure */
1021                         rs->sr_matched = match;
1022                 }
1023         }
1024         if ( op->o_conn &&
1025                         ( ( sendok & LDAP_BACK_SENDOK ) 
1026                           || ( ( sendok & LDAP_BACK_SENDERR ) && rs->sr_err != LDAP_SUCCESS ) ) )
1027         {
1028                 send_ldap_result( op, rs );
1029         }
1030         if ( match ) {
1031                 if ( rs->sr_matched != match ) {
1032                         free( (char *)rs->sr_matched );
1033                 }
1034                 rs->sr_matched = NULL;
1035                 ldap_memfree( match );
1036         }
1037         if ( text ) {
1038                 ldap_memfree( text );
1039         }
1040         rs->sr_text = NULL;
1041         return( ERR_OK( rs->sr_err ) ? LDAP_SUCCESS : rs->sr_err );
1042 }
1043
1044 /* return true if bound, false if failed */
1045 int
1046 ldap_back_retry( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1047 {
1048         int             rc = 0;
1049         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1050
1051         assert( lcp != NULL );
1052         assert( *lcp != NULL );
1053
1054         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1055
1056         if ( (*lcp)->lc_refcnt == 1 ) {
1057                 Debug( LDAP_DEBUG_ANY,
1058                         "%s ldap_back_retry: retrying URI=\"%s\" DN=\"%s\"\n",
1059                         op->o_log_prefix, li->li_uri,
1060                         BER_BVISNULL( &(*lcp)->lc_bound_ndn ) ?
1061                                 "" : (*lcp)->lc_bound_ndn.bv_val );
1062
1063                 ldap_unbind_ext( (*lcp)->lc_ld, NULL, NULL );
1064                 (*lcp)->lc_ld = NULL;
1065                 LDAP_BACK_CONN_ISBOUND_CLEAR( (*lcp) );
1066
1067                 /* lc here must be the regular lc, reset and ready for init */
1068                 rc = ldap_back_prepare_conn( lcp, op, rs, sendok );
1069                 if ( rc != LDAP_SUCCESS ) {
1070                         rc = 0;
1071                         *lcp = NULL;
1072
1073                 } else {
1074                         rc = ldap_back_dobind_int( *lcp, op, rs, sendok, 0, 0 );
1075                         if ( rc == 0 ) {
1076                                 *lcp = NULL;
1077                         }
1078                 }
1079         }
1080
1081         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1082
1083         return rc;
1084 }
1085
1086 static int
1087 ldap_back_proxy_authz_bind( ldapconn_t *lc, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1088 {
1089         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1090         struct berval   binddn = slap_empty_bv;
1091         struct berval   bindcred = slap_empty_bv;
1092         struct berval   ndn;
1093         int             dobind = 0;
1094         int             msgid;
1095         int             rc;
1096
1097         if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1098                 ndn = op->o_conn->c_ndn;
1099
1100         } else {
1101                 ndn = op->o_ndn;
1102         }
1103
1104         /*
1105          * FIXME: we need to let clients use proxyAuthz
1106          * otherwise we cannot do symmetric pools of servers;
1107          * we have to live with the fact that a user can
1108          * authorize itself as any ID that is allowed
1109          * by the authzTo directive of the "proxyauthzdn".
1110          */
1111         /*
1112          * NOTE: current Proxy Authorization specification
1113          * and implementation do not allow proxy authorization
1114          * control to be provided with Bind requests
1115          */
1116         /*
1117          * if no bind took place yet, but the connection is bound
1118          * and the "proxyauthzdn" is set, then bind as 
1119          * "proxyauthzdn" and explicitly add the proxyAuthz 
1120          * control to every operation with the dn bound 
1121          * to the connection as control value.
1122          */
1123
1124         /* bind as proxyauthzdn only if no idassert mode
1125          * is requested, or if the client's identity
1126          * is authorized */
1127         switch ( li->li_idassert_mode ) {
1128         case LDAP_BACK_IDASSERT_LEGACY:
1129                 if ( !BER_BVISNULL( &ndn ) && !BER_BVISEMPTY( &ndn ) ) {
1130                         if ( !BER_BVISNULL( &li->li_idassert_authcDN ) && !BER_BVISEMPTY( &li->li_idassert_authcDN ) )
1131                         {
1132                                 binddn = li->li_idassert_authcDN;
1133                                 bindcred = li->li_idassert_passwd;
1134                                 dobind = 1;
1135                         }
1136                 }
1137                 break;
1138
1139         default:
1140                 /* NOTE: rootdn can always idassert */
1141                 if ( BER_BVISNULL( &ndn ) && li->li_idassert_authz == NULL ) {
1142                         if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1143                                 rs->sr_err = LDAP_INAPPROPRIATE_AUTH;
1144                                 if ( sendok & LDAP_BACK_SENDERR ) {
1145                                         send_ldap_result( op, rs );
1146                                 }
1147                                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1148
1149                         } else {
1150                                 rs->sr_err = LDAP_SUCCESS;
1151                                 binddn = slap_empty_bv;
1152                                 bindcred = slap_empty_bv;
1153                                 break;
1154                         }
1155
1156                         goto done;
1157
1158                 } else if ( li->li_idassert_authz && !be_isroot( op ) ) {
1159                         struct berval authcDN;
1160
1161                         if ( BER_BVISNULL( &ndn ) ) {
1162                                 authcDN = slap_empty_bv;
1163
1164                         } else {
1165                                 authcDN = ndn;
1166                         }       
1167                         rs->sr_err = slap_sasl_matches( op, li->li_idassert_authz,
1168                                         &authcDN, &authcDN );
1169                         if ( rs->sr_err != LDAP_SUCCESS ) {
1170                                 if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1171                                         if ( sendok & LDAP_BACK_SENDERR ) {
1172                                                 send_ldap_result( op, rs );
1173                                         }
1174                                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1175
1176                                 } else {
1177                                         rs->sr_err = LDAP_SUCCESS;
1178                                         binddn = slap_empty_bv;
1179                                         bindcred = slap_empty_bv;
1180                                         break;
1181                                 }
1182
1183                                 goto done;
1184                         }
1185                 }
1186
1187                 binddn = li->li_idassert_authcDN;
1188                 bindcred = li->li_idassert_passwd;
1189                 dobind = 1;
1190                 break;
1191         }
1192
1193         if ( dobind && li->li_idassert_authmethod == LDAP_AUTH_SASL ) {
1194 #ifdef HAVE_CYRUS_SASL
1195                 void            *defaults = NULL;
1196                 struct berval   authzID = BER_BVNULL;
1197                 int             freeauthz = 0;
1198
1199                 /* if SASL supports native authz, prepare for it */
1200                 if ( ( !op->o_do_not_cache || !op->o_is_auth_check ) &&
1201                                 ( li->li_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
1202                 {
1203                         switch ( li->li_idassert_mode ) {
1204                         case LDAP_BACK_IDASSERT_OTHERID:
1205                         case LDAP_BACK_IDASSERT_OTHERDN:
1206                                 authzID = li->li_idassert_authzID;
1207                                 break;
1208
1209                         case LDAP_BACK_IDASSERT_ANONYMOUS:
1210                                 BER_BVSTR( &authzID, "dn:" );
1211                                 break;
1212
1213                         case LDAP_BACK_IDASSERT_SELF:
1214                                 if ( BER_BVISNULL( &ndn ) ) {
1215                                         /* connection is not authc'd, so don't idassert */
1216                                         BER_BVSTR( &authzID, "dn:" );
1217                                         break;
1218                                 }
1219                                 authzID.bv_len = STRLENOF( "dn:" ) + ndn.bv_len;
1220                                 authzID.bv_val = slap_sl_malloc( authzID.bv_len + 1, op->o_tmpmemctx );
1221                                 AC_MEMCPY( authzID.bv_val, "dn:", STRLENOF( "dn:" ) );
1222                                 AC_MEMCPY( authzID.bv_val + STRLENOF( "dn:" ),
1223                                                 ndn.bv_val, ndn.bv_len + 1 );
1224                                 freeauthz = 1;
1225                                 break;
1226
1227                         default:
1228                                 break;
1229                         }
1230                 }
1231
1232                 if ( li->li_idassert_secprops != NULL ) {
1233                         rs->sr_err = ldap_set_option( lc->lc_ld,
1234                                 LDAP_OPT_X_SASL_SECPROPS,
1235                                 (void *)li->li_idassert_secprops );
1236
1237                         if ( rs->sr_err != LDAP_OPT_SUCCESS ) {
1238                                 rs->sr_err = LDAP_OTHER;
1239                                 if ( sendok & LDAP_BACK_SENDERR ) {
1240                                         send_ldap_result( op, rs );
1241                                 }
1242                                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1243                                 goto done;
1244                         }
1245                 }
1246
1247                 defaults = lutil_sasl_defaults( lc->lc_ld,
1248                                 li->li_idassert_sasl_mech.bv_val,
1249                                 li->li_idassert_sasl_realm.bv_val,
1250                                 li->li_idassert_authcID.bv_val,
1251                                 li->li_idassert_passwd.bv_val,
1252                                 authzID.bv_val );
1253
1254                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld, binddn.bv_val,
1255                                 li->li_idassert_sasl_mech.bv_val, NULL, NULL,
1256                                 LDAP_SASL_QUIET, lutil_sasl_interact,
1257                                 defaults );
1258
1259                 rs->sr_err = slap_map_api2result( rs );
1260                 if ( rs->sr_err != LDAP_SUCCESS ) {
1261                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1262                         if ( sendok & LDAP_BACK_SENDERR ) {
1263                                 send_ldap_result( op, rs );
1264                         }
1265
1266                 } else {
1267                         LDAP_BACK_CONN_ISBOUND_SET( lc );
1268                 }
1269
1270                 lutil_sasl_freedefs( defaults );
1271                 if ( freeauthz ) {
1272                         slap_sl_free( authzID.bv_val, op->o_tmpmemctx );
1273                 }
1274
1275                 goto done;
1276 #endif /* HAVE_CYRUS_SASL */
1277         }
1278
1279         switch ( li->li_idassert_authmethod ) {
1280         case LDAP_AUTH_NONE:
1281                 LDAP_BACK_CONN_ISBOUND_SET( lc );
1282                 goto done;
1283
1284         case LDAP_AUTH_SIMPLE:
1285                 rs->sr_err = ldap_sasl_bind( lc->lc_ld,
1286                                 binddn.bv_val, LDAP_SASL_SIMPLE,
1287                                 &bindcred, NULL, NULL, &msgid );
1288                 break;
1289
1290         default:
1291                 /* unsupported! */
1292                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1293                 rs->sr_err = LDAP_AUTH_METHOD_NOT_SUPPORTED;
1294                 if ( sendok & LDAP_BACK_SENDERR ) {
1295                         send_ldap_result( op, rs );
1296                 }
1297                 goto done;
1298         }
1299
1300         rc = ldap_back_op_result( lc, op, rs, msgid, 0, sendok );
1301         if ( rc == LDAP_SUCCESS ) {
1302                 LDAP_BACK_CONN_ISBOUND_SET( lc );
1303         }
1304 done:;
1305         return LDAP_BACK_CONN_ISBOUND( lc );
1306 }
1307
1308 /*
1309  * ldap_back_proxy_authz_ctrl() prepends a proxyAuthz control
1310  * to existing server-side controls if required; if not,
1311  * the existing server-side controls are placed in *pctrls.
1312  * The caller, after using the controls in client API 
1313  * operations, if ( *pctrls != op->o_ctrls ), should
1314  * free( (*pctrls)[ 0 ] ) and free( *pctrls ).
1315  * The function returns success if the control could
1316  * be added if required, or if it did nothing; in the future,
1317  * it might return some error if it failed.
1318  * 
1319  * if no bind took place yet, but the connection is bound
1320  * and the "proxyauthzdn" is set, then bind as "proxyauthzdn" 
1321  * and explicitly add proxyAuthz the control to every operation
1322  * with the dn bound to the connection as control value.
1323  *
1324  * If no server-side controls are defined for the operation,
1325  * simply add the proxyAuthz control; otherwise, if the
1326  * proxyAuthz control is not already set, add it as
1327  * the first one
1328  *
1329  * FIXME: is controls order significant for security?
1330  * ANSWER: controls ordering and interoperability
1331  * must be indicated by the specs of each control; if none
1332  * is specified, the order is irrelevant.
1333  */
1334 int
1335 ldap_back_proxy_authz_ctrl(
1336                 ldapconn_t      *lc,
1337                 Operation       *op,
1338                 SlapReply       *rs,
1339                 LDAPControl     ***pctrls )
1340 {
1341         ldapinfo_t      *li = (ldapinfo_t *) op->o_bd->be_private;
1342         LDAPControl     **ctrls = NULL;
1343         int             i = 0,
1344                         mode;
1345         struct berval   assertedID,
1346                         ndn;
1347
1348         *pctrls = NULL;
1349
1350         rs->sr_err = LDAP_SUCCESS;
1351
1352         /* FIXME: SASL/EXTERNAL over ldapi:// doesn't honor the authcID,
1353          * but if it is not set this test fails.  We need a different
1354          * means to detect if idassert is enabled */
1355         if ( ( BER_BVISNULL( &li->li_idassert_authcID ) || BER_BVISEMPTY( &li->li_idassert_authcID ) )
1356                         && ( BER_BVISNULL( &li->li_idassert_authcDN ) || BER_BVISEMPTY( &li->li_idassert_authcDN ) ) )
1357         {
1358                 goto done;
1359         }
1360
1361         if ( !op->o_conn || op->o_do_not_cache || be_isroot( op ) ) {
1362                 goto done;
1363         }
1364
1365         if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1366                 ndn = op->o_conn->c_ndn;
1367
1368         } else {
1369                 ndn = op->o_ndn;
1370         }
1371
1372         if ( li->li_idassert_mode == LDAP_BACK_IDASSERT_LEGACY ) {
1373                 if ( op->o_proxy_authz ) {
1374                         /*
1375                          * FIXME: we do not want to perform proxyAuthz
1376                          * on behalf of the client, because this would
1377                          * be performed with "proxyauthzdn" privileges.
1378                          *
1379                          * This might actually be too strict, since
1380                          * the "proxyauthzdn" authzTo, and each entry's
1381                          * authzFrom attributes may be crafted
1382                          * to avoid unwanted proxyAuthz to take place.
1383                          */
1384 #if 0
1385                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1386                         rs->sr_text = "proxyAuthz not allowed within namingContext";
1387 #endif
1388                         goto done;
1389                 }
1390
1391                 if ( !BER_BVISNULL( &lc->lc_bound_ndn ) ) {
1392                         goto done;
1393                 }
1394
1395                 if ( BER_BVISNULL( &ndn ) ) {
1396                         goto done;
1397                 }
1398
1399                 if ( BER_BVISNULL( &li->li_idassert_authcDN ) ) {
1400                         goto done;
1401                 }
1402
1403         } else if ( li->li_idassert_authmethod == LDAP_AUTH_SASL ) {
1404                 if ( ( li->li_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ )
1405                                 /* && ( !BER_BVISNULL( &ndn )
1406                                         || LDAP_BACK_CONN_ISBOUND( lc ) ) */ )
1407                 {
1408                         /* already asserted in SASL via native authz */
1409                         /* NOTE: the test on lc->lc_bound is used to trap
1410                          * native authorization of anonymous users,
1411                          * since in that case ndn is NULL */
1412                         goto done;
1413                 }
1414
1415         } else if ( li->li_idassert_authz && !be_isroot( op ) ) {
1416                 int             rc;
1417                 struct berval authcDN;
1418
1419                 if ( BER_BVISNULL( &ndn ) ) {
1420                         authcDN = slap_empty_bv;
1421                 } else {
1422                         authcDN = ndn;
1423                 }
1424                 rc = slap_sasl_matches( op, li->li_idassert_authz,
1425                                 &authcDN, & authcDN );
1426                 if ( rc != LDAP_SUCCESS ) {
1427                         if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE )
1428                         {
1429                                 /* ndn is not authorized
1430                                  * to use idassert */
1431                                 return rc;
1432                         }
1433                         return rs->sr_err;
1434                 }
1435         }
1436
1437         if ( op->o_proxy_authz ) {
1438                 /*
1439                  * FIXME: we can:
1440                  * 1) ignore the already set proxyAuthz control
1441                  * 2) leave it in place, and don't set ours
1442                  * 3) add both
1443                  * 4) reject the operation
1444                  *
1445                  * option (4) is very drastic
1446                  * option (3) will make the remote server reject
1447                  * the operation, thus being equivalent to (4)
1448                  * option (2) will likely break the idassert
1449                  * assumptions, so we cannot accept it;
1450                  * option (1) means that we are contradicting
1451                  * the client's reques.
1452                  *
1453                  * I think (4) is the only correct choice.
1454                  */
1455                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1456                 rs->sr_text = "proxyAuthz not allowed within namingContext";
1457         }
1458
1459         if ( op->o_is_auth_check ) {
1460                 mode = LDAP_BACK_IDASSERT_NOASSERT;
1461
1462         } else {
1463                 mode = li->li_idassert_mode;
1464         }
1465
1466         switch ( mode ) {
1467         case LDAP_BACK_IDASSERT_SELF:
1468                 if ( BER_BVISNULL( &ndn ) ) {
1469                         goto done;
1470                 }
1471                 assertedID = ndn;
1472                 break;
1473
1474         case LDAP_BACK_IDASSERT_LEGACY:
1475                 /* original behavior:
1476                  * assert the client's identity */
1477                 if ( BER_BVISNULL( &ndn ) ) {
1478                         assertedID = slap_empty_bv;
1479                 } else {
1480                         assertedID = ndn;
1481                 }
1482                 break;
1483
1484         case LDAP_BACK_IDASSERT_ANONYMOUS:
1485                 /* assert "anonymous" */
1486                 assertedID = slap_empty_bv;
1487                 break;
1488
1489         case LDAP_BACK_IDASSERT_NOASSERT:
1490                 /* don't assert; bind as proxyauthzdn */
1491                 goto done;
1492
1493         case LDAP_BACK_IDASSERT_OTHERID:
1494         case LDAP_BACK_IDASSERT_OTHERDN:
1495                 /* assert idassert DN */
1496                 assertedID = li->li_idassert_authzID;
1497                 break;
1498
1499         default:
1500                 assert( 0 );
1501         }
1502
1503         if ( BER_BVISNULL( &assertedID ) ) {
1504                 assertedID = slap_empty_bv;
1505         }
1506
1507         if ( op->o_ctrls ) {
1508                 for ( i = 0; op->o_ctrls[ i ]; i++ )
1509                         /* just count ctrls */ ;
1510         }
1511
1512         ctrls = op->o_tmpalloc( sizeof( LDAPControl * ) * (i + 2) + sizeof( LDAPControl ),
1513                         op->o_tmpmemctx );
1514         ctrls[ 0 ] = (LDAPControl *)&ctrls[ i + 2 ];
1515         
1516         ctrls[ 0 ]->ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1517         ctrls[ 0 ]->ldctl_iscritical = 1;
1518
1519         switch ( li->li_idassert_mode ) {
1520         /* already in u:ID or dn:DN form */
1521         case LDAP_BACK_IDASSERT_OTHERID:
1522         case LDAP_BACK_IDASSERT_OTHERDN:
1523                 ber_dupbv_x( &ctrls[ 0 ]->ldctl_value, &assertedID, op->o_tmpmemctx );
1524                 break;
1525
1526         /* needs the dn: prefix */
1527         default:
1528                 ctrls[ 0 ]->ldctl_value.bv_len = assertedID.bv_len + STRLENOF( "dn:" );
1529                 ctrls[ 0 ]->ldctl_value.bv_val = op->o_tmpalloc( ctrls[ 0 ]->ldctl_value.bv_len + 1,
1530                                 op->o_tmpmemctx );
1531                 AC_MEMCPY( ctrls[ 0 ]->ldctl_value.bv_val, "dn:", STRLENOF( "dn:" ) );
1532                 AC_MEMCPY( &ctrls[ 0 ]->ldctl_value.bv_val[ STRLENOF( "dn:" ) ],
1533                                 assertedID.bv_val, assertedID.bv_len + 1 );
1534                 break;
1535         }
1536
1537         if ( op->o_ctrls ) {
1538                 for ( i = 0; op->o_ctrls[ i ]; i++ ) {
1539                         ctrls[ i + 1 ] = op->o_ctrls[ i ];
1540                 }
1541         }
1542         ctrls[ i + 1 ] = NULL;
1543
1544 done:;
1545         if ( ctrls == NULL ) {
1546                 ctrls = op->o_ctrls;
1547         }
1548
1549         *pctrls = ctrls;
1550         
1551         return rs->sr_err;
1552 }
1553
1554 int
1555 ldap_back_proxy_authz_ctrl_free( Operation *op, LDAPControl ***pctrls )
1556 {
1557         LDAPControl     **ctrls = *pctrls;
1558
1559         /* we assume that the first control is the proxyAuthz
1560          * added by back-ldap, so it's the only one we explicitly 
1561          * free */
1562         if ( ctrls && ctrls != op->o_ctrls ) {
1563                 assert( ctrls[ 0 ] != NULL );
1564
1565                 if ( !BER_BVISNULL( &ctrls[ 0 ]->ldctl_value ) ) {
1566                         op->o_tmpfree( ctrls[ 0 ]->ldctl_value.bv_val, op->o_tmpmemctx );
1567                 }
1568
1569                 op->o_tmpfree( ctrls, op->o_tmpmemctx );
1570         } 
1571
1572         *pctrls = NULL;
1573
1574         return 0;
1575 }