]> git.sur5r.net Git - openldap/blob - servers/slapd/back-ldap/bind.c
9ef163c879d61cca0c537fed119f413947bfc518
[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-2011 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                         assert( rc == 1 );
1405                 }
1406                 rc = ldap_back_proxy_authz_bind( lc, op, rs, sendok, &binddn, &bindcred );
1407                 goto done;
1408         }
1409
1410 #ifdef HAVE_CYRUS_SASL
1411         if ( LDAP_BACK_CONN_ISPRIV( lc )) {
1412         slap_bindconf *sb;
1413         if ( li->li_acl_authmethod != LDAP_AUTH_NONE )
1414                 sb = &li->li_acl;
1415         else
1416                 sb = &li->li_idassert.si_bc;
1417
1418         if ( sb->sb_method == LDAP_AUTH_SASL ) {
1419                 void            *defaults = NULL;
1420
1421                 if ( sb->sb_secprops != NULL ) {
1422                         rc = ldap_set_option( lc->lc_ld,
1423                                 LDAP_OPT_X_SASL_SECPROPS, sb->sb_secprops );
1424
1425                         if ( rc != LDAP_OPT_SUCCESS ) {
1426                                 Debug( LDAP_DEBUG_ANY, "Error: ldap_set_option "
1427                                         "(SECPROPS,\"%s\") failed!\n",
1428                                         sb->sb_secprops, 0, 0 );
1429                                 goto done;
1430                         }
1431                 }
1432
1433                 defaults = lutil_sasl_defaults( lc->lc_ld,
1434                                 sb->sb_saslmech.bv_val,
1435                                 sb->sb_realm.bv_val,
1436                                 sb->sb_authcId.bv_val,
1437                                 sb->sb_cred.bv_val,
1438                                 NULL );
1439                 if ( defaults == NULL ) {
1440                         rs->sr_err = LDAP_OTHER;
1441                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1442                         if ( sendok & LDAP_BACK_SENDERR ) {
1443                                 send_ldap_result( op, rs );
1444                         }
1445                         goto done;
1446                 }
1447
1448                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld,
1449                                 sb->sb_binddn.bv_val,
1450                                 sb->sb_saslmech.bv_val, NULL, NULL,
1451                                 LDAP_SASL_QUIET, lutil_sasl_interact,
1452                                 defaults );
1453
1454                 lutil_sasl_freedefs( defaults );
1455
1456                 switch ( rs->sr_err ) {
1457                 case LDAP_SUCCESS:
1458                         LDAP_BACK_CONN_ISBOUND_SET( lc );
1459                         break;
1460
1461                 case LDAP_LOCAL_ERROR:
1462                         /* list client API error codes that require
1463                          * to taint the connection */
1464                         /* FIXME: should actually retry? */
1465                         LDAP_BACK_CONN_TAINTED_SET( lc );
1466
1467                         /* fallthru */
1468
1469                 default:
1470                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1471                         rs->sr_err = slap_map_api2result( rs );
1472                         if ( sendok & LDAP_BACK_SENDERR ) {
1473                                 send_ldap_result( op, rs );
1474                         }
1475                         break;
1476                 }
1477
1478                 if ( LDAP_BACK_QUARANTINE( li ) ) {
1479                         ldap_back_quarantine( op, rs );
1480                 }
1481
1482                 goto done;
1483         }
1484         }
1485 #endif /* HAVE_CYRUS_SASL */
1486
1487 retry:;
1488         if ( BER_BVISNULL( &lc->lc_cred ) ) {
1489                 tmp_dn = "";
1490                 if ( !BER_BVISNULL( &lc->lc_bound_ndn ) && !BER_BVISEMPTY( &lc->lc_bound_ndn ) ) {
1491                         Debug( LDAP_DEBUG_ANY, "%s ldap_back_dobind_int: DN=\"%s\" without creds, binding anonymously",
1492                                 op->o_log_prefix, lc->lc_bound_ndn.bv_val, 0 );
1493                 }
1494
1495         } else {
1496                 tmp_dn = lc->lc_bound_ndn.bv_val;
1497         }
1498         rs->sr_err = ldap_sasl_bind( lc->lc_ld,
1499                         tmp_dn,
1500                         LDAP_SASL_SIMPLE, &lc->lc_cred,
1501                         NULL, NULL, &msgid );
1502
1503         if ( rs->sr_err == LDAP_SERVER_DOWN ) {
1504                 if ( retries != LDAP_BACK_RETRY_NEVER ) {
1505                         if ( dolock ) {
1506                                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1507                         }
1508
1509                         assert( lc->lc_refcnt > 0 );
1510                         if ( lc->lc_refcnt == 1 ) {
1511                                 ldap_unbind_ext( lc->lc_ld, NULL, NULL );
1512                                 lc->lc_ld = NULL;
1513
1514                                 /* lc here must be the regular lc, reset and ready for init */
1515                                 rs->sr_err = ldap_back_prepare_conn( lc, op, rs, sendok );
1516                                 if ( rs->sr_err != LDAP_SUCCESS ) {
1517                                         sendok &= ~LDAP_BACK_SENDERR;
1518                                         lc->lc_refcnt = 0;
1519                                 }
1520                         }
1521
1522                         if ( dolock ) {
1523                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1524                         }
1525
1526                         if ( rs->sr_err == LDAP_SUCCESS ) {
1527                                 if ( retries > 0 ) {
1528                                         retries--;
1529                                 }
1530                                 goto retry;
1531                         }
1532                 }
1533
1534                 assert( lc->lc_refcnt == 1 );
1535                 lc->lc_refcnt = 0;
1536                 ldap_back_freeconn( li, lc, dolock );
1537                 *lcp = NULL;
1538                 rs->sr_err = slap_map_api2result( rs );
1539
1540                 if ( LDAP_BACK_QUARANTINE( li ) ) {
1541                         ldap_back_quarantine( op, rs );
1542                 }
1543
1544                 if ( rs->sr_err != LDAP_SUCCESS &&
1545                         ( sendok & LDAP_BACK_SENDERR ) )
1546                 {
1547                         if ( op->o_callback == &cb )
1548                                 op->o_callback = cb.sc_next;
1549                         op->o_tag = o_tag;
1550                         rs->sr_text = "Proxy can't contact remote server";
1551                         send_ldap_result( op, rs );
1552                 }
1553
1554                 rc = 0;
1555                 goto func_leave;
1556         }
1557
1558         rc = ldap_back_op_result( lc, op, rs, msgid,
1559                 -1, ( sendok | LDAP_BACK_BINDING ) );
1560         if ( rc == LDAP_SUCCESS ) {
1561                 op->o_conn->c_authz_cookie = op->o_bd->be_private;
1562                 LDAP_BACK_CONN_ISBOUND_SET( lc );
1563         }
1564
1565 done:;
1566         LDAP_BACK_CONN_BINDING_CLEAR( lc );
1567         rc = LDAP_BACK_CONN_ISBOUND( lc );
1568         if ( !rc ) {
1569                 ldap_back_release_conn_lock( li, lcp, dolock );
1570
1571         } else if ( LDAP_BACK_SAVECRED( li ) ) {
1572                 ldap_set_rebind_proc( lc->lc_ld, li->li_rebind_f, lc );
1573         }
1574
1575 func_leave:;
1576         if ( op->o_callback == &cb )
1577                 op->o_callback = cb.sc_next;
1578         op->o_tag = o_tag;
1579
1580         return rc;
1581 }
1582
1583 /*
1584  * ldap_back_dobind
1585  *
1586  * Note: dolock indicates whether li->li_conninfo.lai_mutex must be locked or not
1587  */
1588 int
1589 ldap_back_dobind( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1590 {
1591         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1592
1593         return ldap_back_dobind_int( lcp, op, rs,
1594                 ( sendok | LDAP_BACK_GETCONN ), li->li_nretries, 1 );
1595 }
1596
1597 /*
1598  * ldap_back_default_rebind
1599  *
1600  * This is a callback used for chasing referrals using the same
1601  * credentials as the original user on this session.
1602  */
1603 int 
1604 ldap_back_default_rebind( LDAP *ld, LDAP_CONST char *url, ber_tag_t request,
1605         ber_int_t msgid, void *params )
1606 {
1607         ldapconn_t      *lc = (ldapconn_t *)params;
1608
1609 #ifdef HAVE_TLS
1610         /* ... otherwise we couldn't get here */
1611         assert( lc != NULL );
1612
1613         if ( !ldap_tls_inplace( ld ) ) {
1614                 int             is_tls = LDAP_BACK_CONN_ISTLS( lc ),
1615                                 rc;
1616                 const char      *text = NULL;
1617
1618                 rc = ldap_back_start_tls( ld, 0, &is_tls, url, lc->lc_flags,
1619                         LDAP_BACK_RETRY_DEFAULT, &text );
1620                 if ( rc != LDAP_SUCCESS ) {
1621                         return rc;
1622                 }
1623         }
1624 #endif /* HAVE_TLS */
1625
1626         /* FIXME: add checks on the URL/identity? */
1627
1628         return ldap_sasl_bind_s( ld,
1629                         BER_BVISNULL( &lc->lc_cred ) ? "" : lc->lc_bound_ndn.bv_val,
1630                         LDAP_SASL_SIMPLE, &lc->lc_cred, NULL, NULL, NULL );
1631 }
1632
1633 /*
1634  * ldap_back_default_urllist
1635  */
1636 int 
1637 ldap_back_default_urllist(
1638         LDAP            *ld,
1639         LDAPURLDesc     **urllist,
1640         LDAPURLDesc     **url,
1641         void            *params )
1642 {
1643         ldapinfo_t      *li = (ldapinfo_t *)params;
1644         LDAPURLDesc     **urltail;
1645
1646         if ( urllist == url ) {
1647                 return LDAP_SUCCESS;
1648         }
1649
1650         for ( urltail = &(*url)->lud_next; *urltail; urltail = &(*urltail)->lud_next )
1651                 /* count */ ;
1652
1653         *urltail = *urllist;
1654         *urllist = *url;
1655         *url = NULL;
1656
1657         if ( !li->li_uri_mutex_do_not_lock ) {
1658                 ldap_pvt_thread_mutex_lock( &li->li_uri_mutex );
1659         }
1660
1661         if ( li->li_uri ) {
1662                 ch_free( li->li_uri );
1663         }
1664
1665         ldap_get_option( ld, LDAP_OPT_URI, (void *)&li->li_uri );
1666
1667         if ( !li->li_uri_mutex_do_not_lock ) {
1668                 ldap_pvt_thread_mutex_unlock( &li->li_uri_mutex );
1669         }
1670
1671         return LDAP_SUCCESS;
1672 }
1673
1674 int
1675 ldap_back_cancel(
1676                 ldapconn_t              *lc,
1677                 Operation               *op,
1678                 SlapReply               *rs,
1679                 ber_int_t               msgid,
1680                 ldap_back_send_t        sendok )
1681 {
1682         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1683
1684         /* default behavior */
1685         if ( LDAP_BACK_ABANDON( li ) ) {
1686                 return ldap_abandon_ext( lc->lc_ld, msgid, NULL, NULL );
1687         }
1688
1689         if ( LDAP_BACK_IGNORE( li ) ) {
1690                 return ldap_pvt_discard( lc->lc_ld, msgid );
1691         }
1692
1693         if ( LDAP_BACK_CANCEL( li ) ) {
1694                 /* FIXME: asynchronous? */
1695                 return ldap_cancel_s( lc->lc_ld, msgid, NULL, NULL );
1696         }
1697
1698         assert( 0 );
1699
1700         return LDAP_OTHER;
1701 }
1702
1703 int
1704 ldap_back_op_result(
1705                 ldapconn_t              *lc,
1706                 Operation               *op,
1707                 SlapReply               *rs,
1708                 ber_int_t               msgid,
1709                 time_t                  timeout,
1710                 ldap_back_send_t        sendok )
1711 {
1712         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1713
1714         char            *match = NULL;
1715         char            *text = NULL;
1716         char            **refs = NULL;
1717         LDAPControl     **ctrls = NULL;
1718
1719         rs->sr_text = NULL;
1720         rs->sr_matched = NULL;
1721         rs->sr_ref = NULL;
1722         rs->sr_ctrls = NULL;
1723
1724         /* if the error recorded in the reply corresponds
1725          * to a successful state, get the error from the
1726          * remote server response */
1727         if ( LDAP_ERR_OK( rs->sr_err ) ) {
1728                 int             rc;
1729                 struct timeval  tv;
1730                 LDAPMessage     *res = NULL;
1731                 time_t          stoptime = (time_t)(-1);
1732                 int             timeout_err = op->o_protocol >= LDAP_VERSION3 ?
1733                                         LDAP_ADMINLIMIT_EXCEEDED : LDAP_OTHER;
1734                 const char      *timeout_text = "Operation timed out";
1735
1736                 /* if timeout is not specified, compute and use
1737                  * the one specific to the ongoing operation */
1738                 if ( timeout == (time_t)(-1) ) {
1739                         slap_op_t       opidx = slap_req2op( op->o_tag );
1740
1741                         if ( opidx == SLAP_OP_SEARCH ) {
1742                                 if ( op->ors_tlimit <= 0 ) {
1743                                         timeout = 0;
1744
1745                                 } else {
1746                                         timeout = op->ors_tlimit;
1747                                         timeout_err = LDAP_TIMELIMIT_EXCEEDED;
1748                                         timeout_text = NULL;
1749                                 }
1750
1751                         } else {
1752                                 timeout = li->li_timeout[ opidx ];
1753                         }
1754                 }
1755
1756                 /* better than nothing :) */
1757                 if ( timeout == 0 ) {
1758                         if ( li->li_idle_timeout ) {
1759                                 timeout = li->li_idle_timeout;
1760
1761                         } else if ( li->li_conn_ttl ) {
1762                                 timeout = li->li_conn_ttl;
1763                         }
1764                 }
1765
1766                 if ( timeout ) {
1767                         stoptime = op->o_time + timeout;
1768                 }
1769
1770                 LDAP_BACK_TV_SET( &tv );
1771
1772 retry:;
1773                 /* if result parsing fails, note the failure reason */
1774                 rc = ldap_result( lc->lc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
1775                 switch ( rc ) {
1776                 case 0:
1777                         if ( timeout && slap_get_time() > stoptime ) {
1778                                 if ( sendok & LDAP_BACK_BINDING ) {
1779                                         ldap_unbind_ext( lc->lc_ld, NULL, NULL );
1780                                         lc->lc_ld = NULL;
1781
1782                                         /* let it be used, but taint/delete it so that 
1783                                          * no-one else can look it up any further */
1784                                         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1785
1786 #if LDAP_BACK_PRINT_CONNTREE > 0
1787                                         ldap_back_print_conntree( li, ">>> ldap_back_getconn(timeout)" );
1788 #endif /* LDAP_BACK_PRINT_CONNTREE */
1789
1790                                         (void)ldap_back_conn_delete( li, lc );
1791                                         LDAP_BACK_CONN_TAINTED_SET( lc );
1792
1793 #if LDAP_BACK_PRINT_CONNTREE > 0
1794                                         ldap_back_print_conntree( li, "<<< ldap_back_getconn(timeout)" );
1795 #endif /* LDAP_BACK_PRINT_CONNTREE */
1796                                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1797
1798                                 } else {
1799                                         (void)ldap_back_cancel( lc, op, rs, msgid, sendok );
1800                                 }
1801                                 rs->sr_err = timeout_err;
1802                                 rs->sr_text = timeout_text;
1803                                 break;
1804                         }
1805
1806                         /* timeout == 0 */
1807                         LDAP_BACK_TV_SET( &tv );
1808                         ldap_pvt_thread_yield();
1809                         goto retry;
1810
1811                 case -1:
1812                         ldap_get_option( lc->lc_ld, LDAP_OPT_ERROR_NUMBER,
1813                                         &rs->sr_err );
1814                         break;
1815
1816
1817                 /* otherwise get the result; if it is not
1818                  * LDAP_SUCCESS, record it in the reply
1819                  * structure (this includes 
1820                  * LDAP_COMPARE_{TRUE|FALSE}) */
1821                 default:
1822                         /* only touch when activity actually took place... */
1823                         if ( li->li_idle_timeout && lc ) {
1824                                 lc->lc_time = op->o_time;
1825                         }
1826
1827                         rc = ldap_parse_result( lc->lc_ld, res, &rs->sr_err,
1828                                         &match, &text, &refs, &ctrls, 1 );
1829                         if ( rc == LDAP_SUCCESS ) {
1830                                 rs->sr_text = text;
1831                         } else {
1832                                 rs->sr_err = rc;
1833                         }
1834                         rs->sr_err = slap_map_api2result( rs );
1835
1836                         /* RFC 4511: referrals can only appear
1837                          * if result code is LDAP_REFERRAL */
1838                         if ( refs != NULL
1839                                 && refs[ 0 ] != NULL
1840                                 && refs[ 0 ][ 0 ] != '\0' )
1841                         {
1842                                 if ( rs->sr_err != LDAP_REFERRAL ) {
1843                                         Debug( LDAP_DEBUG_ANY,
1844                                                 "%s ldap_back_op_result: "
1845                                                 "got referrals with err=%d\n",
1846                                                 op->o_log_prefix,
1847                                                 rs->sr_err, 0 );
1848
1849                                 } else {
1850                                         int     i;
1851
1852                                         for ( i = 0; refs[ i ] != NULL; i++ )
1853                                                 /* count */ ;
1854                                         rs->sr_ref = op->o_tmpalloc( sizeof( struct berval ) * ( i + 1 ),
1855                                                 op->o_tmpmemctx );
1856                                         for ( i = 0; refs[ i ] != NULL; i++ ) {
1857                                                 ber_str2bv( refs[ i ], 0, 0, &rs->sr_ref[ i ] );
1858                                         }
1859                                         BER_BVZERO( &rs->sr_ref[ i ] );
1860                                 }
1861
1862                         } else if ( rs->sr_err == LDAP_REFERRAL ) {
1863                                 Debug( LDAP_DEBUG_ANY,
1864                                         "%s ldap_back_op_result: "
1865                                         "got err=%d with null "
1866                                         "or empty referrals\n",
1867                                         op->o_log_prefix,
1868                                         rs->sr_err, 0 );
1869
1870                                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
1871                         }
1872
1873                         if ( ctrls != NULL ) {
1874                                 rs->sr_ctrls = ctrls;
1875                         }
1876                 }
1877         }
1878
1879         /* if the error in the reply structure is not
1880          * LDAP_SUCCESS, try to map it from client 
1881          * to server error */
1882         if ( !LDAP_ERR_OK( rs->sr_err ) ) {
1883                 rs->sr_err = slap_map_api2result( rs );
1884
1885                 /* internal ops ( op->o_conn == NULL ) 
1886                  * must not reply to client */
1887                 if ( op->o_conn && !op->o_do_not_cache && match ) {
1888
1889                         /* record the (massaged) matched
1890                          * DN into the reply structure */
1891                         rs->sr_matched = match;
1892                 }
1893         }
1894
1895         if ( rs->sr_err == LDAP_UNAVAILABLE ) {
1896                 if ( !( sendok & LDAP_BACK_RETRYING ) ) {
1897                         if ( LDAP_BACK_QUARANTINE( li ) ) {
1898                                 ldap_back_quarantine( op, rs );
1899                         }
1900                         if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
1901                                 if ( rs->sr_text == NULL ) rs->sr_text = "Proxy operation retry failed";
1902                                 send_ldap_result( op, rs );
1903                         }
1904                 }
1905
1906         } else if ( op->o_conn &&
1907                 ( ( ( sendok & LDAP_BACK_SENDOK ) && LDAP_ERR_OK( rs->sr_err ) )
1908                         || ( ( sendok & LDAP_BACK_SENDERR ) && !LDAP_ERR_OK( rs->sr_err ) ) ) )
1909         {
1910                 send_ldap_result( op, rs );
1911         }
1912
1913         if ( text ) {
1914                 ldap_memfree( text );
1915         }
1916         rs->sr_text = NULL;
1917
1918         /* there can't be refs with a (successful) bind */
1919         if ( rs->sr_ref ) {
1920                 op->o_tmpfree( rs->sr_ref, op->o_tmpmemctx );
1921                 rs->sr_ref = NULL;
1922         }
1923
1924         if ( refs ) {
1925                 ber_memvfree( (void **)refs );
1926         }
1927
1928         /* match should not be possible with a successful bind */
1929         if ( match ) {
1930                 if ( rs->sr_matched != match ) {
1931                         free( (char *)rs->sr_matched );
1932                 }
1933                 rs->sr_matched = NULL;
1934                 ldap_memfree( match );
1935         }
1936
1937         if ( ctrls != NULL ) {
1938                 if ( op->o_tag == LDAP_REQ_BIND && rs->sr_err == LDAP_SUCCESS ) {
1939                         int i;
1940
1941                         for ( i = 0; ctrls[i] != NULL; i++ );
1942
1943                         rs->sr_ctrls = op->o_tmpalloc( sizeof( LDAPControl * )*( i + 1 ),
1944                                 op->o_tmpmemctx );
1945                         for ( i = 0; ctrls[ i ] != NULL; i++ ) {
1946                                 char *ptr;
1947                                 ber_len_t oidlen = strlen( ctrls[i]->ldctl_oid );
1948                                 ber_len_t size = sizeof( LDAPControl )
1949                                         + oidlen + 1
1950                                         + ctrls[i]->ldctl_value.bv_len + 1;
1951         
1952                                 rs->sr_ctrls[ i ] = op->o_tmpalloc( size, op->o_tmpmemctx );
1953                                 rs->sr_ctrls[ i ]->ldctl_oid = (char *)&rs->sr_ctrls[ i ][ 1 ];
1954                                 lutil_strcopy( rs->sr_ctrls[ i ]->ldctl_oid, ctrls[i]->ldctl_oid );
1955                                 rs->sr_ctrls[ i ]->ldctl_value.bv_val
1956                                                 = (char *)&rs->sr_ctrls[ i ]->ldctl_oid[oidlen + 1];
1957                                 rs->sr_ctrls[ i ]->ldctl_value.bv_len
1958                                         = ctrls[i]->ldctl_value.bv_len;
1959                                 ptr = lutil_memcopy( rs->sr_ctrls[ i ]->ldctl_value.bv_val,
1960                                         ctrls[i]->ldctl_value.bv_val, ctrls[i]->ldctl_value.bv_len );
1961                                 *ptr = '\0';
1962                         }
1963                         rs->sr_ctrls[ i ] = NULL;
1964                         rs->sr_flags |= REP_CTRLS_MUSTBEFREED;
1965
1966                 } else {
1967                         assert( rs->sr_ctrls != NULL );
1968                         rs->sr_ctrls = NULL;
1969                 }
1970
1971                 ldap_controls_free( ctrls );
1972         }
1973
1974         return( LDAP_ERR_OK( rs->sr_err ) ? LDAP_SUCCESS : rs->sr_err );
1975 }
1976
1977 /* return true if bound, false if failed */
1978 int
1979 ldap_back_retry( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1980 {
1981         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1982         int             rc = 0;
1983
1984         assert( lcp != NULL );
1985         assert( *lcp != NULL );
1986
1987         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1988
1989         if ( (*lcp)->lc_refcnt == 1 ) {
1990                 int binding = LDAP_BACK_CONN_BINDING( *lcp );
1991
1992                 ldap_pvt_thread_mutex_lock( &li->li_uri_mutex );
1993                 Debug( LDAP_DEBUG_ANY,
1994                         "%s ldap_back_retry: retrying URI=\"%s\" DN=\"%s\"\n",
1995                         op->o_log_prefix, li->li_uri,
1996                         BER_BVISNULL( &(*lcp)->lc_bound_ndn ) ?
1997                                 "" : (*lcp)->lc_bound_ndn.bv_val );
1998                 ldap_pvt_thread_mutex_unlock( &li->li_uri_mutex );
1999
2000                 ldap_unbind_ext( (*lcp)->lc_ld, NULL, NULL );
2001                 (*lcp)->lc_ld = NULL;
2002                 LDAP_BACK_CONN_ISBOUND_CLEAR( (*lcp) );
2003
2004                 /* lc here must be the regular lc, reset and ready for init */
2005                 rc = ldap_back_prepare_conn( *lcp, op, rs, sendok );
2006                 if ( rc != LDAP_SUCCESS ) {
2007                         /* freeit, because lc_refcnt == 1 */
2008                         (*lcp)->lc_refcnt = 0;
2009                         (void)ldap_back_freeconn( li, *lcp, 0 );
2010                         *lcp = NULL;
2011                         rc = 0;
2012
2013                 } else if ( ( sendok & LDAP_BACK_BINDING ) ) {
2014                         if ( binding ) {
2015                                 LDAP_BACK_CONN_BINDING_SET( *lcp );
2016                         }
2017                         rc = 1;
2018
2019                 } else {
2020                         rc = ldap_back_dobind_int( lcp, op, rs, sendok, 0, 0 );
2021                         if ( rc == 0 && *lcp != NULL ) {
2022                                 /* freeit, because lc_refcnt == 1 */
2023                                 (*lcp)->lc_refcnt = 0;
2024                                 LDAP_BACK_CONN_TAINTED_SET( *lcp );
2025                                 (void)ldap_back_freeconn( li, *lcp, 0 );
2026                                 *lcp = NULL;
2027                         }
2028                 }
2029
2030         } else {
2031                 Debug( LDAP_DEBUG_TRACE,
2032                         "ldap_back_retry: conn %p refcnt=%u unable to retry.\n",
2033                         (void *)(*lcp), (*lcp)->lc_refcnt, 0 );
2034
2035                 LDAP_BACK_CONN_TAINTED_SET( *lcp );
2036                 ldap_back_release_conn_lock( li, lcp, 0 );
2037                 assert( *lcp == NULL );
2038
2039                 if ( sendok & LDAP_BACK_SENDERR ) {
2040                         rs->sr_err = LDAP_UNAVAILABLE;
2041                         rs->sr_text = "Unable to retry";
2042                         send_ldap_result( op, rs );
2043                 }
2044         }
2045
2046         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
2047
2048         return rc;
2049 }
2050
2051 static int
2052 ldap_back_is_proxy_authz( Operation *op, SlapReply *rs, ldap_back_send_t sendok,
2053         struct berval *binddn, struct berval *bindcred )
2054 {
2055         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
2056         struct berval   ndn;
2057         int             dobind = 0;
2058
2059         if ( op->o_conn == NULL || op->o_do_not_cache ) {
2060                 goto done;
2061         }
2062
2063         /* don't proxyAuthz if protocol is not LDAPv3 */
2064         switch ( li->li_version ) {
2065         case LDAP_VERSION3:
2066                 break;
2067
2068         case 0:
2069                 if ( op->o_protocol == 0 || op->o_protocol == LDAP_VERSION3 ) {
2070                         break;
2071                 }
2072                 /* fall thru */
2073
2074         default:
2075                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
2076                 if ( sendok & LDAP_BACK_SENDERR ) {
2077                         send_ldap_result( op, rs );
2078                         dobind = -1;
2079                 }
2080                 goto done;
2081         }
2082
2083         /* safe default */
2084         *binddn = slap_empty_bv;
2085         *bindcred = slap_empty_bv;
2086
2087         if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
2088                 ndn = op->o_conn->c_ndn;
2089
2090         } else {
2091                 ndn = op->o_ndn;
2092         }
2093
2094         switch ( li->li_idassert_mode ) {
2095         case LDAP_BACK_IDASSERT_LEGACY:
2096                 if ( !BER_BVISNULL( &ndn ) && !BER_BVISEMPTY( &ndn ) ) {
2097                         if ( !BER_BVISNULL( &li->li_idassert_authcDN ) && !BER_BVISEMPTY( &li->li_idassert_authcDN ) )
2098                         {
2099                                 *binddn = li->li_idassert_authcDN;
2100                                 *bindcred = li->li_idassert_passwd;
2101                                 dobind = 1;
2102                         }
2103                 }
2104                 break;
2105
2106         default:
2107                 /* NOTE: rootdn can always idassert */
2108                 if ( BER_BVISNULL( &ndn )
2109                         && li->li_idassert_authz == NULL
2110                         && !( li->li_idassert_flags & LDAP_BACK_AUTH_AUTHZ_ALL ) )
2111                 {
2112                         if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
2113                                 rs->sr_err = LDAP_INAPPROPRIATE_AUTH;
2114                                 if ( sendok & LDAP_BACK_SENDERR ) {
2115                                         send_ldap_result( op, rs );
2116                                         dobind = -1;
2117                                 }
2118
2119                         } else {
2120                                 rs->sr_err = LDAP_SUCCESS;
2121                                 *binddn = slap_empty_bv;
2122                                 *bindcred = slap_empty_bv;
2123                                 break;
2124                         }
2125
2126                         goto done;
2127
2128                 } else if ( !be_isroot( op ) ) {
2129                         if ( li->li_idassert_passthru ) {
2130                                 struct berval authcDN;
2131
2132                                 if ( BER_BVISNULL( &ndn ) ) {
2133                                         authcDN = slap_empty_bv;
2134
2135                                 } else {
2136                                         authcDN = ndn;
2137                                 }       
2138                                 rs->sr_err = slap_sasl_matches( op, li->li_idassert_passthru,
2139                                                 &authcDN, &authcDN );
2140                                 if ( rs->sr_err == LDAP_SUCCESS ) {
2141                                         dobind = 0;
2142                                         break;
2143                                 }
2144                         }
2145
2146                         if ( li->li_idassert_authz ) {
2147                                 struct berval authcDN;
2148
2149                                 if ( BER_BVISNULL( &ndn ) ) {
2150                                         authcDN = slap_empty_bv;
2151
2152                                 } else {
2153                                         authcDN = ndn;
2154                                 }       
2155                                 rs->sr_err = slap_sasl_matches( op, li->li_idassert_authz,
2156                                                 &authcDN, &authcDN );
2157                                 if ( rs->sr_err != LDAP_SUCCESS ) {
2158                                         if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
2159                                                 if ( sendok & LDAP_BACK_SENDERR ) {
2160                                                         send_ldap_result( op, rs );
2161                                                         dobind = -1;
2162                                                 }
2163
2164                                         } else {
2165                                                 rs->sr_err = LDAP_SUCCESS;
2166                                                 *binddn = slap_empty_bv;
2167                                                 *bindcred = slap_empty_bv;
2168                                                 break;
2169                                         }
2170
2171                                         goto done;
2172                                 }
2173                         }
2174                 }
2175
2176                 *binddn = li->li_idassert_authcDN;
2177                 *bindcred = li->li_idassert_passwd;
2178                 dobind = 1;
2179                 break;
2180         }
2181
2182 done:;
2183         return dobind;
2184 }
2185
2186 static int
2187 ldap_back_proxy_authz_bind(
2188         ldapconn_t              *lc,
2189         Operation               *op,
2190         SlapReply               *rs,
2191         ldap_back_send_t        sendok,
2192         struct berval           *binddn,
2193         struct berval           *bindcred )
2194 {
2195         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
2196         struct berval   ndn;
2197         int             msgid;
2198         int             rc;
2199
2200         if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
2201                 ndn = op->o_conn->c_ndn;
2202
2203         } else {
2204                 ndn = op->o_ndn;
2205         }
2206
2207         if ( li->li_idassert_authmethod == LDAP_AUTH_SASL ) {
2208 #ifdef HAVE_CYRUS_SASL
2209                 void            *defaults = NULL;
2210                 struct berval   authzID = BER_BVNULL;
2211                 int             freeauthz = 0;
2212                 LDAPControl **ctrlsp = NULL;
2213                 LDAPMessage *result = NULL;
2214                 const char *rmech = NULL;
2215                 const char *save_text = rs->sr_text;
2216
2217 #ifdef SLAP_AUTH_DN
2218                 LDAPControl ctrl, *ctrls[2];
2219                 int msgid;
2220 #endif /* SLAP_AUTH_DN */
2221
2222                 /* if SASL supports native authz, prepare for it */
2223                 if ( ( !op->o_do_not_cache || !op->o_is_auth_check ) &&
2224                                 ( li->li_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
2225                 {
2226                         switch ( li->li_idassert_mode ) {
2227                         case LDAP_BACK_IDASSERT_OTHERID:
2228                         case LDAP_BACK_IDASSERT_OTHERDN:
2229                                 authzID = li->li_idassert_authzID;
2230                                 break;
2231
2232                         case LDAP_BACK_IDASSERT_ANONYMOUS:
2233                                 BER_BVSTR( &authzID, "dn:" );
2234                                 break;
2235
2236                         case LDAP_BACK_IDASSERT_SELF:
2237                                 if ( BER_BVISNULL( &ndn ) ) {
2238                                         /* connection is not authc'd, so don't idassert */
2239                                         BER_BVSTR( &authzID, "dn:" );
2240                                         break;
2241                                 }
2242                                 authzID.bv_len = STRLENOF( "dn:" ) + ndn.bv_len;
2243                                 authzID.bv_val = slap_sl_malloc( authzID.bv_len + 1, op->o_tmpmemctx );
2244                                 AC_MEMCPY( authzID.bv_val, "dn:", STRLENOF( "dn:" ) );
2245                                 AC_MEMCPY( authzID.bv_val + STRLENOF( "dn:" ),
2246                                                 ndn.bv_val, ndn.bv_len + 1 );
2247                                 freeauthz = 1;
2248                                 break;
2249
2250                         default:
2251                                 break;
2252                         }
2253                 }
2254
2255                 if ( li->li_idassert_secprops != NULL ) {
2256                         rs->sr_err = ldap_set_option( lc->lc_ld,
2257                                 LDAP_OPT_X_SASL_SECPROPS,
2258                                 (void *)li->li_idassert_secprops );
2259
2260                         if ( rs->sr_err != LDAP_OPT_SUCCESS ) {
2261                                 rs->sr_err = LDAP_OTHER;
2262                                 if ( sendok & LDAP_BACK_SENDERR ) {
2263                                         send_ldap_result( op, rs );
2264                                 }
2265                                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
2266                                 goto done;
2267                         }
2268                 }
2269
2270                 defaults = lutil_sasl_defaults( lc->lc_ld,
2271                                 li->li_idassert_sasl_mech.bv_val,
2272                                 li->li_idassert_sasl_realm.bv_val,
2273                                 li->li_idassert_authcID.bv_val,
2274                                 li->li_idassert_passwd.bv_val,
2275                                 authzID.bv_val );
2276                 if ( defaults == NULL ) {
2277                         rs->sr_err = LDAP_OTHER;
2278                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
2279                         if ( sendok & LDAP_BACK_SENDERR ) {
2280                                 send_ldap_result( op, rs );
2281                         }
2282                         goto done;
2283                 }
2284
2285 #ifdef SLAP_AUTH_DN
2286                 if ( li->li_idassert_flags & LDAP_BACK_AUTH_DN_AUTHZID ) {
2287                         assert( BER_BVISNULL( binddn ) );
2288
2289                         ctrl.ldctl_oid = LDAP_CONTROL_AUTHZID_REQUEST;
2290                         ctrl.ldctl_iscritical = 0;
2291                         BER_BVZERO( &ctrl.ldctl_value );
2292                         ctrls[0] = &ctrl;
2293                         ctrls[1] = NULL;
2294                         ctrlsp = ctrls;
2295                 }
2296 #endif /* SLAP_AUTH_DN */
2297
2298                 do {
2299                         rs->sr_err = ldap_sasl_interactive_bind( lc->lc_ld, binddn->bv_val,
2300                                 li->li_idassert_sasl_mech.bv_val, 
2301                                 ctrlsp, NULL, LDAP_SASL_QUIET, lutil_sasl_interact, defaults,
2302                                 result, &rmech, &msgid );
2303
2304                         if ( rs->sr_err != LDAP_SASL_BIND_IN_PROGRESS )
2305                                 break;
2306
2307                         ldap_msgfree( result );
2308
2309                         if ( ldap_result( lc->lc_ld, msgid, LDAP_MSG_ALL, NULL, &result ) == -1 || !result ) {
2310                                 ldap_get_option( lc->lc_ld, LDAP_OPT_RESULT_CODE, (void*)&rs->sr_err );
2311                                 ldap_get_option( lc->lc_ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&rs->sr_text );
2312                                 break;
2313                         }
2314                 } while ( rs->sr_err == LDAP_SASL_BIND_IN_PROGRESS );
2315
2316                 switch ( rs->sr_err ) {
2317                 case LDAP_SUCCESS:
2318 #ifdef SLAP_AUTH_DN
2319                         /* FIXME: right now, the only reason to check
2320                          * response controls is RFC 3829 authzid */
2321                         if ( li->li_idassert_flags & LDAP_BACK_AUTH_DN_AUTHZID ) {
2322                                 ctrlsp = NULL;
2323                                 rc = ldap_parse_result( lc->lc_ld, result, NULL, NULL, NULL, NULL,
2324                                         &ctrlsp, 0 );
2325                                 if ( rc == LDAP_SUCCESS && ctrlsp ) {
2326                                         LDAPControl *ctrl;
2327                 
2328                                         ctrl = ldap_control_find( LDAP_CONTROL_AUTHZID_RESPONSE,
2329                                                 ctrlsp, NULL );
2330                                         if ( ctrl ) {
2331                                                 Debug( LDAP_DEBUG_TRACE, "%s: ldap_back_proxy_authz_bind: authzID=\"%s\" (authzid)\n",
2332                                                         op->o_log_prefix, ctrl->ldctl_value.bv_val, 0 );
2333                                                 if ( ctrl->ldctl_value.bv_len > STRLENOF("dn:") &&
2334                                                         strncasecmp( ctrl->ldctl_value.bv_val, "dn:", STRLENOF("dn:") ) == 0 )
2335                                                 {
2336                                                         struct berval bv;
2337                                                         bv.bv_val = &ctrl->ldctl_value.bv_val[STRLENOF("dn:")];
2338                                                         bv.bv_len = ctrl->ldctl_value.bv_len - STRLENOF("dn:");
2339                                                         ber_bvreplace( &lc->lc_bound_ndn, &bv );
2340                                                 }
2341                                         }
2342                                 }
2343
2344                                 ldap_controls_free( ctrlsp );
2345
2346                         } else if ( li->li_idassert_flags & LDAP_BACK_AUTH_DN_WHOAMI ) {
2347                                 struct berval *val = NULL;
2348                                 rc = ldap_whoami_s( lc->lc_ld, &val, NULL, NULL );
2349                                 if ( rc == LDAP_SUCCESS && val != NULL ) {
2350                                         Debug( LDAP_DEBUG_TRACE, "%s: ldap_back_proxy_authz_bind: authzID=\"%s\" (whoami)\n",
2351                                                 op->o_log_prefix, val->bv_val, 0 );
2352                                         if ( val->bv_len > STRLENOF("dn:") &&
2353                                                 strncasecmp( val->bv_val, "dn:", STRLENOF("dn:") ) == 0 )
2354                                         {
2355                                                 struct berval bv;
2356                                                 bv.bv_val = &val->bv_val[STRLENOF("dn:")];
2357                                                 bv.bv_len = val->bv_len - STRLENOF("dn:");
2358                                                 ber_bvreplace( &lc->lc_bound_ndn, &bv );
2359                                         }
2360                                         ber_bvfree( val );
2361                                 }
2362                         }
2363
2364                         if ( ( li->li_idassert_flags & LDAP_BACK_AUTH_DN_MASK ) &&
2365                                 BER_BVISNULL( &lc->lc_bound_ndn ) )
2366                         {
2367                                 /* all in all, we only need it to be non-null */
2368                                 /* FIXME: should this be configurable? */
2369                                 static struct berval bv = BER_BVC("cn=authzdn");
2370                                 ber_bvreplace( &lc->lc_bound_ndn, &bv );
2371                         }
2372 #endif /* SLAP_AUTH_DN */
2373                         op->o_conn->c_authz_cookie = op->o_bd->be_private;
2374                         LDAP_BACK_CONN_ISBOUND_SET( lc );
2375                         break;
2376
2377                 case LDAP_LOCAL_ERROR:
2378                         /* list client API error codes that require
2379                          * to taint the connection */
2380                         /* FIXME: should actually retry? */
2381                         LDAP_BACK_CONN_TAINTED_SET( lc );
2382
2383                         /* fallthru */
2384
2385                 default:
2386                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
2387                         rs->sr_err = slap_map_api2result( rs );
2388                         if ( sendok & LDAP_BACK_SENDERR ) {
2389                                 send_ldap_result( op, rs );
2390                         }
2391                         break;
2392                 }
2393
2394                 if ( save_text != rs->sr_text ) {
2395                         ldap_memfree( (char *)rs->sr_text );
2396                         rs->sr_text = save_text;
2397                 }
2398
2399                 ldap_msgfree( result );
2400
2401                 lutil_sasl_freedefs( defaults );
2402                 if ( freeauthz ) {
2403                         slap_sl_free( authzID.bv_val, op->o_tmpmemctx );
2404                 }
2405
2406                 goto done;
2407 #endif /* HAVE_CYRUS_SASL */
2408         }
2409
2410         switch ( li->li_idassert_authmethod ) {
2411         case LDAP_AUTH_NONE:
2412                 /* FIXME: do we really need this? */
2413                 BER_BVSTR( binddn, "" );
2414                 BER_BVSTR( bindcred, "" );
2415                 /* fallthru */
2416
2417         case LDAP_AUTH_SIMPLE:
2418                 rs->sr_err = ldap_sasl_bind( lc->lc_ld,
2419                                 binddn->bv_val, LDAP_SASL_SIMPLE,
2420                                 bindcred, NULL, NULL, &msgid );
2421                 rc = ldap_back_op_result( lc, op, rs, msgid,
2422                         -1, ( sendok | LDAP_BACK_BINDING ) );
2423                 break;
2424
2425         default:
2426                 /* unsupported! */
2427                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
2428                 rs->sr_err = LDAP_AUTH_METHOD_NOT_SUPPORTED;
2429                 if ( sendok & LDAP_BACK_SENDERR ) {
2430                         send_ldap_result( op, rs );
2431                 }
2432                 goto done;
2433         }
2434
2435         if ( rc == LDAP_SUCCESS ) {
2436                 /* set rebind stuff in case of successful proxyAuthz bind,
2437                  * so that referral chasing is attempted using the right
2438                  * identity */
2439                 LDAP_BACK_CONN_ISBOUND_SET( lc );
2440                 op->o_conn->c_authz_cookie = op->o_bd->be_private;
2441                 if ( !BER_BVISNULL( binddn ) ) {
2442                         ber_bvreplace( &lc->lc_bound_ndn, binddn );
2443                 }
2444
2445                 if ( !BER_BVISNULL( &lc->lc_cred ) ) {
2446                         memset( lc->lc_cred.bv_val, 0,
2447                                         lc->lc_cred.bv_len );
2448                 }
2449
2450                 if ( LDAP_BACK_SAVECRED( li ) ) {
2451                         if ( !BER_BVISNULL( bindcred ) ) {
2452                                 ber_bvreplace( &lc->lc_cred, bindcred );
2453                                 ldap_set_rebind_proc( lc->lc_ld, li->li_rebind_f, lc );
2454                         }
2455
2456                 } else {
2457                         lc->lc_cred.bv_len = 0;
2458                 }
2459         }
2460
2461 done:;
2462         return LDAP_BACK_CONN_ISBOUND( lc );
2463 }
2464
2465 /*
2466  * ldap_back_proxy_authz_ctrl() prepends a proxyAuthz control
2467  * to existing server-side controls if required; if not,
2468  * the existing server-side controls are placed in *pctrls.
2469  * The caller, after using the controls in client API 
2470  * operations, if ( *pctrls != op->o_ctrls ), should
2471  * free( (*pctrls)[ 0 ] ) and free( *pctrls ).
2472  * The function returns success if the control could
2473  * be added if required, or if it did nothing; in the future,
2474  * it might return some error if it failed.
2475  * 
2476  * if no bind took place yet, but the connection is bound
2477  * and the "proxyauthzdn" is set, then bind as "proxyauthzdn" 
2478  * and explicitly add proxyAuthz the control to every operation
2479  * with the dn bound to the connection as control value.
2480  *
2481  * If no server-side controls are defined for the operation,
2482  * simply add the proxyAuthz control; otherwise, if the
2483  * proxyAuthz control is not already set, add it as
2484  * the first one
2485  *
2486  * FIXME: is controls order significant for security?
2487  * ANSWER: controls ordering and interoperability
2488  * must be indicated by the specs of each control; if none
2489  * is specified, the order is irrelevant.
2490  */
2491 int
2492 ldap_back_proxy_authz_ctrl(
2493                 Operation       *op,
2494                 SlapReply       *rs,
2495                 struct berval   *bound_ndn,
2496                 int             version,
2497                 slap_idassert_t *si,
2498                 LDAPControl     *ctrl )
2499 {
2500         slap_idassert_mode_t    mode;
2501         struct berval           assertedID,
2502                                 ndn;
2503         int                     isroot = 0;
2504
2505         rs->sr_err = SLAP_CB_CONTINUE;
2506
2507         /* FIXME: SASL/EXTERNAL over ldapi:// doesn't honor the authcID,
2508          * but if it is not set this test fails.  We need a different
2509          * means to detect if idassert is enabled */
2510         if ( ( BER_BVISNULL( &si->si_bc.sb_authcId ) || BER_BVISEMPTY( &si->si_bc.sb_authcId ) )
2511                 && ( BER_BVISNULL( &si->si_bc.sb_binddn ) || BER_BVISEMPTY( &si->si_bc.sb_binddn ) )
2512                 && BER_BVISNULL( &si->si_bc.sb_saslmech ) )
2513         {
2514                 goto done;
2515         }
2516
2517         if ( !op->o_conn || op->o_do_not_cache || ( isroot = be_isroot( op ) ) ) {
2518                 goto done;
2519         }
2520
2521         if ( op->o_tag == LDAP_REQ_BIND ) {
2522                 ndn = op->o_req_ndn;
2523
2524         } else if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
2525                 ndn = op->o_conn->c_ndn;
2526
2527         } else {
2528                 ndn = op->o_ndn;
2529         }
2530
2531         if ( si->si_mode == LDAP_BACK_IDASSERT_LEGACY ) {
2532                 if ( op->o_proxy_authz ) {
2533                         /*
2534                          * FIXME: we do not want to perform proxyAuthz
2535                          * on behalf of the client, because this would
2536                          * be performed with "proxyauthzdn" privileges.
2537                          *
2538                          * This might actually be too strict, since
2539                          * the "proxyauthzdn" authzTo, and each entry's
2540                          * authzFrom attributes may be crafted
2541                          * to avoid unwanted proxyAuthz to take place.
2542                          */
2543 #if 0
2544                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
2545                         rs->sr_text = "proxyAuthz not allowed within namingContext";
2546 #endif
2547                         goto done;
2548                 }
2549
2550                 if ( !BER_BVISNULL( bound_ndn ) ) {
2551                         goto done;
2552                 }
2553
2554                 if ( BER_BVISNULL( &ndn ) ) {
2555                         goto done;
2556                 }
2557
2558                 if ( BER_BVISNULL( &si->si_bc.sb_binddn ) ) {
2559                         goto done;
2560                 }
2561
2562         } else if ( si->si_bc.sb_method == LDAP_AUTH_SASL ) {
2563                 if ( ( si->si_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
2564                 {
2565                         /* already asserted in SASL via native authz */
2566                         goto done;
2567                 }
2568
2569         } else if ( si->si_authz && !isroot ) {
2570                 int             rc;
2571                 struct berval authcDN;
2572
2573                 if ( BER_BVISNULL( &ndn ) ) {
2574                         authcDN = slap_empty_bv;
2575                 } else {
2576                         authcDN = ndn;
2577                 }
2578                 rc = slap_sasl_matches( op, si->si_authz,
2579                                 &authcDN, &authcDN );
2580                 if ( rc != LDAP_SUCCESS ) {
2581                         if ( si->si_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
2582                                 /* ndn is not authorized
2583                                  * to use idassert */
2584                                 rs->sr_err = rc;
2585                         }
2586                         goto done;
2587                 }
2588         }
2589
2590         if ( op->o_proxy_authz ) {
2591                 /*
2592                  * FIXME: we can:
2593                  * 1) ignore the already set proxyAuthz control
2594                  * 2) leave it in place, and don't set ours
2595                  * 3) add both
2596                  * 4) reject the operation
2597                  *
2598                  * option (4) is very drastic
2599                  * option (3) will make the remote server reject
2600                  * the operation, thus being equivalent to (4)
2601                  * option (2) will likely break the idassert
2602                  * assumptions, so we cannot accept it;
2603                  * option (1) means that we are contradicting
2604                  * the client's reques.
2605                  *
2606                  * I think (4) is the only correct choice.
2607                  */
2608                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
2609                 rs->sr_text = "proxyAuthz not allowed within namingContext";
2610         }
2611
2612         if ( op->o_is_auth_check ) {
2613                 mode = LDAP_BACK_IDASSERT_NOASSERT;
2614
2615         } else {
2616                 mode = si->si_mode;
2617         }
2618
2619         switch ( mode ) {
2620         case LDAP_BACK_IDASSERT_LEGACY:
2621                 /* original behavior:
2622                  * assert the client's identity */
2623         case LDAP_BACK_IDASSERT_SELF:
2624                 assertedID = ndn;
2625                 break;
2626
2627         case LDAP_BACK_IDASSERT_ANONYMOUS:
2628                 /* assert "anonymous" */
2629                 assertedID = slap_empty_bv;
2630                 break;
2631
2632         case LDAP_BACK_IDASSERT_NOASSERT:
2633                 /* don't assert; bind as proxyauthzdn */
2634                 goto done;
2635
2636         case LDAP_BACK_IDASSERT_OTHERID:
2637         case LDAP_BACK_IDASSERT_OTHERDN:
2638                 /* assert idassert DN */
2639                 assertedID = si->si_bc.sb_authzId;
2640                 break;
2641
2642         default:
2643                 assert( 0 );
2644         }
2645
2646         /* if we got here, "" is allowed to proxyAuthz */
2647         if ( BER_BVISNULL( &assertedID ) ) {
2648                 assertedID = slap_empty_bv;
2649         }
2650
2651         /* don't idassert the bound DN (ITS#4497) */
2652         if ( dn_match( &assertedID, bound_ndn ) ) {
2653                 goto done;
2654         }
2655
2656         ctrl->ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
2657         ctrl->ldctl_iscritical = ( ( si->si_flags & LDAP_BACK_AUTH_PROXYAUTHZ_CRITICAL ) == LDAP_BACK_AUTH_PROXYAUTHZ_CRITICAL );
2658
2659         switch ( si->si_mode ) {
2660         /* already in u:ID or dn:DN form */
2661         case LDAP_BACK_IDASSERT_OTHERID:
2662         case LDAP_BACK_IDASSERT_OTHERDN:
2663                 ber_dupbv_x( &ctrl->ldctl_value, &assertedID, op->o_tmpmemctx );
2664                 rs->sr_err = LDAP_SUCCESS;
2665                 break;
2666
2667         /* needs the dn: prefix */
2668         default:
2669                 ctrl->ldctl_value.bv_len = assertedID.bv_len + STRLENOF( "dn:" );
2670                 ctrl->ldctl_value.bv_val = op->o_tmpalloc( ctrl->ldctl_value.bv_len + 1,
2671                                 op->o_tmpmemctx );
2672                 AC_MEMCPY( ctrl->ldctl_value.bv_val, "dn:", STRLENOF( "dn:" ) );
2673                 AC_MEMCPY( &ctrl->ldctl_value.bv_val[ STRLENOF( "dn:" ) ],
2674                                 assertedID.bv_val, assertedID.bv_len + 1 );
2675                 rs->sr_err = LDAP_SUCCESS;
2676                 break;
2677         }
2678
2679         /* Older versions of <draft-weltman-ldapv3-proxy> required
2680          * to encode the value of the authzID (and called it proxyDN);
2681          * this hack provides compatibility with those DSAs that
2682          * implement it this way */
2683         if ( si->si_flags & LDAP_BACK_AUTH_OBSOLETE_ENCODING_WORKAROUND ) {
2684                 struct berval           authzID = ctrl->ldctl_value;
2685                 BerElementBuffer        berbuf;
2686                 BerElement              *ber = (BerElement *)&berbuf;
2687                 ber_tag_t               tag;
2688
2689                 ber_init2( ber, 0, LBER_USE_DER );
2690                 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
2691
2692                 tag = ber_printf( ber, "O", &authzID );
2693                 if ( tag == LBER_ERROR ) {
2694                         rs->sr_err = LDAP_OTHER;
2695                         goto free_ber;
2696                 }
2697
2698                 if ( ber_flatten2( ber, &ctrl->ldctl_value, 1 ) == -1 ) {
2699                         rs->sr_err = LDAP_OTHER;
2700                         goto free_ber;
2701                 }
2702
2703                 rs->sr_err = LDAP_SUCCESS;
2704
2705 free_ber:;
2706                 op->o_tmpfree( authzID.bv_val, op->o_tmpmemctx );
2707                 ber_free_buf( ber );
2708
2709                 if ( rs->sr_err != LDAP_SUCCESS ) {
2710                         goto done;
2711                 }
2712
2713         } else if ( si->si_flags & LDAP_BACK_AUTH_OBSOLETE_PROXY_AUTHZ ) {
2714                 struct berval           authzID = ctrl->ldctl_value,
2715                                         tmp;
2716                 BerElementBuffer        berbuf;
2717                 BerElement              *ber = (BerElement *)&berbuf;
2718                 ber_tag_t               tag;
2719
2720                 if ( strncasecmp( authzID.bv_val, "dn:", STRLENOF( "dn:" ) ) != 0 ) {
2721                         rs->sr_err = LDAP_PROTOCOL_ERROR;
2722                         goto done;
2723                 }
2724
2725                 tmp = authzID;
2726                 tmp.bv_val += STRLENOF( "dn:" );
2727                 tmp.bv_len -= STRLENOF( "dn:" );
2728
2729                 ber_init2( ber, 0, LBER_USE_DER );
2730                 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
2731
2732                 /* apparently, Mozilla API encodes this
2733                  * as "SEQUENCE { LDAPDN }" */
2734                 tag = ber_printf( ber, "{O}", &tmp );
2735                 if ( tag == LBER_ERROR ) {
2736                         rs->sr_err = LDAP_OTHER;
2737                         goto free_ber2;
2738                 }
2739
2740                 if ( ber_flatten2( ber, &ctrl->ldctl_value, 1 ) == -1 ) {
2741                         rs->sr_err = LDAP_OTHER;
2742                         goto free_ber2;
2743                 }
2744
2745                 ctrl->ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
2746                 rs->sr_err = LDAP_SUCCESS;
2747
2748 free_ber2:;
2749                 op->o_tmpfree( authzID.bv_val, op->o_tmpmemctx );
2750                 ber_free_buf( ber );
2751
2752                 if ( rs->sr_err != LDAP_SUCCESS ) {
2753                         goto done;
2754                 }
2755         }
2756
2757 done:;
2758
2759         return rs->sr_err;
2760 }
2761
2762 /*
2763  * Add controls;
2764  *
2765  * if any needs to be added, it is prepended to existing ones,
2766  * in a newly allocated array.  The companion function
2767  * ldap_back_controls_free() must be used to restore the original
2768  * status of op->o_ctrls.
2769  */
2770 int
2771 ldap_back_controls_add(
2772                 Operation       *op,
2773                 SlapReply       *rs,
2774                 ldapconn_t      *lc,
2775                 LDAPControl     ***pctrls )
2776 {
2777         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
2778
2779         LDAPControl     **ctrls = NULL;
2780         /* set to the maximum number of controls this backend can add */
2781         LDAPControl     c[ 2 ] = { { 0 } };
2782         int             n = 0, i, j1 = 0, j2 = 0;
2783
2784         *pctrls = NULL;
2785
2786         rs->sr_err = LDAP_SUCCESS;
2787
2788         /* don't add controls if protocol is not LDAPv3 */
2789         switch ( li->li_version ) {
2790         case LDAP_VERSION3:
2791                 break;
2792
2793         case 0:
2794                 if ( op->o_protocol == 0 || op->o_protocol == LDAP_VERSION3 ) {
2795                         break;
2796                 }
2797                 /* fall thru */
2798
2799         default:
2800                 goto done;
2801         }
2802
2803         /* put controls that go __before__ existing ones here */
2804
2805         /* proxyAuthz for identity assertion */
2806         switch ( ldap_back_proxy_authz_ctrl( op, rs, &lc->lc_bound_ndn,
2807                 li->li_version, &li->li_idassert, &c[ j1 ] ) )
2808         {
2809         case SLAP_CB_CONTINUE:
2810                 break;
2811
2812         case LDAP_SUCCESS:
2813                 j1++;
2814                 break;
2815
2816         default:
2817                 goto done;
2818         }
2819
2820         /* put controls that go __after__ existing ones here */
2821
2822 #ifdef SLAP_CONTROL_X_SESSION_TRACKING
2823         /* FIXME: according to <draft-wahl-ldap-session>, 
2824          * the server should check if the control can be added
2825          * based on the identity of the client and so */
2826
2827         /* session tracking */
2828         if ( LDAP_BACK_ST_REQUEST( li ) ) {
2829                 switch ( slap_ctrl_session_tracking_request_add( op, rs, &c[ j1 + j2 ] ) ) {
2830                 case SLAP_CB_CONTINUE:
2831                         break;
2832
2833                 case LDAP_SUCCESS:
2834                         j2++;
2835                         break;
2836
2837                 default:
2838                         goto done;
2839                 }
2840         }
2841 #endif /* SLAP_CONTROL_X_SESSION_TRACKING */
2842
2843         if ( rs->sr_err == SLAP_CB_CONTINUE ) {
2844                 rs->sr_err = LDAP_SUCCESS;
2845         }
2846
2847         /* if nothing to do, just bail out */
2848         if ( j1 == 0 && j2 == 0 ) {
2849                 goto done;
2850         }
2851
2852         assert( j1 + j2 <= (int) (sizeof( c )/sizeof( c[0] )) );
2853
2854         if ( op->o_ctrls ) {
2855                 for ( n = 0; op->o_ctrls[ n ]; n++ )
2856                         /* just count ctrls */ ;
2857         }
2858
2859         ctrls = op->o_tmpalloc( (n + j1 + j2 + 1) * sizeof( LDAPControl * ) + ( j1 + j2 ) * sizeof( LDAPControl ),
2860                         op->o_tmpmemctx );
2861         if ( j1 ) {
2862                 ctrls[ 0 ] = (LDAPControl *)&ctrls[ n + j1 + j2 + 1 ];
2863                 *ctrls[ 0 ] = c[ 0 ];
2864                 for ( i = 1; i < j1; i++ ) {
2865                         ctrls[ i ] = &ctrls[ 0 ][ i ];
2866                         *ctrls[ i ] = c[ i ];
2867                 }
2868         }
2869
2870         i = 0;
2871         if ( op->o_ctrls ) {
2872                 for ( i = 0; op->o_ctrls[ i ]; i++ ) {
2873                         ctrls[ i + j1 ] = op->o_ctrls[ i ];
2874                 }
2875         }
2876
2877         n += j1;
2878         if ( j2 ) {
2879                 ctrls[ n ] = (LDAPControl *)&ctrls[ n + j2 + 1 ] + j1;
2880                 *ctrls[ n ] = c[ j1 ];
2881                 for ( i = 1; i < j2; i++ ) {
2882                         ctrls[ n + i ] = &ctrls[ n ][ i ];
2883                         *ctrls[ n + i ] = c[ i ];
2884                 }
2885         }
2886
2887         ctrls[ n + j2 ] = NULL;
2888
2889 done:;
2890         if ( ctrls == NULL ) {
2891                 ctrls = op->o_ctrls;
2892         }
2893
2894         *pctrls = ctrls;
2895         
2896         return rs->sr_err;
2897 }
2898
2899 int
2900 ldap_back_controls_free( Operation *op, SlapReply *rs, LDAPControl ***pctrls )
2901 {
2902         LDAPControl     **ctrls = *pctrls;
2903
2904         /* we assume that the controls added by the proxy come first,
2905          * so as soon as we find op->o_ctrls[ 0 ] we can stop */
2906         if ( ctrls && ctrls != op->o_ctrls ) {
2907                 int             i = 0, n = 0, n_added;
2908                 LDAPControl     *lower, *upper;
2909
2910                 assert( ctrls[ 0 ] != NULL );
2911
2912                 for ( n = 0; ctrls[ n ] != NULL; n++ )
2913                         /* count 'em */ ;
2914
2915                 if ( op->o_ctrls ) {
2916                         for ( i = 0; op->o_ctrls[ i ] != NULL; i++ )
2917                                 /* count 'em */ ;
2918                 }
2919
2920                 n_added = n - i;
2921                 lower = (LDAPControl *)&ctrls[ n ];
2922                 upper = &lower[ n_added ];
2923
2924                 for ( i = 0; ctrls[ i ] != NULL; i++ ) {
2925                         if ( ctrls[ i ] < lower || ctrls[ i ] >= upper ) {
2926                                 /* original; don't touch */
2927                                 continue;
2928                         }
2929
2930                         if ( !BER_BVISNULL( &ctrls[ i ]->ldctl_value ) ) {
2931                                 op->o_tmpfree( ctrls[ i ]->ldctl_value.bv_val, op->o_tmpmemctx );
2932                         }
2933                 }
2934
2935                 op->o_tmpfree( ctrls, op->o_tmpmemctx );
2936         } 
2937
2938         *pctrls = NULL;
2939
2940         return 0;
2941 }
2942
2943 int
2944 ldap_back_conn2str( const ldapconn_base_t *lc, char *buf, ber_len_t buflen )
2945 {
2946         char tbuf[ SLAP_TEXT_BUFLEN ];
2947         char *ptr = buf, *end = buf + buflen;
2948         int len;
2949
2950         if ( ptr + sizeof("conn=") > end ) return -1;
2951         ptr = lutil_strcopy( ptr, "conn=" );
2952
2953         len = ldap_back_connid2str( lc, ptr, (ber_len_t)(end - ptr) );
2954         ptr += len;
2955         if ( ptr >= end ) return -1;
2956
2957         if ( !BER_BVISNULL( &lc->lcb_local_ndn ) ) {
2958                 if ( ptr + sizeof(" DN=\"\"") + lc->lcb_local_ndn.bv_len > end ) return -1;
2959                 ptr = lutil_strcopy( ptr, " DN=\"" );
2960                 ptr = lutil_strncopy( ptr, lc->lcb_local_ndn.bv_val, lc->lcb_local_ndn.bv_len );
2961                 *ptr++ = '"';
2962         }
2963
2964         if ( lc->lcb_create_time != 0 ) {
2965                 len = snprintf( tbuf, sizeof(tbuf), "%ld", lc->lcb_create_time );
2966                 if ( ptr + sizeof(" created=") + len >= end ) return -1;
2967                 ptr = lutil_strcopy( ptr, " created=" );
2968                 ptr = lutil_strcopy( ptr, tbuf );
2969         }
2970
2971         if ( lc->lcb_time != 0 ) {
2972                 len = snprintf( tbuf, sizeof(tbuf), "%ld", lc->lcb_time );
2973                 if ( ptr + sizeof(" modified=") + len >= end ) return -1;
2974                 ptr = lutil_strcopy( ptr, " modified=" );
2975                 ptr = lutil_strcopy( ptr, tbuf );
2976         }
2977
2978         len = snprintf( tbuf, sizeof(tbuf), "%u", lc->lcb_refcnt );
2979         if ( ptr + sizeof(" refcnt=") + len >= end ) return -1;
2980         ptr = lutil_strcopy( ptr, " refcnt=" );
2981         ptr = lutil_strcopy( ptr, tbuf );
2982
2983         return ptr - buf;
2984 }
2985
2986 int
2987 ldap_back_connid2str( const ldapconn_base_t *lc, char *buf, ber_len_t buflen )
2988 {
2989         static struct berval conns[] = {
2990                 BER_BVC("ROOTDN"),
2991                 BER_BVC("ROOTDN-TLS"),
2992                 BER_BVC("ANON"),
2993                 BER_BVC("ANON-TLS"),
2994                 BER_BVC("BIND"),
2995                 BER_BVC("BIND-TLS"),
2996                 BER_BVNULL
2997         };
2998
2999         int len = 0;
3000
3001         if ( LDAP_BACK_PCONN_ISPRIV( (const ldapconn_t *)lc ) ) {
3002                 long cid;
3003                 struct berval *bv;
3004
3005                 cid = (long)lc->lcb_conn;
3006                 assert( cid >= LDAP_BACK_PCONN_FIRST && cid < LDAP_BACK_PCONN_LAST );
3007
3008                 bv = &conns[ cid ];
3009
3010                 if ( bv->bv_len >= buflen ) {
3011                         return bv->bv_len + 1;
3012                 }
3013
3014                 len = bv->bv_len;
3015                 lutil_strncopy( buf, bv->bv_val, bv->bv_len + 1 );
3016
3017         } else {
3018                 len = snprintf( buf, buflen, "%lu", lc->lcb_conn->c_connid );
3019         }
3020
3021         return len;
3022 }