]> git.sur5r.net Git - openldap/blob - servers/slapd/back-ldap/bind.c
Changes suggested by Ando.
[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 #ifndef LDAP_NULL_IS_NULL
1047                         if ( match != NULL && match[ 0 ] == '\0' ) {
1048                                 ldap_memfree( match );
1049                                 match = NULL;
1050                         }
1051                         if ( text != NULL && text[ 0 ] == '\0' ) {
1052                                 ldap_memfree( text );
1053                                 text = NULL;
1054                         }
1055 #endif /* LDAP_NULL_IS_NULL */
1056                         rs->sr_text = text;
1057                         if ( rc != LDAP_SUCCESS ) {
1058                                 rs->sr_err = rc;
1059                         }
1060                 }
1061         }
1062
1063         /* if the error in the reply structure is not
1064          * LDAP_SUCCESS, try to map it from client 
1065          * to server error */
1066         if ( !ERR_OK( rs->sr_err ) ) {
1067                 rs->sr_err = slap_map_api2result( rs );
1068
1069                 /* internal ops ( op->o_conn == NULL ) 
1070                  * must not reply to client */
1071                 if ( op->o_conn && !op->o_do_not_cache && match ) {
1072
1073                         /* record the (massaged) matched
1074                          * DN into the reply structure */
1075                         rs->sr_matched = match;
1076                 }
1077         }
1078         if ( op->o_conn &&
1079                         ( ( sendok & LDAP_BACK_SENDOK ) 
1080                           || ( ( sendok & LDAP_BACK_SENDERR ) && rs->sr_err != LDAP_SUCCESS ) ) )
1081         {
1082                 send_ldap_result( op, rs );
1083         }
1084         if ( match ) {
1085                 if ( rs->sr_matched != match ) {
1086                         free( (char *)rs->sr_matched );
1087                 }
1088                 rs->sr_matched = NULL;
1089                 ldap_memfree( match );
1090         }
1091         if ( text ) {
1092                 ldap_memfree( text );
1093         }
1094         rs->sr_text = NULL;
1095         return( ERR_OK( rs->sr_err ) ? LDAP_SUCCESS : rs->sr_err );
1096 }
1097
1098 /* return true if bound, false if failed */
1099 int
1100 ldap_back_retry( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1101 {
1102         int             rc = 0;
1103         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1104
1105         assert( lcp != NULL );
1106         assert( *lcp != NULL );
1107
1108         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1109
1110         if ( (*lcp)->lc_refcnt == 1 ) {
1111                 Debug( LDAP_DEBUG_ANY,
1112                         "%s ldap_back_retry: retrying URI=\"%s\" DN=\"%s\"\n",
1113                         op->o_log_prefix, li->li_uri,
1114                         BER_BVISNULL( &(*lcp)->lc_bound_ndn ) ?
1115                                 "" : (*lcp)->lc_bound_ndn.bv_val );
1116
1117                 ldap_unbind_ext( (*lcp)->lc_ld, NULL, NULL );
1118                 (*lcp)->lc_ld = NULL;
1119                 LDAP_BACK_CONN_ISBOUND_CLEAR( (*lcp) );
1120
1121                 /* lc here must be the regular lc, reset and ready for init */
1122                 rc = ldap_back_prepare_conn( lcp, op, rs, sendok );
1123                 if ( rc != LDAP_SUCCESS ) {
1124                         rc = 0;
1125                         *lcp = NULL;
1126
1127                 } else {
1128                         rc = ldap_back_dobind_int( *lcp, op, rs, sendok, 0, 0 );
1129                         if ( rc == 0 ) {
1130                                 *lcp = NULL;
1131                         }
1132                 }
1133
1134         } else {
1135                 Debug( LDAP_DEBUG_TRACE,
1136                         "ldap_back_retry: conn %p refcnt=%u unable to retry.\n",
1137                         (void *)(*lcp), (*lcp)->lc_refcnt, 0 );
1138
1139                 ldap_back_release_conn_lock( op, rs, *lcp, 0 );
1140                 *lcp = NULL;
1141
1142                 if ( sendok ) {
1143                         rs->sr_err = LDAP_UNAVAILABLE;
1144                         rs->sr_text = "unable to retry";
1145                         send_ldap_result( op, rs );
1146                 }
1147         }
1148
1149         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1150
1151         return rc;
1152 }
1153
1154 static int
1155 ldap_back_proxy_authz_bind( ldapconn_t *lc, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1156 {
1157         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1158         struct berval   binddn = slap_empty_bv;
1159         struct berval   bindcred = slap_empty_bv;
1160         struct berval   ndn;
1161         int             dobind = 0;
1162         int             msgid;
1163         int             rc;
1164
1165         if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1166                 ndn = op->o_conn->c_ndn;
1167
1168         } else {
1169                 ndn = op->o_ndn;
1170         }
1171
1172         /*
1173          * FIXME: we need to let clients use proxyAuthz
1174          * otherwise we cannot do symmetric pools of servers;
1175          * we have to live with the fact that a user can
1176          * authorize itself as any ID that is allowed
1177          * by the authzTo directive of the "proxyauthzdn".
1178          */
1179         /*
1180          * NOTE: current Proxy Authorization specification
1181          * and implementation do not allow proxy authorization
1182          * control to be provided with Bind requests
1183          */
1184         /*
1185          * if no bind took place yet, but the connection is bound
1186          * and the "proxyauthzdn" is set, then bind as 
1187          * "proxyauthzdn" and explicitly add the proxyAuthz 
1188          * control to every operation with the dn bound 
1189          * to the connection as control value.
1190          */
1191
1192         /* bind as proxyauthzdn only if no idassert mode
1193          * is requested, or if the client's identity
1194          * is authorized */
1195         switch ( li->li_idassert_mode ) {
1196         case LDAP_BACK_IDASSERT_LEGACY:
1197                 if ( !BER_BVISNULL( &ndn ) && !BER_BVISEMPTY( &ndn ) ) {
1198                         if ( !BER_BVISNULL( &li->li_idassert_authcDN ) && !BER_BVISEMPTY( &li->li_idassert_authcDN ) )
1199                         {
1200                                 binddn = li->li_idassert_authcDN;
1201                                 bindcred = li->li_idassert_passwd;
1202                                 dobind = 1;
1203                         }
1204                 }
1205                 break;
1206
1207         default:
1208                 /* NOTE: rootdn can always idassert */
1209                 if ( BER_BVISNULL( &ndn ) && li->li_idassert_authz == NULL ) {
1210                         if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1211                                 rs->sr_err = LDAP_INAPPROPRIATE_AUTH;
1212                                 if ( sendok & LDAP_BACK_SENDERR ) {
1213                                         send_ldap_result( op, rs );
1214                                 }
1215                                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1216
1217                         } else {
1218                                 rs->sr_err = LDAP_SUCCESS;
1219                                 binddn = slap_empty_bv;
1220                                 bindcred = slap_empty_bv;
1221                                 break;
1222                         }
1223
1224                         goto done;
1225
1226                 } else if ( li->li_idassert_authz && !be_isroot( op ) ) {
1227                         struct berval authcDN;
1228
1229                         if ( BER_BVISNULL( &ndn ) ) {
1230                                 authcDN = slap_empty_bv;
1231
1232                         } else {
1233                                 authcDN = ndn;
1234                         }       
1235                         rs->sr_err = slap_sasl_matches( op, li->li_idassert_authz,
1236                                         &authcDN, &authcDN );
1237                         if ( rs->sr_err != LDAP_SUCCESS ) {
1238                                 if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1239                                         if ( sendok & LDAP_BACK_SENDERR ) {
1240                                                 send_ldap_result( op, rs );
1241                                         }
1242                                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1243
1244                                 } else {
1245                                         rs->sr_err = LDAP_SUCCESS;
1246                                         binddn = slap_empty_bv;
1247                                         bindcred = slap_empty_bv;
1248                                         break;
1249                                 }
1250
1251                                 goto done;
1252                         }
1253                 }
1254
1255                 binddn = li->li_idassert_authcDN;
1256                 bindcred = li->li_idassert_passwd;
1257                 dobind = 1;
1258                 break;
1259         }
1260
1261         if ( dobind && li->li_idassert_authmethod == LDAP_AUTH_SASL ) {
1262 #ifdef HAVE_CYRUS_SASL
1263                 void            *defaults = NULL;
1264                 struct berval   authzID = BER_BVNULL;
1265                 int             freeauthz = 0;
1266
1267                 /* if SASL supports native authz, prepare for it */
1268                 if ( ( !op->o_do_not_cache || !op->o_is_auth_check ) &&
1269                                 ( li->li_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
1270                 {
1271                         switch ( li->li_idassert_mode ) {
1272                         case LDAP_BACK_IDASSERT_OTHERID:
1273                         case LDAP_BACK_IDASSERT_OTHERDN:
1274                                 authzID = li->li_idassert_authzID;
1275                                 break;
1276
1277                         case LDAP_BACK_IDASSERT_ANONYMOUS:
1278                                 BER_BVSTR( &authzID, "dn:" );
1279                                 break;
1280
1281                         case LDAP_BACK_IDASSERT_SELF:
1282                                 if ( BER_BVISNULL( &ndn ) ) {
1283                                         /* connection is not authc'd, so don't idassert */
1284                                         BER_BVSTR( &authzID, "dn:" );
1285                                         break;
1286                                 }
1287                                 authzID.bv_len = STRLENOF( "dn:" ) + ndn.bv_len;
1288                                 authzID.bv_val = slap_sl_malloc( authzID.bv_len + 1, op->o_tmpmemctx );
1289                                 AC_MEMCPY( authzID.bv_val, "dn:", STRLENOF( "dn:" ) );
1290                                 AC_MEMCPY( authzID.bv_val + STRLENOF( "dn:" ),
1291                                                 ndn.bv_val, ndn.bv_len + 1 );
1292                                 freeauthz = 1;
1293                                 break;
1294
1295                         default:
1296                                 break;
1297                         }
1298                 }
1299
1300                 if ( li->li_idassert_secprops != NULL ) {
1301                         rs->sr_err = ldap_set_option( lc->lc_ld,
1302                                 LDAP_OPT_X_SASL_SECPROPS,
1303                                 (void *)li->li_idassert_secprops );
1304
1305                         if ( rs->sr_err != LDAP_OPT_SUCCESS ) {
1306                                 rs->sr_err = LDAP_OTHER;
1307                                 if ( sendok & LDAP_BACK_SENDERR ) {
1308                                         send_ldap_result( op, rs );
1309                                 }
1310                                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1311                                 goto done;
1312                         }
1313                 }
1314
1315                 defaults = lutil_sasl_defaults( lc->lc_ld,
1316                                 li->li_idassert_sasl_mech.bv_val,
1317                                 li->li_idassert_sasl_realm.bv_val,
1318                                 li->li_idassert_authcID.bv_val,
1319                                 li->li_idassert_passwd.bv_val,
1320                                 authzID.bv_val );
1321
1322                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld, binddn.bv_val,
1323                                 li->li_idassert_sasl_mech.bv_val, NULL, NULL,
1324                                 LDAP_SASL_QUIET, lutil_sasl_interact,
1325                                 defaults );
1326
1327                 rs->sr_err = slap_map_api2result( rs );
1328                 if ( rs->sr_err != LDAP_SUCCESS ) {
1329                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1330                         if ( sendok & LDAP_BACK_SENDERR ) {
1331                                 send_ldap_result( op, rs );
1332                         }
1333
1334                 } else {
1335                         LDAP_BACK_CONN_ISBOUND_SET( lc );
1336                 }
1337
1338                 lutil_sasl_freedefs( defaults );
1339                 if ( freeauthz ) {
1340                         slap_sl_free( authzID.bv_val, op->o_tmpmemctx );
1341                 }
1342
1343                 goto done;
1344 #endif /* HAVE_CYRUS_SASL */
1345         }
1346
1347         switch ( li->li_idassert_authmethod ) {
1348         case LDAP_AUTH_NONE:
1349                 LDAP_BACK_CONN_ISBOUND_SET( lc );
1350                 goto done;
1351
1352         case LDAP_AUTH_SIMPLE:
1353                 rs->sr_err = ldap_sasl_bind( lc->lc_ld,
1354                                 binddn.bv_val, LDAP_SASL_SIMPLE,
1355                                 &bindcred, NULL, NULL, &msgid );
1356                 break;
1357
1358         default:
1359                 /* unsupported! */
1360                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1361                 rs->sr_err = LDAP_AUTH_METHOD_NOT_SUPPORTED;
1362                 if ( sendok & LDAP_BACK_SENDERR ) {
1363                         send_ldap_result( op, rs );
1364                 }
1365                 goto done;
1366         }
1367
1368         rc = ldap_back_op_result( lc, op, rs, msgid, 0, sendok );
1369         if ( rc == LDAP_SUCCESS ) {
1370                 LDAP_BACK_CONN_ISBOUND_SET( lc );
1371         }
1372 done:;
1373         return LDAP_BACK_CONN_ISBOUND( lc );
1374 }
1375
1376 /*
1377  * ldap_back_proxy_authz_ctrl() prepends a proxyAuthz control
1378  * to existing server-side controls if required; if not,
1379  * the existing server-side controls are placed in *pctrls.
1380  * The caller, after using the controls in client API 
1381  * operations, if ( *pctrls != op->o_ctrls ), should
1382  * free( (*pctrls)[ 0 ] ) and free( *pctrls ).
1383  * The function returns success if the control could
1384  * be added if required, or if it did nothing; in the future,
1385  * it might return some error if it failed.
1386  * 
1387  * if no bind took place yet, but the connection is bound
1388  * and the "proxyauthzdn" is set, then bind as "proxyauthzdn" 
1389  * and explicitly add proxyAuthz the control to every operation
1390  * with the dn bound to the connection as control value.
1391  *
1392  * If no server-side controls are defined for the operation,
1393  * simply add the proxyAuthz control; otherwise, if the
1394  * proxyAuthz control is not already set, add it as
1395  * the first one
1396  *
1397  * FIXME: is controls order significant for security?
1398  * ANSWER: controls ordering and interoperability
1399  * must be indicated by the specs of each control; if none
1400  * is specified, the order is irrelevant.
1401  */
1402 int
1403 ldap_back_proxy_authz_ctrl(
1404                 ldapconn_t      *lc,
1405                 Operation       *op,
1406                 SlapReply       *rs,
1407                 LDAPControl     ***pctrls )
1408 {
1409         ldapinfo_t      *li = (ldapinfo_t *) op->o_bd->be_private;
1410         LDAPControl     **ctrls = NULL;
1411         int             i = 0,
1412                         mode;
1413         struct berval   assertedID,
1414                         ndn;
1415
1416         *pctrls = NULL;
1417
1418         rs->sr_err = LDAP_SUCCESS;
1419
1420         /* FIXME: SASL/EXTERNAL over ldapi:// doesn't honor the authcID,
1421          * but if it is not set this test fails.  We need a different
1422          * means to detect if idassert is enabled */
1423         if ( ( BER_BVISNULL( &li->li_idassert_authcID ) || BER_BVISEMPTY( &li->li_idassert_authcID ) )
1424                         && ( BER_BVISNULL( &li->li_idassert_authcDN ) || BER_BVISEMPTY( &li->li_idassert_authcDN ) ) )
1425         {
1426                 goto done;
1427         }
1428
1429         if ( !op->o_conn || op->o_do_not_cache || be_isroot( op ) ) {
1430                 goto done;
1431         }
1432
1433         if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1434                 ndn = op->o_conn->c_ndn;
1435
1436         } else {
1437                 ndn = op->o_ndn;
1438         }
1439
1440         if ( li->li_idassert_mode == LDAP_BACK_IDASSERT_LEGACY ) {
1441                 if ( op->o_proxy_authz ) {
1442                         /*
1443                          * FIXME: we do not want to perform proxyAuthz
1444                          * on behalf of the client, because this would
1445                          * be performed with "proxyauthzdn" privileges.
1446                          *
1447                          * This might actually be too strict, since
1448                          * the "proxyauthzdn" authzTo, and each entry's
1449                          * authzFrom attributes may be crafted
1450                          * to avoid unwanted proxyAuthz to take place.
1451                          */
1452 #if 0
1453                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1454                         rs->sr_text = "proxyAuthz not allowed within namingContext";
1455 #endif
1456                         goto done;
1457                 }
1458
1459                 if ( !BER_BVISNULL( &lc->lc_bound_ndn ) ) {
1460                         goto done;
1461                 }
1462
1463                 if ( BER_BVISNULL( &ndn ) ) {
1464                         goto done;
1465                 }
1466
1467                 if ( BER_BVISNULL( &li->li_idassert_authcDN ) ) {
1468                         goto done;
1469                 }
1470
1471         } else if ( li->li_idassert_authmethod == LDAP_AUTH_SASL ) {
1472                 if ( ( li->li_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ )
1473                                 /* && ( !BER_BVISNULL( &ndn )
1474                                         || LDAP_BACK_CONN_ISBOUND( lc ) ) */ )
1475                 {
1476                         /* already asserted in SASL via native authz */
1477                         /* NOTE: the test on lc->lc_bound is used to trap
1478                          * native authorization of anonymous users,
1479                          * since in that case ndn is NULL */
1480                         goto done;
1481                 }
1482
1483         } else if ( li->li_idassert_authz && !be_isroot( op ) ) {
1484                 int             rc;
1485                 struct berval authcDN;
1486
1487                 if ( BER_BVISNULL( &ndn ) ) {
1488                         authcDN = slap_empty_bv;
1489                 } else {
1490                         authcDN = ndn;
1491                 }
1492                 rc = slap_sasl_matches( op, li->li_idassert_authz,
1493                                 &authcDN, & authcDN );
1494                 if ( rc != LDAP_SUCCESS ) {
1495                         if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE )
1496                         {
1497                                 /* ndn is not authorized
1498                                  * to use idassert */
1499                                 rs->sr_err = rc;
1500                         }
1501                         goto done;
1502                 }
1503         }
1504
1505         if ( op->o_proxy_authz ) {
1506                 /*
1507                  * FIXME: we can:
1508                  * 1) ignore the already set proxyAuthz control
1509                  * 2) leave it in place, and don't set ours
1510                  * 3) add both
1511                  * 4) reject the operation
1512                  *
1513                  * option (4) is very drastic
1514                  * option (3) will make the remote server reject
1515                  * the operation, thus being equivalent to (4)
1516                  * option (2) will likely break the idassert
1517                  * assumptions, so we cannot accept it;
1518                  * option (1) means that we are contradicting
1519                  * the client's reques.
1520                  *
1521                  * I think (4) is the only correct choice.
1522                  */
1523                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1524                 rs->sr_text = "proxyAuthz not allowed within namingContext";
1525         }
1526
1527         if ( op->o_is_auth_check ) {
1528                 mode = LDAP_BACK_IDASSERT_NOASSERT;
1529
1530         } else {
1531                 mode = li->li_idassert_mode;
1532         }
1533
1534         switch ( mode ) {
1535         case LDAP_BACK_IDASSERT_SELF:
1536                 if ( BER_BVISNULL( &ndn ) ) {
1537                         goto done;
1538                 }
1539                 assertedID = ndn;
1540                 break;
1541
1542         case LDAP_BACK_IDASSERT_LEGACY:
1543                 /* original behavior:
1544                  * assert the client's identity */
1545                 if ( BER_BVISNULL( &ndn ) ) {
1546                         assertedID = slap_empty_bv;
1547                 } else {
1548                         assertedID = ndn;
1549                 }
1550                 break;
1551
1552         case LDAP_BACK_IDASSERT_ANONYMOUS:
1553                 /* assert "anonymous" */
1554                 assertedID = slap_empty_bv;
1555                 break;
1556
1557         case LDAP_BACK_IDASSERT_NOASSERT:
1558                 /* don't assert; bind as proxyauthzdn */
1559                 goto done;
1560
1561         case LDAP_BACK_IDASSERT_OTHERID:
1562         case LDAP_BACK_IDASSERT_OTHERDN:
1563                 /* assert idassert DN */
1564                 assertedID = li->li_idassert_authzID;
1565                 break;
1566
1567         default:
1568                 assert( 0 );
1569         }
1570
1571         if ( BER_BVISNULL( &assertedID ) ) {
1572                 assertedID = slap_empty_bv;
1573         }
1574
1575         if ( op->o_ctrls ) {
1576                 for ( i = 0; op->o_ctrls[ i ]; i++ )
1577                         /* just count ctrls */ ;
1578         }
1579
1580         ctrls = op->o_tmpalloc( sizeof( LDAPControl * ) * (i + 2) + sizeof( LDAPControl ),
1581                         op->o_tmpmemctx );
1582         ctrls[ 0 ] = (LDAPControl *)&ctrls[ i + 2 ];
1583         
1584         ctrls[ 0 ]->ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1585         ctrls[ 0 ]->ldctl_iscritical = 1;
1586
1587         switch ( li->li_idassert_mode ) {
1588         /* already in u:ID or dn:DN form */
1589         case LDAP_BACK_IDASSERT_OTHERID:
1590         case LDAP_BACK_IDASSERT_OTHERDN:
1591                 ber_dupbv_x( &ctrls[ 0 ]->ldctl_value, &assertedID, op->o_tmpmemctx );
1592                 break;
1593
1594         /* needs the dn: prefix */
1595         default:
1596                 ctrls[ 0 ]->ldctl_value.bv_len = assertedID.bv_len + STRLENOF( "dn:" );
1597                 ctrls[ 0 ]->ldctl_value.bv_val = op->o_tmpalloc( ctrls[ 0 ]->ldctl_value.bv_len + 1,
1598                                 op->o_tmpmemctx );
1599                 AC_MEMCPY( ctrls[ 0 ]->ldctl_value.bv_val, "dn:", STRLENOF( "dn:" ) );
1600                 AC_MEMCPY( &ctrls[ 0 ]->ldctl_value.bv_val[ STRLENOF( "dn:" ) ],
1601                                 assertedID.bv_val, assertedID.bv_len + 1 );
1602                 break;
1603         }
1604
1605         if ( op->o_ctrls ) {
1606                 for ( i = 0; op->o_ctrls[ i ]; i++ ) {
1607                         ctrls[ i + 1 ] = op->o_ctrls[ i ];
1608                 }
1609         }
1610         ctrls[ i + 1 ] = NULL;
1611
1612 done:;
1613         if ( ctrls == NULL ) {
1614                 ctrls = op->o_ctrls;
1615         }
1616
1617         *pctrls = ctrls;
1618         
1619         return rs->sr_err;
1620 }
1621
1622 int
1623 ldap_back_proxy_authz_ctrl_free( Operation *op, LDAPControl ***pctrls )
1624 {
1625         LDAPControl     **ctrls = *pctrls;
1626
1627         /* we assume that the first control is the proxyAuthz
1628          * added by back-ldap, so it's the only one we explicitly 
1629          * free */
1630         if ( ctrls && ctrls != op->o_ctrls ) {
1631                 assert( ctrls[ 0 ] != NULL );
1632
1633                 if ( !BER_BVISNULL( &ctrls[ 0 ]->ldctl_value ) ) {
1634                         op->o_tmpfree( ctrls[ 0 ]->ldctl_value.bv_val, op->o_tmpmemctx );
1635                 }
1636
1637                 op->o_tmpfree( ctrls, op->o_tmpmemctx );
1638         } 
1639
1640         *pctrls = NULL;
1641
1642         return 0;
1643 }