]> git.sur5r.net Git - openldap/blob - servers/slapd/back-ldap/bind.c
b8fc62aaafe67777b32b8c834a23b5d32dfde60a
[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\n",
233                 (void *)lc, lc->lc_local_ndn.bv_val, (void *)lc->lc_conn,
234                 avl_bf2str( root->avl_bf) );
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 ("[dont-]chase-referrals" statement) */
451         if ( LDAP_BACK_CHASE_REFERRALS( li ) ) {
452                 ldap_set_option( ld, LDAP_OPT_REFERRALS, LDAP_OPT_ON );
453         }
454
455 #ifdef HAVE_TLS
456         rs->sr_err = ldap_back_start_tls( ld, op->o_protocol, &is_tls,
457                         li->li_uri, li->li_flags, li->li_nretries, &rs->sr_text );
458         if ( rs->sr_err != LDAP_SUCCESS ) {
459                 ldap_unbind_ext( ld, NULL, NULL );
460                 goto error_return;
461         }
462 #endif /* HAVE_TLS */
463
464         if ( *lcp == NULL ) {
465                 *lcp = (ldapconn_t *)ch_calloc( 1, sizeof( ldapconn_t ) );
466                 (*lcp)->lc_flags= li->li_flags;
467         }
468         (*lcp)->lc_ld = ld;
469         (*lcp)->lc_refcnt = 1;
470         (*lcp)->lc_binding = 1;
471 #ifdef HAVE_TLS
472         if ( is_tls ) {
473                 LDAP_BACK_CONN_ISTLS_SET( *lcp );
474         } else {
475                 LDAP_BACK_CONN_ISTLS_CLEAR( *lcp );
476         }
477 #endif /* HAVE_TLS */
478
479 error_return:;
480         if ( rs->sr_err != LDAP_SUCCESS ) {
481                 rs->sr_err = slap_map_api2result( rs );
482                 if ( sendok & LDAP_BACK_SENDERR ) {
483                         if ( rs->sr_text == NULL ) {
484                                 rs->sr_text = "ldap_initialize() failed";
485                         }
486                         send_ldap_result( op, rs );
487                         rs->sr_text = NULL;
488                 }
489
490         } else {
491                 if ( li->li_conn_ttl > 0 ) {
492                         (*lcp)->lc_create_time = op->o_time;
493                 }
494         }
495
496         return rs->sr_err;
497 }
498
499 ldapconn_t *
500 ldap_back_getconn( Operation *op, SlapReply *rs, ldap_back_send_t sendok )
501 {
502         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
503         ldapconn_t      *lc = NULL,
504                         lc_curr = { 0 };
505         int             refcnt = 1, binding = 1;
506
507         /* Internal searches are privileged and shared. So is root. */
508         if ( op->o_do_not_cache || be_isroot( op ) ) {
509                 LDAP_BACK_CONN_ISPRIV_SET( &lc_curr );
510                 lc_curr.lc_local_ndn = op->o_bd->be_rootndn;
511                 lc_curr.lc_conn = LDAP_BACK_PCONN_SET( op );
512
513         } else {
514                 lc_curr.lc_local_ndn = op->o_ndn;
515                 /* Explicit binds must not be shared */
516                 if ( op->o_tag == LDAP_REQ_BIND || SLAP_IS_AUTHZ_BACKEND( op ) ) {
517                         lc_curr.lc_conn = op->o_conn;
518         
519                 } else {
520                         lc_curr.lc_conn = LDAP_BACK_PCONN_SET( op );
521                 }
522         }
523
524         /* Explicit Bind requests always get their own conn */
525         if ( !( sendok & LDAP_BACK_BINDING ) ) {
526                 /* Searches for a ldapconn in the avl tree */
527 retry_lock:
528                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
529
530                 lc = (ldapconn_t *)avl_find( li->li_conninfo.lai_tree, 
531                                 (caddr_t)&lc_curr, ldap_back_conndn_cmp );
532                 if ( lc != NULL ) {
533                         /* Don't reuse connections while they're still binding */
534                         if ( LDAP_BACK_CONN_BINDING( lc ) ) {
535                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
536                                 ldap_pvt_thread_yield();
537                                 goto retry_lock;
538                         }
539                         refcnt = ++lc->lc_refcnt;
540                         binding = ++lc->lc_binding;
541                 }
542                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
543         }
544
545         /* Looks like we didn't get a bind. Open a new session... */
546         if ( lc == NULL ) {
547                 if ( ldap_back_prepare_conn( &lc, op, rs, sendok ) != LDAP_SUCCESS ) {
548                         return NULL;
549                 }
550                 if ( sendok & LDAP_BACK_BINDING ) {
551                         LDAP_BACK_CONN_BINDING_SET( lc );
552                 }
553                 lc->lc_conn = lc_curr.lc_conn;
554                 ber_dupbv( &lc->lc_local_ndn, &lc_curr.lc_local_ndn );
555
556                 if ( LDAP_BACK_CONN_ISPRIV( &lc_curr ) ) {
557                         ber_dupbv( &lc->lc_cred, &li->li_acl_passwd );
558                         ber_dupbv( &lc->lc_bound_ndn, &li->li_acl_authcDN );
559                         LDAP_BACK_CONN_ISPRIV_SET( lc );
560
561                 } else {
562                         BER_BVZERO( &lc->lc_cred );
563                         BER_BVZERO( &lc->lc_bound_ndn );
564 #if 0
565                         /* FIXME: if we set lc_bound_ndn = o_ndn
566                          * we end up with a bind with DN but no password! */
567                         if ( !BER_BVISEMPTY( &op->o_ndn )
568                                 && SLAP_IS_AUTHZ_BACKEND( op ) )
569                         {
570                                 ber_dupbv( &lc->lc_bound_ndn, &op->o_ndn );
571                         }
572 #endif
573                 }
574
575 #ifdef HAVE_TLS
576                 /* if start TLS failed but it was not mandatory,
577                  * check if the non-TLS connection was already
578                  * in cache; in case, destroy the newly created
579                  * connection and use the existing one */
580                 if ( lc->lc_conn == LDAP_BACK_PCONN_TLS
581                                 && !ldap_tls_inplace( lc->lc_ld ) )
582                 {
583                         ldapconn_t *tmplc;
584                         
585                         lc_curr.lc_conn = LDAP_BACK_PCONN;
586                         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
587                         tmplc = (ldapconn_t *)avl_find( li->li_conninfo.lai_tree, 
588                                         (caddr_t)&lc_curr, ldap_back_conndn_cmp );
589                         if ( tmplc != NULL ) {
590                                 refcnt = ++tmplc->lc_refcnt;
591                                 binding = ++tmplc->lc_binding;
592                                 ldap_back_conn_free( lc );
593                                 lc = tmplc;
594                         }
595                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
596
597                         if ( tmplc != NULL ) {
598                                 goto done;
599                         }
600                 }
601 #endif /* HAVE_TLS */
602
603                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
604
605                 /* Inserts the newly created ldapconn in the avl tree */
606                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
607
608                 assert( lc->lc_refcnt == 1 );
609                 assert( lc->lc_binding == 1 );
610                 rs->sr_err = avl_insert( &li->li_conninfo.lai_tree, (caddr_t)lc,
611                         ldap_back_conndn_cmp, ldap_back_conndn_dup );
612
613 #if PRINT_CONNTREE > 0
614                 myprint( li->li_conninfo.lai_tree );
615 #endif /* PRINT_CONNTREE */
616         
617                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
618
619                 Debug( LDAP_DEBUG_TRACE,
620                         "=>ldap_back_getconn: conn %p inserted refcnt=%u binding=%u\n",
621                         (void *)lc, refcnt, binding );
622         
623                 /* Err could be -1 in case a duplicate ldapconn is inserted */
624                 if ( rs->sr_err != 0 ) {
625                         ldap_back_conn_free( lc );
626                         rs->sr_err = LDAP_OTHER;
627                         if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
628                                 send_ldap_error( op, rs, LDAP_OTHER,
629                                         "internal server error" );
630                         }
631                         return NULL;
632                 }
633
634         } else {
635                 if ( ( li->li_idle_timeout != 0 && op->o_time > lc->lc_time + li->li_idle_timeout )
636                         || ( li->li_conn_ttl != 0 && op->o_time > lc->lc_create_time + li->li_conn_ttl ) )
637                 {
638                         /* in case of failure, it frees/taints lc and sets it to NULL */
639                         if ( !ldap_back_retry( &lc, op, rs, sendok ) ) {
640                                 lc = NULL;
641                         }
642                 }
643
644                 if ( lc ) {
645                         Debug( LDAP_DEBUG_TRACE,
646                                 "=>ldap_back_getconn: conn %p fetched refcnt=%u binding=%u\n",
647                                 (void *)lc, refcnt, binding );
648                 }
649         }
650
651         if ( li->li_idle_timeout && lc ) {
652                 lc->lc_time = op->o_time;
653         }
654
655 done:;
656         return lc;
657 }
658
659 void
660 ldap_back_release_conn_lock(
661         Operation               *op,
662         SlapReply               *rs,
663         ldapconn_t              *lc,
664         int                     dolock )
665 {
666         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
667
668         if ( dolock ) {
669                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
670         }
671         assert( lc->lc_refcnt > 0 );
672         lc->lc_refcnt--;
673         LDAP_BACK_CONN_BINDING_CLEAR( lc );
674         if ( dolock ) {
675                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
676         }
677 }
678
679 /*
680  * ldap_back_dobind
681  *
682  * Note: as the check for the value of lc->lc_bound was already here, I removed
683  * it from all the callers, and I made the function return the flag, so
684  * it can be used to simplify the check.
685  *
686  * Note: dolock indicates whether li->li_conninfo.lai_mutex must be locked or not
687  */
688 static int
689 ldap_back_dobind_int(
690         ldapconn_t              *lc,
691         Operation               *op,
692         SlapReply               *rs,
693         ldap_back_send_t        sendok,
694         int                     retries,
695         int                     dolock )
696 {       
697         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
698
699         int             rc, binding = 0;
700         ber_int_t       msgid;
701
702         assert( retries >= 0 );
703
704 retry_lock:;
705         if ( dolock ) {
706                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
707         }
708
709         if ( binding == 0 ) {
710                 /* check if already bound */
711                 rc = LDAP_BACK_CONN_ISBOUND( lc );
712                 if ( rc ) {
713                         lc->lc_binding--;
714                         if ( dolock ) {
715                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
716                         }
717                         return rc;
718                 }
719
720                 if ( LDAP_BACK_CONN_BINDING( lc ) ) {
721                         /* if someone else is about to bind it, give up and retry */
722                         if ( dolock ) {
723                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
724                         }
725                         ldap_pvt_thread_yield();
726                         goto retry_lock;
727
728                 } else {
729                         /* otherwise this thread will bind it */
730                         LDAP_BACK_CONN_BINDING_SET( lc );
731                         binding = 1;
732                 }
733         }
734
735         /* wait for pending operations to finish */
736         /* FIXME: may become a bottleneck! */
737         if ( lc->lc_refcnt != lc->lc_binding ) {
738                 if ( dolock ) {
739                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
740                 }
741                 ldap_pvt_thread_yield();
742                 goto retry_lock;
743         }
744
745         if ( dolock ) {
746                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
747         }
748
749 #if 0
750         while ( lc->lc_refcnt > 1 ) {
751                 ldap_pvt_thread_yield();
752                 rc = LDAP_BACK_CONN_ISBOUND( lc );
753                 if ( rc ) {
754                         return rc;
755                 }
756         }
757
758         if ( dolock ) {
759                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
760         }
761         LDAP_BACK_CONN_BINDING_SET( lc );
762         if ( dolock ) {
763                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
764         }
765 #endif
766
767         /*
768          * FIXME: we need to let clients use proxyAuthz
769          * otherwise we cannot do symmetric pools of servers;
770          * we have to live with the fact that a user can
771          * authorize itself as any ID that is allowed
772          * by the authzTo directive of the "proxyauthzdn".
773          */
774         /*
775          * NOTE: current Proxy Authorization specification
776          * and implementation do not allow proxy authorization
777          * control to be provided with Bind requests
778          */
779         /*
780          * if no bind took place yet, but the connection is bound
781          * and the "idassert-authcDN" (or other ID) is set, 
782          * then bind as the asserting identity and explicitly 
783          * add the proxyAuthz control to every operation with the
784          * dn bound to the connection as control value.
785          * This is done also if this is the authrizing backend,
786          * but the "override" flag is given to idassert.
787          * It allows to use SASL bind and yet proxyAuthz users
788          */
789         if ( op->o_conn != NULL &&
790                         !op->o_do_not_cache &&
791                         ( BER_BVISNULL( &lc->lc_bound_ndn ) ||
792                           ( li->li_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) ) )
793         {
794                 (void)ldap_back_proxy_authz_bind( lc, op, rs, sendok );
795                 goto done;
796         }
797
798 #ifdef HAVE_CYRUS_SASL
799         if ( LDAP_BACK_CONN_ISPRIV( lc )
800                 && li->li_acl_authmethod == LDAP_AUTH_SASL )
801         {
802                 void            *defaults = NULL;
803
804                 if ( li->li_acl_secprops != NULL ) {
805                         rc = ldap_set_option( lc->lc_ld,
806                                 LDAP_OPT_X_SASL_SECPROPS, li->li_acl_secprops);
807
808                         if ( rc != LDAP_OPT_SUCCESS ) {
809                                 Debug( LDAP_DEBUG_ANY, "Error: ldap_set_option "
810                                         "(%s,SECPROPS,\"%s\") failed!\n",
811                                         li->li_uri, li->li_acl_secprops, 0 );
812                                 goto done;
813                         }
814                 }
815
816                 defaults = lutil_sasl_defaults( lc->lc_ld,
817                                 li->li_acl_sasl_mech.bv_val,
818                                 li->li_acl_sasl_realm.bv_val,
819                                 li->li_acl_authcID.bv_val,
820                                 li->li_acl_passwd.bv_val,
821                                 NULL );
822
823                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld,
824                                 li->li_acl_authcDN.bv_val,
825                                 li->li_acl_sasl_mech.bv_val, NULL, NULL,
826                                 LDAP_SASL_QUIET, lutil_sasl_interact,
827                                 defaults );
828
829                 lutil_sasl_freedefs( defaults );
830
831                 rs->sr_err = slap_map_api2result( rs );
832                 if ( rs->sr_err != LDAP_SUCCESS ) {
833                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
834                         send_ldap_result( op, rs );
835
836                 } else {
837                         LDAP_BACK_CONN_ISBOUND_SET( lc );
838                 }
839                 goto done;
840         }
841 #endif /* HAVE_CYRUS_SASL */
842
843 retry:;
844         rs->sr_err = ldap_sasl_bind( lc->lc_ld,
845                         lc->lc_bound_ndn.bv_val,
846                         LDAP_SASL_SIMPLE, &lc->lc_cred,
847                         NULL, NULL, &msgid );
848
849         if ( rs->sr_err == LDAP_SERVER_DOWN ) {
850                 if ( retries != LDAP_BACK_RETRY_NEVER ) {
851                         if ( dolock ) {
852                                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
853                         }
854
855                         assert( lc->lc_refcnt > 0 );
856                         if ( lc->lc_refcnt == 1 ) {
857                                 ldap_unbind_ext( lc->lc_ld, NULL, NULL );
858                                 lc->lc_ld = NULL;
859
860                                 /* lc here must be the regular lc, reset and ready for init */
861                                 rs->sr_err = ldap_back_prepare_conn( &lc, op, rs, sendok );
862                         }
863                         if ( dolock ) {
864                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
865                         }
866                         if ( rs->sr_err == LDAP_SUCCESS ) {
867                                 if ( retries > 0 ) {
868                                         retries--;
869                                 }
870                                 goto retry;
871                         }
872                 }
873
874                 lc->lc_binding--;
875                 ldap_back_freeconn( op, lc, dolock );
876                 rs->sr_err = slap_map_api2result( rs );
877
878                 return 0;
879         }
880
881         rc = ldap_back_op_result( lc, op, rs, msgid, 0, sendok );
882         if ( rc == LDAP_SUCCESS ) {
883                 LDAP_BACK_CONN_ISBOUND_SET( lc );
884         }
885
886 done:;
887         lc->lc_binding--;
888         LDAP_BACK_CONN_BINDING_CLEAR( lc );
889         rc = LDAP_BACK_CONN_ISBOUND( lc );
890         if ( !rc ) {
891                 ldap_back_release_conn_lock( op, rs, lc, dolock );
892         }
893
894         return rc;
895 }
896
897 int
898 ldap_back_dobind( ldapconn_t *lc, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
899 {
900         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
901
902         return ldap_back_dobind_int( lc, op, rs, sendok, li->li_nretries, 1 );
903 }
904
905 /*
906  * ldap_back_default_rebind
907  *
908  * This is a callback used for chasing referrals using the same
909  * credentials as the original user on this session.
910  */
911 static int 
912 ldap_back_default_rebind( LDAP *ld, LDAP_CONST char *url, ber_tag_t request,
913         ber_int_t msgid, void *params )
914 {
915         ldapconn_t      *lc = (ldapconn_t *)params;
916
917 #ifdef HAVE_TLS
918         /* ... otherwise we couldn't get here */
919         assert( lc != NULL );
920
921         if ( !ldap_tls_inplace( ld ) ) {
922                 int             is_tls = LDAP_BACK_CONN_ISTLS( lc ),
923                                 rc;
924                 const char      *text = NULL;
925
926                 rc = ldap_back_start_tls( ld, 0, &is_tls, url, lc->lc_flags,
927                         LDAP_BACK_RETRY_DEFAULT, &text );
928                 if ( rc != LDAP_SUCCESS ) {
929                         return rc;
930                 }
931         }
932 #endif /* HAVE_TLS */
933
934         /* FIXME: add checks on the URL/identity? */
935
936         return ldap_sasl_bind_s( ld, lc->lc_bound_ndn.bv_val,
937                         LDAP_SASL_SIMPLE, &lc->lc_cred, NULL, NULL, NULL );
938 }
939
940 int
941 ldap_back_op_result(
942                 ldapconn_t              *lc,
943                 Operation               *op,
944                 SlapReply               *rs,
945                 ber_int_t               msgid,
946                 time_t                  timeout,
947                 ldap_back_send_t        sendok )
948 {
949         char            *match = NULL;
950         LDAPMessage     *res = NULL;
951         char            *text = NULL;
952
953 #define ERR_OK(err) ((err) == LDAP_SUCCESS || (err) == LDAP_COMPARE_FALSE || (err) == LDAP_COMPARE_TRUE)
954
955         rs->sr_text = NULL;
956         rs->sr_matched = NULL;
957
958         /* if the error recorded in the reply corresponds
959          * to a successful state, get the error from the
960          * remote server response */
961         if ( ERR_OK( rs->sr_err ) ) {
962                 int             rc;
963                 struct timeval  tv;
964
965                 if ( timeout ) {
966                         tv.tv_sec = timeout;
967                         tv.tv_usec = 0;
968
969                 } else {
970                         LDAP_BACK_TV_SET( &tv );
971                 }
972
973 retry:;
974                 /* if result parsing fails, note the failure reason */
975                 rc = ldap_result( lc->lc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
976                 switch ( rc ) {
977                 case 0:
978                         if ( timeout ) {
979                                 (void)ldap_abandon_ext( lc->lc_ld, msgid, NULL, NULL );
980                                 rs->sr_err = op->o_protocol >= LDAP_VERSION3 ?
981                                         LDAP_ADMINLIMIT_EXCEEDED : LDAP_OPERATIONS_ERROR;
982                                 rs->sr_text = "Operation timed out";
983                                 break;
984                         }
985
986                         LDAP_BACK_TV_SET( &tv );
987                         ldap_pvt_thread_yield();
988                         goto retry;
989
990                 case -1:
991                         ldap_get_option( lc->lc_ld, LDAP_OPT_ERROR_NUMBER,
992                                         &rs->sr_err );
993                         break;
994
995
996                 /* otherwise get the result; if it is not
997                  * LDAP_SUCCESS, record it in the reply
998                  * structure (this includes 
999                  * LDAP_COMPARE_{TRUE|FALSE}) */
1000                 default:
1001                         rc = ldap_parse_result( lc->lc_ld, res, &rs->sr_err,
1002                                         &match, &text, NULL, NULL, 1 );
1003                         rs->sr_text = text;
1004                         if ( rc != LDAP_SUCCESS ) {
1005                                 rs->sr_err = rc;
1006                         }
1007                 }
1008         }
1009
1010         /* if the error in the reply structure is not
1011          * LDAP_SUCCESS, try to map it from client 
1012          * to server error */
1013         if ( !ERR_OK( rs->sr_err ) ) {
1014                 rs->sr_err = slap_map_api2result( rs );
1015
1016                 /* internal ops ( op->o_conn == NULL ) 
1017                  * must not reply to client */
1018                 if ( op->o_conn && !op->o_do_not_cache && match ) {
1019
1020                         /* record the (massaged) matched
1021                          * DN into the reply structure */
1022                         rs->sr_matched = match;
1023                 }
1024         }
1025         if ( op->o_conn &&
1026                         ( ( sendok & LDAP_BACK_SENDOK ) 
1027                           || ( ( sendok & LDAP_BACK_SENDERR ) && rs->sr_err != LDAP_SUCCESS ) ) )
1028         {
1029                 send_ldap_result( op, rs );
1030         }
1031         if ( match ) {
1032                 if ( rs->sr_matched != match ) {
1033                         free( (char *)rs->sr_matched );
1034                 }
1035                 rs->sr_matched = NULL;
1036                 ldap_memfree( match );
1037         }
1038         if ( text ) {
1039                 ldap_memfree( text );
1040         }
1041         rs->sr_text = NULL;
1042         return( ERR_OK( rs->sr_err ) ? LDAP_SUCCESS : rs->sr_err );
1043 }
1044
1045 /* return true if bound, false if failed */
1046 int
1047 ldap_back_retry( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1048 {
1049         int             rc = 0;
1050         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1051
1052         assert( lcp != NULL );
1053         assert( *lcp != NULL );
1054
1055         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1056
1057         if ( (*lcp)->lc_refcnt == 1 ) {
1058                 Debug( LDAP_DEBUG_ANY,
1059                         "%s ldap_back_retry: retrying URI=\"%s\" DN=\"%s\"\n",
1060                         op->o_log_prefix, li->li_uri,
1061                         BER_BVISNULL( &(*lcp)->lc_bound_ndn ) ?
1062                                 "" : (*lcp)->lc_bound_ndn.bv_val );
1063
1064                 ldap_unbind_ext( (*lcp)->lc_ld, NULL, NULL );
1065                 (*lcp)->lc_ld = NULL;
1066                 LDAP_BACK_CONN_ISBOUND_CLEAR( (*lcp) );
1067
1068                 /* lc here must be the regular lc, reset and ready for init */
1069                 rc = ldap_back_prepare_conn( lcp, op, rs, sendok );
1070                 if ( rc != LDAP_SUCCESS ) {
1071                         rc = 0;
1072                         *lcp = NULL;
1073
1074                 } else {
1075                         rc = ldap_back_dobind_int( *lcp, op, rs, sendok, 0, 0 );
1076                         if ( rc == 0 ) {
1077                                 *lcp = NULL;
1078                         }
1079                 }
1080         }
1081
1082         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1083
1084         return rc;
1085 }
1086
1087 static int
1088 ldap_back_proxy_authz_bind( ldapconn_t *lc, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1089 {
1090         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1091         struct berval   binddn = slap_empty_bv;
1092         struct berval   bindcred = slap_empty_bv;
1093         struct berval   ndn;
1094         int             dobind = 0;
1095         int             msgid;
1096         int             rc;
1097
1098         if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1099                 ndn = op->o_conn->c_ndn;
1100
1101         } else {
1102                 ndn = op->o_ndn;
1103         }
1104
1105         /*
1106          * FIXME: we need to let clients use proxyAuthz
1107          * otherwise we cannot do symmetric pools of servers;
1108          * we have to live with the fact that a user can
1109          * authorize itself as any ID that is allowed
1110          * by the authzTo directive of the "proxyauthzdn".
1111          */
1112         /*
1113          * NOTE: current Proxy Authorization specification
1114          * and implementation do not allow proxy authorization
1115          * control to be provided with Bind requests
1116          */
1117         /*
1118          * if no bind took place yet, but the connection is bound
1119          * and the "proxyauthzdn" is set, then bind as 
1120          * "proxyauthzdn" and explicitly add the proxyAuthz 
1121          * control to every operation with the dn bound 
1122          * to the connection as control value.
1123          */
1124
1125         /* bind as proxyauthzdn only if no idassert mode
1126          * is requested, or if the client's identity
1127          * is authorized */
1128         switch ( li->li_idassert_mode ) {
1129         case LDAP_BACK_IDASSERT_LEGACY:
1130                 if ( !BER_BVISNULL( &ndn ) && !BER_BVISEMPTY( &ndn ) ) {
1131                         if ( !BER_BVISNULL( &li->li_idassert_authcDN ) && !BER_BVISEMPTY( &li->li_idassert_authcDN ) )
1132                         {
1133                                 binddn = li->li_idassert_authcDN;
1134                                 bindcred = li->li_idassert_passwd;
1135                                 dobind = 1;
1136                         }
1137                 }
1138                 break;
1139
1140         default:
1141                 /* NOTE: rootdn can always idassert */
1142                 if ( BER_BVISNULL( &ndn ) && li->li_idassert_authz == NULL ) {
1143                         if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1144                                 rs->sr_err = LDAP_INAPPROPRIATE_AUTH;
1145                                 if ( sendok & LDAP_BACK_SENDERR ) {
1146                                         send_ldap_result( op, rs );
1147                                 }
1148                                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1149
1150                         } else {
1151                                 rs->sr_err = LDAP_SUCCESS;
1152                                 binddn = slap_empty_bv;
1153                                 bindcred = slap_empty_bv;
1154                                 break;
1155                         }
1156
1157                         goto done;
1158
1159                 } else if ( li->li_idassert_authz && !be_isroot( op ) ) {
1160                         struct berval authcDN;
1161
1162                         if ( BER_BVISNULL( &ndn ) ) {
1163                                 authcDN = slap_empty_bv;
1164
1165                         } else {
1166                                 authcDN = ndn;
1167                         }       
1168                         rs->sr_err = slap_sasl_matches( op, li->li_idassert_authz,
1169                                         &authcDN, &authcDN );
1170                         if ( rs->sr_err != LDAP_SUCCESS ) {
1171                                 if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1172                                         if ( sendok & LDAP_BACK_SENDERR ) {
1173                                                 send_ldap_result( op, rs );
1174                                         }
1175                                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1176
1177                                 } else {
1178                                         rs->sr_err = LDAP_SUCCESS;
1179                                         binddn = slap_empty_bv;
1180                                         bindcred = slap_empty_bv;
1181                                         break;
1182                                 }
1183
1184                                 goto done;
1185                         }
1186                 }
1187
1188                 binddn = li->li_idassert_authcDN;
1189                 bindcred = li->li_idassert_passwd;
1190                 dobind = 1;
1191                 break;
1192         }
1193
1194         if ( dobind && li->li_idassert_authmethod == LDAP_AUTH_SASL ) {
1195 #ifdef HAVE_CYRUS_SASL
1196                 void            *defaults = NULL;
1197                 struct berval   authzID = BER_BVNULL;
1198                 int             freeauthz = 0;
1199
1200                 /* if SASL supports native authz, prepare for it */
1201                 if ( ( !op->o_do_not_cache || !op->o_is_auth_check ) &&
1202                                 ( li->li_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
1203                 {
1204                         switch ( li->li_idassert_mode ) {
1205                         case LDAP_BACK_IDASSERT_OTHERID:
1206                         case LDAP_BACK_IDASSERT_OTHERDN:
1207                                 authzID = li->li_idassert_authzID;
1208                                 break;
1209
1210                         case LDAP_BACK_IDASSERT_ANONYMOUS:
1211                                 BER_BVSTR( &authzID, "dn:" );
1212                                 break;
1213
1214                         case LDAP_BACK_IDASSERT_SELF:
1215                                 if ( BER_BVISNULL( &ndn ) ) {
1216                                         /* connection is not authc'd, so don't idassert */
1217                                         BER_BVSTR( &authzID, "dn:" );
1218                                         break;
1219                                 }
1220                                 authzID.bv_len = STRLENOF( "dn:" ) + ndn.bv_len;
1221                                 authzID.bv_val = slap_sl_malloc( authzID.bv_len + 1, op->o_tmpmemctx );
1222                                 AC_MEMCPY( authzID.bv_val, "dn:", STRLENOF( "dn:" ) );
1223                                 AC_MEMCPY( authzID.bv_val + STRLENOF( "dn:" ),
1224                                                 ndn.bv_val, ndn.bv_len + 1 );
1225                                 freeauthz = 1;
1226                                 break;
1227
1228                         default:
1229                                 break;
1230                         }
1231                 }
1232
1233                 if ( li->li_idassert_secprops != NULL ) {
1234                         rs->sr_err = ldap_set_option( lc->lc_ld,
1235                                 LDAP_OPT_X_SASL_SECPROPS,
1236                                 (void *)li->li_idassert_secprops );
1237
1238                         if ( rs->sr_err != LDAP_OPT_SUCCESS ) {
1239                                 rs->sr_err = LDAP_OTHER;
1240                                 if ( sendok & LDAP_BACK_SENDERR ) {
1241                                         send_ldap_result( op, rs );
1242                                 }
1243                                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1244                                 goto done;
1245                         }
1246                 }
1247
1248                 defaults = lutil_sasl_defaults( lc->lc_ld,
1249                                 li->li_idassert_sasl_mech.bv_val,
1250                                 li->li_idassert_sasl_realm.bv_val,
1251                                 li->li_idassert_authcID.bv_val,
1252                                 li->li_idassert_passwd.bv_val,
1253                                 authzID.bv_val );
1254
1255                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld, binddn.bv_val,
1256                                 li->li_idassert_sasl_mech.bv_val, NULL, NULL,
1257                                 LDAP_SASL_QUIET, lutil_sasl_interact,
1258                                 defaults );
1259
1260                 rs->sr_err = slap_map_api2result( rs );
1261                 if ( rs->sr_err != LDAP_SUCCESS ) {
1262                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1263                         if ( sendok & LDAP_BACK_SENDERR ) {
1264                                 send_ldap_result( op, rs );
1265                         }
1266
1267                 } else {
1268                         LDAP_BACK_CONN_ISBOUND_SET( lc );
1269                 }
1270
1271                 lutil_sasl_freedefs( defaults );
1272                 if ( freeauthz ) {
1273                         slap_sl_free( authzID.bv_val, op->o_tmpmemctx );
1274                 }
1275
1276                 goto done;
1277 #endif /* HAVE_CYRUS_SASL */
1278         }
1279
1280         switch ( li->li_idassert_authmethod ) {
1281         case LDAP_AUTH_NONE:
1282                 LDAP_BACK_CONN_ISBOUND_SET( lc );
1283                 goto done;
1284
1285         case LDAP_AUTH_SIMPLE:
1286                 rs->sr_err = ldap_sasl_bind( lc->lc_ld,
1287                                 binddn.bv_val, LDAP_SASL_SIMPLE,
1288                                 &bindcred, NULL, NULL, &msgid );
1289                 break;
1290
1291         default:
1292                 /* unsupported! */
1293                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1294                 rs->sr_err = LDAP_AUTH_METHOD_NOT_SUPPORTED;
1295                 if ( sendok & LDAP_BACK_SENDERR ) {
1296                         send_ldap_result( op, rs );
1297                 }
1298                 goto done;
1299         }
1300
1301         rc = ldap_back_op_result( lc, op, rs, msgid, 0, sendok );
1302         if ( rc == LDAP_SUCCESS ) {
1303                 LDAP_BACK_CONN_ISBOUND_SET( lc );
1304         }
1305 done:;
1306         return LDAP_BACK_CONN_ISBOUND( lc );
1307 }
1308
1309 /*
1310  * ldap_back_proxy_authz_ctrl() prepends a proxyAuthz control
1311  * to existing server-side controls if required; if not,
1312  * the existing server-side controls are placed in *pctrls.
1313  * The caller, after using the controls in client API 
1314  * operations, if ( *pctrls != op->o_ctrls ), should
1315  * free( (*pctrls)[ 0 ] ) and free( *pctrls ).
1316  * The function returns success if the control could
1317  * be added if required, or if it did nothing; in the future,
1318  * it might return some error if it failed.
1319  * 
1320  * if no bind took place yet, but the connection is bound
1321  * and the "proxyauthzdn" is set, then bind as "proxyauthzdn" 
1322  * and explicitly add proxyAuthz the control to every operation
1323  * with the dn bound to the connection as control value.
1324  *
1325  * If no server-side controls are defined for the operation,
1326  * simply add the proxyAuthz control; otherwise, if the
1327  * proxyAuthz control is not already set, add it as
1328  * the first one
1329  *
1330  * FIXME: is controls order significant for security?
1331  * ANSWER: controls ordering and interoperability
1332  * must be indicated by the specs of each control; if none
1333  * is specified, the order is irrelevant.
1334  */
1335 int
1336 ldap_back_proxy_authz_ctrl(
1337                 ldapconn_t      *lc,
1338                 Operation       *op,
1339                 SlapReply       *rs,
1340                 LDAPControl     ***pctrls )
1341 {
1342         ldapinfo_t      *li = (ldapinfo_t *) op->o_bd->be_private;
1343         LDAPControl     **ctrls = NULL;
1344         int             i = 0,
1345                         mode;
1346         struct berval   assertedID,
1347                         ndn;
1348
1349         *pctrls = NULL;
1350
1351         rs->sr_err = LDAP_SUCCESS;
1352
1353         /* FIXME: SASL/EXTERNAL over ldapi:// doesn't honor the authcID,
1354          * but if it is not set this test fails.  We need a different
1355          * means to detect if idassert is enabled */
1356         if ( ( BER_BVISNULL( &li->li_idassert_authcID ) || BER_BVISEMPTY( &li->li_idassert_authcID ) )
1357                         && ( BER_BVISNULL( &li->li_idassert_authcDN ) || BER_BVISEMPTY( &li->li_idassert_authcDN ) ) )
1358         {
1359                 goto done;
1360         }
1361
1362         if ( !op->o_conn || op->o_do_not_cache || be_isroot( op ) ) {
1363                 goto done;
1364         }
1365
1366         if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1367                 ndn = op->o_conn->c_ndn;
1368
1369         } else {
1370                 ndn = op->o_ndn;
1371         }
1372
1373         if ( li->li_idassert_mode == LDAP_BACK_IDASSERT_LEGACY ) {
1374                 if ( op->o_proxy_authz ) {
1375                         /*
1376                          * FIXME: we do not want to perform proxyAuthz
1377                          * on behalf of the client, because this would
1378                          * be performed with "proxyauthzdn" privileges.
1379                          *
1380                          * This might actually be too strict, since
1381                          * the "proxyauthzdn" authzTo, and each entry's
1382                          * authzFrom attributes may be crafted
1383                          * to avoid unwanted proxyAuthz to take place.
1384                          */
1385 #if 0
1386                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1387                         rs->sr_text = "proxyAuthz not allowed within namingContext";
1388 #endif
1389                         goto done;
1390                 }
1391
1392                 if ( !BER_BVISNULL( &lc->lc_bound_ndn ) ) {
1393                         goto done;
1394                 }
1395
1396                 if ( BER_BVISNULL( &ndn ) ) {
1397                         goto done;
1398                 }
1399
1400                 if ( BER_BVISNULL( &li->li_idassert_authcDN ) ) {
1401                         goto done;
1402                 }
1403
1404         } else if ( li->li_idassert_authmethod == LDAP_AUTH_SASL ) {
1405                 if ( ( li->li_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ )
1406                                 /* && ( !BER_BVISNULL( &ndn )
1407                                         || LDAP_BACK_CONN_ISBOUND( lc ) ) */ )
1408                 {
1409                         /* already asserted in SASL via native authz */
1410                         /* NOTE: the test on lc->lc_bound is used to trap
1411                          * native authorization of anonymous users,
1412                          * since in that case ndn is NULL */
1413                         goto done;
1414                 }
1415
1416         } else if ( li->li_idassert_authz && !be_isroot( op ) ) {
1417                 int             rc;
1418                 struct berval authcDN;
1419
1420                 if ( BER_BVISNULL( &ndn ) ) {
1421                         authcDN = slap_empty_bv;
1422                 } else {
1423                         authcDN = ndn;
1424                 }
1425                 rc = slap_sasl_matches( op, li->li_idassert_authz,
1426                                 &authcDN, & authcDN );
1427                 if ( rc != LDAP_SUCCESS ) {
1428                         if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE )
1429                         {
1430                                 /* ndn is not authorized
1431                                  * to use idassert */
1432                                 return rc;
1433                         }
1434                         return rs->sr_err;
1435                 }
1436         }
1437
1438         if ( op->o_proxy_authz ) {
1439                 /*
1440                  * FIXME: we can:
1441                  * 1) ignore the already set proxyAuthz control
1442                  * 2) leave it in place, and don't set ours
1443                  * 3) add both
1444                  * 4) reject the operation
1445                  *
1446                  * option (4) is very drastic
1447                  * option (3) will make the remote server reject
1448                  * the operation, thus being equivalent to (4)
1449                  * option (2) will likely break the idassert
1450                  * assumptions, so we cannot accept it;
1451                  * option (1) means that we are contradicting
1452                  * the client's reques.
1453                  *
1454                  * I think (4) is the only correct choice.
1455                  */
1456                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1457                 rs->sr_text = "proxyAuthz not allowed within namingContext";
1458         }
1459
1460         if ( op->o_is_auth_check ) {
1461                 mode = LDAP_BACK_IDASSERT_NOASSERT;
1462
1463         } else {
1464                 mode = li->li_idassert_mode;
1465         }
1466
1467         switch ( mode ) {
1468         case LDAP_BACK_IDASSERT_SELF:
1469                 if ( BER_BVISNULL( &ndn ) ) {
1470                         goto done;
1471                 }
1472                 assertedID = ndn;
1473                 break;
1474
1475         case LDAP_BACK_IDASSERT_LEGACY:
1476                 /* original behavior:
1477                  * assert the client's identity */
1478                 if ( BER_BVISNULL( &ndn ) ) {
1479                         assertedID = slap_empty_bv;
1480                 } else {
1481                         assertedID = ndn;
1482                 }
1483                 break;
1484
1485         case LDAP_BACK_IDASSERT_ANONYMOUS:
1486                 /* assert "anonymous" */
1487                 assertedID = slap_empty_bv;
1488                 break;
1489
1490         case LDAP_BACK_IDASSERT_NOASSERT:
1491                 /* don't assert; bind as proxyauthzdn */
1492                 goto done;
1493
1494         case LDAP_BACK_IDASSERT_OTHERID:
1495         case LDAP_BACK_IDASSERT_OTHERDN:
1496                 /* assert idassert DN */
1497                 assertedID = li->li_idassert_authzID;
1498                 break;
1499
1500         default:
1501                 assert( 0 );
1502         }
1503
1504         if ( BER_BVISNULL( &assertedID ) ) {
1505                 assertedID = slap_empty_bv;
1506         }
1507
1508         if ( op->o_ctrls ) {
1509                 for ( i = 0; op->o_ctrls[ i ]; i++ )
1510                         /* just count ctrls */ ;
1511         }
1512
1513         ctrls = op->o_tmpalloc( sizeof( LDAPControl * ) * (i + 2) + sizeof( LDAPControl ),
1514                         op->o_tmpmemctx );
1515         ctrls[ 0 ] = (LDAPControl *)&ctrls[ i + 2 ];
1516         
1517         ctrls[ 0 ]->ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1518         ctrls[ 0 ]->ldctl_iscritical = 1;
1519
1520         switch ( li->li_idassert_mode ) {
1521         /* already in u:ID or dn:DN form */
1522         case LDAP_BACK_IDASSERT_OTHERID:
1523         case LDAP_BACK_IDASSERT_OTHERDN:
1524                 ber_dupbv_x( &ctrls[ 0 ]->ldctl_value, &assertedID, op->o_tmpmemctx );
1525                 break;
1526
1527         /* needs the dn: prefix */
1528         default:
1529                 ctrls[ 0 ]->ldctl_value.bv_len = assertedID.bv_len + STRLENOF( "dn:" );
1530                 ctrls[ 0 ]->ldctl_value.bv_val = op->o_tmpalloc( ctrls[ 0 ]->ldctl_value.bv_len + 1,
1531                                 op->o_tmpmemctx );
1532                 AC_MEMCPY( ctrls[ 0 ]->ldctl_value.bv_val, "dn:", STRLENOF( "dn:" ) );
1533                 AC_MEMCPY( &ctrls[ 0 ]->ldctl_value.bv_val[ STRLENOF( "dn:" ) ],
1534                                 assertedID.bv_val, assertedID.bv_len + 1 );
1535                 break;
1536         }
1537
1538         if ( op->o_ctrls ) {
1539                 for ( i = 0; op->o_ctrls[ i ]; i++ ) {
1540                         ctrls[ i + 1 ] = op->o_ctrls[ i ];
1541                 }
1542         }
1543         ctrls[ i + 1 ] = NULL;
1544
1545 done:;
1546         if ( ctrls == NULL ) {
1547                 ctrls = op->o_ctrls;
1548         }
1549
1550         *pctrls = ctrls;
1551         
1552         return rs->sr_err;
1553 }
1554
1555 int
1556 ldap_back_proxy_authz_ctrl_free( Operation *op, LDAPControl ***pctrls )
1557 {
1558         LDAPControl     **ctrls = *pctrls;
1559
1560         /* we assume that the first control is the proxyAuthz
1561          * added by back-ldap, so it's the only one we explicitly 
1562          * free */
1563         if ( ctrls && ctrls != op->o_ctrls ) {
1564                 assert( ctrls[ 0 ] != NULL );
1565
1566                 if ( !BER_BVISNULL( &ctrls[ 0 ]->ldctl_value ) ) {
1567                         op->o_tmpfree( ctrls[ 0 ]->ldctl_value.bv_val, op->o_tmpmemctx );
1568                 }
1569
1570                 op->o_tmpfree( ctrls, op->o_tmpmemctx );
1571         } 
1572
1573         *pctrls = NULL;
1574
1575         return 0;
1576 }