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