]> git.sur5r.net Git - openldap/blob - servers/slapd/back-ldap/bind.c
better logging of privileged connections (more to come; might be unstable for a bit)
[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-2009 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 #undef ldap_debug       /* silence a warning in ldap-int.h */
36 #include "../../../libraries/libldap/ldap-int.h"
37
38 #include "lutil_ldap.h"
39
40 #define LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ       "2.16.840.1.113730.3.4.12"
41
42 #if LDAP_BACK_PRINT_CONNTREE > 0
43 static void
44 ldap_back_ravl_print( Avlnode *root, int depth )
45 {
46         int             i;
47         ldapconn_t      *lc;
48         
49         if ( root == 0 ) {
50                 return;
51         }
52         
53         ldap_back_ravl_print( root->avl_right, depth+1 );
54         
55         for ( i = 0; i < depth; i++ ) {
56                 fprintf( stderr, "-" );
57         }
58
59         lc = root->avl_data;
60         fprintf( stderr, "lc=%p local=\"%s\" conn=%p %s refcnt=%d flags=0x%08x\n",
61                 (void *)lc,
62                 lc->lc_local_ndn.bv_val ? lc->lc_local_ndn.bv_val : "",
63                 (void *)lc->lc_conn,
64                 avl_bf2str( root->avl_bf ), lc->lc_refcnt, lc->lc_lcflags );
65         
66         ldap_back_ravl_print( root->avl_left, depth+1 );
67 }
68
69 static char* priv2str[] = {
70         "privileged",
71         "privileged/TLS",
72         "anonymous",
73         "anonymous/TLS",
74         "bind",
75         "bind/TLS",
76         NULL
77 };
78
79 void
80 ldap_back_print_conntree( ldapinfo_t *li, char *msg )
81 {
82         int     c;
83
84         fprintf( stderr, "========> %s\n", msg );
85
86         for ( c = LDAP_BACK_PCONN_FIRST; c < LDAP_BACK_PCONN_LAST; c++ ) {
87                 int             i = 0;
88                 ldapconn_t      *lc;
89
90                 fprintf( stderr, "  %s[%d]\n", priv2str[ c ], li->li_conn_priv[ c ].lic_num );
91
92                 LDAP_TAILQ_FOREACH( lc, &li->li_conn_priv[ c ].lic_priv, lc_q )
93                 {
94                         fprintf( stderr, "    [%d] lc=%p local=\"%s\" conn=%p refcnt=%d flags=0x%08x\n",
95                                 i,
96                                 (void *)lc,
97                                 lc->lc_local_ndn.bv_val ? lc->lc_local_ndn.bv_val : "",
98                                 (void *)lc->lc_conn, lc->lc_refcnt, lc->lc_lcflags );
99                         i++;
100                 }
101         }
102         
103         if ( li->li_conninfo.lai_tree == 0 ) {
104                 fprintf( stderr, "\t(empty)\n" );
105
106         } else {
107                 ldap_back_ravl_print( li->li_conninfo.lai_tree, 0 );
108         }
109         
110         fprintf( stderr, "<======== %s\n", msg );
111 }
112 #endif /* LDAP_BACK_PRINT_CONNTREE */
113
114 static int
115 ldap_back_freeconn( ldapinfo_t *li, ldapconn_t *lc, int dolock );
116
117 static ldapconn_t *
118 ldap_back_getconn( Operation *op, SlapReply *rs, ldap_back_send_t sendok,
119         struct berval *binddn, struct berval *bindcred );
120
121 static int
122 ldap_back_is_proxy_authz( Operation *op, SlapReply *rs, ldap_back_send_t sendok,
123         struct berval *binddn, struct berval *bindcred );
124
125 static int
126 ldap_back_proxy_authz_bind( ldapconn_t *lc, Operation *op, SlapReply *rs,
127         ldap_back_send_t sendok, struct berval *binddn, struct berval *bindcred );
128
129 static int
130 ldap_back_prepare_conn( ldapconn_t *lc, Operation *op, SlapReply *rs,
131         ldap_back_send_t sendok );
132
133 static int
134 ldap_back_conndnlc_cmp( const void *c1, const void *c2 );
135
136 ldapconn_t *
137 ldap_back_conn_delete( ldapinfo_t *li, ldapconn_t *lc )
138 {
139         if ( LDAP_BACK_PCONN_ISPRIV( lc ) ) {
140                 if ( LDAP_BACK_CONN_CACHED( lc ) ) {
141                         assert( lc->lc_q.tqe_prev != NULL );
142                         assert( li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_num > 0 );
143                         li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_num--;
144                         LDAP_TAILQ_REMOVE( &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_priv, lc, lc_q );
145                         LDAP_TAILQ_ENTRY_INIT( lc, lc_q );
146                         LDAP_BACK_CONN_CACHED_CLEAR( lc );
147
148                 } else {
149                         assert( LDAP_BACK_CONN_TAINTED( lc ) );
150                         assert( lc->lc_q.tqe_prev == NULL );
151                 }
152
153         } else {
154                 ldapconn_t      *tmplc = NULL;
155
156                 if ( LDAP_BACK_CONN_CACHED( lc ) ) {
157                         assert( !LDAP_BACK_CONN_TAINTED( lc ) );
158                         tmplc = avl_delete( &li->li_conninfo.lai_tree, (caddr_t)lc,
159                                 ldap_back_conndnlc_cmp );
160                         assert( tmplc == lc );
161                         LDAP_BACK_CONN_CACHED_CLEAR( lc );
162                 }
163
164                 assert( LDAP_BACK_CONN_TAINTED( lc ) || tmplc == lc );
165         }
166
167         return lc;
168 }
169
170 int
171 ldap_back_bind( Operation *op, SlapReply *rs )
172 {
173         ldapinfo_t              *li = (ldapinfo_t *) op->o_bd->be_private;
174         ldapconn_t              *lc;
175
176         LDAPControl             **ctrls = NULL;
177         struct berval           save_o_dn;
178         int                     save_o_do_not_cache,
179                                 rc = 0;
180         ber_int_t               msgid;
181         ldap_back_send_t        retrying = LDAP_BACK_RETRYING;
182
183         /* allow rootdn as a means to auth without the need to actually
184          * contact the proxied DSA */
185         switch ( be_rootdn_bind( op, rs ) ) {
186         case SLAP_CB_CONTINUE:
187                 break;
188
189         default:
190                 return rs->sr_err;
191         }
192
193         lc = ldap_back_getconn( op, rs, LDAP_BACK_BIND_SERR, NULL, NULL );
194         if ( !lc ) {
195                 return rs->sr_err;
196         }
197
198         /* we can do (almost) whatever we want with this conn,
199          * because either it's temporary, or it's marked as binding */
200         if ( !BER_BVISNULL( &lc->lc_bound_ndn ) ) {
201                 ch_free( lc->lc_bound_ndn.bv_val );
202                 BER_BVZERO( &lc->lc_bound_ndn );
203         }
204         if ( !BER_BVISNULL( &lc->lc_cred ) ) {
205                 memset( lc->lc_cred.bv_val, 0, lc->lc_cred.bv_len );
206                 ch_free( lc->lc_cred.bv_val );
207                 BER_BVZERO( &lc->lc_cred );
208         }
209         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
210
211         /* don't add proxyAuthz; set the bindDN */
212         save_o_dn = op->o_dn;
213         save_o_do_not_cache = op->o_do_not_cache;
214         op->o_dn = op->o_req_dn;
215         op->o_do_not_cache = 1;
216
217         ctrls = op->o_ctrls;
218         rc = ldap_back_controls_add( op, rs, lc, &ctrls );
219         op->o_dn = save_o_dn;
220         op->o_do_not_cache = save_o_do_not_cache;
221         if ( rc != LDAP_SUCCESS ) {
222                 send_ldap_result( op, rs );
223                 ldap_back_release_conn( li, lc );
224                 return( rc );
225         }
226
227 retry:;
228         /* method is always LDAP_AUTH_SIMPLE if we got here */
229         rs->sr_err = ldap_sasl_bind( lc->lc_ld, op->o_req_dn.bv_val,
230                         LDAP_SASL_SIMPLE,
231                         &op->orb_cred, ctrls, NULL, &msgid );
232         /* FIXME: should we always retry, or only when piping the bind
233          * in the "override" connection pool? */
234         rc = ldap_back_op_result( lc, op, rs, msgid,
235                 li->li_timeout[ SLAP_OP_BIND ],
236                 LDAP_BACK_BIND_SERR | retrying );
237         if ( rc == LDAP_UNAVAILABLE && retrying ) {
238                 retrying &= ~LDAP_BACK_RETRYING;
239                 if ( ldap_back_retry( &lc, op, rs, LDAP_BACK_BIND_SERR ) ) {
240                         goto retry;
241                 }
242         }
243
244         ldap_back_controls_free( op, rs, &ctrls );
245
246         if ( rc == LDAP_SUCCESS ) {
247                 /* If defined, proxyAuthz will be used also when
248                  * back-ldap is the authorizing backend; for this
249                  * purpose, after a successful bind the connection
250                  * is left for further binds, and further operations 
251                  * on this client connection will use a default
252                  * connection with identity assertion */
253                 /* NOTE: use with care */
254                 if ( li->li_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) {
255                         ldap_back_release_conn( li, lc );
256                         return( rc );
257                 }
258
259                 /* rebind is now done inside ldap_back_proxy_authz_bind()
260                  * in case of success */
261                 LDAP_BACK_CONN_ISBOUND_SET( lc );
262                 ber_dupbv( &lc->lc_bound_ndn, &op->o_req_ndn );
263
264                 if ( !BER_BVISNULL( &lc->lc_cred ) ) {
265                         memset( lc->lc_cred.bv_val, 0,
266                                         lc->lc_cred.bv_len );
267                 }
268
269                 if ( LDAP_BACK_SAVECRED( li ) ) {
270                         ber_bvreplace( &lc->lc_cred, &op->orb_cred );
271                         ldap_set_rebind_proc( lc->lc_ld, li->li_rebind_f, lc );
272
273                 } else {
274                         lc->lc_cred.bv_len = 0;
275                 }
276         }
277
278         /* must re-insert if local DN changed as result of bind */
279         if ( !LDAP_BACK_CONN_ISBOUND( lc )
280                 || ( !dn_match( &op->o_req_ndn, &lc->lc_local_ndn )
281                         && !LDAP_BACK_PCONN_ISPRIV( lc ) ) )
282         {
283                 int             lerr = -1;
284                 ldapconn_t      *tmplc;
285
286                 /* wait for all other ops to release the connection */
287 retry_lock:;
288                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
289                 if ( lc->lc_refcnt > 1 ) {
290                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
291                         ldap_pvt_thread_yield();
292                         goto retry_lock;
293                 }
294
295 #if LDAP_BACK_PRINT_CONNTREE > 0
296                 ldap_back_print_conntree( li, ">>> ldap_back_bind" );
297 #endif /* LDAP_BACK_PRINT_CONNTREE */
298
299                 assert( lc->lc_refcnt == 1 );
300                 ldap_back_conn_delete( li, lc );
301
302                 /* delete all cached connections with the current connection */
303                 if ( LDAP_BACK_SINGLECONN( li ) ) {
304                         while ( ( tmplc = avl_delete( &li->li_conninfo.lai_tree, (caddr_t)lc, ldap_back_conn_cmp ) ) != NULL )
305                         {
306                                 assert( !LDAP_BACK_PCONN_ISPRIV( lc ) );
307                                 Debug( LDAP_DEBUG_TRACE,
308                                         "=>ldap_back_bind: destroying conn %lu (refcnt=%u)\n",
309                                         lc->lc_conn->c_connid, lc->lc_refcnt, 0 );
310
311                                 if ( tmplc->lc_refcnt != 0 ) {
312                                         /* taint it */
313                                         LDAP_BACK_CONN_TAINTED_SET( tmplc );
314                                         LDAP_BACK_CONN_CACHED_CLEAR( tmplc );
315
316                                 } else {
317                                         /*
318                                          * Needs a test because the handler may be corrupted,
319                                          * and calling ldap_unbind on a corrupted header results
320                                          * in a segmentation fault
321                                          */
322                                         ldap_back_conn_free( tmplc );
323                                 }
324                         }
325                 }
326
327                 if ( LDAP_BACK_CONN_ISBOUND( lc ) ) {
328                         ber_bvreplace( &lc->lc_local_ndn, &op->o_req_ndn );
329                         if ( be_isroot_dn( op->o_bd, &op->o_req_ndn ) ) {
330                                 LDAP_BACK_PCONN_ROOTDN_SET( lc, op );
331                         }
332                         lerr = avl_insert( &li->li_conninfo.lai_tree, (caddr_t)lc,
333                                 ldap_back_conndn_cmp, ldap_back_conndn_dup );
334                 }
335
336 #if LDAP_BACK_PRINT_CONNTREE > 0
337                 ldap_back_print_conntree( li, "<<< ldap_back_bind" );
338 #endif /* LDAP_BACK_PRINT_CONNTREE */
339         
340                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
341                 switch ( lerr ) {
342                 case 0:
343                         LDAP_BACK_CONN_CACHED_SET( lc );
344                         break;
345
346                 case -1:
347                         /* duplicate; someone else successfully bound
348                          * on the same connection with the same identity;
349                          * we can do this because lc_refcnt == 1 */
350                         ldap_back_conn_free( lc );
351                         lc = NULL;
352                 }
353         }
354
355         if ( lc != NULL ) {
356                 ldap_back_release_conn( li, lc );
357         }
358
359         return( rc );
360 }
361
362 /*
363  * ldap_back_conndn_cmp
364  *
365  * compares two ldapconn_t based on the value of the conn pointer
366  * and of the local DN; used by avl stuff for insert, lookup
367  * and direct delete
368  */
369 int
370 ldap_back_conndn_cmp( const void *c1, const void *c2 )
371 {
372         const ldapconn_t        *lc1 = (const ldapconn_t *)c1;
373         const ldapconn_t        *lc2 = (const ldapconn_t *)c2;
374         int rc;
375
376         /* If local DNs don't match, it is definitely not a match */
377         /* For shared sessions, conn is NULL. Only explicitly
378          * bound sessions will have non-NULL conn.
379          */
380         rc = SLAP_PTRCMP( lc1->lc_conn, lc2->lc_conn );
381         if ( rc == 0 ) {
382                 rc = ber_bvcmp( &lc1->lc_local_ndn, &lc2->lc_local_ndn );
383         }
384
385         return rc;
386 }
387
388 /*
389  * ldap_back_conndnlc_cmp
390  *
391  * compares two ldapconn_t based on the value of the conn pointer,
392  * the local DN and the lc pointer; used by avl stuff for insert, lookup
393  * and direct delete
394  */
395 static int
396 ldap_back_conndnlc_cmp( const void *c1, const void *c2 )
397 {
398         const ldapconn_t        *lc1 = (const ldapconn_t *)c1;
399         const ldapconn_t        *lc2 = (const ldapconn_t *)c2;
400         int rc;
401
402         /* If local DNs don't match, it is definitely not a match */
403         /* For shared sessions, conn is NULL. Only explicitly
404          * bound sessions will have non-NULL conn.
405          */
406         rc = SLAP_PTRCMP( lc1->lc_conn, lc2->lc_conn );
407         if ( rc == 0 ) {
408                 rc = ber_bvcmp( &lc1->lc_local_ndn, &lc2->lc_local_ndn );
409                 if ( rc == 0 ) {
410                         rc = SLAP_PTRCMP( lc1, lc2 );
411                 }
412         }
413
414         return rc;
415 }
416
417 /*
418  * ldap_back_conn_cmp
419  *
420  * compares two ldapconn_t based on the value of the conn pointer;
421  * used by avl stuff for delete of all conns with the same connid
422  */
423 int
424 ldap_back_conn_cmp( const void *c1, const void *c2 )
425 {
426         const ldapconn_t        *lc1 = (const ldapconn_t *)c1;
427         const ldapconn_t        *lc2 = (const ldapconn_t *)c2;
428
429         /* For shared sessions, conn is NULL. Only explicitly
430          * bound sessions will have non-NULL conn.
431          */
432         return SLAP_PTRCMP( lc1->lc_conn, lc2->lc_conn );
433 }
434
435 /*
436  * ldap_back_conndn_dup
437  *
438  * returns -1 in case a duplicate ldapconn_t has been inserted;
439  * used by avl stuff
440  */
441 int
442 ldap_back_conndn_dup( void *c1, void *c2 )
443 {
444         ldapconn_t      *lc1 = (ldapconn_t *)c1;
445         ldapconn_t      *lc2 = (ldapconn_t *)c2;
446
447         /* Cannot have more than one shared session with same DN */
448         if ( lc1->lc_conn == lc2->lc_conn &&
449                 dn_match( &lc1->lc_local_ndn, &lc2->lc_local_ndn ) )
450         {
451                 return -1;
452         }
453                 
454         return 0;
455 }
456
457 static int
458 ldap_back_freeconn( ldapinfo_t *li, ldapconn_t *lc, int dolock )
459 {
460         if ( dolock ) {
461                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
462         }
463
464 #if LDAP_BACK_PRINT_CONNTREE > 0
465         ldap_back_print_conntree( li, ">>> ldap_back_freeconn" );
466 #endif /* LDAP_BACK_PRINT_CONNTREE */
467
468         (void)ldap_back_conn_delete( li, lc );
469
470         if ( lc->lc_refcnt == 0 ) {
471                 ldap_back_conn_free( (void *)lc );
472         }
473
474 #if LDAP_BACK_PRINT_CONNTREE > 0
475         ldap_back_print_conntree( li, "<<< ldap_back_freeconn" );
476 #endif /* LDAP_BACK_PRINT_CONNTREE */
477
478         if ( dolock ) {
479                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
480         }
481
482         return 0;
483 }
484
485 #ifdef HAVE_TLS
486 static int
487 ldap_back_start_tls(
488         LDAP            *ld,
489         int             protocol,
490         int             *is_tls,
491         const char      *url,
492         unsigned        flags,
493         int             retries,
494         const char      **text )
495 {
496         int             rc = LDAP_SUCCESS;
497
498         /* start TLS ("tls-[try-]{start,propagate}" statements) */
499         if ( ( LDAP_BACK_USE_TLS_F( flags ) || ( *is_tls && LDAP_BACK_PROPAGATE_TLS_F( flags ) ) )
500                                 && !ldap_is_ldaps_url( url ) )
501         {
502 #ifdef SLAP_STARTTLS_ASYNCHRONOUS
503                 /*
504                  * use asynchronous StartTLS
505                  * in case, chase referral (not implemented yet)
506                  */
507                 int             msgid;
508
509                 if ( protocol == 0 ) {
510                         ldap_get_option( ld, LDAP_OPT_PROTOCOL_VERSION,
511                                         (void *)&protocol );
512                 }
513
514                 if ( protocol < LDAP_VERSION3 ) {
515                         /* we should rather bail out... */
516                         rc = LDAP_UNWILLING_TO_PERFORM;
517                         *text = "invalid protocol version";
518                 }
519
520                 if ( rc == LDAP_SUCCESS ) {
521                         rc = ldap_start_tls( ld, NULL, NULL, &msgid );
522                 }
523
524                 if ( rc == LDAP_SUCCESS ) {
525                         LDAPMessage     *res = NULL;
526                         struct timeval  tv;
527
528                         LDAP_BACK_TV_SET( &tv );
529
530 retry:;
531                         rc = ldap_result( ld, msgid, LDAP_MSG_ALL, &tv, &res );
532                         if ( rc < 0 ) {
533                                 rc = LDAP_UNAVAILABLE;
534
535                         } else if ( rc == 0 ) {
536                                 if ( retries != LDAP_BACK_RETRY_NEVER ) {
537                                         ldap_pvt_thread_yield();
538                                         if ( retries > 0 ) {
539                                                 retries--;
540                                         }
541                                         LDAP_BACK_TV_SET( &tv );
542                                         goto retry;
543                                 }
544                                 rc = LDAP_UNAVAILABLE;
545
546                         } else if ( rc == LDAP_RES_EXTENDED ) {
547                                 struct berval   *data = NULL;
548
549                                 rc = ldap_parse_extended_result( ld, res,
550                                                 NULL, &data, 0 );
551                                 if ( rc == LDAP_SUCCESS ) {
552                                         int err;
553                                         rc = ldap_parse_result( ld, res, &err,
554                                                 NULL, NULL, NULL, NULL, 1 );
555                                         if ( rc == LDAP_SUCCESS ) {
556                                                 rc = err;
557                                         }
558                                         res = NULL;
559                                         
560                                         /* FIXME: in case a referral 
561                                          * is returned, should we try
562                                          * using it instead of the 
563                                          * configured URI? */
564                                         if ( rc == LDAP_SUCCESS ) {
565                                                 rc = ldap_install_tls( ld );
566
567                                         } else if ( rc == LDAP_REFERRAL ) {
568                                                 rc = LDAP_UNWILLING_TO_PERFORM;
569                                                 *text = "unwilling to chase referral returned by Start TLS exop";
570                                         }
571
572                                         if ( data ) {
573                                                 if ( data->bv_val ) {
574                                                         ber_memfree( data->bv_val );
575                                                 }
576                                                 ber_memfree( data );
577                                         }
578                                 }
579
580                         } else {
581                                 rc = LDAP_OTHER;
582                         }
583
584                         if ( res != NULL ) {
585                                 ldap_msgfree( res );
586                         }
587                 }
588 #else /* ! SLAP_STARTTLS_ASYNCHRONOUS */
589                 /*
590                  * use synchronous StartTLS
591                  */
592                 rc = ldap_start_tls_s( ld, NULL, NULL );
593 #endif /* ! SLAP_STARTTLS_ASYNCHRONOUS */
594
595                 /* if StartTLS is requested, only attempt it if the URL
596                  * is not "ldaps://"; this may occur not only in case
597                  * of misconfiguration, but also when used in the chain 
598                  * overlay, where the "uri" can be parsed out of a referral */
599                 switch ( rc ) {
600                 case LDAP_SUCCESS:
601                         *is_tls = 1;
602                         break;
603
604                 case LDAP_SERVER_DOWN:
605                         break;
606
607                 default:
608                         if ( LDAP_BACK_TLS_CRITICAL_F( flags ) ) {
609                                 *text = "could not start TLS";
610                                 break;
611                         }
612
613                         /* in case Start TLS is not critical */
614                         *is_tls = 0;
615                         rc = LDAP_SUCCESS;
616                         break;
617                 }
618
619         } else {
620                 *is_tls = 0;
621         }
622
623         return rc;
624 }
625 #endif /* HAVE_TLS */
626
627 static int
628 ldap_back_prepare_conn( ldapconn_t *lc, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
629 {
630         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
631         int             version;
632         LDAP            *ld = NULL;
633 #ifdef HAVE_TLS
634         int             is_tls = op->o_conn->c_is_tls;
635         time_t          lc_time = (time_t)(-1);
636         slap_bindconf *sb;
637 #endif /* HAVE_TLS */
638
639         ldap_pvt_thread_mutex_lock( &li->li_uri_mutex );
640         rs->sr_err = ldap_initialize( &ld, li->li_uri );
641         ldap_pvt_thread_mutex_unlock( &li->li_uri_mutex );
642         if ( rs->sr_err != LDAP_SUCCESS ) {
643                 goto error_return;
644         }
645
646         if ( li->li_urllist_f ) {
647                 ldap_set_urllist_proc( ld, li->li_urllist_f, li->li_urllist_p );
648         }
649
650         /* Set LDAP version. This will always succeed: If the client
651          * bound with a particular version, then so can we.
652          */
653         if ( li->li_version != 0 ) {
654                 version = li->li_version;
655
656         } else if ( op->o_protocol != 0 ) {
657                 version = op->o_protocol;
658
659         } else {
660                 /* assume it's an internal op; set to LDAPv3 */
661                 version = LDAP_VERSION3;
662         }
663         ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, (const void *)&version );
664
665         /* automatically chase referrals ("chase-referrals [{yes|no}]" statement) */
666         ldap_set_option( ld, LDAP_OPT_REFERRALS,
667                 LDAP_BACK_CHASE_REFERRALS( li ) ? LDAP_OPT_ON : LDAP_OPT_OFF );
668
669         if ( li->li_network_timeout > 0 ) {
670                 struct timeval          tv;
671
672                 tv.tv_sec = li->li_network_timeout;
673                 tv.tv_usec = 0;
674                 ldap_set_option( ld, LDAP_OPT_NETWORK_TIMEOUT, (const void *)&tv );
675         }
676
677 #ifdef HAVE_TLS
678         if ( LDAP_BACK_CONN_ISPRIV( lc ) ) {
679                 sb = &li->li_acl;
680
681         } else if ( LDAP_BACK_CONN_ISIDASSERT( lc ) ) {
682                 sb = &li->li_idassert.si_bc;
683
684         } else {
685                 sb = &li->li_tls;
686         }
687
688         if ( sb->sb_tls_do_init ) {
689                 bindconf_tls_set( sb, ld );
690         } else if ( sb->sb_tls_ctx ) {
691                 ldap_set_option( ld, LDAP_OPT_X_TLS_CTX, sb->sb_tls_ctx );
692         }
693
694         ldap_pvt_thread_mutex_lock( &li->li_uri_mutex );
695         assert( li->li_uri_mutex_do_not_lock == 0 );
696         li->li_uri_mutex_do_not_lock = 1;
697         rs->sr_err = ldap_back_start_tls( ld, op->o_protocol, &is_tls,
698                         li->li_uri, li->li_flags, li->li_nretries, &rs->sr_text );
699         li->li_uri_mutex_do_not_lock = 0;
700         ldap_pvt_thread_mutex_unlock( &li->li_uri_mutex );
701         if ( rs->sr_err != LDAP_SUCCESS ) {
702                 ldap_unbind_ext( ld, NULL, NULL );
703                 rs->sr_text = "Start TLS failed";
704                 goto error_return;
705
706         } else if ( li->li_idle_timeout ) {
707                 /* only touch when activity actually took place... */
708                 lc_time = op->o_time;
709         }
710 #endif /* HAVE_TLS */
711
712         lc->lc_ld = ld;
713         lc->lc_refcnt = 1;
714 #ifdef HAVE_TLS
715         if ( is_tls ) {
716                 LDAP_BACK_CONN_ISTLS_SET( lc );
717         } else {
718                 LDAP_BACK_CONN_ISTLS_CLEAR( lc );
719         }
720         if ( lc_time != (time_t)(-1) ) {
721                 lc->lc_time = lc_time;
722         }
723 #endif /* HAVE_TLS */
724
725 error_return:;
726         if ( rs->sr_err != LDAP_SUCCESS ) {
727                 rs->sr_err = slap_map_api2result( rs );
728                 if ( sendok & LDAP_BACK_SENDERR ) {
729                         if ( rs->sr_text == NULL ) {
730                                 rs->sr_text = "Proxy connection initialization failed";
731                         }
732                         send_ldap_result( op, rs );
733                 }
734
735         } else {
736                 if ( li->li_conn_ttl > 0 ) {
737                         lc->lc_create_time = op->o_time;
738                 }
739         }
740
741         return rs->sr_err;
742 }
743
744 static ldapconn_t *
745 ldap_back_getconn(
746         Operation               *op,
747         SlapReply               *rs,
748         ldap_back_send_t        sendok,
749         struct berval           *binddn,
750         struct berval           *bindcred )
751 {
752         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
753         ldapconn_t      *lc = NULL,
754                         lc_curr = { 0 };
755         int             refcnt = 1,
756                         lookupconn = !( sendok & LDAP_BACK_BINDING );
757
758         /* if the server is quarantined, and
759          * - the current interval did not expire yet, or
760          * - no more retries should occur,
761          * don't return the connection */
762         if ( li->li_isquarantined ) {
763                 slap_retry_info_t       *ri = &li->li_quarantine;
764                 int                     dont_retry = 1;
765
766                 if ( li->li_quarantine.ri_interval ) {
767                         ldap_pvt_thread_mutex_lock( &li->li_quarantine_mutex );
768                         if ( li->li_isquarantined == LDAP_BACK_FQ_YES ) {
769                                 dont_retry = ( ri->ri_num[ ri->ri_idx ] == SLAP_RETRYNUM_TAIL
770                                         || slap_get_time() < ri->ri_last + ri->ri_interval[ ri->ri_idx ] );
771                                 if ( !dont_retry ) {
772                                         Debug( LDAP_DEBUG_ANY,
773                                                 "%s: ldap_back_getconn quarantine "
774                                                 "retry block #%d try #%d.\n",
775                                                 op->o_log_prefix, ri->ri_idx, ri->ri_count );
776                                         li->li_isquarantined = LDAP_BACK_FQ_RETRYING;
777                                 }
778                         }
779                         ldap_pvt_thread_mutex_unlock( &li->li_quarantine_mutex );
780                 }
781
782                 if ( dont_retry ) {
783                         rs->sr_err = LDAP_UNAVAILABLE;
784                         if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
785                                 rs->sr_text = "Target is quarantined";
786                                 send_ldap_result( op, rs );
787                         }
788                         return NULL;
789                 }
790         }
791
792         /* Internal searches are privileged and shared. So is root. */
793         if ( op->o_do_not_cache || be_isroot( op ) ) {
794                 LDAP_BACK_CONN_ISPRIV_SET( &lc_curr );
795                 lc_curr.lc_local_ndn = op->o_bd->be_rootndn;
796                 LDAP_BACK_PCONN_ROOTDN_SET( &lc_curr, op );
797
798         } else {
799                 struct berval   tmpbinddn,
800                                 tmpbindcred,
801                                 save_o_dn,
802                                 save_o_ndn;
803                 int             isproxyauthz;
804
805                 /* need cleanup */
806                 if ( binddn == NULL ) {
807                         binddn = &tmpbinddn;
808                 }       
809                 if ( bindcred == NULL ) {
810                         bindcred = &tmpbindcred;
811                 }
812                 if ( op->o_tag == LDAP_REQ_BIND ) {
813                         save_o_dn = op->o_dn;
814                         save_o_ndn = op->o_ndn;
815                         op->o_dn = op->o_req_dn;
816                         op->o_ndn = op->o_req_ndn;
817                 }
818                 isproxyauthz = ldap_back_is_proxy_authz( op, rs, sendok, binddn, bindcred );
819                 if ( op->o_tag == LDAP_REQ_BIND ) {
820                         op->o_dn = save_o_dn;
821                         op->o_ndn = save_o_ndn;
822                 }
823                 if ( isproxyauthz == -1 ) {
824                         return NULL;
825                 }
826
827                 lc_curr.lc_local_ndn = op->o_ndn;
828                 /* Explicit binds must not be shared;
829                  * however, explicit binds are piped in a special connection
830                  * when idassert is to occur with "override" set */
831                 if ( op->o_tag == LDAP_REQ_BIND && !isproxyauthz ) {
832                         lc_curr.lc_conn = op->o_conn;
833
834                 } else {
835                         if ( isproxyauthz && !( sendok & LDAP_BACK_BINDING ) ) {
836                                 lc_curr.lc_local_ndn = *binddn;
837                                 LDAP_BACK_PCONN_ROOTDN_SET( &lc_curr, op );
838                                 LDAP_BACK_CONN_ISIDASSERT_SET( &lc_curr );
839
840                         } else if ( isproxyauthz && ( li->li_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) ) {
841                                 lc_curr.lc_local_ndn = slap_empty_bv;
842                                 LDAP_BACK_PCONN_BIND_SET( &lc_curr, op );
843                                 LDAP_BACK_CONN_ISIDASSERT_SET( &lc_curr );
844                                 lookupconn = 1;
845
846                         } else if ( SLAP_IS_AUTHZ_BACKEND( op ) ) {
847                                 lc_curr.lc_conn = op->o_conn;
848
849                         } else {
850                                 LDAP_BACK_PCONN_ANON_SET( &lc_curr, op );
851                         }
852                 }
853         }
854
855         /* Explicit Bind requests always get their own conn */
856         if ( lookupconn ) {
857 retry_lock:
858                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
859                 if ( LDAP_BACK_PCONN_ISPRIV( &lc_curr ) ) {
860                         /* lookup a conn that's not binding */
861                         LDAP_TAILQ_FOREACH( lc,
862                                 &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( &lc_curr ) ].lic_priv,
863                                 lc_q )
864                         {
865                                 if ( !LDAP_BACK_CONN_BINDING( lc ) && lc->lc_refcnt == 0 ) {
866                                         break;
867                                 }
868                         }
869
870                         if ( lc != NULL ) {
871                                 if ( lc != LDAP_TAILQ_LAST( &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_priv,
872                                         ldapconn_t, lc_q ) )
873                                 {
874                                         LDAP_TAILQ_REMOVE( &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_priv,
875                                                 lc, lc_q );
876                                         LDAP_TAILQ_ENTRY_INIT( lc, lc_q );
877                                         LDAP_TAILQ_INSERT_TAIL( &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_priv,
878                                                 lc, lc_q );
879                                 }
880
881                         } else if ( !LDAP_BACK_USE_TEMPORARIES( li )
882                                 && li->li_conn_priv[ LDAP_BACK_CONN2PRIV( &lc_curr ) ].lic_num == li->li_conn_priv_max )
883                         {
884                                 lc = LDAP_TAILQ_FIRST( &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( &lc_curr ) ].lic_priv );
885                         }
886                         
887                 } else {
888
889                         /* Searches for a ldapconn in the avl tree */
890                         lc = (ldapconn_t *)avl_find( li->li_conninfo.lai_tree, 
891                                         (caddr_t)&lc_curr, ldap_back_conndn_cmp );
892                 }
893
894                 if ( lc != NULL ) {
895                         /* Don't reuse connections while they're still binding */
896                         if ( LDAP_BACK_CONN_BINDING( lc ) ) {
897                                 if ( !LDAP_BACK_USE_TEMPORARIES( li ) ) {
898                                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
899
900                                         ldap_pvt_thread_yield();
901                                         goto retry_lock;
902                                 }
903                                 lc = NULL;
904                         }
905
906                         if ( lc != NULL ) {
907                                 if ( op->o_tag == LDAP_REQ_BIND ) {
908                                         /* right now, this is the only possible case */
909                                         assert( ( li->li_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) );
910                                         LDAP_BACK_CONN_BINDING_SET( lc );
911                                 }
912
913                                 refcnt = ++lc->lc_refcnt;
914                         }
915                 }
916                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
917         }
918
919         /* Looks like we didn't get a bind. Open a new session... */
920         if ( lc == NULL ) {
921                 lc = (ldapconn_t *)ch_calloc( 1, sizeof( ldapconn_t ) );
922                 lc->lc_flags = li->li_flags;
923                 lc->lc_lcflags = lc_curr.lc_lcflags;
924                 if ( ldap_back_prepare_conn( lc, op, rs, sendok ) != LDAP_SUCCESS ) {
925                         ch_free( lc );
926                         return NULL;
927                 }
928
929                 if ( sendok & LDAP_BACK_BINDING ) {
930                         LDAP_BACK_CONN_BINDING_SET( lc );
931                 }
932
933                 lc->lc_conn = lc_curr.lc_conn;
934                 ber_dupbv( &lc->lc_local_ndn, &lc_curr.lc_local_ndn );
935
936                 /*
937                  * the rationale is: connections as the rootdn are privileged,
938                  * so acl_authcDN is to be used; however, in some cases
939                  * one already configured identity assertion with a highly
940                  * privileged idassert_authcDN, so if acl_authcDN is NULL
941                  * and idassert_authcDN is not, use the second instead.
942                  *
943                  * might change in the future, because it's preferable
944                  * to make clear what identity is being used, since
945                  * the only drawback is that one risks to configure
946                  * the same identity twice...
947                  */
948                 if ( LDAP_BACK_CONN_ISPRIV( &lc_curr ) ) {
949                         if ( BER_BVISNULL( &li->li_acl_authcDN ) && !BER_BVISNULL( &li->li_idassert_authcDN ) ) {
950                                 ber_dupbv( &lc->lc_bound_ndn, &li->li_idassert_authcDN );
951                                 ber_dupbv( &lc->lc_cred, &li->li_idassert_passwd );
952
953                         } else {
954                                 ber_dupbv( &lc->lc_bound_ndn, &li->li_acl_authcDN );
955                                 ber_dupbv( &lc->lc_cred, &li->li_acl_passwd );
956                         }
957                         LDAP_BACK_CONN_ISPRIV_SET( lc );
958
959                 } else if ( LDAP_BACK_CONN_ISIDASSERT( &lc_curr ) ) {
960                         if ( !LDAP_BACK_PCONN_ISBIND( &lc_curr ) ) {
961                                 ber_dupbv( &lc->lc_bound_ndn, &li->li_idassert_authcDN );
962                                 ber_dupbv( &lc->lc_cred, &li->li_idassert_passwd );
963                         }
964                         LDAP_BACK_CONN_ISIDASSERT_SET( lc );
965
966                 } else {
967                         BER_BVZERO( &lc->lc_cred );
968                         BER_BVZERO( &lc->lc_bound_ndn );
969                         if ( !BER_BVISEMPTY( &op->o_ndn )
970                                 && SLAP_IS_AUTHZ_BACKEND( op ) )
971                         {
972                                 ber_dupbv( &lc->lc_bound_ndn, &op->o_ndn );
973                         }
974                 }
975
976 #ifdef HAVE_TLS
977                 /* if start TLS failed but it was not mandatory,
978                  * check if the non-TLS connection was already
979                  * in cache; in case, destroy the newly created
980                  * connection and use the existing one */
981                 if ( LDAP_BACK_PCONN_ISTLS( lc ) 
982                                 && !ldap_tls_inplace( lc->lc_ld ) )
983                 {
984                         ldapconn_t      *tmplc = NULL;
985                         int             idx = LDAP_BACK_CONN2PRIV( &lc_curr ) - 1;
986                         
987                         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
988                         LDAP_TAILQ_FOREACH( tmplc,
989                                 &li->li_conn_priv[ idx ].lic_priv,
990                                 lc_q )
991                         {
992                                 if ( !LDAP_BACK_CONN_BINDING( tmplc ) ) {
993                                         break;
994                                 }
995                         }
996
997                         if ( tmplc != NULL ) {
998                                 refcnt = ++tmplc->lc_refcnt;
999                                 ldap_back_conn_free( lc );
1000                                 lc = tmplc;
1001                         }
1002                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1003
1004                         if ( tmplc != NULL ) {
1005                                 goto done;
1006                         }
1007                 }
1008 #endif /* HAVE_TLS */
1009
1010                 /* Inserts the newly created ldapconn in the avl tree */
1011                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1012
1013                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1014
1015                 assert( lc->lc_refcnt == 1 );
1016
1017 #if LDAP_BACK_PRINT_CONNTREE > 0
1018                 ldap_back_print_conntree( li, ">>> ldap_back_getconn(insert)" );
1019 #endif /* LDAP_BACK_PRINT_CONNTREE */
1020         
1021                 if ( LDAP_BACK_PCONN_ISPRIV( lc ) ) {
1022                         if ( li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_num < li->li_conn_priv_max ) {
1023                                 LDAP_TAILQ_INSERT_TAIL( &li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_priv, lc, lc_q );
1024                                 li->li_conn_priv[ LDAP_BACK_CONN2PRIV( lc ) ].lic_num++;
1025                                 LDAP_BACK_CONN_CACHED_SET( lc );
1026
1027                         } else {
1028                                 LDAP_BACK_CONN_TAINTED_SET( lc );
1029                         }
1030                         rs->sr_err = 0;
1031
1032                 } else {
1033                         rs->sr_err = avl_insert( &li->li_conninfo.lai_tree, (caddr_t)lc,
1034                                 ldap_back_conndn_cmp, ldap_back_conndn_dup );
1035                         LDAP_BACK_CONN_CACHED_SET( lc );
1036                 }
1037
1038 #if LDAP_BACK_PRINT_CONNTREE > 0
1039                 ldap_back_print_conntree( li, "<<< ldap_back_getconn(insert)" );
1040 #endif /* LDAP_BACK_PRINT_CONNTREE */
1041         
1042                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1043
1044                 if ( LogTest( LDAP_DEBUG_TRACE ) ) {
1045                         char    buf[ SLAP_TEXT_BUFLEN ];
1046
1047                         snprintf( buf, sizeof( buf ),
1048                                 "lc=%p inserted refcnt=%u rc=%d",
1049                                 (void *)lc, refcnt, rs->sr_err );
1050                                 
1051                         Debug( LDAP_DEBUG_TRACE,
1052                                 "=>ldap_back_getconn: %s: %s\n",
1053                                 op->o_log_prefix, buf, 0 );
1054                 }
1055         
1056                 if ( !LDAP_BACK_PCONN_ISPRIV( lc ) ) {
1057                         /* Err could be -1 in case a duplicate ldapconn is inserted */
1058                         switch ( rs->sr_err ) {
1059                         case 0:
1060                                 break;
1061
1062                         case -1:
1063                                 LDAP_BACK_CONN_CACHED_CLEAR( lc );
1064                                 if ( !( sendok & LDAP_BACK_BINDING ) && !LDAP_BACK_USE_TEMPORARIES( li ) ) {
1065                                         /* duplicate: free and try to get the newly created one */
1066                                         ldap_back_conn_free( lc );
1067                                         lc = NULL;
1068                                         goto retry_lock;
1069                                 }
1070
1071                                 /* taint connection, so that it'll be freed when released */
1072                                 LDAP_BACK_CONN_TAINTED_SET( lc );
1073                                 break;
1074
1075                         default:
1076                                 LDAP_BACK_CONN_CACHED_CLEAR( lc );
1077                                 ldap_back_conn_free( lc );
1078                                 rs->sr_err = LDAP_OTHER;
1079                                 rs->sr_text = "Proxy bind collision";
1080                                 if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
1081                                         send_ldap_result( op, rs );
1082                                 }
1083                                 return NULL;
1084                         }
1085                 }
1086
1087         } else {
1088                 int     expiring = 0;
1089
1090                 if ( ( li->li_idle_timeout != 0 && op->o_time > lc->lc_time + li->li_idle_timeout )
1091                         || ( li->li_conn_ttl != 0 && op->o_time > lc->lc_create_time + li->li_conn_ttl ) )
1092                 {
1093                         expiring = 1;
1094
1095                         /* let it be used, but taint/delete it so that 
1096                          * no-one else can look it up any further */
1097                         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1098
1099 #if LDAP_BACK_PRINT_CONNTREE > 0
1100                         ldap_back_print_conntree( li, ">>> ldap_back_getconn(timeout)" );
1101 #endif /* LDAP_BACK_PRINT_CONNTREE */
1102
1103                         (void)ldap_back_conn_delete( li, lc );
1104                         LDAP_BACK_CONN_TAINTED_SET( lc );
1105
1106 #if LDAP_BACK_PRINT_CONNTREE > 0
1107                         ldap_back_print_conntree( li, "<<< ldap_back_getconn(timeout)" );
1108 #endif /* LDAP_BACK_PRINT_CONNTREE */
1109
1110                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1111                 }
1112
1113                 if ( LogTest( LDAP_DEBUG_TRACE ) ) {
1114                         char    buf[ SLAP_TEXT_BUFLEN ];
1115
1116                         snprintf( buf, sizeof( buf ),
1117                                 "conn %p fetched refcnt=%u%s",
1118                                 (void *)lc, refcnt,
1119                                 expiring ? " expiring" : "" );
1120                         Debug( LDAP_DEBUG_TRACE,
1121                                 "=>ldap_back_getconn: %s.\n", buf, 0, 0 );
1122                 }
1123         }
1124
1125 #ifdef HAVE_TLS
1126 done:;
1127 #endif /* HAVE_TLS */
1128
1129         return lc;
1130 }
1131
1132 void
1133 ldap_back_release_conn_lock(
1134         ldapinfo_t              *li,
1135         ldapconn_t              **lcp,
1136         int                     dolock )
1137 {
1138
1139         ldapconn_t      *lc = *lcp;
1140
1141         if ( dolock ) {
1142                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1143         }
1144         assert( lc->lc_refcnt > 0 );
1145         LDAP_BACK_CONN_BINDING_CLEAR( lc );
1146         lc->lc_refcnt--;
1147         if ( LDAP_BACK_CONN_TAINTED( lc ) ) {
1148                 ldap_back_freeconn( li, lc, 0 );
1149                 *lcp = NULL;
1150         }
1151         if ( dolock ) {
1152                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1153         }
1154 }
1155
1156 void
1157 ldap_back_quarantine(
1158         Operation       *op,
1159         SlapReply       *rs )
1160 {
1161         ldapinfo_t              *li = (ldapinfo_t *)op->o_bd->be_private;
1162
1163         slap_retry_info_t       *ri = &li->li_quarantine;
1164
1165         ldap_pvt_thread_mutex_lock( &li->li_quarantine_mutex );
1166
1167         if ( rs->sr_err == LDAP_UNAVAILABLE ) {
1168                 time_t          new_last = slap_get_time();
1169
1170                 switch ( li->li_isquarantined ) {
1171                 case LDAP_BACK_FQ_NO:
1172                         if ( ri->ri_last == new_last ) {
1173                                 goto done;
1174                         }
1175
1176                         Debug( LDAP_DEBUG_ANY,
1177                                 "%s: ldap_back_quarantine enter.\n",
1178                                 op->o_log_prefix, 0, 0 );
1179
1180                         ri->ri_idx = 0;
1181                         ri->ri_count = 0;
1182                         break;
1183
1184                 case LDAP_BACK_FQ_RETRYING:
1185                         Debug( LDAP_DEBUG_ANY,
1186                                 "%s: ldap_back_quarantine block #%d try #%d failed.\n",
1187                                 op->o_log_prefix, ri->ri_idx, ri->ri_count );
1188
1189                         ++ri->ri_count;
1190                         if ( ri->ri_num[ ri->ri_idx ] != SLAP_RETRYNUM_FOREVER
1191                                 && ri->ri_count == ri->ri_num[ ri->ri_idx ] )
1192                         {
1193                                 ri->ri_count = 0;
1194                                 ++ri->ri_idx;
1195                         }
1196                         break;
1197
1198                 default:
1199                         break;
1200                 }
1201
1202                 li->li_isquarantined = LDAP_BACK_FQ_YES;
1203                 ri->ri_last = new_last;
1204
1205         } else if ( li->li_isquarantined != LDAP_BACK_FQ_NO ) {
1206                 if ( ri->ri_last == slap_get_time() ) {
1207                         goto done;
1208                 }
1209
1210                 Debug( LDAP_DEBUG_ANY,
1211                         "%s: ldap_back_quarantine exit (%d) err=%d.\n",
1212                         op->o_log_prefix, li->li_isquarantined, rs->sr_err );
1213
1214                 if ( li->li_quarantine_f ) {
1215                         (void)li->li_quarantine_f( li, li->li_quarantine_p );
1216                 }
1217
1218                 ri->ri_count = 0;
1219                 ri->ri_idx = 0;
1220                 li->li_isquarantined = LDAP_BACK_FQ_NO;
1221         }
1222
1223 done:;
1224         ldap_pvt_thread_mutex_unlock( &li->li_quarantine_mutex );
1225 }
1226
1227 static int
1228 ldap_back_dobind_cb(
1229         Operation *op,
1230         SlapReply *rs
1231 )
1232 {
1233         ber_tag_t *tptr = op->o_callback->sc_private;
1234         op->o_tag = *tptr;
1235         rs->sr_tag = slap_req2res( op->o_tag );
1236
1237         return SLAP_CB_CONTINUE;
1238 }
1239
1240 /*
1241  * ldap_back_dobind_int
1242  *
1243  * Note: dolock indicates whether li->li_conninfo.lai_mutex must be locked or not
1244  */
1245 static int
1246 ldap_back_dobind_int(
1247         ldapconn_t              **lcp,
1248         Operation               *op,
1249         SlapReply               *rs,
1250         ldap_back_send_t        sendok,
1251         int                     retries,
1252         int                     dolock )
1253 {       
1254         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1255
1256         ldapconn_t      *lc;
1257         struct berval   binddn = slap_empty_bv,
1258                         bindcred = slap_empty_bv;
1259
1260         int             rc = 0,
1261                         isbound,
1262                         binding = 0;
1263         ber_int_t       msgid;
1264         ber_tag_t       o_tag = op->o_tag;
1265         slap_callback cb = {0};
1266
1267         assert( lcp != NULL );
1268         assert( retries >= 0 );
1269
1270         if ( sendok & LDAP_BACK_GETCONN ) {
1271                 assert( *lcp == NULL );
1272
1273                 lc = ldap_back_getconn( op, rs, sendok, &binddn, &bindcred );
1274                 if ( lc == NULL ) {
1275                         return 0;
1276                 }
1277                 *lcp = lc;
1278
1279         } else {
1280                 lc = *lcp;
1281         }
1282
1283         assert( lc != NULL );
1284
1285 retry_lock:;
1286         if ( dolock ) {
1287                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1288         }
1289
1290         if ( binding == 0 ) {
1291                 /* check if already bound */
1292                 rc = isbound = LDAP_BACK_CONN_ISBOUND( lc );
1293                 if ( isbound ) {
1294                         if ( dolock ) {
1295                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1296                         }
1297                         return rc;
1298                 }
1299
1300                 if ( LDAP_BACK_CONN_BINDING( lc ) ) {
1301                         /* if someone else is about to bind it, give up and retry */
1302                         if ( dolock ) {
1303                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1304                         }
1305                         ldap_pvt_thread_yield();
1306                         goto retry_lock;
1307
1308                 } else {
1309                         /* otherwise this thread will bind it */
1310                         LDAP_BACK_CONN_BINDING_SET( lc );
1311                         binding = 1;
1312                 }
1313         }
1314
1315         if ( dolock ) {
1316                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1317         }
1318
1319         /*
1320          * FIXME: we need to let clients use proxyAuthz
1321          * otherwise we cannot do symmetric pools of servers;
1322          * we have to live with the fact that a user can
1323          * authorize itself as any ID that is allowed
1324          * by the authzTo directive of the "proxyauthzdn".
1325          */
1326         /*
1327          * NOTE: current Proxy Authorization specification
1328          * and implementation do not allow proxy authorization
1329          * control to be provided with Bind requests
1330          */
1331         /*
1332          * if no bind took place yet, but the connection is bound
1333          * and the "idassert-authcDN" (or other ID) is set, 
1334          * then bind as the asserting identity and explicitly 
1335          * add the proxyAuthz control to every operation with the
1336          * dn bound to the connection as control value.
1337          * This is done also if this is the authorizing backend,
1338          * but the "override" flag is given to idassert.
1339          * It allows to use SASL bind and yet proxyAuthz users
1340          */
1341         op->o_tag = LDAP_REQ_BIND;
1342         cb.sc_next = op->o_callback;
1343         cb.sc_private = &o_tag;
1344         cb.sc_response = ldap_back_dobind_cb;
1345         op->o_callback = &cb;
1346
1347         if ( LDAP_BACK_CONN_ISIDASSERT( lc ) ) {
1348                 if ( BER_BVISEMPTY( &binddn ) && BER_BVISEMPTY( &bindcred ) ) {
1349                         /* if we got here, it shouldn't return result */
1350                         rc = ldap_back_is_proxy_authz( op, rs,
1351                                 LDAP_BACK_DONTSEND, &binddn, &bindcred );
1352                         assert( rc == 1 );
1353                 }
1354                 rc = ldap_back_proxy_authz_bind( lc, op, rs, sendok, &binddn, &bindcred );
1355                 goto done;
1356         }
1357
1358 #ifdef HAVE_CYRUS_SASL
1359         if ( LDAP_BACK_CONN_ISPRIV( lc )
1360                 && li->li_acl_authmethod == LDAP_AUTH_SASL )
1361         {
1362                 void            *defaults = NULL;
1363
1364                 if ( li->li_acl_secprops != NULL ) {
1365                         rc = ldap_set_option( lc->lc_ld,
1366                                 LDAP_OPT_X_SASL_SECPROPS, li->li_acl_secprops );
1367
1368                         if ( rc != LDAP_OPT_SUCCESS ) {
1369                                 Debug( LDAP_DEBUG_ANY, "Error: ldap_set_option "
1370                                         "(SECPROPS,\"%s\") failed!\n",
1371                                         li->li_acl_secprops, 0, 0 );
1372                                 goto done;
1373                         }
1374                 }
1375
1376                 defaults = lutil_sasl_defaults( lc->lc_ld,
1377                                 li->li_acl_sasl_mech.bv_val,
1378                                 li->li_acl_sasl_realm.bv_val,
1379                                 li->li_acl_authcID.bv_val,
1380                                 li->li_acl_passwd.bv_val,
1381                                 NULL );
1382                 if ( defaults == NULL ) {
1383                         rs->sr_err = LDAP_OTHER;
1384                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1385                         if ( sendok & LDAP_BACK_SENDERR ) {
1386                                 send_ldap_result( op, rs );
1387                         }
1388                         goto done;
1389                 }
1390
1391                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld,
1392                                 li->li_acl_authcDN.bv_val,
1393                                 li->li_acl_sasl_mech.bv_val, NULL, NULL,
1394                                 LDAP_SASL_QUIET, lutil_sasl_interact,
1395                                 defaults );
1396
1397                 lutil_sasl_freedefs( defaults );
1398
1399                 switch ( rs->sr_err ) {
1400                 case LDAP_SUCCESS:
1401                         LDAP_BACK_CONN_ISBOUND_SET( lc );
1402                         break;
1403
1404                 case LDAP_LOCAL_ERROR:
1405                         /* list client API error codes that require
1406                          * to taint the connection */
1407                         /* FIXME: should actually retry? */
1408                         LDAP_BACK_CONN_TAINTED_SET( lc );
1409
1410                         /* fallthru */
1411
1412                 default:
1413                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1414                         rs->sr_err = slap_map_api2result( rs );
1415                         if ( sendok & LDAP_BACK_SENDERR ) {
1416                                 send_ldap_result( op, rs );
1417                         }
1418                         break;
1419                 }
1420
1421                 if ( LDAP_BACK_QUARANTINE( li ) ) {
1422                         ldap_back_quarantine( op, rs );
1423                 }
1424
1425                 goto done;
1426         }
1427 #endif /* HAVE_CYRUS_SASL */
1428
1429 retry:;
1430         rs->sr_err = ldap_sasl_bind( lc->lc_ld,
1431                         BER_BVISNULL( &lc->lc_cred ) ? "" : lc->lc_bound_ndn.bv_val,
1432                         LDAP_SASL_SIMPLE, &lc->lc_cred,
1433                         NULL, NULL, &msgid );
1434
1435         if ( rs->sr_err == LDAP_SERVER_DOWN ) {
1436                 if ( retries != LDAP_BACK_RETRY_NEVER ) {
1437                         if ( dolock ) {
1438                                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1439                         }
1440
1441                         assert( lc->lc_refcnt > 0 );
1442                         if ( lc->lc_refcnt == 1 ) {
1443                                 ldap_unbind_ext( lc->lc_ld, NULL, NULL );
1444                                 lc->lc_ld = NULL;
1445
1446                                 /* lc here must be the regular lc, reset and ready for init */
1447                                 rs->sr_err = ldap_back_prepare_conn( lc, op, rs, sendok );
1448                                 if ( rs->sr_err != LDAP_SUCCESS ) {
1449                                         sendok &= ~LDAP_BACK_SENDERR;
1450                                         lc->lc_refcnt = 0;
1451                                 }
1452                         }
1453
1454                         if ( dolock ) {
1455                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1456                         }
1457
1458                         if ( rs->sr_err == LDAP_SUCCESS ) {
1459                                 if ( retries > 0 ) {
1460                                         retries--;
1461                                 }
1462                                 goto retry;
1463                         }
1464                 }
1465
1466                 assert( lc->lc_refcnt == 1 );
1467                 lc->lc_refcnt = 0;
1468                 ldap_back_freeconn( li, lc, dolock );
1469                 *lcp = NULL;
1470                 rs->sr_err = slap_map_api2result( rs );
1471
1472                 if ( LDAP_BACK_QUARANTINE( li ) ) {
1473                         ldap_back_quarantine( op, rs );
1474                 }
1475
1476                 if ( rs->sr_err != LDAP_SUCCESS &&
1477                         ( sendok & LDAP_BACK_SENDERR ) )
1478                 {
1479                         if ( op->o_callback == &cb )
1480                                 op->o_callback = cb.sc_next;
1481                         op->o_tag = o_tag;
1482                         rs->sr_text = "Proxy can't contact remote server";
1483                         send_ldap_result( op, rs );
1484                 }
1485
1486                 rc = 0;
1487                 goto func_leave;
1488         }
1489
1490         rc = ldap_back_op_result( lc, op, rs, msgid,
1491                 -1, ( sendok | LDAP_BACK_BINDING ) );
1492         if ( rc == LDAP_SUCCESS ) {
1493                 LDAP_BACK_CONN_ISBOUND_SET( lc );
1494         }
1495
1496 done:;
1497         LDAP_BACK_CONN_BINDING_CLEAR( lc );
1498         rc = LDAP_BACK_CONN_ISBOUND( lc );
1499         if ( !rc ) {
1500                 ldap_back_release_conn_lock( li, lcp, dolock );
1501
1502         } else if ( LDAP_BACK_SAVECRED( li ) ) {
1503                 ldap_set_rebind_proc( lc->lc_ld, li->li_rebind_f, lc );
1504         }
1505
1506 func_leave:;
1507         if ( op->o_callback == &cb )
1508                 op->o_callback = cb.sc_next;
1509         op->o_tag = o_tag;
1510
1511         return rc;
1512 }
1513
1514 /*
1515  * ldap_back_dobind
1516  *
1517  * Note: dolock indicates whether li->li_conninfo.lai_mutex must be locked or not
1518  */
1519 int
1520 ldap_back_dobind( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1521 {
1522         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1523
1524         return ldap_back_dobind_int( lcp, op, rs,
1525                 ( sendok | LDAP_BACK_GETCONN ), li->li_nretries, 1 );
1526 }
1527
1528 /*
1529  * ldap_back_default_rebind
1530  *
1531  * This is a callback used for chasing referrals using the same
1532  * credentials as the original user on this session.
1533  */
1534 int 
1535 ldap_back_default_rebind( LDAP *ld, LDAP_CONST char *url, ber_tag_t request,
1536         ber_int_t msgid, void *params )
1537 {
1538         ldapconn_t      *lc = (ldapconn_t *)params;
1539
1540 #ifdef HAVE_TLS
1541         /* ... otherwise we couldn't get here */
1542         assert( lc != NULL );
1543
1544         if ( !ldap_tls_inplace( ld ) ) {
1545                 int             is_tls = LDAP_BACK_CONN_ISTLS( lc ),
1546                                 rc;
1547                 const char      *text = NULL;
1548
1549                 rc = ldap_back_start_tls( ld, 0, &is_tls, url, lc->lc_flags,
1550                         LDAP_BACK_RETRY_DEFAULT, &text );
1551                 if ( rc != LDAP_SUCCESS ) {
1552                         return rc;
1553                 }
1554         }
1555 #endif /* HAVE_TLS */
1556
1557         /* FIXME: add checks on the URL/identity? */
1558
1559         return ldap_sasl_bind_s( ld,
1560                         BER_BVISNULL( &lc->lc_cred ) ? "" : lc->lc_bound_ndn.bv_val,
1561                         LDAP_SASL_SIMPLE, &lc->lc_cred, NULL, NULL, NULL );
1562 }
1563
1564 /*
1565  * ldap_back_default_urllist
1566  */
1567 int 
1568 ldap_back_default_urllist(
1569         LDAP            *ld,
1570         LDAPURLDesc     **urllist,
1571         LDAPURLDesc     **url,
1572         void            *params )
1573 {
1574         ldapinfo_t      *li = (ldapinfo_t *)params;
1575         LDAPURLDesc     **urltail;
1576
1577         if ( urllist == url ) {
1578                 return LDAP_SUCCESS;
1579         }
1580
1581         for ( urltail = &(*url)->lud_next; *urltail; urltail = &(*urltail)->lud_next )
1582                 /* count */ ;
1583
1584         *urltail = *urllist;
1585         *urllist = *url;
1586         *url = NULL;
1587
1588         if ( !li->li_uri_mutex_do_not_lock ) {
1589                 ldap_pvt_thread_mutex_lock( &li->li_uri_mutex );
1590         }
1591
1592         if ( li->li_uri ) {
1593                 ch_free( li->li_uri );
1594         }
1595
1596         ldap_get_option( ld, LDAP_OPT_URI, (void *)&li->li_uri );
1597
1598         if ( !li->li_uri_mutex_do_not_lock ) {
1599                 ldap_pvt_thread_mutex_unlock( &li->li_uri_mutex );
1600         }
1601
1602         return LDAP_SUCCESS;
1603 }
1604
1605 int
1606 ldap_back_cancel(
1607                 ldapconn_t              *lc,
1608                 Operation               *op,
1609                 SlapReply               *rs,
1610                 ber_int_t               msgid,
1611                 ldap_back_send_t        sendok )
1612 {
1613         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1614
1615         /* default behavior */
1616         if ( LDAP_BACK_ABANDON( li ) ) {
1617                 return ldap_abandon_ext( lc->lc_ld, msgid, NULL, NULL );
1618         }
1619
1620         if ( LDAP_BACK_IGNORE( li ) ) {
1621                 return ldap_pvt_discard( lc->lc_ld, msgid );
1622         }
1623
1624         if ( LDAP_BACK_CANCEL( li ) ) {
1625                 /* FIXME: asynchronous? */
1626                 return ldap_cancel_s( lc->lc_ld, msgid, NULL, NULL );
1627         }
1628
1629         assert( 0 );
1630
1631         return LDAP_OTHER;
1632 }
1633
1634 int
1635 ldap_back_op_result(
1636                 ldapconn_t              *lc,
1637                 Operation               *op,
1638                 SlapReply               *rs,
1639                 ber_int_t               msgid,
1640                 time_t                  timeout,
1641                 ldap_back_send_t        sendok )
1642 {
1643         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1644
1645         char            *match = NULL;
1646         char            *text = NULL;
1647         char            **refs = NULL;
1648         LDAPControl     **ctrls = NULL;
1649
1650         rs->sr_text = NULL;
1651         rs->sr_matched = NULL;
1652         rs->sr_ref = NULL;
1653         rs->sr_ctrls = NULL;
1654
1655         /* if the error recorded in the reply corresponds
1656          * to a successful state, get the error from the
1657          * remote server response */
1658         if ( LDAP_ERR_OK( rs->sr_err ) ) {
1659                 int             rc;
1660                 struct timeval  tv;
1661                 LDAPMessage     *res = NULL;
1662                 time_t          stoptime = (time_t)(-1);
1663                 int             timeout_err = op->o_protocol >= LDAP_VERSION3 ?
1664                                         LDAP_ADMINLIMIT_EXCEEDED : LDAP_OTHER;
1665                 const char      *timeout_text = "Operation timed out";
1666
1667                 /* if timeout is not specified, compute and use
1668                  * the one specific to the ongoing operation */
1669                 if ( timeout == (time_t)(-1) ) {
1670                         slap_op_t       opidx = slap_req2op( op->o_tag );
1671
1672                         if ( opidx == SLAP_OP_SEARCH ) {
1673                                 if ( op->ors_tlimit <= 0 ) {
1674                                         timeout = 0;
1675
1676                                 } else {
1677                                         timeout = op->ors_tlimit;
1678                                         timeout_err = LDAP_TIMELIMIT_EXCEEDED;
1679                                         timeout_text = NULL;
1680                                 }
1681
1682                         } else {
1683                                 timeout = li->li_timeout[ opidx ];
1684                         }
1685                 }
1686
1687                 /* better than nothing :) */
1688                 if ( timeout == 0 ) {
1689                         if ( li->li_idle_timeout ) {
1690                                 timeout = li->li_idle_timeout;
1691
1692                         } else if ( li->li_conn_ttl ) {
1693                                 timeout = li->li_conn_ttl;
1694                         }
1695                 }
1696
1697                 if ( timeout ) {
1698                         stoptime = op->o_time + timeout;
1699                 }
1700
1701                 LDAP_BACK_TV_SET( &tv );
1702
1703 retry:;
1704                 /* if result parsing fails, note the failure reason */
1705                 rc = ldap_result( lc->lc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
1706                 switch ( rc ) {
1707                 case 0:
1708                         if ( timeout && slap_get_time() > stoptime ) {
1709                                 if ( sendok & LDAP_BACK_BINDING ) {
1710                                         ldap_unbind_ext( lc->lc_ld, NULL, NULL );
1711                                         lc->lc_ld = NULL;
1712
1713                                         /* let it be used, but taint/delete it so that 
1714                                          * no-one else can look it up any further */
1715                                         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1716
1717 #if LDAP_BACK_PRINT_CONNTREE > 0
1718                                         ldap_back_print_conntree( li, ">>> ldap_back_getconn(timeout)" );
1719 #endif /* LDAP_BACK_PRINT_CONNTREE */
1720
1721                                         (void)ldap_back_conn_delete( li, lc );
1722                                         LDAP_BACK_CONN_TAINTED_SET( lc );
1723
1724 #if LDAP_BACK_PRINT_CONNTREE > 0
1725                                         ldap_back_print_conntree( li, "<<< ldap_back_getconn(timeout)" );
1726 #endif /* LDAP_BACK_PRINT_CONNTREE */
1727                                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1728
1729                                 } else {
1730                                         (void)ldap_back_cancel( lc, op, rs, msgid, sendok );
1731                                 }
1732                                 rs->sr_err = timeout_err;
1733                                 rs->sr_text = timeout_text;
1734                                 break;
1735                         }
1736
1737                         /* timeout == 0 */
1738                         LDAP_BACK_TV_SET( &tv );
1739                         ldap_pvt_thread_yield();
1740                         goto retry;
1741
1742                 case -1:
1743                         ldap_get_option( lc->lc_ld, LDAP_OPT_ERROR_NUMBER,
1744                                         &rs->sr_err );
1745                         break;
1746
1747
1748                 /* otherwise get the result; if it is not
1749                  * LDAP_SUCCESS, record it in the reply
1750                  * structure (this includes 
1751                  * LDAP_COMPARE_{TRUE|FALSE}) */
1752                 default:
1753                         /* only touch when activity actually took place... */
1754                         if ( li->li_idle_timeout && lc ) {
1755                                 lc->lc_time = op->o_time;
1756                         }
1757
1758                         rc = ldap_parse_result( lc->lc_ld, res, &rs->sr_err,
1759                                         &match, &text, &refs, &ctrls, 1 );
1760                         rs->sr_text = text;
1761                         if ( rc != LDAP_SUCCESS ) {
1762                                 rs->sr_err = rc;
1763                         }
1764
1765                         /* RFC 4511: referrals can only appear
1766                          * if result code is LDAP_REFERRAL */
1767                         if ( refs != NULL
1768                                 && refs[ 0 ] != NULL
1769                                 && refs[ 0 ][ 0 ] != '\0' )
1770                         {
1771                                 if ( rs->sr_err != LDAP_REFERRAL ) {
1772                                         Debug( LDAP_DEBUG_ANY,
1773                                                 "%s ldap_back_op_result: "
1774                                                 "got referrals with err=%d\n",
1775                                                 op->o_log_prefix,
1776                                                 rs->sr_err, 0 );
1777
1778                                 } else {
1779                                         int     i;
1780
1781                                         for ( i = 0; refs[ i ] != NULL; i++ )
1782                                                 /* count */ ;
1783                                         rs->sr_ref = op->o_tmpalloc( sizeof( struct berval ) * ( i + 1 ),
1784                                                 op->o_tmpmemctx );
1785                                         for ( i = 0; refs[ i ] != NULL; i++ ) {
1786                                                 ber_str2bv( refs[ i ], 0, 0, &rs->sr_ref[ i ] );
1787                                         }
1788                                         BER_BVZERO( &rs->sr_ref[ i ] );
1789                                 }
1790
1791                         } else if ( rs->sr_err == LDAP_REFERRAL ) {
1792                                 Debug( LDAP_DEBUG_ANY,
1793                                         "%s ldap_back_op_result: "
1794                                         "got err=%d with null "
1795                                         "or empty referrals\n",
1796                                         op->o_log_prefix,
1797                                         rs->sr_err, 0 );
1798
1799                                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
1800                         }
1801
1802                         if ( ctrls != NULL ) {
1803                                 rs->sr_ctrls = ctrls;
1804                         }
1805                 }
1806         }
1807
1808         /* if the error in the reply structure is not
1809          * LDAP_SUCCESS, try to map it from client 
1810          * to server error */
1811         if ( !LDAP_ERR_OK( rs->sr_err ) ) {
1812                 rs->sr_err = slap_map_api2result( rs );
1813
1814                 /* internal ops ( op->o_conn == NULL ) 
1815                  * must not reply to client */
1816                 if ( op->o_conn && !op->o_do_not_cache && match ) {
1817
1818                         /* record the (massaged) matched
1819                          * DN into the reply structure */
1820                         rs->sr_matched = match;
1821                 }
1822         }
1823
1824         if ( rs->sr_err == LDAP_UNAVAILABLE ) {
1825                 if ( !( sendok & LDAP_BACK_RETRYING ) ) {
1826                         if ( LDAP_BACK_QUARANTINE( li ) ) {
1827                                 ldap_back_quarantine( op, rs );
1828                         }
1829                         if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
1830                                 if ( rs->sr_text == NULL ) rs->sr_text = "Proxy operation retry failed";
1831                                 send_ldap_result( op, rs );
1832                         }
1833                 }
1834
1835         } else if ( op->o_conn &&
1836                 ( ( ( sendok & LDAP_BACK_SENDOK ) && LDAP_ERR_OK( rs->sr_err ) )
1837                         || ( ( sendok & LDAP_BACK_SENDERR ) && !LDAP_ERR_OK( rs->sr_err ) ) ) )
1838         {
1839                 send_ldap_result( op, rs );
1840         }
1841
1842         if ( match ) {
1843                 if ( rs->sr_matched != match ) {
1844                         free( (char *)rs->sr_matched );
1845                 }
1846                 rs->sr_matched = NULL;
1847                 ldap_memfree( match );
1848         }
1849
1850         if ( text ) {
1851                 ldap_memfree( text );
1852         }
1853         rs->sr_text = NULL;
1854
1855         if ( rs->sr_ref ) {
1856                 op->o_tmpfree( rs->sr_ref, op->o_tmpmemctx );
1857                 rs->sr_ref = NULL;
1858         }
1859
1860         if ( refs ) {
1861                 ber_memvfree( (void **)refs );
1862         }
1863
1864         if ( ctrls ) {
1865                 assert( rs->sr_ctrls != NULL );
1866                 ldap_controls_free( ctrls );
1867                 rs->sr_ctrls = NULL;
1868         }
1869
1870         return( LDAP_ERR_OK( rs->sr_err ) ? LDAP_SUCCESS : rs->sr_err );
1871 }
1872
1873 /* return true if bound, false if failed */
1874 int
1875 ldap_back_retry( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1876 {
1877         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1878         int             rc = 0;
1879
1880         assert( lcp != NULL );
1881         assert( *lcp != NULL );
1882
1883         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1884
1885         if ( (*lcp)->lc_refcnt == 1 ) {
1886                 int binding = LDAP_BACK_CONN_BINDING( *lcp );
1887
1888                 ldap_pvt_thread_mutex_lock( &li->li_uri_mutex );
1889                 Debug( LDAP_DEBUG_ANY,
1890                         "%s ldap_back_retry: retrying URI=\"%s\" DN=\"%s\"\n",
1891                         op->o_log_prefix, li->li_uri,
1892                         BER_BVISNULL( &(*lcp)->lc_bound_ndn ) ?
1893                                 "" : (*lcp)->lc_bound_ndn.bv_val );
1894                 ldap_pvt_thread_mutex_unlock( &li->li_uri_mutex );
1895
1896                 ldap_unbind_ext( (*lcp)->lc_ld, NULL, NULL );
1897                 (*lcp)->lc_ld = NULL;
1898                 LDAP_BACK_CONN_ISBOUND_CLEAR( (*lcp) );
1899
1900                 /* lc here must be the regular lc, reset and ready for init */
1901                 rc = ldap_back_prepare_conn( *lcp, op, rs, sendok );
1902                 if ( rc != LDAP_SUCCESS ) {
1903                         /* freeit, because lc_refcnt == 1 */
1904                         (*lcp)->lc_refcnt = 0;
1905                         (void)ldap_back_freeconn( li, *lcp, 0 );
1906                         *lcp = NULL;
1907                         rc = 0;
1908
1909                 } else if ( ( sendok & LDAP_BACK_BINDING ) ) {
1910                         if ( binding ) {
1911                                 LDAP_BACK_CONN_BINDING_SET( *lcp );
1912                         }
1913                         rc = 1;
1914
1915                 } else {
1916                         rc = ldap_back_dobind_int( lcp, op, rs, sendok, 0, 0 );
1917                         if ( rc == 0 && *lcp != NULL ) {
1918                                 /* freeit, because lc_refcnt == 1 */
1919                                 (*lcp)->lc_refcnt = 0;
1920                                 LDAP_BACK_CONN_TAINTED_SET( *lcp );
1921                                 (void)ldap_back_freeconn( li, *lcp, 0 );
1922                                 *lcp = NULL;
1923                         }
1924                 }
1925
1926         } else {
1927                 Debug( LDAP_DEBUG_TRACE,
1928                         "ldap_back_retry: conn %p refcnt=%u unable to retry.\n",
1929                         (void *)(*lcp), (*lcp)->lc_refcnt, 0 );
1930
1931                 LDAP_BACK_CONN_TAINTED_SET( *lcp );
1932                 ldap_back_release_conn_lock( li, lcp, 0 );
1933                 assert( *lcp == NULL );
1934
1935                 if ( sendok & LDAP_BACK_SENDERR ) {
1936                         rs->sr_err = LDAP_UNAVAILABLE;
1937                         rs->sr_text = "Unable to retry";
1938                         send_ldap_result( op, rs );
1939                 }
1940         }
1941
1942         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1943
1944         return rc;
1945 }
1946
1947 static int
1948 ldap_back_is_proxy_authz( Operation *op, SlapReply *rs, ldap_back_send_t sendok,
1949         struct berval *binddn, struct berval *bindcred )
1950 {
1951         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1952         struct berval   ndn;
1953         int             dobind = 0;
1954
1955         if ( op->o_conn == NULL || op->o_do_not_cache ) {
1956                 goto done;
1957         }
1958
1959         /* don't proxyAuthz if protocol is not LDAPv3 */
1960         switch ( li->li_version ) {
1961         case LDAP_VERSION3:
1962                 break;
1963
1964         case 0:
1965                 if ( op->o_protocol == 0 || op->o_protocol == LDAP_VERSION3 ) {
1966                         break;
1967                 }
1968                 /* fall thru */
1969
1970         default:
1971                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1972                 if ( sendok & LDAP_BACK_SENDERR ) {
1973                         send_ldap_result( op, rs );
1974                         dobind = -1;
1975                 }
1976                 goto done;
1977         }
1978
1979         /* safe default */
1980         *binddn = slap_empty_bv;
1981         *bindcred = slap_empty_bv;
1982
1983         if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1984                 ndn = op->o_conn->c_ndn;
1985
1986         } else {
1987                 ndn = op->o_ndn;
1988         }
1989
1990         switch ( li->li_idassert_mode ) {
1991         case LDAP_BACK_IDASSERT_LEGACY:
1992                 if ( !BER_BVISNULL( &ndn ) && !BER_BVISEMPTY( &ndn ) ) {
1993                         if ( !BER_BVISNULL( &li->li_idassert_authcDN ) && !BER_BVISEMPTY( &li->li_idassert_authcDN ) )
1994                         {
1995                                 *binddn = li->li_idassert_authcDN;
1996                                 *bindcred = li->li_idassert_passwd;
1997                                 dobind = 1;
1998                         }
1999                 }
2000                 break;
2001
2002         default:
2003                 /* NOTE: rootdn can always idassert */
2004                 if ( BER_BVISNULL( &ndn )
2005                         && li->li_idassert_authz == NULL
2006                         && !( li->li_idassert_flags & LDAP_BACK_AUTH_AUTHZ_ALL ) )
2007                 {
2008                         if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
2009                                 rs->sr_err = LDAP_INAPPROPRIATE_AUTH;
2010                                 if ( sendok & LDAP_BACK_SENDERR ) {
2011                                         send_ldap_result( op, rs );
2012                                         dobind = -1;
2013                                 }
2014
2015                         } else {
2016                                 rs->sr_err = LDAP_SUCCESS;
2017                                 *binddn = slap_empty_bv;
2018                                 *bindcred = slap_empty_bv;
2019                                 break;
2020                         }
2021
2022                         goto done;
2023
2024                 } else if ( li->li_idassert_authz && !be_isroot( op ) ) {
2025                         struct berval authcDN;
2026
2027                         if ( BER_BVISNULL( &ndn ) ) {
2028                                 authcDN = slap_empty_bv;
2029
2030                         } else {
2031                                 authcDN = ndn;
2032                         }       
2033                         rs->sr_err = slap_sasl_matches( op, li->li_idassert_authz,
2034                                         &authcDN, &authcDN );
2035                         if ( rs->sr_err != LDAP_SUCCESS ) {
2036                                 if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
2037                                         if ( sendok & LDAP_BACK_SENDERR ) {
2038                                                 send_ldap_result( op, rs );
2039                                                 dobind = -1;
2040                                         }
2041
2042                                 } else {
2043                                         rs->sr_err = LDAP_SUCCESS;
2044                                         *binddn = slap_empty_bv;
2045                                         *bindcred = slap_empty_bv;
2046                                         break;
2047                                 }
2048
2049                                 goto done;
2050                         }
2051                 }
2052
2053                 *binddn = li->li_idassert_authcDN;
2054                 *bindcred = li->li_idassert_passwd;
2055                 dobind = 1;
2056                 break;
2057         }
2058
2059 done:;
2060         return dobind;
2061 }
2062
2063 static int
2064 ldap_back_proxy_authz_bind(
2065         ldapconn_t              *lc,
2066         Operation               *op,
2067         SlapReply               *rs,
2068         ldap_back_send_t        sendok,
2069         struct berval           *binddn,
2070         struct berval           *bindcred )
2071 {
2072         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
2073         struct berval   ndn;
2074         int             msgid;
2075         int             rc;
2076
2077         if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
2078                 ndn = op->o_conn->c_ndn;
2079
2080         } else {
2081                 ndn = op->o_ndn;
2082         }
2083
2084         if ( li->li_idassert_authmethod == LDAP_AUTH_SASL ) {
2085 #ifdef HAVE_CYRUS_SASL
2086                 void            *defaults = NULL;
2087                 struct berval   authzID = BER_BVNULL;
2088                 int             freeauthz = 0;
2089
2090                 /* if SASL supports native authz, prepare for it */
2091                 if ( ( !op->o_do_not_cache || !op->o_is_auth_check ) &&
2092                                 ( li->li_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
2093                 {
2094                         switch ( li->li_idassert_mode ) {
2095                         case LDAP_BACK_IDASSERT_OTHERID:
2096                         case LDAP_BACK_IDASSERT_OTHERDN:
2097                                 authzID = li->li_idassert_authzID;
2098                                 break;
2099
2100                         case LDAP_BACK_IDASSERT_ANONYMOUS:
2101                                 BER_BVSTR( &authzID, "dn:" );
2102                                 break;
2103
2104                         case LDAP_BACK_IDASSERT_SELF:
2105                                 if ( BER_BVISNULL( &ndn ) ) {
2106                                         /* connection is not authc'd, so don't idassert */
2107                                         BER_BVSTR( &authzID, "dn:" );
2108                                         break;
2109                                 }
2110                                 authzID.bv_len = STRLENOF( "dn:" ) + ndn.bv_len;
2111                                 authzID.bv_val = slap_sl_malloc( authzID.bv_len + 1, op->o_tmpmemctx );
2112                                 AC_MEMCPY( authzID.bv_val, "dn:", STRLENOF( "dn:" ) );
2113                                 AC_MEMCPY( authzID.bv_val + STRLENOF( "dn:" ),
2114                                                 ndn.bv_val, ndn.bv_len + 1 );
2115                                 freeauthz = 1;
2116                                 break;
2117
2118                         default:
2119                                 break;
2120                         }
2121                 }
2122
2123                 if ( li->li_idassert_secprops != NULL ) {
2124                         rs->sr_err = ldap_set_option( lc->lc_ld,
2125                                 LDAP_OPT_X_SASL_SECPROPS,
2126                                 (void *)li->li_idassert_secprops );
2127
2128                         if ( rs->sr_err != LDAP_OPT_SUCCESS ) {
2129                                 rs->sr_err = LDAP_OTHER;
2130                                 if ( sendok & LDAP_BACK_SENDERR ) {
2131                                         send_ldap_result( op, rs );
2132                                 }
2133                                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
2134                                 goto done;
2135                         }
2136                 }
2137
2138                 defaults = lutil_sasl_defaults( lc->lc_ld,
2139                                 li->li_idassert_sasl_mech.bv_val,
2140                                 li->li_idassert_sasl_realm.bv_val,
2141                                 li->li_idassert_authcID.bv_val,
2142                                 li->li_idassert_passwd.bv_val,
2143                                 authzID.bv_val );
2144                 if ( defaults == NULL ) {
2145                         rs->sr_err = LDAP_OTHER;
2146                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
2147                         if ( sendok & LDAP_BACK_SENDERR ) {
2148                                 send_ldap_result( op, rs );
2149                         }
2150                         goto done;
2151                 }
2152
2153                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld, binddn->bv_val,
2154                                 li->li_idassert_sasl_mech.bv_val, NULL, NULL,
2155                                 LDAP_SASL_QUIET, lutil_sasl_interact,
2156                                 defaults );
2157
2158                 switch ( rs->sr_err ) {
2159                 case LDAP_SUCCESS:
2160                         LDAP_BACK_CONN_ISBOUND_SET( lc );
2161                         break;
2162
2163                 case LDAP_LOCAL_ERROR:
2164                         /* list client API error codes that require
2165                          * to taint the connection */
2166                         /* FIXME: should actually retry? */
2167                         LDAP_BACK_CONN_TAINTED_SET( lc );
2168
2169                         /* fallthru */
2170
2171                 default:
2172                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
2173                         rs->sr_err = slap_map_api2result( rs );
2174                         if ( sendok & LDAP_BACK_SENDERR ) {
2175                                 send_ldap_result( op, rs );
2176                         }
2177                         break;
2178                 }
2179
2180                 lutil_sasl_freedefs( defaults );
2181                 if ( freeauthz ) {
2182                         slap_sl_free( authzID.bv_val, op->o_tmpmemctx );
2183                 }
2184
2185                 goto done;
2186 #endif /* HAVE_CYRUS_SASL */
2187         }
2188
2189         switch ( li->li_idassert_authmethod ) {
2190         case LDAP_AUTH_NONE:
2191                 /* FIXME: do we really need this? */
2192                 BER_BVSTR( binddn, "" );
2193                 BER_BVSTR( bindcred, "" );
2194                 /* fallthru */
2195
2196         case LDAP_AUTH_SIMPLE:
2197                 rs->sr_err = ldap_sasl_bind( lc->lc_ld,
2198                                 binddn->bv_val, LDAP_SASL_SIMPLE,
2199                                 bindcred, NULL, NULL, &msgid );
2200                 rc = ldap_back_op_result( lc, op, rs, msgid,
2201                         -1, ( sendok | LDAP_BACK_BINDING ) );
2202                 break;
2203
2204         default:
2205                 /* unsupported! */
2206                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
2207                 rs->sr_err = LDAP_AUTH_METHOD_NOT_SUPPORTED;
2208                 if ( sendok & LDAP_BACK_SENDERR ) {
2209                         send_ldap_result( op, rs );
2210                 }
2211                 goto done;
2212         }
2213
2214         if ( rc == LDAP_SUCCESS ) {
2215                 /* set rebind stuff in case of successful proxyAuthz bind,
2216                  * so that referral chasing is attempted using the right
2217                  * identity */
2218                 LDAP_BACK_CONN_ISBOUND_SET( lc );
2219                 if ( !BER_BVISNULL( binddn ) ) {
2220                         ber_bvreplace( &lc->lc_bound_ndn, binddn );
2221                 }
2222
2223                 if ( !BER_BVISNULL( &lc->lc_cred ) ) {
2224                         memset( lc->lc_cred.bv_val, 0,
2225                                         lc->lc_cred.bv_len );
2226                 }
2227
2228                 if ( LDAP_BACK_SAVECRED( li ) ) {
2229                         if ( !BER_BVISNULL( bindcred ) ) {
2230                                 ber_bvreplace( &lc->lc_cred, bindcred );
2231                                 ldap_set_rebind_proc( lc->lc_ld, li->li_rebind_f, lc );
2232                         }
2233
2234                 } else {
2235                         lc->lc_cred.bv_len = 0;
2236                 }
2237         }
2238 done:;
2239         return LDAP_BACK_CONN_ISBOUND( lc );
2240 }
2241
2242 /*
2243  * ldap_back_proxy_authz_ctrl() prepends a proxyAuthz control
2244  * to existing server-side controls if required; if not,
2245  * the existing server-side controls are placed in *pctrls.
2246  * The caller, after using the controls in client API 
2247  * operations, if ( *pctrls != op->o_ctrls ), should
2248  * free( (*pctrls)[ 0 ] ) and free( *pctrls ).
2249  * The function returns success if the control could
2250  * be added if required, or if it did nothing; in the future,
2251  * it might return some error if it failed.
2252  * 
2253  * if no bind took place yet, but the connection is bound
2254  * and the "proxyauthzdn" is set, then bind as "proxyauthzdn" 
2255  * and explicitly add proxyAuthz the control to every operation
2256  * with the dn bound to the connection as control value.
2257  *
2258  * If no server-side controls are defined for the operation,
2259  * simply add the proxyAuthz control; otherwise, if the
2260  * proxyAuthz control is not already set, add it as
2261  * the first one
2262  *
2263  * FIXME: is controls order significant for security?
2264  * ANSWER: controls ordering and interoperability
2265  * must be indicated by the specs of each control; if none
2266  * is specified, the order is irrelevant.
2267  */
2268 int
2269 ldap_back_proxy_authz_ctrl(
2270                 Operation       *op,
2271                 SlapReply       *rs,
2272                 struct berval   *bound_ndn,
2273                 int             version,
2274                 slap_idassert_t *si,
2275                 LDAPControl     *ctrl )
2276 {
2277         slap_idassert_mode_t    mode;
2278         struct berval           assertedID,
2279                                 ndn;
2280         int                     isroot = 0;
2281
2282         rs->sr_err = SLAP_CB_CONTINUE;
2283
2284         /* FIXME: SASL/EXTERNAL over ldapi:// doesn't honor the authcID,
2285          * but if it is not set this test fails.  We need a different
2286          * means to detect if idassert is enabled */
2287         if ( ( BER_BVISNULL( &si->si_bc.sb_authcId ) || BER_BVISEMPTY( &si->si_bc.sb_authcId ) )
2288                 && ( BER_BVISNULL( &si->si_bc.sb_binddn ) || BER_BVISEMPTY( &si->si_bc.sb_binddn ) )
2289                 && BER_BVISNULL( &si->si_bc.sb_saslmech ) )
2290         {
2291                 goto done;
2292         }
2293
2294         if ( !op->o_conn || op->o_do_not_cache || ( isroot = be_isroot( op ) ) ) {
2295                 goto done;
2296         }
2297
2298         if ( op->o_tag == LDAP_REQ_BIND ) {
2299                 ndn = op->o_req_ndn;
2300
2301         } else if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
2302                 ndn = op->o_conn->c_ndn;
2303
2304         } else {
2305                 ndn = op->o_ndn;
2306         }
2307
2308         if ( si->si_mode == LDAP_BACK_IDASSERT_LEGACY ) {
2309                 if ( op->o_proxy_authz ) {
2310                         /*
2311                          * FIXME: we do not want to perform proxyAuthz
2312                          * on behalf of the client, because this would
2313                          * be performed with "proxyauthzdn" privileges.
2314                          *
2315                          * This might actually be too strict, since
2316                          * the "proxyauthzdn" authzTo, and each entry's
2317                          * authzFrom attributes may be crafted
2318                          * to avoid unwanted proxyAuthz to take place.
2319                          */
2320 #if 0
2321                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
2322                         rs->sr_text = "proxyAuthz not allowed within namingContext";
2323 #endif
2324                         goto done;
2325                 }
2326
2327                 if ( !BER_BVISNULL( bound_ndn ) ) {
2328                         goto done;
2329                 }
2330
2331                 if ( BER_BVISNULL( &ndn ) ) {
2332                         goto done;
2333                 }
2334
2335                 if ( BER_BVISNULL( &si->si_bc.sb_binddn ) ) {
2336                         goto done;
2337                 }
2338
2339         } else if ( si->si_bc.sb_method == LDAP_AUTH_SASL ) {
2340                 if ( ( si->si_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
2341                 {
2342                         /* already asserted in SASL via native authz */
2343                         goto done;
2344                 }
2345
2346         } else if ( si->si_authz && !isroot ) {
2347                 int             rc;
2348                 struct berval authcDN;
2349
2350                 if ( BER_BVISNULL( &ndn ) ) {
2351                         authcDN = slap_empty_bv;
2352                 } else {
2353                         authcDN = ndn;
2354                 }
2355                 rc = slap_sasl_matches( op, si->si_authz,
2356                                 &authcDN, &authcDN );
2357                 if ( rc != LDAP_SUCCESS ) {
2358                         if ( si->si_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
2359                                 /* ndn is not authorized
2360                                  * to use idassert */
2361                                 rs->sr_err = rc;
2362                         }
2363                         goto done;
2364                 }
2365         }
2366
2367         if ( op->o_proxy_authz ) {
2368                 /*
2369                  * FIXME: we can:
2370                  * 1) ignore the already set proxyAuthz control
2371                  * 2) leave it in place, and don't set ours
2372                  * 3) add both
2373                  * 4) reject the operation
2374                  *
2375                  * option (4) is very drastic
2376                  * option (3) will make the remote server reject
2377                  * the operation, thus being equivalent to (4)
2378                  * option (2) will likely break the idassert
2379                  * assumptions, so we cannot accept it;
2380                  * option (1) means that we are contradicting
2381                  * the client's reques.
2382                  *
2383                  * I think (4) is the only correct choice.
2384                  */
2385                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
2386                 rs->sr_text = "proxyAuthz not allowed within namingContext";
2387         }
2388
2389         if ( op->o_is_auth_check ) {
2390                 mode = LDAP_BACK_IDASSERT_NOASSERT;
2391
2392         } else {
2393                 mode = si->si_mode;
2394         }
2395
2396         switch ( mode ) {
2397         case LDAP_BACK_IDASSERT_LEGACY:
2398                 /* original behavior:
2399                  * assert the client's identity */
2400         case LDAP_BACK_IDASSERT_SELF:
2401                 assertedID = ndn;
2402                 break;
2403
2404         case LDAP_BACK_IDASSERT_ANONYMOUS:
2405                 /* assert "anonymous" */
2406                 assertedID = slap_empty_bv;
2407                 break;
2408
2409         case LDAP_BACK_IDASSERT_NOASSERT:
2410                 /* don't assert; bind as proxyauthzdn */
2411                 goto done;
2412
2413         case LDAP_BACK_IDASSERT_OTHERID:
2414         case LDAP_BACK_IDASSERT_OTHERDN:
2415                 /* assert idassert DN */
2416                 assertedID = si->si_bc.sb_authzId;
2417                 break;
2418
2419         default:
2420                 assert( 0 );
2421         }
2422
2423         /* if we got here, "" is allowed to proxyAuthz */
2424         if ( BER_BVISNULL( &assertedID ) ) {
2425                 assertedID = slap_empty_bv;
2426         }
2427
2428         /* don't idassert the bound DN (ITS#4497) */
2429         if ( dn_match( &assertedID, bound_ndn ) ) {
2430                 goto done;
2431         }
2432
2433         ctrl->ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
2434
2435         switch ( si->si_mode ) {
2436         /* already in u:ID or dn:DN form */
2437         case LDAP_BACK_IDASSERT_OTHERID:
2438         case LDAP_BACK_IDASSERT_OTHERDN:
2439                 ber_dupbv_x( &ctrl->ldctl_value, &assertedID, op->o_tmpmemctx );
2440                 rs->sr_err = LDAP_SUCCESS;
2441                 break;
2442
2443         /* needs the dn: prefix */
2444         default:
2445                 ctrl->ldctl_value.bv_len = assertedID.bv_len + STRLENOF( "dn:" );
2446                 ctrl->ldctl_value.bv_val = op->o_tmpalloc( ctrl->ldctl_value.bv_len + 1,
2447                                 op->o_tmpmemctx );
2448                 AC_MEMCPY( ctrl->ldctl_value.bv_val, "dn:", STRLENOF( "dn:" ) );
2449                 AC_MEMCPY( &ctrl->ldctl_value.bv_val[ STRLENOF( "dn:" ) ],
2450                                 assertedID.bv_val, assertedID.bv_len + 1 );
2451                 rs->sr_err = LDAP_SUCCESS;
2452                 break;
2453         }
2454
2455         /* Older versions of <draft-weltman-ldapv3-proxy> required
2456          * to encode the value of the authzID (and called it proxyDN);
2457          * this hack provides compatibility with those DSAs that
2458          * implement it this way */
2459         if ( si->si_flags & LDAP_BACK_AUTH_OBSOLETE_ENCODING_WORKAROUND ) {
2460                 struct berval           authzID = ctrl->ldctl_value;
2461                 BerElementBuffer        berbuf;
2462                 BerElement              *ber = (BerElement *)&berbuf;
2463                 ber_tag_t               tag;
2464
2465                 ber_init2( ber, 0, LBER_USE_DER );
2466                 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
2467
2468                 tag = ber_printf( ber, "O", &authzID );
2469                 if ( tag == LBER_ERROR ) {
2470                         rs->sr_err = LDAP_OTHER;
2471                         goto free_ber;
2472                 }
2473
2474                 if ( ber_flatten2( ber, &ctrl->ldctl_value, 1 ) == -1 ) {
2475                         rs->sr_err = LDAP_OTHER;
2476                         goto free_ber;
2477                 }
2478
2479                 rs->sr_err = LDAP_SUCCESS;
2480
2481 free_ber:;
2482                 op->o_tmpfree( authzID.bv_val, op->o_tmpmemctx );
2483                 ber_free_buf( ber );
2484
2485                 if ( rs->sr_err != LDAP_SUCCESS ) {
2486                         goto done;
2487                 }
2488
2489         } else if ( si->si_flags & LDAP_BACK_AUTH_OBSOLETE_PROXY_AUTHZ ) {
2490                 struct berval           authzID = ctrl->ldctl_value,
2491                                         tmp;
2492                 BerElementBuffer        berbuf;
2493                 BerElement              *ber = (BerElement *)&berbuf;
2494                 ber_tag_t               tag;
2495
2496                 if ( strncasecmp( authzID.bv_val, "dn:", STRLENOF( "dn:" ) ) != 0 ) {
2497                         rs->sr_err = LDAP_PROTOCOL_ERROR;
2498                         goto done;
2499                 }
2500
2501                 tmp = authzID;
2502                 tmp.bv_val += STRLENOF( "dn:" );
2503                 tmp.bv_len -= STRLENOF( "dn:" );
2504
2505                 ber_init2( ber, 0, LBER_USE_DER );
2506                 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
2507
2508                 /* apparently, Mozilla API encodes this
2509                  * as "SEQUENCE { LDAPDN }" */
2510                 tag = ber_printf( ber, "{O}", &tmp );
2511                 if ( tag == LBER_ERROR ) {
2512                         rs->sr_err = LDAP_OTHER;
2513                         goto free_ber2;
2514                 }
2515
2516                 if ( ber_flatten2( ber, &ctrl->ldctl_value, 1 ) == -1 ) {
2517                         rs->sr_err = LDAP_OTHER;
2518                         goto free_ber2;
2519                 }
2520
2521                 ctrl->ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
2522                 rs->sr_err = LDAP_SUCCESS;
2523
2524 free_ber2:;
2525                 op->o_tmpfree( authzID.bv_val, op->o_tmpmemctx );
2526                 ber_free_buf( ber );
2527
2528                 if ( rs->sr_err != LDAP_SUCCESS ) {
2529                         goto done;
2530                 }
2531         }
2532
2533 done:;
2534
2535         return rs->sr_err;
2536 }
2537
2538 /*
2539  * Add controls;
2540  *
2541  * if any needs to be added, it is prepended to existing ones,
2542  * in a newly allocated array.  The companion function
2543  * ldap_back_controls_free() must be used to restore the original
2544  * status of op->o_ctrls.
2545  */
2546 int
2547 ldap_back_controls_add(
2548                 Operation       *op,
2549                 SlapReply       *rs,
2550                 ldapconn_t      *lc,
2551                 LDAPControl     ***pctrls )
2552 {
2553         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
2554
2555         LDAPControl     **ctrls = NULL;
2556         /* set to the maximum number of controls this backend can add */
2557         LDAPControl     c[ 2 ] = { { 0 } };
2558         int             n = 0, i, j1 = 0, j2 = 0;
2559
2560         *pctrls = NULL;
2561
2562         rs->sr_err = LDAP_SUCCESS;
2563
2564         /* don't add controls if protocol is not LDAPv3 */
2565         switch ( li->li_version ) {
2566         case LDAP_VERSION3:
2567                 break;
2568
2569         case 0:
2570                 if ( op->o_protocol == 0 || op->o_protocol == LDAP_VERSION3 ) {
2571                         break;
2572                 }
2573                 /* fall thru */
2574
2575         default:
2576                 goto done;
2577         }
2578
2579         /* put controls that go __before__ existing ones here */
2580
2581         /* proxyAuthz for identity assertion */
2582         switch ( ldap_back_proxy_authz_ctrl( op, rs, &lc->lc_bound_ndn,
2583                 li->li_version, &li->li_idassert, &c[ j1 ] ) )
2584         {
2585         case SLAP_CB_CONTINUE:
2586                 break;
2587
2588         case LDAP_SUCCESS:
2589                 j1++;
2590                 break;
2591
2592         default:
2593                 goto done;
2594         }
2595
2596         /* put controls that go __after__ existing ones here */
2597
2598 #ifdef SLAP_CONTROL_X_SESSION_TRACKING
2599         /* FIXME: according to <draft-wahl-ldap-session>, 
2600          * the server should check if the control can be added
2601          * based on the identity of the client and so */
2602
2603         /* session tracking */
2604         if ( LDAP_BACK_ST_REQUEST( li ) ) {
2605                 switch ( slap_ctrl_session_tracking_request_add( op, rs, &c[ j1 + j2 ] ) ) {
2606                 case SLAP_CB_CONTINUE:
2607                         break;
2608
2609                 case LDAP_SUCCESS:
2610                         j2++;
2611                         break;
2612
2613                 default:
2614                         goto done;
2615                 }
2616         }
2617 #endif /* SLAP_CONTROL_X_SESSION_TRACKING */
2618
2619         if ( rs->sr_err == SLAP_CB_CONTINUE ) {
2620                 rs->sr_err = LDAP_SUCCESS;
2621         }
2622
2623         /* if nothing to do, just bail out */
2624         if ( j1 == 0 && j2 == 0 ) {
2625                 goto done;
2626         }
2627
2628         assert( j1 + j2 <= (int) (sizeof( c )/sizeof( c[0] )) );
2629
2630         if ( op->o_ctrls ) {
2631                 for ( n = 0; op->o_ctrls[ n ]; n++ )
2632                         /* just count ctrls */ ;
2633         }
2634
2635         ctrls = op->o_tmpalloc( (n + j1 + j2 + 1) * sizeof( LDAPControl * ) + ( j1 + j2 ) * sizeof( LDAPControl ),
2636                         op->o_tmpmemctx );
2637         if ( j1 ) {
2638                 ctrls[ 0 ] = (LDAPControl *)&ctrls[ n + j1 + j2 + 1 ];
2639                 *ctrls[ 0 ] = c[ 0 ];
2640                 for ( i = 1; i < j1; i++ ) {
2641                         ctrls[ i ] = &ctrls[ 0 ][ i ];
2642                         *ctrls[ i ] = c[ i ];
2643                 }
2644         }
2645
2646         i = 0;
2647         if ( op->o_ctrls ) {
2648                 for ( i = 0; op->o_ctrls[ i ]; i++ ) {
2649                         ctrls[ i + j1 ] = op->o_ctrls[ i ];
2650                 }
2651         }
2652
2653         n += j1;
2654         if ( j2 ) {
2655                 ctrls[ n ] = (LDAPControl *)&ctrls[ n + j2 + 1 ] + j1;
2656                 *ctrls[ n ] = c[ j1 ];
2657                 for ( i = 1; i < j2; i++ ) {
2658                         ctrls[ n + i ] = &ctrls[ n ][ i ];
2659                         *ctrls[ n + i ] = c[ i ];
2660                 }
2661         }
2662
2663         ctrls[ n + j2 ] = NULL;
2664
2665 done:;
2666         if ( ctrls == NULL ) {
2667                 ctrls = op->o_ctrls;
2668         }
2669
2670         *pctrls = ctrls;
2671         
2672         return rs->sr_err;
2673 }
2674
2675 int
2676 ldap_back_controls_free( Operation *op, SlapReply *rs, LDAPControl ***pctrls )
2677 {
2678         LDAPControl     **ctrls = *pctrls;
2679
2680         /* we assume that the controls added by the proxy come first,
2681          * so as soon as we find op->o_ctrls[ 0 ] we can stop */
2682         if ( ctrls && ctrls != op->o_ctrls ) {
2683                 int             i = 0, n = 0, n_added;
2684                 LDAPControl     *lower, *upper;
2685
2686                 assert( ctrls[ 0 ] != NULL );
2687
2688                 for ( n = 0; ctrls[ n ] != NULL; n++ )
2689                         /* count 'em */ ;
2690
2691                 if ( op->o_ctrls ) {
2692                         for ( i = 0; op->o_ctrls[ i ] != NULL; i++ )
2693                                 /* count 'em */ ;
2694                 }
2695
2696                 n_added = n - i;
2697                 lower = (LDAPControl *)&ctrls[ n ];
2698                 upper = &lower[ n_added ];
2699
2700                 for ( i = 0; ctrls[ i ] != NULL; i++ ) {
2701                         if ( ctrls[ i ] < lower || ctrls[ i ] >= upper ) {
2702                                 /* original; don't touch */
2703                                 continue;
2704                         }
2705
2706                         if ( !BER_BVISNULL( &ctrls[ i ]->ldctl_value ) ) {
2707                                 op->o_tmpfree( ctrls[ i ]->ldctl_value.bv_val, op->o_tmpmemctx );
2708                         }
2709                 }
2710
2711                 op->o_tmpfree( ctrls, op->o_tmpmemctx );
2712         } 
2713
2714         *pctrls = NULL;
2715
2716         return 0;
2717 }
2718
2719 int
2720 ldap_back_conn2str( ldapconn_t *lc, char *buf, ber_len_t buflen )
2721 {
2722         static struct berval conns[] = {
2723                 BER_BVC("ROOTDN"),
2724                 BER_BVC("ROOTDN-TLS"),
2725                 BER_BVC("ANON"),
2726                 BER_BVC("ANON-TLS"),
2727                 BER_BVC("BIND"),
2728                 BER_BVC("BIND-TLS"),
2729                 BER_BVNULL
2730         };
2731
2732         int len = 0;
2733
2734         if ( LDAP_BACK_PCONN_ISPRIV( lc ) ) {
2735                 long cid;
2736                 struct berval *bv;
2737
2738                 cid = (long)lc->lc_conn;
2739                 assert( cid >= LDAP_BACK_PCONN_FIRST && cid < LDAP_BACK_PCONN_LAST );
2740
2741                 bv = &conns[ cid ];
2742
2743                 if ( bv->bv_len >= buflen ) {
2744                         return bv->bv_len + 1;
2745                 }
2746
2747                 len = bv->bv_len;
2748                 lutil_strncopy( buf, bv->bv_val, bv->bv_len + 1 );
2749
2750         } else {
2751                 len = snprintf( buf, buflen, "%lu", lc->lc_conn->c_connid );
2752         }
2753
2754         return len;
2755 }