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