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