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