]> git.sur5r.net Git - openldap/blob - libraries/libldap/request.c
Merge remote-tracking branch 'origin/mdb.RE/0.9'
[openldap] / libraries / libldap / request.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2015 The OpenLDAP Foundation.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted only as authorized by the OpenLDAP
9  * Public License.
10  *
11  * A copy of this license is available in the file LICENSE in the
12  * top-level directory of the distribution or, alternatively, at
13  * <http://www.OpenLDAP.org/license.html>.
14  */
15 /* Portions Copyright (c) 1995 Regents of the University of Michigan.
16  * All rights reserved.
17  */
18 /* This notice applies to changes, created by or for Novell, Inc.,
19  * to preexisting works for which notices appear elsewhere in this file.
20  *
21  * Copyright (C) 1999, 2000 Novell, Inc. All Rights Reserved.
22  *
23  * THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND TREATIES.
24  * USE, MODIFICATION, AND REDISTRIBUTION OF THIS WORK IS SUBJECT TO VERSION
25  * 2.0.1 OF THE OPENLDAP PUBLIC LICENSE, A COPY OF WHICH IS AVAILABLE AT
26  * HTTP://WWW.OPENLDAP.ORG/LICENSE.HTML OR IN THE FILE "LICENSE" IN THE
27  * TOP-LEVEL DIRECTORY OF THE DISTRIBUTION. ANY USE OR EXPLOITATION OF THIS
28  * WORK OTHER THAN AS AUTHORIZED IN VERSION 2.0.1 OF THE OPENLDAP PUBLIC
29  * LICENSE, OR OTHER PRIOR WRITTEN CONSENT FROM NOVELL, COULD SUBJECT THE
30  * PERPETRATOR TO CRIMINAL AND CIVIL LIABILITY. 
31  *---
32  * Modification to OpenLDAP source by Novell, Inc.
33  * April 2000 sfs  Added code to chase V3 referrals
34  *  request.c - sending of ldap requests; handling of referrals
35  *---
36  * Note: A verbatim copy of version 2.0.1 of the OpenLDAP Public License 
37  * can be found in the file "build/LICENSE-2.0.1" in this distribution
38  * of OpenLDAP Software.
39  */
40
41 #include "portable.h"
42
43 #include <stdio.h>
44
45 #include <ac/stdlib.h>
46
47 #include <ac/errno.h>
48 #include <ac/socket.h>
49 #include <ac/string.h>
50 #include <ac/time.h>
51 #include <ac/unistd.h>
52
53 #include "ldap-int.h"
54 #include "lber.h"
55
56 /* used by ldap_send_server_request and ldap_new_connection */
57 #ifdef LDAP_R_COMPILE
58 #define LDAP_CONN_LOCK_IF(nolock) \
59         { if (nolock) LDAP_MUTEX_LOCK( &ld->ld_conn_mutex ); }
60 #define LDAP_CONN_UNLOCK_IF(nolock) \
61         { if (nolock) LDAP_MUTEX_UNLOCK( &ld->ld_conn_mutex ); }
62 #define LDAP_REQ_LOCK_IF(nolock) \
63         { if (nolock) LDAP_MUTEX_LOCK( &ld->ld_req_mutex ); }
64 #define LDAP_REQ_UNLOCK_IF(nolock) \
65         { if (nolock) LDAP_MUTEX_UNLOCK( &ld->ld_req_mutex ); }
66 #define LDAP_RES_LOCK_IF(nolock) \
67         { if (nolock) LDAP_MUTEX_LOCK( &ld->ld_res_mutex ); }
68 #define LDAP_RES_UNLOCK_IF(nolock) \
69         { if (nolock) LDAP_MUTEX_UNLOCK( &ld->ld_res_mutex ); }
70 #else
71 #define LDAP_CONN_LOCK_IF(nolock)
72 #define LDAP_CONN_UNLOCK_IF(nolock)
73 #define LDAP_REQ_LOCK_IF(nolock)
74 #define LDAP_REQ_UNLOCK_IF(nolock)
75 #define LDAP_RES_LOCK_IF(nolock)
76 #define LDAP_RES_UNLOCK_IF(nolock)
77 #endif
78
79 static LDAPConn *find_connection LDAP_P(( LDAP *ld, LDAPURLDesc *srv, int any ));
80 static void use_connection LDAP_P(( LDAP *ld, LDAPConn *lc ));
81 static void ldap_free_request_int LDAP_P(( LDAP *ld, LDAPRequest *lr ));
82
83 static BerElement *
84 re_encode_request( LDAP *ld,
85         BerElement *origber,
86         ber_int_t msgid,
87         int sref,
88         LDAPURLDesc *srv,
89         int *type );
90
91 BerElement *
92 ldap_alloc_ber_with_options( LDAP *ld )
93 {
94         BerElement      *ber;
95
96         ber = ber_alloc_t( ld->ld_lberoptions );
97         if ( ber == NULL ) {
98                 ld->ld_errno = LDAP_NO_MEMORY;
99         }
100
101         return( ber );
102 }
103
104
105 void
106 ldap_set_ber_options( LDAP *ld, BerElement *ber )
107 {
108         /* ld_lberoptions is constant, hence no lock */
109         ber->ber_options = ld->ld_lberoptions;
110 }
111
112
113 /* sets needed mutexes - no mutexes set to this point */
114 ber_int_t
115 ldap_send_initial_request(
116         LDAP *ld,
117         ber_tag_t msgtype,
118         const char *dn,
119         BerElement *ber,
120         ber_int_t msgid)
121 {
122         int rc = 1;
123         ber_socket_t sd = AC_SOCKET_INVALID;
124
125         Debug( LDAP_DEBUG_TRACE, "ldap_send_initial_request\n", 0, 0, 0 );
126
127         LDAP_MUTEX_LOCK( &ld->ld_conn_mutex );
128         if ( ber_sockbuf_ctrl( ld->ld_sb, LBER_SB_OPT_GET_FD, &sd ) == -1 ) {
129                 /* not connected yet */
130                 rc = ldap_open_defconn( ld );
131                 if ( rc == 0 ) {
132                         ber_sockbuf_ctrl( ld->ld_defconn->lconn_sb,
133                                 LBER_SB_OPT_GET_FD, &sd );
134                 }
135         }
136         if ( ld->ld_defconn && ld->ld_defconn->lconn_status == LDAP_CONNST_CONNECTING )
137                 rc = ldap_int_check_async_open( ld, sd );
138         if( rc < 0 ) {
139                 ber_free( ber, 1 );
140                 LDAP_MUTEX_UNLOCK( &ld->ld_conn_mutex );
141                 return( -1 );
142         } else if ( rc == 0 ) {
143                 Debug( LDAP_DEBUG_TRACE,
144                         "ldap_open_defconn: successful\n",
145                         0, 0, 0 );
146         }
147
148 #ifdef LDAP_CONNECTIONLESS
149         if (LDAP_IS_UDP(ld)) {
150                 if (msgtype == LDAP_REQ_BIND) {
151                         LDAP_MUTEX_LOCK( &ld->ld_options.ldo_mutex );
152                         if (ld->ld_options.ldo_cldapdn)
153                                 ldap_memfree(ld->ld_options.ldo_cldapdn);
154                         ld->ld_options.ldo_cldapdn = ldap_strdup(dn);
155                         ber_free( ber, 1 );
156                         LDAP_MUTEX_UNLOCK( &ld->ld_options.ldo_mutex );
157                         LDAP_MUTEX_UNLOCK( &ld->ld_conn_mutex );
158                         return 0;
159                 }
160                 if (msgtype != LDAP_REQ_ABANDON && msgtype != LDAP_REQ_SEARCH)
161                 {
162                         ber_free( ber, 1 );
163                         LDAP_MUTEX_UNLOCK( &ld->ld_conn_mutex );
164                         return LDAP_PARAM_ERROR;
165                 }
166         }
167 #endif
168         LDAP_MUTEX_LOCK( &ld->ld_req_mutex );
169         rc = ldap_send_server_request( ld, ber, msgid, NULL,
170                 NULL, NULL, NULL, 0, 0 );
171         LDAP_MUTEX_UNLOCK( &ld->ld_req_mutex );
172         LDAP_MUTEX_UNLOCK( &ld->ld_conn_mutex );
173         return(rc);
174 }
175
176
177 /* protected by conn_mutex */
178 int
179 ldap_int_flush_request(
180         LDAP *ld,
181         LDAPRequest *lr )
182 {
183         LDAPConn *lc = lr->lr_conn;
184
185         LDAP_ASSERT_MUTEX_OWNER( &ld->ld_conn_mutex );
186         if ( ber_flush2( lc->lconn_sb, lr->lr_ber, LBER_FLUSH_FREE_NEVER ) != 0 ) {
187                 if ( sock_errno() == EAGAIN ) {
188                         /* need to continue write later */
189                         lr->lr_status = LDAP_REQST_WRITING;
190                         ldap_mark_select_write( ld, lc->lconn_sb );
191                         ld->ld_errno = LDAP_BUSY;
192                         return -2;
193                 } else {
194                         ld->ld_errno = LDAP_SERVER_DOWN;
195                         ldap_free_request( ld, lr );
196                         ldap_free_connection( ld, lc, 0, 0 );
197                         return( -1 );
198                 }
199         } else {
200                 if ( lr->lr_parent == NULL ) {
201                         lr->lr_ber->ber_end = lr->lr_ber->ber_ptr;
202                         lr->lr_ber->ber_ptr = lr->lr_ber->ber_buf;
203                 }
204                 lr->lr_status = LDAP_REQST_INPROGRESS;
205
206                 /* sent -- waiting for a response */
207                 ldap_mark_select_read( ld, lc->lconn_sb );
208                 ldap_clear_select_write( ld, lc->lconn_sb );
209         }
210         return 0;
211 }
212
213 /*
214  * protected by req_mutex
215  * if m_noconn then protect using conn_lock
216  * else already protected with conn_lock
217  * if m_res then also protected by res_mutex
218  */
219
220 int
221 ldap_send_server_request(
222         LDAP *ld,
223         BerElement *ber,
224         ber_int_t msgid,
225         LDAPRequest *parentreq,
226         LDAPURLDesc **srvlist,
227         LDAPConn *lc,
228         LDAPreqinfo *bind,
229         int m_noconn,
230         int m_res )
231 {
232         LDAPRequest     *lr;
233         int             incparent, rc;
234
235         LDAP_ASSERT_MUTEX_OWNER( &ld->ld_req_mutex );
236         Debug( LDAP_DEBUG_TRACE, "ldap_send_server_request\n", 0, 0, 0 );
237
238         incparent = 0;
239         ld->ld_errno = LDAP_SUCCESS;    /* optimistic */
240
241         LDAP_CONN_LOCK_IF(m_noconn);
242         if ( lc == NULL ) {
243                 if ( srvlist == NULL ) {
244                         lc = ld->ld_defconn;
245                 } else {
246                         lc = find_connection( ld, *srvlist, 1 );
247                         if ( lc == NULL ) {
248                                 if ( (bind != NULL) && (parentreq != NULL) ) {
249                                         /* Remember the bind in the parent */
250                                         incparent = 1;
251                                         ++parentreq->lr_outrefcnt;
252                                 }
253                                 lc = ldap_new_connection( ld, srvlist, 0,
254                                         1, bind, 1, m_res );
255                         }
256                 }
257         }
258
259         /* async connect... */
260         if ( lc != NULL && lc->lconn_status == LDAP_CONNST_CONNECTING ) {
261                 ber_socket_t    sd = AC_SOCKET_ERROR;
262                 struct timeval  tv = { 0 };
263
264                 ber_sockbuf_ctrl( lc->lconn_sb, LBER_SB_OPT_GET_FD, &sd );
265
266                 /* poll ... */
267                 switch ( ldap_int_poll( ld, sd, &tv, 1 ) ) {
268                 case 0:
269                         /* go on! */
270                         lc->lconn_status = LDAP_CONNST_CONNECTED;
271                         break;
272
273                 case -2:
274                         /* async only occurs if a network timeout is set */
275
276                         /* honor network timeout */
277                         LDAP_MUTEX_LOCK( &ld->ld_options.ldo_mutex );
278                         if ( time( NULL ) - lc->lconn_created <= ld->ld_options.ldo_tm_net.tv_sec )
279                         {
280                                 /* caller will have to call again */
281                                 ld->ld_errno = LDAP_X_CONNECTING;
282                         }
283                         LDAP_MUTEX_UNLOCK( &ld->ld_options.ldo_mutex );
284                         /* fallthru */
285
286                 default:
287                         /* error */
288                         break;
289                 }
290         }
291
292         if ( lc == NULL || lc->lconn_status != LDAP_CONNST_CONNECTED ) {
293                 if ( ld->ld_errno == LDAP_SUCCESS ) {
294                         ld->ld_errno = LDAP_SERVER_DOWN;
295                 }
296
297                 ber_free( ber, 1 );
298                 if ( incparent ) {
299                         /* Forget about the bind */
300                         --parentreq->lr_outrefcnt; 
301                 }
302                 LDAP_CONN_UNLOCK_IF(m_noconn);
303                 return( -1 );
304         }
305
306         use_connection( ld, lc );
307
308 #ifdef LDAP_CONNECTIONLESS
309         if ( LDAP_IS_UDP( ld )) {
310                 BerElement tmpber = *ber;
311                 ber_rewind( &tmpber );
312                 LDAP_MUTEX_LOCK( &ld->ld_options.ldo_mutex );
313                 rc = ber_write( &tmpber, ld->ld_options.ldo_peer,
314                         sizeof( struct sockaddr_storage ), 0 );
315                 LDAP_MUTEX_UNLOCK( &ld->ld_options.ldo_mutex );
316                 if ( rc == -1 ) {
317                         ld->ld_errno = LDAP_ENCODING_ERROR;
318                         LDAP_CONN_UNLOCK_IF(m_noconn);
319                         return rc;
320                 }
321         }
322 #endif
323
324         /* If we still have an incomplete write, try to finish it before
325          * dealing with the new request. If we don't finish here, return
326          * LDAP_BUSY and let the caller retry later. We only allow a single
327          * request to be in WRITING state.
328          */
329         rc = 0;
330         if ( ld->ld_requests &&
331                 ld->ld_requests->lr_status == LDAP_REQST_WRITING &&
332                 ldap_int_flush_request( ld, ld->ld_requests ) < 0 )
333         {
334                 rc = -1;
335         }
336         if ( rc ) {
337                 LDAP_CONN_UNLOCK_IF(m_noconn);
338                 return rc;
339         }
340
341         lr = (LDAPRequest *)LDAP_CALLOC( 1, sizeof( LDAPRequest ) );
342         if ( lr == NULL ) {
343                 ld->ld_errno = LDAP_NO_MEMORY;
344                 ldap_free_connection( ld, lc, 0, 0 );
345                 ber_free( ber, 1 );
346                 if ( incparent ) {
347                         /* Forget about the bind */
348                         --parentreq->lr_outrefcnt; 
349                 }
350                 LDAP_CONN_UNLOCK_IF(m_noconn);
351                 return( -1 );
352         } 
353         lr->lr_msgid = msgid;
354         lr->lr_status = LDAP_REQST_INPROGRESS;
355         lr->lr_res_errno = LDAP_SUCCESS;        /* optimistic */
356         lr->lr_ber = ber;
357         lr->lr_conn = lc;
358         if ( parentreq != NULL ) {      /* sub-request */
359                 if ( !incparent ) { 
360                         /* Increment if we didn't do it before the bind */
361                         ++parentreq->lr_outrefcnt;
362                 }
363                 lr->lr_origid = parentreq->lr_origid;
364                 lr->lr_parentcnt = ++parentreq->lr_parentcnt;
365                 lr->lr_parent = parentreq;
366                 lr->lr_refnext = parentreq->lr_child;
367                 parentreq->lr_child = lr;
368         } else {                        /* original request */
369                 lr->lr_origid = lr->lr_msgid;
370         }
371
372         /* Extract requestDN for future reference */
373 #ifdef LDAP_CONNECTIONLESS
374         if ( !LDAP_IS_UDP(ld) )
375 #endif
376         {
377                 BerElement tmpber = *ber;
378                 ber_int_t       bint;
379                 ber_tag_t       tag, rtag;
380
381                 ber_reset( &tmpber, 1 );
382                 rtag = ber_scanf( &tmpber, "{it", /*}*/ &bint, &tag );
383                 switch ( tag ) {
384                 case LDAP_REQ_BIND:
385                         rtag = ber_scanf( &tmpber, "{i" /*}*/, &bint );
386                         break;
387                 case LDAP_REQ_DELETE:
388                         break;
389                 default:
390                         rtag = ber_scanf( &tmpber, "{" /*}*/ );
391                 case LDAP_REQ_ABANDON:
392                         break;
393                 }
394                 if ( tag != LDAP_REQ_ABANDON ) {
395                         ber_skip_tag( &tmpber, &lr->lr_dn.bv_len );
396                         lr->lr_dn.bv_val = tmpber.ber_ptr;
397                 }
398         }
399
400         lr->lr_prev = NULL;
401         lr->lr_next = ld->ld_requests;
402         if ( lr->lr_next != NULL ) {
403                 lr->lr_next->lr_prev = lr;
404         }
405         ld->ld_requests = lr;
406
407         ld->ld_errno = LDAP_SUCCESS;
408         if ( ldap_int_flush_request( ld, lr ) == -1 ) {
409                 msgid = -1;
410         }
411
412         LDAP_CONN_UNLOCK_IF(m_noconn);
413         return( msgid );
414 }
415
416 /* return 0 if no StartTLS ext, 1 if present, 2 if critical */
417 static int
418 find_tls_ext( LDAPURLDesc *srv )
419 {
420         int i, crit;
421         char *ext;
422
423         if ( !srv->lud_exts )
424                 return 0;
425
426         for (i=0; srv->lud_exts[i]; i++) {
427                 crit = 0;
428                 ext = srv->lud_exts[i];
429                 if ( ext[0] == '!') {
430                         ext++;
431                         crit = 1;
432                 }
433                 if ( !strcasecmp( ext, "StartTLS" ) ||
434                         !strcasecmp( ext, "X-StartTLS" ) ||
435                         !strcmp( ext, LDAP_EXOP_START_TLS )) {
436                         return crit + 1;
437                 }
438         }
439         return 0;
440 }
441
442 /*
443  * always protected by conn_mutex
444  * optionally protected by req_mutex and res_mutex
445  */
446 LDAPConn *
447 ldap_new_connection( LDAP *ld, LDAPURLDesc **srvlist, int use_ldsb,
448         int connect, LDAPreqinfo *bind, int m_req, int m_res )
449 {
450         LDAPConn        *lc;
451         int             async = 0;
452
453         LDAP_ASSERT_MUTEX_OWNER( &ld->ld_conn_mutex );
454         Debug( LDAP_DEBUG_TRACE, "ldap_new_connection %d %d %d\n",
455                 use_ldsb, connect, (bind != NULL) );
456         /*
457          * make a new LDAP server connection
458          * XXX open connection synchronously for now
459          */
460         lc = (LDAPConn *)LDAP_CALLOC( 1, sizeof( LDAPConn ) );
461         if ( lc == NULL ) {
462                 ld->ld_errno = LDAP_NO_MEMORY;
463                 return( NULL );
464         }
465         
466         if ( use_ldsb ) {
467                 assert( ld->ld_sb != NULL );
468                 lc->lconn_sb = ld->ld_sb;
469
470         } else {
471                 lc->lconn_sb = ber_sockbuf_alloc();
472                 if ( lc->lconn_sb == NULL ) {
473                         LDAP_FREE( (char *)lc );
474                         ld->ld_errno = LDAP_NO_MEMORY;
475                         return( NULL );
476                 }
477         }
478
479         if ( connect ) {
480                 LDAPURLDesc     **srvp, *srv = NULL;
481
482                 async = LDAP_BOOL_GET( &ld->ld_options, LDAP_BOOL_CONNECT_ASYNC );
483
484                 for ( srvp = srvlist; *srvp != NULL; srvp = &(*srvp)->lud_next ) {
485                         int             rc;
486
487                         rc = ldap_int_open_connection( ld, lc, *srvp, async );
488                         if ( rc != -1 ) {
489                                 srv = *srvp;
490
491                                 /* If we fully connected, async is moot */
492                                 if ( rc == 0 )
493                                         async = 0;
494
495                                 if ( ld->ld_urllist_proc && ( !async || rc != -2 ) ) {
496                                         ld->ld_urllist_proc( ld, srvlist, srvp, ld->ld_urllist_params );
497                                 }
498
499                                 break;
500                         }
501                 }
502
503                 if ( srv == NULL ) {
504                         if ( !use_ldsb ) {
505                                 ber_sockbuf_free( lc->lconn_sb );
506                         }
507                         LDAP_FREE( (char *)lc );
508                         ld->ld_errno = LDAP_SERVER_DOWN;
509                         return( NULL );
510                 }
511
512                 lc->lconn_server = ldap_url_dup( srv );
513                 if ( !lc->lconn_server ) {
514                         if ( !use_ldsb )
515                                 ber_sockbuf_free( lc->lconn_sb );
516                         LDAP_FREE( (char *)lc );
517                         ld->ld_errno = LDAP_NO_MEMORY;
518                         return( NULL );
519                 }
520         }
521
522         lc->lconn_status = async ? LDAP_CONNST_CONNECTING : LDAP_CONNST_CONNECTED;
523         lc->lconn_next = ld->ld_conns;
524         ld->ld_conns = lc;
525
526         if ( connect ) {
527 #ifdef HAVE_TLS
528                 if ( lc->lconn_server->lud_exts ) {
529                         int rc, ext = find_tls_ext( lc->lconn_server );
530                         if ( ext ) {
531                                 LDAPConn        *savedefconn;
532
533                                 savedefconn = ld->ld_defconn;
534                                 ++lc->lconn_refcnt;     /* avoid premature free */
535                                 ld->ld_defconn = lc;
536
537                                 LDAP_REQ_UNLOCK_IF(m_req);
538                                 LDAP_MUTEX_UNLOCK( &ld->ld_conn_mutex );
539                                 LDAP_RES_UNLOCK_IF(m_res);
540                                 rc = ldap_start_tls_s( ld, NULL, NULL );
541                                 LDAP_RES_LOCK_IF(m_res);
542                                 LDAP_MUTEX_LOCK( &ld->ld_conn_mutex );
543                                 LDAP_REQ_LOCK_IF(m_req);
544                                 ld->ld_defconn = savedefconn;
545                                 --lc->lconn_refcnt;
546
547                                 if ( rc != LDAP_SUCCESS && ext == 2 ) {
548                                         ldap_free_connection( ld, lc, 1, 0 );
549                                         return NULL;
550                                 }
551                         }
552                 }
553 #endif
554         }
555
556         if ( bind != NULL ) {
557                 int             err = 0;
558                 LDAPConn        *savedefconn;
559
560                 /* Set flag to prevent additional referrals
561                  * from being processed on this
562                  * connection until the bind has completed
563                  */
564                 lc->lconn_rebind_inprogress = 1;
565                 /* V3 rebind function */
566                 if ( ld->ld_rebind_proc != NULL) {
567                         LDAPURLDesc     *srvfunc;
568
569                         srvfunc = ldap_url_dup( *srvlist );
570                         if ( srvfunc == NULL ) {
571                                 ld->ld_errno = LDAP_NO_MEMORY;
572                                 err = -1;
573                         } else {
574                                 savedefconn = ld->ld_defconn;
575                                 ++lc->lconn_refcnt;     /* avoid premature free */
576                                 ld->ld_defconn = lc;
577
578                                 Debug( LDAP_DEBUG_TRACE, "Call application rebind_proc\n", 0, 0, 0);
579                                 LDAP_REQ_UNLOCK_IF(m_req);
580                                 LDAP_MUTEX_UNLOCK( &ld->ld_conn_mutex );
581                                 LDAP_RES_UNLOCK_IF(m_res);
582                                 err = (*ld->ld_rebind_proc)( ld,
583                                         bind->ri_url, bind->ri_request, bind->ri_msgid,
584                                         ld->ld_rebind_params );
585                                 LDAP_RES_LOCK_IF(m_res);
586                                 LDAP_MUTEX_LOCK( &ld->ld_conn_mutex );
587                                 LDAP_REQ_LOCK_IF(m_req);
588
589                                 ld->ld_defconn = savedefconn;
590                                 --lc->lconn_refcnt;
591
592                                 if ( err != 0 ) {
593                                         err = -1;
594                                         ldap_free_connection( ld, lc, 1, 0 );
595                                         lc = NULL;
596                                 }
597                                 ldap_free_urldesc( srvfunc );
598                         }
599
600                 } else {
601                         int             msgid, rc;
602                         struct berval   passwd = BER_BVNULL;
603
604                         savedefconn = ld->ld_defconn;
605                         ++lc->lconn_refcnt;     /* avoid premature free */
606                         ld->ld_defconn = lc;
607
608                         Debug( LDAP_DEBUG_TRACE,
609                                 "anonymous rebind via ldap_sasl_bind(\"\")\n",
610                                 0, 0, 0);
611
612                         LDAP_REQ_UNLOCK_IF(m_req);
613                         LDAP_MUTEX_UNLOCK( &ld->ld_conn_mutex );
614                         LDAP_RES_UNLOCK_IF(m_res);
615                         rc = ldap_sasl_bind( ld, "", LDAP_SASL_SIMPLE, &passwd,
616                                 NULL, NULL, &msgid );
617                         if ( rc != LDAP_SUCCESS ) {
618                                 err = -1;
619
620                         } else {
621                                 for ( err = 1; err > 0; ) {
622                                         struct timeval  tv = { 0, 100000 };
623                                         LDAPMessage     *res = NULL;
624
625                                         switch ( ldap_result( ld, msgid, LDAP_MSG_ALL, &tv, &res ) ) {
626                                         case -1:
627                                                 err = -1;
628                                                 break;
629
630                                         case 0:
631 #ifdef LDAP_R_COMPILE
632                                                 ldap_pvt_thread_yield();
633 #endif
634                                                 break;
635
636                                         case LDAP_RES_BIND:
637                                                 rc = ldap_parse_result( ld, res, &err, NULL, NULL, NULL, NULL, 1 );
638                                                 if ( rc != LDAP_SUCCESS ) {
639                                                         err = -1;
640
641                                                 } else if ( err != LDAP_SUCCESS ) {
642                                                         err = -1;
643                                                 }
644                                                 /* else err == LDAP_SUCCESS == 0 */
645                                                 break;
646
647                                         default:
648                                                 Debug( LDAP_DEBUG_TRACE,
649                                                         "ldap_new_connection %p: "
650                                                         "unexpected response %d "
651                                                         "from BIND request id=%d\n",
652                                                         (void *) ld, ldap_msgtype( res ), msgid );
653                                                 err = -1;
654                                                 break;
655                                         }
656                                 }
657                         }
658                         LDAP_RES_LOCK_IF(m_res);
659                         LDAP_MUTEX_LOCK( &ld->ld_conn_mutex );
660                         LDAP_REQ_LOCK_IF(m_req);
661                         ld->ld_defconn = savedefconn;
662                         --lc->lconn_refcnt;
663
664                         if ( err != 0 ) {
665                                 ldap_free_connection( ld, lc, 1, 0 );
666                                 lc = NULL;
667                         }
668                 }
669                 if ( lc != NULL )
670                         lc->lconn_rebind_inprogress = 0;
671         }
672         return( lc );
673 }
674
675
676 /* protected by ld_conn_mutex */
677 static LDAPConn *
678 find_connection( LDAP *ld, LDAPURLDesc *srv, int any )
679 /*
680  * return an existing connection (if any) to the server srv
681  * if "any" is non-zero, check for any server in the "srv" chain
682  */
683 {
684         LDAPConn        *lc;
685         LDAPURLDesc     *lcu, *lsu;
686         int lcu_port, lsu_port;
687         int found = 0;
688
689         LDAP_ASSERT_MUTEX_OWNER( &ld->ld_conn_mutex );
690         for ( lc = ld->ld_conns; lc != NULL; lc = lc->lconn_next ) {
691                 lcu = lc->lconn_server;
692                 lcu_port = ldap_pvt_url_scheme_port( lcu->lud_scheme,
693                         lcu->lud_port );
694
695                 for ( lsu = srv; lsu != NULL; lsu = lsu->lud_next ) {
696                         lsu_port = ldap_pvt_url_scheme_port( lsu->lud_scheme,
697                                 lsu->lud_port );
698
699                         if ( lsu_port == lcu_port
700                                 && strcmp( lcu->lud_scheme, lsu->lud_scheme ) == 0
701                                 && lcu->lud_host != NULL && lsu->lud_host != NULL
702                                 && strcasecmp( lsu->lud_host, lcu->lud_host ) == 0 )
703                         {
704                                 found = 1;
705                                 break;
706                         }
707
708                         if ( !any ) break;
709                 }
710                 if ( found )
711                         break;
712         }
713         return lc;
714 }
715
716
717
718 /* protected by ld_conn_mutex */
719 static void
720 use_connection( LDAP *ld, LDAPConn *lc )
721 {
722         LDAP_ASSERT_MUTEX_OWNER( &ld->ld_conn_mutex );
723         ++lc->lconn_refcnt;
724         lc->lconn_lastused = time( NULL );
725 }
726
727
728 /* protected by ld_conn_mutex */
729 void
730 ldap_free_connection( LDAP *ld, LDAPConn *lc, int force, int unbind )
731 {
732         LDAPConn        *tmplc, *prevlc;
733
734         LDAP_ASSERT_MUTEX_OWNER( &ld->ld_conn_mutex );
735         Debug( LDAP_DEBUG_TRACE,
736                 "ldap_free_connection %d %d\n",
737                 force, unbind, 0 );
738
739         if ( force || --lc->lconn_refcnt <= 0 ) {
740                 /* remove from connections list first */
741
742                 for ( prevlc = NULL, tmplc = ld->ld_conns;
743                         tmplc != NULL;
744                         tmplc = tmplc->lconn_next )
745                 {
746                         if ( tmplc == lc ) {
747                                 if ( prevlc == NULL ) {
748                                     ld->ld_conns = tmplc->lconn_next;
749                                 } else {
750                                     prevlc->lconn_next = tmplc->lconn_next;
751                                 }
752                                 if ( ld->ld_defconn == lc ) {
753                                         ld->ld_defconn = NULL;
754                                 }
755                                 break;
756                         }
757                         prevlc = tmplc;
758                 }
759
760                 /* process connection callbacks */
761                 {
762                         struct ldapoptions *lo;
763                         ldaplist *ll;
764                         ldap_conncb *cb;
765
766                         lo = &ld->ld_options;
767                         LDAP_MUTEX_LOCK( &lo->ldo_mutex );
768                         if ( lo->ldo_conn_cbs ) {
769                                 for ( ll=lo->ldo_conn_cbs; ll; ll=ll->ll_next ) {
770                                         cb = ll->ll_data;
771                                         cb->lc_del( ld, lc->lconn_sb, cb );
772                                 }
773                         }
774                         LDAP_MUTEX_UNLOCK( &lo->ldo_mutex );
775                         lo = LDAP_INT_GLOBAL_OPT();
776                         LDAP_MUTEX_LOCK( &lo->ldo_mutex );
777                         if ( lo->ldo_conn_cbs ) {
778                                 for ( ll=lo->ldo_conn_cbs; ll; ll=ll->ll_next ) {
779                                         cb = ll->ll_data;
780                                         cb->lc_del( ld, lc->lconn_sb, cb );
781                                 }
782                         }
783                         LDAP_MUTEX_UNLOCK( &lo->ldo_mutex );
784                 }
785
786                 if ( lc->lconn_status == LDAP_CONNST_CONNECTED ) {
787                         ldap_mark_select_clear( ld, lc->lconn_sb );
788                         if ( unbind ) {
789                                 ldap_send_unbind( ld, lc->lconn_sb,
790                                                 NULL, NULL );
791                         }
792                 }
793
794                 if ( lc->lconn_ber != NULL ) {
795                         ber_free( lc->lconn_ber, 1 );
796                 }
797
798                 ldap_int_sasl_close( ld, lc );
799 #ifdef HAVE_GSSAPI
800                 ldap_int_gssapi_close( ld, lc );
801 #endif
802
803                 ldap_free_urllist( lc->lconn_server );
804
805                 /* FIXME: is this at all possible?
806                  * ldap_ld_free() in unbind.c calls ldap_free_connection()
807                  * with force == 1 __after__ explicitly calling
808                  * ldap_free_request() on all requests */
809                 if ( force ) {
810                         LDAPRequest     *lr;
811
812                         for ( lr = ld->ld_requests; lr; ) {
813                                 LDAPRequest     *lr_next = lr->lr_next;
814
815                                 if ( lr->lr_conn == lc ) {
816                                         ldap_free_request_int( ld, lr );
817                                 }
818
819                                 lr = lr_next;
820                         }
821                 }
822
823                 if ( lc->lconn_sb != ld->ld_sb ) {
824                         ber_sockbuf_free( lc->lconn_sb );
825                 } else {
826                         ber_int_sb_close( lc->lconn_sb );
827                 }
828
829                 if ( lc->lconn_rebind_queue != NULL) {
830                         int i;
831                         for( i = 0; lc->lconn_rebind_queue[i] != NULL; i++ ) {
832                                 LDAP_VFREE( lc->lconn_rebind_queue[i] );
833                         }
834                         LDAP_FREE( lc->lconn_rebind_queue );
835                 }
836
837                 LDAP_FREE( lc );
838
839                 Debug( LDAP_DEBUG_TRACE,
840                         "ldap_free_connection: actually freed\n",
841                         0, 0, 0 );
842
843         } else {
844                 lc->lconn_lastused = time( NULL );
845                 Debug( LDAP_DEBUG_TRACE, "ldap_free_connection: refcnt %d\n",
846                                 lc->lconn_refcnt, 0, 0 );
847         }
848 }
849
850
851 /* Protects self with ld_conn_mutex */
852 #ifdef LDAP_DEBUG
853 void
854 ldap_dump_connection( LDAP *ld, LDAPConn *lconns, int all )
855 {
856         LDAPConn        *lc;
857         char            timebuf[32];
858
859         Debug( LDAP_DEBUG_TRACE, "** ld %p Connection%s:\n", (void *)ld, all ? "s" : "", 0 );
860         LDAP_MUTEX_LOCK( &ld->ld_conn_mutex );
861         for ( lc = lconns; lc != NULL; lc = lc->lconn_next ) {
862                 if ( lc->lconn_server != NULL ) {
863                         Debug( LDAP_DEBUG_TRACE, "* host: %s  port: %d%s\n",
864                                 ( lc->lconn_server->lud_host == NULL ) ? "(null)"
865                                 : lc->lconn_server->lud_host,
866                                 lc->lconn_server->lud_port, ( lc->lconn_sb ==
867                                 ld->ld_sb ) ? "  (default)" : "" );
868                 }
869                 Debug( LDAP_DEBUG_TRACE, "  refcnt: %d  status: %s\n", lc->lconn_refcnt,
870                         ( lc->lconn_status == LDAP_CONNST_NEEDSOCKET )
871                                 ? "NeedSocket" :
872                                 ( lc->lconn_status == LDAP_CONNST_CONNECTING )
873                                         ? "Connecting" : "Connected", 0 );
874                 Debug( LDAP_DEBUG_TRACE, "  last used: %s%s\n",
875                         ldap_pvt_ctime( &lc->lconn_lastused, timebuf ),
876                         lc->lconn_rebind_inprogress ? "  rebind in progress" : "", 0 );
877                 if ( lc->lconn_rebind_inprogress ) {
878                         if ( lc->lconn_rebind_queue != NULL) {
879                                 int     i;
880
881                                 for ( i = 0; lc->lconn_rebind_queue[i] != NULL; i++ ) {
882                                         int     j;
883                                         for( j = 0; lc->lconn_rebind_queue[i][j] != 0; j++ ) {
884                                                 Debug( LDAP_DEBUG_TRACE, "    queue %d entry %d - %s\n",
885                                                         i, j, lc->lconn_rebind_queue[i][j] );
886                                         }
887                                 }
888                         } else {
889                                 Debug( LDAP_DEBUG_TRACE, "    queue is empty\n", 0, 0, 0 );
890                         }
891                 }
892                 Debug( LDAP_DEBUG_TRACE, "\n", 0, 0, 0 );
893                 if ( !all ) {
894                         break;
895                 }
896         }
897         LDAP_MUTEX_UNLOCK( &ld->ld_conn_mutex );
898 }
899
900
901 /* protected by req_mutex and res_mutex */
902 void
903 ldap_dump_requests_and_responses( LDAP *ld )
904 {
905         LDAPRequest     *lr;
906         LDAPMessage     *lm, *l;
907         int             i;
908
909         Debug( LDAP_DEBUG_TRACE, "** ld %p Outstanding Requests:\n",
910                 (void *)ld, 0, 0 );
911         lr = ld->ld_requests;
912         if ( lr == NULL ) {
913                 Debug( LDAP_DEBUG_TRACE, "   Empty\n", 0, 0, 0 );
914         }
915         for ( i = 0; lr != NULL; lr = lr->lr_next, i++ ) {
916                 Debug( LDAP_DEBUG_TRACE, " * msgid %d,  origid %d, status %s\n",
917                         lr->lr_msgid, lr->lr_origid,
918                         ( lr->lr_status == LDAP_REQST_INPROGRESS ) ? "InProgress" :
919                         ( lr->lr_status == LDAP_REQST_CHASINGREFS ) ? "ChasingRefs" :
920                         ( lr->lr_status == LDAP_REQST_NOTCONNECTED ) ? "NotConnected" :
921                         ( lr->lr_status == LDAP_REQST_WRITING ) ? "Writing" :
922                         ( lr->lr_status == LDAP_REQST_COMPLETED ) ? "RequestCompleted"
923                                 : "InvalidStatus" );
924                 Debug( LDAP_DEBUG_TRACE, "   outstanding referrals %d, parent count %d\n",
925                         lr->lr_outrefcnt, lr->lr_parentcnt, 0 );
926         }
927         Debug( LDAP_DEBUG_TRACE, "  ld %p request count %d (abandoned %lu)\n",
928                 (void *)ld, i, ld->ld_nabandoned );
929         Debug( LDAP_DEBUG_TRACE, "** ld %p Response Queue:\n", (void *)ld, 0, 0 );
930         if ( ( lm = ld->ld_responses ) == NULL ) {
931                 Debug( LDAP_DEBUG_TRACE, "   Empty\n", 0, 0, 0 );
932         }
933         for ( i = 0; lm != NULL; lm = lm->lm_next, i++ ) {
934                 Debug( LDAP_DEBUG_TRACE, " * msgid %d,  type %lu\n",
935                     lm->lm_msgid, (unsigned long)lm->lm_msgtype, 0 );
936                 if ( lm->lm_chain != NULL ) {
937                         Debug( LDAP_DEBUG_TRACE, "   chained responses:\n", 0, 0, 0 );
938                         for ( l = lm->lm_chain; l != NULL; l = l->lm_chain ) {
939                                 Debug( LDAP_DEBUG_TRACE,
940                                         "  * msgid %d,  type %lu\n",
941                                         l->lm_msgid,
942                                         (unsigned long)l->lm_msgtype, 0 );
943                         }
944                 }
945         }
946         Debug( LDAP_DEBUG_TRACE, "  ld %p response count %d\n", (void *)ld, i, 0 );
947 }
948 #endif /* LDAP_DEBUG */
949
950 /* protected by req_mutex */
951 static void
952 ldap_free_request_int( LDAP *ld, LDAPRequest *lr )
953 {
954         LDAP_ASSERT_MUTEX_OWNER( &ld->ld_req_mutex );
955         /* if lr_refcnt > 0, the request has been looked up 
956          * by ldap_find_request_by_msgid(); if in the meanwhile
957          * the request is free()'d by someone else, just decrease
958          * the reference count and extract it from the request
959          * list; later on, it will be freed. */
960         if ( lr->lr_prev == NULL ) {
961                 if ( lr->lr_refcnt == 0 ) {
962                         /* free'ing the first request? */
963                         assert( ld->ld_requests == lr );
964                 }
965
966                 if ( ld->ld_requests == lr ) {
967                         ld->ld_requests = lr->lr_next;
968                 }
969
970         } else {
971                 lr->lr_prev->lr_next = lr->lr_next;
972         }
973
974         if ( lr->lr_next != NULL ) {
975                 lr->lr_next->lr_prev = lr->lr_prev;
976         }
977
978         if ( lr->lr_refcnt > 0 ) {
979                 lr->lr_refcnt = -lr->lr_refcnt;
980
981                 lr->lr_prev = NULL;
982                 lr->lr_next = NULL;
983
984                 return;
985         }
986
987         if ( lr->lr_ber != NULL ) {
988                 ber_free( lr->lr_ber, 1 );
989                 lr->lr_ber = NULL;
990         }
991
992         if ( lr->lr_res_error != NULL ) {
993                 LDAP_FREE( lr->lr_res_error );
994                 lr->lr_res_error = NULL;
995         }
996
997         if ( lr->lr_res_matched != NULL ) {
998                 LDAP_FREE( lr->lr_res_matched );
999                 lr->lr_res_matched = NULL;
1000         }
1001
1002         LDAP_FREE( lr );
1003 }
1004
1005 /* protected by req_mutex */
1006 void
1007 ldap_free_request( LDAP *ld, LDAPRequest *lr )
1008 {
1009         LDAP_ASSERT_MUTEX_OWNER( &ld->ld_req_mutex );
1010         Debug( LDAP_DEBUG_TRACE, "ldap_free_request (origid %d, msgid %d)\n",
1011                 lr->lr_origid, lr->lr_msgid, 0 );
1012
1013         /* free all referrals (child requests) */
1014         while ( lr->lr_child ) {
1015                 ldap_free_request( ld, lr->lr_child );
1016         }
1017
1018         if ( lr->lr_parent != NULL ) {
1019                 LDAPRequest     **lrp;
1020
1021                 --lr->lr_parent->lr_outrefcnt;
1022                 for ( lrp = &lr->lr_parent->lr_child;
1023                         *lrp && *lrp != lr;
1024                         lrp = &(*lrp)->lr_refnext );
1025
1026                 if ( *lrp == lr ) {
1027                         *lrp = lr->lr_refnext;
1028                 }
1029         }
1030         ldap_free_request_int( ld, lr );
1031 }
1032
1033 /*
1034  * call first time with *cntp = -1
1035  * when returns *cntp == -1, no referrals are left
1036  *
1037  * NOTE: may replace *refsp, or shuffle the contents
1038  * of the original array.
1039  */
1040 static int ldap_int_nextref(
1041         LDAP                    *ld,
1042         char                    ***refsp,
1043         int                     *cntp,
1044         void                    *params )
1045 {
1046         assert( refsp != NULL );
1047         assert( *refsp != NULL );
1048         assert( cntp != NULL );
1049
1050         if ( *cntp < -1 ) {
1051                 *cntp = -1;
1052                 return -1;
1053         }
1054
1055         (*cntp)++;
1056
1057         if ( (*refsp)[ *cntp ] == NULL ) {
1058                 *cntp = -1;
1059         }
1060
1061         return 0;
1062 }
1063
1064 /*
1065  * Chase v3 referrals
1066  *
1067  * Parameters:
1068  *  (IN) ld = LDAP connection handle
1069  *  (IN) lr = LDAP Request structure
1070  *  (IN) refs = array of pointers to referral strings that we will chase
1071  *              The array will be free'd by this function when no longer needed
1072  *  (IN) sref != 0 if following search reference
1073  *  (OUT) errstrp = Place to return a string of referrals which could not be followed
1074  *  (OUT) hadrefp = 1 if sucessfully followed referral
1075  *
1076  * Return value - number of referrals followed
1077  *
1078  * Protected by res_mutex, conn_mutex and req_mutex     (try_read1msg)
1079  */
1080 int
1081 ldap_chase_v3referrals( LDAP *ld, LDAPRequest *lr, char **refs, int sref, char **errstrp, int *hadrefp )
1082 {
1083         char            *unfollowed;
1084         int              unfollowedcnt = 0;
1085         LDAPRequest     *origreq;
1086         LDAPURLDesc     *srv = NULL;
1087         BerElement      *ber;
1088         char            **refarray = NULL;
1089         LDAPConn        *lc;
1090         int                      rc, count, i, j, id;
1091         LDAPreqinfo  rinfo;
1092         LDAP_NEXTREF_PROC       *nextref_proc = ld->ld_nextref_proc ? ld->ld_nextref_proc : ldap_int_nextref;
1093
1094         LDAP_ASSERT_MUTEX_OWNER( &ld->ld_res_mutex );
1095         LDAP_ASSERT_MUTEX_OWNER( &ld->ld_conn_mutex );
1096         LDAP_ASSERT_MUTEX_OWNER( &ld->ld_req_mutex );
1097         Debug( LDAP_DEBUG_TRACE, "ldap_chase_v3referrals\n", 0, 0, 0 );
1098
1099         ld->ld_errno = LDAP_SUCCESS;    /* optimistic */
1100         *hadrefp = 0;
1101
1102         unfollowed = NULL;
1103         rc = count = 0;
1104
1105         /* If no referrals in array, return */
1106         if ( (refs == NULL) || ( (refs)[0] == NULL) ) {
1107                 rc = 0;
1108                 goto done;
1109         }
1110
1111         /* Check for hop limit exceeded */
1112         if ( lr->lr_parentcnt >= ld->ld_refhoplimit ) {
1113                 Debug( LDAP_DEBUG_ANY,
1114                     "more than %d referral hops (dropping)\n", ld->ld_refhoplimit, 0, 0 );
1115                 ld->ld_errno = LDAP_REFERRAL_LIMIT_EXCEEDED;
1116                 rc = -1;
1117                 goto done;
1118         }
1119
1120         /* find original request */
1121         for ( origreq = lr;
1122                 origreq->lr_parent != NULL;
1123                 origreq = origreq->lr_parent )
1124         {
1125                 /* empty */ ;
1126         }
1127
1128         refarray = refs;
1129         refs = NULL;
1130
1131         /* parse out & follow referrals */
1132         /* NOTE: if nextref_proc == ldap_int_nextref, params is ignored */
1133         i = -1;
1134         for ( nextref_proc( ld, &refarray, &i, ld->ld_nextref_params );
1135                         i != -1;
1136                         nextref_proc( ld, &refarray, &i, ld->ld_nextref_params ) )
1137         {
1138
1139                 /* Parse the referral URL */
1140                 rc = ldap_url_parse_ext( refarray[i], &srv, LDAP_PVT_URL_PARSE_NOEMPTY_DN );
1141                 if ( rc != LDAP_URL_SUCCESS ) {
1142                         /* ldap_url_parse_ext() returns LDAP_URL_* errors
1143                          * which do not map on API errors */
1144                         ld->ld_errno = LDAP_PARAM_ERROR;
1145                         rc = -1;
1146                         goto done;
1147                 }
1148
1149                 if( srv->lud_crit_exts ) {
1150                         int ok = 0;
1151 #ifdef HAVE_TLS
1152                         /* If StartTLS is the only critical ext, OK. */
1153                         if ( find_tls_ext( srv ) == 2 && srv->lud_crit_exts == 1 )
1154                                 ok = 1;
1155 #endif
1156                         if ( !ok ) {
1157                                 /* we do not support any other extensions */
1158                                 ld->ld_errno = LDAP_NOT_SUPPORTED;
1159                                 rc = -1;
1160                                 goto done;
1161                         }
1162                 }
1163
1164                 /* check connection for re-bind in progress */
1165                 if (( lc = find_connection( ld, srv, 1 )) != NULL ) {
1166                         /* See if we've already requested this DN with this conn */
1167                         LDAPRequest *lp;
1168                         int looped = 0;
1169                         ber_len_t len = srv->lud_dn ? strlen( srv->lud_dn ) : 0;
1170                         for ( lp = origreq; lp; ) {
1171                                 if ( lp->lr_conn == lc
1172                                         && len == lp->lr_dn.bv_len
1173                                         && len
1174                                         && strncmp( srv->lud_dn, lp->lr_dn.bv_val, len ) == 0 )
1175                                 {
1176                                         looped = 1;
1177                                         break;
1178                                 }
1179                                 if ( lp == origreq ) {
1180                                         lp = lp->lr_child;
1181                                 } else {
1182                                         lp = lp->lr_refnext;
1183                                 }
1184                         }
1185                         if ( looped ) {
1186                                 ldap_free_urllist( srv );
1187                                 srv = NULL;
1188                                 ld->ld_errno = LDAP_CLIENT_LOOP;
1189                                 rc = -1;
1190                                 continue;
1191                         }
1192
1193                         if ( lc->lconn_rebind_inprogress ) {
1194                                 /* We are already chasing a referral or search reference and a
1195                                  * bind on that connection is in progress.  We must queue
1196                                  * referrals on that connection, so we don't get a request
1197                                  * going out before the bind operation completes. This happens
1198                                  * if two search references come in one behind the other
1199                                  * for the same server with different contexts.
1200                                  */
1201                                 Debug( LDAP_DEBUG_TRACE,
1202                                         "ldap_chase_v3referrals: queue referral \"%s\"\n",
1203                                         refarray[i], 0, 0);
1204                                 if( lc->lconn_rebind_queue == NULL ) {
1205                                         /* Create a referral list */
1206                                         lc->lconn_rebind_queue =
1207                                                 (char ***) LDAP_MALLOC( sizeof(void *) * 2);
1208
1209                                         if( lc->lconn_rebind_queue == NULL) {
1210                                                 ld->ld_errno = LDAP_NO_MEMORY;
1211                                                 rc = -1;
1212                                                 goto done;
1213                                         }
1214
1215                                         lc->lconn_rebind_queue[0] = refarray;
1216                                         lc->lconn_rebind_queue[1] = NULL;
1217                                         refarray = NULL;
1218
1219                                 } else {
1220                                         /* Count how many referral arrays we already have */
1221                                         for( j = 0; lc->lconn_rebind_queue[j] != NULL; j++) {
1222                                                 /* empty */;
1223                                         }
1224
1225                                         /* Add the new referral to the list */
1226                                         lc->lconn_rebind_queue = (char ***) LDAP_REALLOC(
1227                                                 lc->lconn_rebind_queue, sizeof(void *) * (j + 2));
1228
1229                                         if( lc->lconn_rebind_queue == NULL ) {
1230                                                 ld->ld_errno = LDAP_NO_MEMORY;
1231                                                 rc = -1;
1232                                                 goto done;
1233                                         }
1234                                         lc->lconn_rebind_queue[j] = refarray;
1235                                         lc->lconn_rebind_queue[j+1] = NULL;
1236                                         refarray = NULL;
1237                                 }
1238
1239                                 /* We have queued the referral/reference, now just return */
1240                                 rc = 0;
1241                                 *hadrefp = 1;
1242                                 count = 1; /* Pretend we already followed referral */
1243                                 goto done;
1244                         }
1245                 } 
1246                 /* Re-encode the request with the new starting point of the search.
1247                  * Note: In the future we also need to replace the filter if one
1248                  * was provided with the search reference
1249                  */
1250
1251                 /* For references we don't want old dn if new dn empty */
1252                 if ( sref && srv->lud_dn == NULL ) {
1253                         srv->lud_dn = LDAP_STRDUP( "" );
1254                 }
1255
1256                 LDAP_NEXT_MSGID( ld, id );
1257                 ber = re_encode_request( ld, origreq->lr_ber, id,
1258                         sref, srv, &rinfo.ri_request );
1259
1260                 if( ber == NULL ) {
1261                         ld->ld_errno = LDAP_ENCODING_ERROR;
1262                         rc = -1;
1263                         goto done;
1264                 }
1265
1266                 Debug( LDAP_DEBUG_TRACE,
1267                         "ldap_chase_v3referral: msgid %d, url \"%s\"\n",
1268                         lr->lr_msgid, refarray[i], 0);
1269
1270                 /* Send the new request to the server - may require a bind */
1271                 rinfo.ri_msgid = origreq->lr_origid;
1272                 rinfo.ri_url = refarray[i];
1273                 rc = ldap_send_server_request( ld, ber, id,
1274                         origreq, &srv, NULL, &rinfo, 0, 1 );
1275                 if ( rc < 0 ) {
1276                         /* Failure, try next referral in the list */
1277                         Debug( LDAP_DEBUG_ANY, "Unable to chase referral \"%s\" (%d: %s)\n", 
1278                                 refarray[i], ld->ld_errno, ldap_err2string( ld->ld_errno ) );
1279                         unfollowedcnt += ldap_append_referral( ld, &unfollowed, refarray[i] );
1280                         ldap_free_urllist( srv );
1281                         srv = NULL;
1282                         ld->ld_errno = LDAP_REFERRAL;
1283                 } else {
1284                         /* Success, no need to try this referral list further */
1285                         rc = 0;
1286                         ++count;
1287                         *hadrefp = 1;
1288
1289                         /* check if there is a queue of referrals that came in during bind */
1290                         if ( lc == NULL) {
1291                                 lc = find_connection( ld, srv, 1 );
1292                                 if ( lc == NULL ) {
1293                                         ld->ld_errno = LDAP_OPERATIONS_ERROR;
1294                                         rc = -1;
1295                                         LDAP_MUTEX_UNLOCK( &ld->ld_conn_mutex );
1296                                         goto done;
1297                                 }
1298                         }
1299
1300                         if ( lc->lconn_rebind_queue != NULL ) {
1301                                 /* Release resources of previous list */
1302                                 LDAP_VFREE( refarray );
1303                                 refarray = NULL;
1304                                 ldap_free_urllist( srv );
1305                                 srv = NULL;
1306
1307                                 /* Pull entries off end of queue so list always null terminated */
1308                                 for( j = 0; lc->lconn_rebind_queue[j] != NULL; j++ )
1309                                         ;
1310                                 refarray = lc->lconn_rebind_queue[j - 1];
1311                                 lc->lconn_rebind_queue[j-1] = NULL;
1312                                 /* we pulled off last entry from queue, free queue */
1313                                 if ( j == 1 ) {
1314                                         LDAP_FREE( lc->lconn_rebind_queue );
1315                                         lc->lconn_rebind_queue = NULL;
1316                                 }
1317                                 /* restart the loop the with new referral list */
1318                                 i = -1;
1319                                 continue;
1320                         }
1321                         break; /* referral followed, break out of for loop */
1322                 }
1323         } /* end for loop */
1324 done:
1325         LDAP_VFREE( refarray );
1326         ldap_free_urllist( srv );
1327         LDAP_FREE( *errstrp );
1328         
1329         if( rc == 0 ) {
1330                 *errstrp = NULL;
1331                 LDAP_FREE( unfollowed );
1332                 return count;
1333         } else {
1334                 *errstrp = unfollowed;
1335                 return rc;
1336         }
1337 }
1338
1339 /*
1340  * XXX merging of errors in this routine needs to be improved
1341  * Protected by res_mutex, conn_mutex and req_mutex     (try_read1msg)
1342  */
1343 int
1344 ldap_chase_referrals( LDAP *ld,
1345         LDAPRequest *lr,
1346         char **errstrp,
1347         int sref,
1348         int *hadrefp )
1349 {
1350         int             rc, count, id;
1351         unsigned        len;
1352         char            *p, *ref, *unfollowed;
1353         LDAPRequest     *origreq;
1354         LDAPURLDesc     *srv;
1355         BerElement      *ber;
1356         LDAPreqinfo  rinfo;
1357         LDAPConn        *lc;
1358
1359         LDAP_ASSERT_MUTEX_OWNER( &ld->ld_res_mutex );
1360         LDAP_ASSERT_MUTEX_OWNER( &ld->ld_conn_mutex );
1361         LDAP_ASSERT_MUTEX_OWNER( &ld->ld_req_mutex );
1362         Debug( LDAP_DEBUG_TRACE, "ldap_chase_referrals\n", 0, 0, 0 );
1363
1364         ld->ld_errno = LDAP_SUCCESS;    /* optimistic */
1365         *hadrefp = 0;
1366
1367         if ( *errstrp == NULL ) {
1368                 return( 0 );
1369         }
1370
1371         len = strlen( *errstrp );
1372         for ( p = *errstrp; len >= LDAP_REF_STR_LEN; ++p, --len ) {
1373                 if ( strncasecmp( p, LDAP_REF_STR, LDAP_REF_STR_LEN ) == 0 ) {
1374                         *p = '\0';
1375                         p += LDAP_REF_STR_LEN;
1376                         break;
1377                 }
1378         }
1379
1380         if ( len < LDAP_REF_STR_LEN ) {
1381                 return( 0 );
1382         }
1383
1384         if ( lr->lr_parentcnt >= ld->ld_refhoplimit ) {
1385                 Debug( LDAP_DEBUG_ANY,
1386                     "more than %d referral hops (dropping)\n",
1387                     ld->ld_refhoplimit, 0, 0 );
1388                     /* XXX report as error in ld->ld_errno? */
1389                     return( 0 );
1390         }
1391
1392         /* find original request */
1393         for ( origreq = lr; origreq->lr_parent != NULL;
1394              origreq = origreq->lr_parent ) {
1395                 /* empty */;
1396         }
1397
1398         unfollowed = NULL;
1399         rc = count = 0;
1400
1401         /* parse out & follow referrals */
1402         for ( ref = p; rc == 0 && ref != NULL; ref = p ) {
1403                 p = strchr( ref, '\n' );
1404                 if ( p != NULL ) {
1405                         *p++ = '\0';
1406                 }
1407
1408                 rc = ldap_url_parse_ext( ref, &srv, LDAP_PVT_URL_PARSE_NOEMPTY_DN );
1409                 if ( rc != LDAP_URL_SUCCESS ) {
1410                         Debug( LDAP_DEBUG_TRACE,
1411                                 "ignoring %s referral <%s>\n",
1412                                 ref, rc == LDAP_URL_ERR_BADSCHEME ? "unknown" : "incorrect", 0 );
1413                         rc = ldap_append_referral( ld, &unfollowed, ref );
1414                         *hadrefp = 1;
1415                         continue;
1416                 }
1417
1418                 Debug( LDAP_DEBUG_TRACE,
1419                     "chasing LDAP referral: <%s>\n", ref, 0, 0 );
1420
1421                 *hadrefp = 1;
1422
1423                 /* See if we've already been here */
1424                 if (( lc = find_connection( ld, srv, 1 )) != NULL ) {
1425                         LDAPRequest *lp;
1426                         int looped = 0;
1427                         ber_len_t len = srv->lud_dn ? strlen( srv->lud_dn ) : 0;
1428                         for ( lp = lr; lp; lp = lp->lr_parent ) {
1429                                 if ( lp->lr_conn == lc
1430                                         && len == lp->lr_dn.bv_len )
1431                                 {
1432                                         if ( len && strncmp( srv->lud_dn, lp->lr_dn.bv_val, len ) )
1433                                                         continue;
1434                                         looped = 1;
1435                                         break;
1436                                 }
1437                         }
1438                         if ( looped ) {
1439                                 ldap_free_urllist( srv );
1440                                 ld->ld_errno = LDAP_CLIENT_LOOP;
1441                                 rc = -1;
1442                                 continue;
1443                         }
1444                 }
1445
1446                 LDAP_NEXT_MSGID( ld, id );
1447                 ber = re_encode_request( ld, origreq->lr_ber,
1448                     id, sref, srv, &rinfo.ri_request );
1449
1450                 if ( ber == NULL ) {
1451                         ldap_free_urllist( srv );
1452                         return -1 ;
1453                 }
1454
1455                 /* copy the complete referral for rebind process */
1456                 rinfo.ri_url = LDAP_STRDUP( ref );
1457
1458                 rinfo.ri_msgid = origreq->lr_origid;
1459
1460                 rc = ldap_send_server_request( ld, ber, id,
1461                         lr, &srv, NULL, &rinfo, 0, 1 );
1462                 LDAP_FREE( rinfo.ri_url );
1463
1464                 if( rc >= 0 ) {
1465                         ++count;
1466                 } else {
1467                         Debug( LDAP_DEBUG_ANY,
1468                                 "Unable to chase referral \"%s\" (%d: %s)\n", 
1469                                 ref, ld->ld_errno, ldap_err2string( ld->ld_errno ) );
1470                         rc = ldap_append_referral( ld, &unfollowed, ref );
1471                 }
1472
1473                 ldap_free_urllist(srv);
1474         }
1475
1476         LDAP_FREE( *errstrp );
1477         *errstrp = unfollowed;
1478
1479         return(( rc == 0 ) ? count : rc );
1480 }
1481
1482
1483 int
1484 ldap_append_referral( LDAP *ld, char **referralsp, char *s )
1485 {
1486         int     first;
1487
1488         if ( *referralsp == NULL ) {
1489                 first = 1;
1490                 *referralsp = (char *)LDAP_MALLOC( strlen( s ) + LDAP_REF_STR_LEN
1491                     + 1 );
1492         } else {
1493                 first = 0;
1494                 *referralsp = (char *)LDAP_REALLOC( *referralsp,
1495                     strlen( *referralsp ) + strlen( s ) + 2 );
1496         }
1497
1498         if ( *referralsp == NULL ) {
1499                 ld->ld_errno = LDAP_NO_MEMORY;
1500                 return( -1 );
1501         }
1502
1503         if ( first ) {
1504                 strcpy( *referralsp, LDAP_REF_STR );
1505         } else {
1506                 strcat( *referralsp, "\n" );
1507         }
1508         strcat( *referralsp, s );
1509
1510         return( 0 );
1511 }
1512
1513
1514
1515 static BerElement *
1516 re_encode_request( LDAP *ld,
1517         BerElement *origber,
1518         ber_int_t msgid,
1519         int sref,
1520         LDAPURLDesc *srv,
1521         int *type )
1522 {
1523         /*
1524          * XXX this routine knows way too much about how the lber library works!
1525          */
1526         ber_int_t       along;
1527         ber_tag_t       tag;
1528         ber_tag_t       rtag;
1529         ber_int_t       ver;
1530         ber_int_t       scope;
1531         int             rc;
1532         BerElement      tmpber, *ber;
1533         struct berval           dn;
1534
1535         Debug( LDAP_DEBUG_TRACE,
1536             "re_encode_request: new msgid %ld, new dn <%s>\n",
1537             (long) msgid,
1538                 ( srv == NULL || srv->lud_dn == NULL) ? "NONE" : srv->lud_dn, 0 );
1539
1540         tmpber = *origber;
1541
1542         /*
1543          * all LDAP requests are sequences that start with a message id.
1544          * For all except delete, this is followed by a sequence that is
1545          * tagged with the operation code.  For delete, the provided DN
1546          * is not wrapped by a sequence.
1547          */
1548         rtag = ber_scanf( &tmpber, "{it", /*}*/ &along, &tag );
1549
1550         if ( rtag == LBER_ERROR ) {
1551                 ld->ld_errno = LDAP_DECODING_ERROR;
1552                 return( NULL );
1553         }
1554
1555         assert( tag != 0);
1556         if ( tag == LDAP_REQ_BIND ) {
1557                 /* bind requests have a version number before the DN & other stuff */
1558                 rtag = ber_scanf( &tmpber, "{im" /*}*/, &ver, &dn );
1559
1560         } else if ( tag == LDAP_REQ_DELETE ) {
1561                 /* delete requests don't have a DN wrapping sequence */
1562                 rtag = ber_scanf( &tmpber, "m", &dn );
1563
1564         } else if ( tag == LDAP_REQ_SEARCH ) {
1565                 /* search requests need to be re-scope-ed */
1566                 rtag = ber_scanf( &tmpber, "{me" /*"}"*/, &dn, &scope );
1567
1568                 if( srv->lud_scope != LDAP_SCOPE_DEFAULT ) {
1569                         /* use the scope provided in reference */
1570                         scope = srv->lud_scope;
1571
1572                 } else if ( sref ) {
1573                         /* use scope implied by previous operation
1574                          *   base -> base
1575                          *   one -> base
1576                          *   subtree -> subtree
1577                          *   subordinate -> subtree
1578                          */
1579                         switch( scope ) {
1580                         default:
1581                         case LDAP_SCOPE_BASE:
1582                         case LDAP_SCOPE_ONELEVEL:
1583                                 scope = LDAP_SCOPE_BASE;
1584                                 break;
1585                         case LDAP_SCOPE_SUBTREE:
1586                         case LDAP_SCOPE_SUBORDINATE:
1587                                 scope = LDAP_SCOPE_SUBTREE;
1588                                 break;
1589                         }
1590                 }
1591
1592         } else {
1593                 rtag = ber_scanf( &tmpber, "{m" /*}*/, &dn );
1594         }
1595
1596         if( rtag == LBER_ERROR ) {
1597                 ld->ld_errno = LDAP_DECODING_ERROR;
1598                 return NULL;
1599         }
1600
1601         /* restore character zero'd out by ber_scanf*/
1602         dn.bv_val[dn.bv_len] = tmpber.ber_tag;
1603
1604         if (( ber = ldap_alloc_ber_with_options( ld )) == NULL ) {
1605                 return NULL;
1606         }
1607
1608         if ( srv->lud_dn ) {
1609                 ber_str2bv( srv->lud_dn, 0, 0, &dn );
1610         }
1611
1612         if ( tag == LDAP_REQ_BIND ) {
1613                 rc = ber_printf( ber, "{it{iO" /*}}*/, msgid, tag, ver, &dn );
1614         } else if ( tag == LDAP_REQ_DELETE ) {
1615                 rc = ber_printf( ber, "{itON}", msgid, tag, &dn );
1616         } else if ( tag == LDAP_REQ_SEARCH ) {
1617                 rc = ber_printf( ber, "{it{Oe" /*}}*/, msgid, tag, &dn, scope );
1618         } else {
1619                 rc = ber_printf( ber, "{it{O" /*}}*/, msgid, tag, &dn );
1620         }
1621
1622         if ( rc == -1 ) {
1623                 ld->ld_errno = LDAP_ENCODING_ERROR;
1624                 ber_free( ber, 1 );
1625                 return NULL;
1626         }
1627
1628         if ( tag != LDAP_REQ_DELETE && (
1629                 ber_write(ber, tmpber.ber_ptr, ( tmpber.ber_end - tmpber.ber_ptr ), 0)
1630                 != ( tmpber.ber_end - tmpber.ber_ptr ) ||
1631             ber_printf( ber, /*{{*/ "N}N}" ) == -1 ) )
1632         {
1633                 ld->ld_errno = LDAP_ENCODING_ERROR;
1634                 ber_free( ber, 1 );
1635                 return NULL;
1636         }
1637
1638 #ifdef LDAP_DEBUG
1639         if ( ldap_debug & LDAP_DEBUG_PACKETS ) {
1640                 Debug( LDAP_DEBUG_ANY, "re_encode_request new request is:\n",
1641                     0, 0, 0 );
1642                 ber_log_dump( LDAP_DEBUG_BER, ldap_debug, ber, 0 );
1643         }
1644 #endif /* LDAP_DEBUG */
1645
1646         *type = tag;    /* return request type */
1647         return ber;
1648 }
1649
1650
1651 /* protected by req_mutex */
1652 LDAPRequest *
1653 ldap_find_request_by_msgid( LDAP *ld, ber_int_t msgid )
1654 {
1655         LDAPRequest     *lr;
1656
1657         for ( lr = ld->ld_requests; lr != NULL; lr = lr->lr_next ) {
1658                 if ( lr->lr_status == LDAP_REQST_COMPLETED ) {
1659                         continue;       /* Skip completed requests */
1660                 }
1661                 if ( msgid == lr->lr_msgid ) {
1662                         lr->lr_refcnt++;
1663                         break;
1664                 }
1665         }
1666
1667         return( lr );
1668 }
1669
1670 /* protected by req_mutex */
1671 void
1672 ldap_return_request( LDAP *ld, LDAPRequest *lrx, int freeit )
1673 {
1674         LDAPRequest     *lr;
1675
1676         for ( lr = ld->ld_requests; lr != NULL; lr = lr->lr_next ) {
1677                 if ( lr == lrx ) {
1678                         if ( lr->lr_refcnt > 0 ) {
1679                                 lr->lr_refcnt--;
1680
1681                         } else if ( lr->lr_refcnt < 0 ) {
1682                                 lr->lr_refcnt++;
1683                                 if ( lr->lr_refcnt == 0 ) {
1684                                         lr = NULL;
1685                                 }
1686                         }
1687                         break;
1688                 }
1689         }
1690         if ( lr == NULL ) {
1691                 ldap_free_request_int( ld, lrx );
1692
1693         } else if ( freeit ) {
1694                 ldap_free_request( ld, lrx );
1695         }
1696 }