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