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