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