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