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