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