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