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