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