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