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