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