]> git.sur5r.net Git - openldap/blob - libraries/libldap/request.c
Sync with HEAD
[openldap] / libraries / libldap / request.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2005 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         lc->lconn_next = ld->ld_conns;
367         ld->ld_conns = lc;
368
369         /*
370          * XXX for now, we always do a synchronous bind.  This will have
371          * to change in the long run...
372          */
373         if ( bind != NULL) {
374                 int             err = 0;
375                 LDAPConn        *savedefconn;
376
377                 /* Set flag to prevent additional referrals
378                  * from being processed on this
379                  * connection until the bind has completed
380                  */
381                 lc->lconn_rebind_inprogress = 1;
382                 /* V3 rebind function */
383                 if ( ld->ld_rebind_proc != NULL) {
384                         LDAPURLDesc     *srvfunc;
385
386                         srvfunc = ldap_url_dup( srvlist );
387                         if ( srvfunc == NULL ) {
388                                 ld->ld_errno = LDAP_NO_MEMORY;
389                                 err = -1;
390                         } else {
391                                 savedefconn = ld->ld_defconn;
392                                 ++lc->lconn_refcnt;     /* avoid premature free */
393                                 ld->ld_defconn = lc;
394
395                                 Debug( LDAP_DEBUG_TRACE, "Call application rebind_proc\n", 0, 0, 0);
396 #ifdef LDAP_R_COMPILE
397                                 ldap_pvt_thread_mutex_unlock( &ld->ld_req_mutex );
398                                 ldap_pvt_thread_mutex_unlock( &ld->ld_res_mutex );
399 #endif
400                                 err = (*ld->ld_rebind_proc)( ld,
401                                         bind->ri_url, bind->ri_request, bind->ri_msgid,
402                                         ld->ld_rebind_params );
403 #ifdef LDAP_R_COMPILE
404                                 ldap_pvt_thread_mutex_lock( &ld->ld_res_mutex );
405                                 ldap_pvt_thread_mutex_lock( &ld->ld_req_mutex );
406 #endif
407
408                                 ld->ld_defconn = savedefconn;
409                                 --lc->lconn_refcnt;
410
411                                 if ( err != 0 ) {
412                                         err = -1;
413                                         ldap_free_connection( ld, lc, 1, 0 );
414                                         lc = NULL;
415                                 }
416                                 ldap_free_urldesc( srvfunc );
417                         }
418                 } else {
419                         savedefconn = ld->ld_defconn;
420                         ++lc->lconn_refcnt;     /* avoid premature free */
421                         ld->ld_defconn = lc;
422
423                         Debug( LDAP_DEBUG_TRACE, "anonymous rebind via ldap_bind_s\n", 0, 0, 0);
424 #ifdef LDAP_R_COMPILE
425                         ldap_pvt_thread_mutex_unlock( &ld->ld_req_mutex );
426                         ldap_pvt_thread_mutex_unlock( &ld->ld_res_mutex );
427 #endif
428                         if ( ldap_bind_s( ld, "", "", LDAP_AUTH_SIMPLE ) != LDAP_SUCCESS ) {
429                                 err = -1;
430                         }
431 #ifdef LDAP_R_COMPILE
432                         ldap_pvt_thread_mutex_lock( &ld->ld_res_mutex );
433                         ldap_pvt_thread_mutex_lock( &ld->ld_req_mutex );
434 #endif
435                         ld->ld_defconn = savedefconn;
436                         --lc->lconn_refcnt;
437
438                         if ( err != 0 ) {
439                                 ldap_free_connection( ld, lc, 1, 0 );
440                                 lc = NULL;
441                         }
442                 }
443                 if ( lc != NULL )
444                         lc->lconn_rebind_inprogress = 0;
445         }
446
447         return( lc );
448 }
449
450
451 static LDAPConn *
452 find_connection( LDAP *ld, LDAPURLDesc *srv, int any )
453 /*
454  * return an existing connection (if any) to the server srv
455  * if "any" is non-zero, check for any server in the "srv" chain
456  */
457 {
458         LDAPConn        *lc;
459         LDAPURLDesc     *lcu, *lsu;
460         int lcu_port, lsu_port;
461
462         for ( lc = ld->ld_conns; lc != NULL; lc = lc->lconn_next ) {
463                 lcu = lc->lconn_server;
464                 lcu_port = ldap_pvt_url_scheme_port( lcu->lud_scheme,
465                         lcu->lud_port );
466
467                 for ( lsu = srv; lsu != NULL; lsu = lsu->lud_next ) {
468                         lsu_port = ldap_pvt_url_scheme_port( lsu->lud_scheme,
469                                 lsu->lud_port );
470
471                         if ( strcmp( lcu->lud_scheme, lsu->lud_scheme ) == 0
472                                 && lcu->lud_host != NULL && *lcu->lud_host != '\0'
473                             && lsu->lud_host != NULL && *lsu->lud_host != '\0'
474                                 && strcasecmp( lsu->lud_host, lcu->lud_host ) == 0
475                             && lsu_port == lcu_port )
476                         {
477                                 return lc;
478                         }
479
480                         if ( !any ) break;
481                 }
482         }
483
484         return NULL;
485 }
486
487
488
489 static void
490 use_connection( LDAP *ld, LDAPConn *lc )
491 {
492         ++lc->lconn_refcnt;
493         lc->lconn_lastused = time( NULL );
494 }
495
496
497 void
498 ldap_free_connection( LDAP *ld, LDAPConn *lc, int force, int unbind )
499 {
500         LDAPConn        *tmplc, *prevlc;
501
502         Debug( LDAP_DEBUG_TRACE,
503                 "ldap_free_connection %d %d\n",
504                 force, unbind, 0 );
505
506         if ( force || --lc->lconn_refcnt <= 0 ) {
507                 if ( lc->lconn_status == LDAP_CONNST_CONNECTED ) {
508                         ldap_mark_select_clear( ld, lc->lconn_sb );
509                         if ( unbind ) {
510                                 ldap_send_unbind( ld, lc->lconn_sb,
511                                                 NULL, NULL );
512                         }
513                 }
514
515                 if ( lc->lconn_ber != NULL ) {
516                         ber_free( lc->lconn_ber, 1 );
517                 }
518
519                 ldap_int_sasl_close( ld, lc );
520
521                 prevlc = NULL;
522                 for ( tmplc = ld->ld_conns;
523                         tmplc != NULL;
524                         tmplc = tmplc->lconn_next )
525                 {
526                         if ( tmplc == lc ) {
527                                 if ( prevlc == NULL ) {
528                                     ld->ld_conns = tmplc->lconn_next;
529                                 } else {
530                                     prevlc->lconn_next = tmplc->lconn_next;
531                                 }
532                                 break;
533                         }
534                         prevlc = tmplc;
535                 }
536                 ldap_free_urllist( lc->lconn_server );
537 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
538                 if ( lc->lconn_krbinstance != NULL ) {
539                         LDAP_FREE( lc->lconn_krbinstance );
540                 }
541 #endif
542
543                 /* FIXME: is this at all possible? */
544                 if ( force ) {
545                         LDAPRequest     *lr;
546
547                         for ( lr = ld->ld_requests; lr; ) {
548                                 LDAPRequest     *lr_next = lr->lr_next;
549
550                                 if ( lr->lr_conn == lc ) {
551                                         ldap_free_request_int( ld, lr );
552                                 }
553
554                                 lr = lr_next;
555                         }
556                 }
557                 if ( lc->lconn_sb != ld->ld_sb ) {
558                         ber_sockbuf_free( lc->lconn_sb );
559                 }
560                 if ( lc->lconn_rebind_queue != NULL) {
561                         int i;
562                         for( i = 0; lc->lconn_rebind_queue[i] != NULL; i++ ) {
563                                 LDAP_VFREE( lc->lconn_rebind_queue[i] );
564                         }
565                         LDAP_FREE( lc->lconn_rebind_queue );
566                 }
567                 LDAP_FREE( lc );
568                 Debug( LDAP_DEBUG_TRACE,
569                         "ldap_free_connection: actually freed\n",
570                         0, 0, 0 );
571         } else {
572                 lc->lconn_lastused = time( NULL );
573                 Debug( LDAP_DEBUG_TRACE, "ldap_free_connection: refcnt %d\n",
574                                 lc->lconn_refcnt, 0, 0 );
575         }
576 }
577
578
579 #ifdef LDAP_DEBUG
580 void
581 ldap_dump_connection( LDAP *ld, LDAPConn *lconns, int all )
582 {
583         LDAPConn        *lc;
584         char            timebuf[32];
585
586         fprintf( stderr, "** Connection%s:\n", all ? "s" : "" );
587         for ( lc = lconns; lc != NULL; lc = lc->lconn_next ) {
588                 if ( lc->lconn_server != NULL ) {
589                         fprintf( stderr, "* host: %s  port: %d%s\n",
590                             ( lc->lconn_server->lud_host == NULL ) ? "(null)"
591                             : lc->lconn_server->lud_host,
592                             lc->lconn_server->lud_port, ( lc->lconn_sb ==
593                             ld->ld_sb ) ? "  (default)" : "" );
594                 }
595                 fprintf( stderr, "  refcnt: %d  status: %s\n", lc->lconn_refcnt,
596                     ( lc->lconn_status == LDAP_CONNST_NEEDSOCKET ) ?
597                     "NeedSocket" : ( lc->lconn_status ==
598                     LDAP_CONNST_CONNECTING ) ? "Connecting" : "Connected" );
599                 fprintf( stderr, "  last used: %s",
600                     ldap_pvt_ctime( &lc->lconn_lastused, timebuf ));
601                 if( lc->lconn_rebind_inprogress ) {
602                         fprintf( stderr, "  rebind in progress\n");
603                         if( lc->lconn_rebind_queue != NULL) {
604                                 int i = 0;
605                                 for( ;lc->lconn_rebind_queue[i] != NULL; i++) {
606                                         int j = 0;
607                                         for( ;lc->lconn_rebind_queue[i][j] != 0; j++) {
608                                                 fprintf( stderr, "    queue %d entry %d - %s\n",
609                                                         i, j, lc->lconn_rebind_queue[i][j]);
610                                         }
611                                 }
612                         } else {
613                                 fprintf( stderr, "    queue is empty\n");
614                         }
615                 }
616                 fprintf(stderr, "\n");
617                 if ( !all ) {
618                         break;
619                 }
620         }
621 }
622
623
624 void
625 ldap_dump_requests_and_responses( LDAP *ld )
626 {
627         LDAPRequest     *lr;
628         LDAPMessage     *lm, *l;
629
630 #ifdef LDAP_R_COMPILE
631         ldap_pvt_thread_mutex_lock( &ld->ld_req_mutex );
632 #endif
633         fprintf( stderr, "** Outstanding Requests:\n" );
634         if (( lr = ld->ld_requests ) == NULL ) {
635                 fprintf( stderr, "   Empty\n" );
636         }
637         for ( ; lr != NULL; lr = lr->lr_next ) {
638             fprintf( stderr, " * msgid %d,  origid %d, status %s\n",
639                 lr->lr_msgid, lr->lr_origid,
640                 ( lr->lr_status == LDAP_REQST_INPROGRESS ) ? "InProgress" :
641                 ( lr->lr_status == LDAP_REQST_CHASINGREFS ) ? "ChasingRefs" :
642                 ( lr->lr_status == LDAP_REQST_NOTCONNECTED ) ? "NotConnected" :
643                 ( lr->lr_status == LDAP_REQST_WRITING) ? "Writing" :
644                 ( lr->lr_status == LDAP_REQST_COMPLETED ? "Request Completed" : "Invalid Status"));
645             fprintf( stderr, "   outstanding referrals %d, parent count %d\n",
646                     lr->lr_outrefcnt, lr->lr_parentcnt );
647         }
648 #ifdef LDAP_R_COMPILE
649         ldap_pvt_thread_mutex_unlock( &ld->ld_req_mutex );
650 #endif
651         fprintf( stderr, "** Response Queue:\n" );
652         if (( lm = ld->ld_responses ) == NULL ) {
653                 fprintf( stderr, "   Empty\n" );
654         }
655         for ( ; lm != NULL; lm = lm->lm_next ) {
656                 fprintf( stderr, " * msgid %d,  type %lu\n",
657                     lm->lm_msgid, (unsigned long) lm->lm_msgtype );
658                 if (( l = lm->lm_chain ) != NULL ) {
659                         fprintf( stderr, "   chained responses:\n" );
660                         for ( ; l != NULL; l = l->lm_chain ) {
661                                 fprintf( stderr,
662                                     "  * msgid %d,  type %lu\n",
663                                     l->lm_msgid,
664                                     (unsigned long) l->lm_msgtype );
665                         }
666                 }
667         }
668 }
669 #endif /* LDAP_DEBUG */
670
671 static void
672 ldap_free_request_int( LDAP *ld, LDAPRequest *lr )
673 {
674         if ( lr->lr_prev == NULL ) {
675                 /* free'ing the first request? */
676                 assert( ld->ld_requests == lr );
677                 ld->ld_requests = lr->lr_next;
678
679         } else {
680                 lr->lr_prev->lr_next = lr->lr_next;
681         }
682
683         if ( lr->lr_next != NULL ) {
684                 lr->lr_next->lr_prev = lr->lr_prev;
685         }
686
687         if ( lr->lr_ber != NULL ) {
688                 ber_free( lr->lr_ber, 1 );
689         }
690
691         if ( lr->lr_res_error != NULL ) {
692                 LDAP_FREE( lr->lr_res_error );
693         }
694
695         if ( lr->lr_res_matched != NULL ) {
696                 LDAP_FREE( lr->lr_res_matched );
697         }
698
699         LDAP_FREE( lr );
700 }
701
702 void
703 ldap_free_request( LDAP *ld, LDAPRequest *lr )
704 {
705         LDAPRequest     **ttmplr;
706
707         Debug( LDAP_DEBUG_TRACE, "ldap_free_request (origid %d, msgid %d)\n",
708                 lr->lr_origid, lr->lr_msgid, 0 );
709
710         /* free all referrals (child requests) */
711         while ( lr->lr_child )
712                 ldap_free_request( ld, lr->lr_child );
713
714         if ( lr->lr_parent != NULL ) {
715                 --lr->lr_parent->lr_outrefcnt;
716                 for ( ttmplr = &lr->lr_parent->lr_child; *ttmplr && *ttmplr != lr; ttmplr = &(*ttmplr)->lr_refnext ); 
717                 if ( *ttmplr == lr )  
718                         *ttmplr = lr->lr_refnext;
719         }
720         ldap_free_request_int( ld, lr );
721 }
722
723 /*
724  * call first time with *cntp = -1
725  * when returns *cntp == -1, no referrals are left
726  *
727  * NOTE: may replace *refsp, or shuffle the contents
728  * of the original array.
729  */
730 static int ldap_int_nextref(
731         LDAP                    *ld,
732         char                    ***refsp,
733         int                     *cntp,
734         void                    *params )
735 {
736         assert( refsp != NULL );
737         assert( *refsp != NULL );
738         assert( cntp != NULL );
739
740         if ( *cntp < -1 ) {
741                 *cntp = -1;
742                 return -1;
743         }
744
745         (*cntp)++;
746
747         if ( (*refsp)[ *cntp ] == NULL ) {
748                 *cntp = -1;
749         }
750
751         return 0;
752 }
753
754 /*
755  * Chase v3 referrals
756  *
757  * Parameters:
758  *  (IN) ld = LDAP connection handle
759  *  (IN) lr = LDAP Request structure
760  *  (IN) refs = array of pointers to referral strings that we will chase
761  *              The array will be free'd by this function when no longer needed
762  *  (IN) sref != 0 if following search reference
763  *  (OUT) errstrp = Place to return a string of referrals which could not be followed
764  *  (OUT) hadrefp = 1 if sucessfully followed referral
765  *
766  * Return value - number of referrals followed
767  */
768 int
769 ldap_chase_v3referrals( LDAP *ld, LDAPRequest *lr, char **refs, int sref, char **errstrp, int *hadrefp )
770 {
771         char            *unfollowed;
772         int              unfollowedcnt = 0;
773         LDAPRequest     *origreq;
774         LDAPURLDesc     *srv = NULL;
775         BerElement      *ber;
776         char            **refarray = NULL;
777         LDAPConn        *lc;
778         int                      rc, count, i, j, id;
779         LDAPreqinfo  rinfo;
780
781         ld->ld_errno = LDAP_SUCCESS;    /* optimistic */
782         *hadrefp = 0;
783
784         Debug( LDAP_DEBUG_TRACE, "ldap_chase_v3referrals\n", 0, 0, 0 );
785
786         unfollowed = NULL;
787         rc = count = 0;
788
789         /* If no referrals in array, return */
790         if ( (refs == NULL) || ( (refs)[0] == NULL) ) {
791                 rc = 0;
792                 goto done;
793         }
794
795         /* Check for hop limit exceeded */
796         if ( lr->lr_parentcnt >= ld->ld_refhoplimit ) {
797                 Debug( LDAP_DEBUG_ANY,
798                     "more than %d referral hops (dropping)\n", ld->ld_refhoplimit, 0, 0 );
799                 ld->ld_errno = LDAP_REFERRAL_LIMIT_EXCEEDED;
800             rc = -1;
801                 goto done;
802         }
803
804         /* find original request */
805         for ( origreq = lr;
806                 origreq->lr_parent != NULL;
807                 origreq = origreq->lr_parent )
808         {
809                 /* empty */ ;
810         }
811
812         refarray = refs;
813         refs = NULL;
814
815         if ( ld->ld_nextref_proc == NULL ) {
816                 ld->ld_nextref_proc = ldap_int_nextref;
817         }
818
819         /* parse out & follow referrals */
820         i = -1;
821         for ( ld->ld_nextref_proc( ld, &refarray, &i, ld->ld_nextref_params );
822                         i != -1;
823                         ld->ld_nextref_proc( ld, &refarray, &i, ld->ld_nextref_params ) )
824         {
825
826                 /* Parse the referral URL */
827                 if (( rc = ldap_url_parse_ext( refarray[i], &srv)) != LDAP_SUCCESS) {
828                         ld->ld_errno = rc;
829                         rc = -1;
830                         goto done;
831                 }
832
833                 if( srv->lud_crit_exts ) {
834                         /* we do not support any extensions */
835                         ld->ld_errno = LDAP_NOT_SUPPORTED;
836                         rc = -1;
837                         goto done;
838                 }
839
840                 /* treat ldap://hostpart and ldap://hostpart/ the same */
841                 if ( srv->lud_dn && srv->lud_dn[0] == '\0' ) {
842                         LDAP_FREE( srv->lud_dn );
843                         srv->lud_dn = NULL;
844                 }
845
846                 /* check connection for re-bind in progress */
847                 if (( lc = find_connection( ld, srv, 1 )) != NULL ) {
848                         /* See if we've already requested this DN with this conn */
849                         LDAPRequest *lp;
850                         int looped = 0;
851                         int len = srv->lud_dn ? strlen( srv->lud_dn ) : 0;
852                         for (lp = origreq; lp; ) {
853                                 if ( lp->lr_conn == lc ) {
854                                         if ( len == lp->lr_dn.bv_len ) {
855                                                 if ( len && strncmp( srv->lud_dn, lp->lr_dn.bv_val,
856                                                         len ))
857                                                         continue;
858                                                 looped = 1;
859                                                 break;
860                                         }
861                                 }
862                                 if ( lp == origreq )
863                                         lp = lp->lr_child;
864                                 else
865                                         lp = lr->lr_refnext;
866                         }
867                         if ( looped ) {
868                                 ldap_free_urllist( srv );
869                                 srv = NULL;
870                                 ld->ld_errno = LDAP_CLIENT_LOOP;
871                                 rc = -1;
872                                 continue;
873                         }
874
875                         if( lc->lconn_rebind_inprogress) {
876                                 /* We are already chasing a referral or search reference and a
877                                  * bind on that connection is in progress.  We must queue
878                                  * referrals on that connection, so we don't get a request
879                                  * going out before the bind operation completes. This happens
880                                  * if two search references come in one behind the other
881                                  * for the same server with different contexts.
882                                  */
883                                 Debug( LDAP_DEBUG_TRACE,
884                                         "ldap_chase_v3referrals: queue referral \"%s\"\n",
885                                         refarray[i], 0, 0);
886                                 if( lc->lconn_rebind_queue == NULL ) {
887                                         /* Create a referral list */
888                                         lc->lconn_rebind_queue =
889                                                 (char ***) LDAP_MALLOC( sizeof(void *) * 2);
890
891                                         if( lc->lconn_rebind_queue == NULL) {
892                                                 ld->ld_errno = LDAP_NO_MEMORY;
893                                                 rc = -1;
894                                                 goto done;
895                                         }
896
897                                         lc->lconn_rebind_queue[0] = refarray;
898                                         lc->lconn_rebind_queue[1] = NULL;
899                                         refarray = NULL;
900
901                                 } else {
902                                         /* Count how many referral arrays we already have */
903                                         for( j = 0; lc->lconn_rebind_queue[j] != NULL; j++) {
904                                                 /* empty */;
905                                         }
906
907                                         /* Add the new referral to the list */
908                                         lc->lconn_rebind_queue = (char ***) LDAP_REALLOC(
909                                                 lc->lconn_rebind_queue, sizeof(void *) * (j + 2));
910
911                                         if( lc->lconn_rebind_queue == NULL ) {
912                                                 ld->ld_errno = LDAP_NO_MEMORY;
913                                                 rc = -1;
914                                                 goto done;
915                                         }
916                                         lc->lconn_rebind_queue[j] = refarray;
917                                         lc->lconn_rebind_queue[j+1] = NULL;
918                                         refarray = NULL;
919                                 }
920
921                                 /* We have queued the referral/reference, now just return */
922                                 rc = 0;
923                                 *hadrefp = 1;
924                                 count = 1; /* Pretend we already followed referral */
925                                 goto done;
926                         }
927                 } 
928                 /* Re-encode the request with the new starting point of the search.
929                  * Note: In the future we also need to replace the filter if one
930                  * was provided with the search reference
931                  */
932
933                 /* For references we don't want old dn if new dn empty */
934                 if ( sref && srv->lud_dn == NULL ) {
935                         srv->lud_dn = LDAP_STRDUP( "" );
936                 }
937
938                 LDAP_NEXT_MSGID( ld, id );
939                 ber = re_encode_request( ld, origreq->lr_ber, id,
940                         sref, srv, &rinfo.ri_request );
941
942                 if( ber == NULL ) {
943                         ld->ld_errno = LDAP_ENCODING_ERROR;
944                         rc = -1;
945                         goto done;
946                 }
947
948                 Debug( LDAP_DEBUG_TRACE,
949                         "ldap_chase_v3referral: msgid %d, url \"%s\"\n",
950                         lr->lr_msgid, refarray[i], 0);
951
952                 /* Send the new request to the server - may require a bind */
953                 rinfo.ri_msgid = origreq->lr_origid;
954                 rinfo.ri_url = refarray[i];
955 #ifdef LDAP_R_COMPILE
956                 ldap_pvt_thread_mutex_lock( &ld->ld_req_mutex );
957 #endif
958                 rc = ldap_send_server_request( ld, ber, id,
959                         origreq, srv, NULL, &rinfo );
960 #ifdef LDAP_R_COMPILE
961                 ldap_pvt_thread_mutex_unlock( &ld->ld_req_mutex );
962 #endif
963                 if ( rc < 0 ) {
964                         /* Failure, try next referral in the list */
965                         Debug( LDAP_DEBUG_ANY, "Unable to chase referral \"%s\" (%d: %s)\n", 
966                                 refarray[i], ld->ld_errno, ldap_err2string( ld->ld_errno ) );
967                         unfollowedcnt += ldap_append_referral( ld, &unfollowed, refarray[i] );
968                         ldap_free_urllist( srv );
969                         srv = NULL;
970                         ld->ld_errno = LDAP_REFERRAL;
971                 } else {
972                         /* Success, no need to try this referral list further */
973                         rc = 0;
974                         ++count;
975                         *hadrefp = 1;
976
977                         /* check if there is a queue of referrals that came in during bind */
978                         if ( lc == NULL) {
979                                 lc = find_connection( ld, srv, 1 );
980                                 if ( lc == NULL ) {
981                                         ld->ld_errno = LDAP_OPERATIONS_ERROR;
982                                         rc = -1;
983                                         goto done;
984                                 }
985                         }
986
987                         if ( lc->lconn_rebind_queue != NULL ) {
988                                 /* Release resources of previous list */
989                                 LDAP_VFREE( refarray );
990                                 refarray = NULL;
991                                 ldap_free_urllist( srv );
992                                 srv = NULL;
993
994                                 /* Pull entries off end of queue so list always null terminated */
995                                 for( j = 0; lc->lconn_rebind_queue[j] != NULL; j++ )
996                                         ;
997                                 refarray = lc->lconn_rebind_queue[j - 1];
998                                 lc->lconn_rebind_queue[j-1] = NULL;
999                                 /* we pulled off last entry from queue, free queue */
1000                                 if ( j == 1 ) {
1001                                         LDAP_FREE( lc->lconn_rebind_queue );
1002                                         lc->lconn_rebind_queue = NULL;
1003                                 }
1004                                 /* restart the loop the with new referral list */
1005                                 i = -1;
1006                                 continue;
1007                         }
1008                         break; /* referral followed, break out of for loop */
1009                 }
1010         } /* end for loop */
1011 done:
1012         LDAP_VFREE( refarray );
1013         ldap_free_urllist( srv );
1014         LDAP_FREE( *errstrp );
1015         
1016         if( rc == 0 ) {
1017                 *errstrp = NULL;
1018                 LDAP_FREE( unfollowed );
1019                 return count;
1020         } else {
1021                 *errstrp = unfollowed;
1022                 return rc;
1023         }
1024 }
1025
1026 /*
1027  * XXX merging of errors in this routine needs to be improved
1028  */
1029 int
1030 ldap_chase_referrals( LDAP *ld,
1031         LDAPRequest *lr,
1032         char **errstrp,
1033         int sref,
1034         int *hadrefp )
1035 {
1036         int             rc, count, id;
1037         unsigned        len;
1038         char            *p, *ref, *unfollowed;
1039         LDAPRequest     *origreq;
1040         LDAPURLDesc     *srv;
1041         BerElement      *ber;
1042         LDAPreqinfo  rinfo;
1043         LDAPConn        *lc;
1044
1045         Debug( LDAP_DEBUG_TRACE, "ldap_chase_referrals\n", 0, 0, 0 );
1046
1047         ld->ld_errno = LDAP_SUCCESS;    /* optimistic */
1048         *hadrefp = 0;
1049
1050         if ( *errstrp == NULL ) {
1051                 return( 0 );
1052         }
1053
1054         len = strlen( *errstrp );
1055         for ( p = *errstrp; len >= LDAP_REF_STR_LEN; ++p, --len ) {
1056                 if ( strncasecmp( p, LDAP_REF_STR, LDAP_REF_STR_LEN ) == 0 ) {
1057                         *p = '\0';
1058                         p += LDAP_REF_STR_LEN;
1059                         break;
1060                 }
1061         }
1062
1063         if ( len < LDAP_REF_STR_LEN ) {
1064                 return( 0 );
1065         }
1066
1067         if ( lr->lr_parentcnt >= ld->ld_refhoplimit ) {
1068                 Debug( LDAP_DEBUG_ANY,
1069                     "more than %d referral hops (dropping)\n",
1070                     ld->ld_refhoplimit, 0, 0 );
1071                     /* XXX report as error in ld->ld_errno? */
1072                     return( 0 );
1073         }
1074
1075         /* find original request */
1076         for ( origreq = lr; origreq->lr_parent != NULL;
1077              origreq = origreq->lr_parent ) {
1078                 /* empty */;
1079         }
1080
1081         unfollowed = NULL;
1082         rc = count = 0;
1083
1084         /* parse out & follow referrals */
1085         for ( ref = p; rc == 0 && ref != NULL; ref = p ) {
1086                 p = strchr( ref, '\n' );
1087                 if ( p != NULL ) {
1088                         *p++ = '\0';
1089                 }
1090
1091                 rc = ldap_url_parse_ext( ref, &srv );
1092
1093                 if ( rc != LDAP_URL_SUCCESS ) {
1094                         Debug( LDAP_DEBUG_TRACE,
1095                             "ignoring unknown referral <%s>\n", ref, 0, 0 );
1096                         rc = ldap_append_referral( ld, &unfollowed, ref );
1097                         *hadrefp = 1;
1098                         continue;
1099                 }
1100
1101                 if ( srv->lud_dn != NULL && srv->lud_dn == '\0' ) {
1102                         LDAP_FREE( srv->lud_dn );
1103                         srv->lud_dn = NULL;
1104                 }
1105
1106                 Debug( LDAP_DEBUG_TRACE,
1107                     "chasing LDAP referral: <%s>\n", ref, 0, 0 );
1108
1109                 *hadrefp = 1;
1110
1111                 /* See if we've already been here */
1112                 if (( lc = find_connection( ld, srv, 1 )) != NULL ) {
1113                         LDAPRequest *lp;
1114                         int looped = 0;
1115                         int len = srv->lud_dn ? strlen( srv->lud_dn ) : 0;
1116                         for (lp = lr; lp; lp = lp->lr_parent ) {
1117                                 if ( lp->lr_conn == lc ) {
1118                                         if ( len == lp->lr_dn.bv_len ) {
1119                                                 if ( len && strncmp( srv->lud_dn, lp->lr_dn.bv_val,
1120                                                         len ))
1121                                                         continue;
1122                                                 looped = 1;
1123                                                 break;
1124                                         }
1125                                 }
1126                         }
1127                         if ( looped ) {
1128                                 ldap_free_urllist(srv);
1129                                 ld->ld_errno = LDAP_CLIENT_LOOP;
1130                                 rc = -1;
1131                                 continue;
1132                         }
1133                 }
1134
1135                 LDAP_NEXT_MSGID( ld, id );
1136                 ber = re_encode_request( ld, origreq->lr_ber,
1137                     id, sref, srv, &rinfo.ri_request );
1138
1139                 if ( ber == NULL ) {
1140                         return -1 ;
1141                 }
1142
1143                 /* copy the complete referral for rebind process */
1144                 rinfo.ri_url = LDAP_STRDUP( ref );
1145
1146                 rinfo.ri_msgid = origreq->lr_origid;
1147
1148 #ifdef LDAP_R_COMPILE
1149                 ldap_pvt_thread_mutex_lock( &ld->ld_req_mutex );
1150 #endif
1151                 rc = ldap_send_server_request( ld, ber, id,
1152                         lr, srv, NULL, &rinfo );
1153 #ifdef LDAP_R_COMPILE
1154                 ldap_pvt_thread_mutex_unlock( &ld->ld_req_mutex );
1155 #endif
1156
1157                 LDAP_FREE( rinfo.ri_url );
1158
1159                 if( rc >= 0 ) {
1160                         ++count;
1161                 } else {
1162                         Debug( LDAP_DEBUG_ANY,
1163                                 "Unable to chase referral \"%s\" (%d: %s)\n", 
1164                                 ref, ld->ld_errno, ldap_err2string( ld->ld_errno ) );
1165                         rc = ldap_append_referral( ld, &unfollowed, ref );
1166                 }
1167
1168                 ldap_free_urllist(srv);
1169         }
1170
1171         LDAP_FREE( *errstrp );
1172         *errstrp = unfollowed;
1173
1174         return(( rc == 0 ) ? count : rc );
1175 }
1176
1177
1178 int
1179 ldap_append_referral( LDAP *ld, char **referralsp, char *s )
1180 {
1181         int     first;
1182
1183         if ( *referralsp == NULL ) {
1184                 first = 1;
1185                 *referralsp = (char *)LDAP_MALLOC( strlen( s ) + LDAP_REF_STR_LEN
1186                     + 1 );
1187         } else {
1188                 first = 0;
1189                 *referralsp = (char *)LDAP_REALLOC( *referralsp,
1190                     strlen( *referralsp ) + strlen( s ) + 2 );
1191         }
1192
1193         if ( *referralsp == NULL ) {
1194                 ld->ld_errno = LDAP_NO_MEMORY;
1195                 return( -1 );
1196         }
1197
1198         if ( first ) {
1199                 strcpy( *referralsp, LDAP_REF_STR );
1200         } else {
1201                 strcat( *referralsp, "\n" );
1202         }
1203         strcat( *referralsp, s );
1204
1205         return( 0 );
1206 }
1207
1208
1209
1210 static BerElement *
1211 re_encode_request( LDAP *ld,
1212         BerElement *origber,
1213         ber_int_t msgid,
1214         int sref,
1215         LDAPURLDesc *srv,
1216         int *type )
1217 {
1218         /*
1219          * XXX this routine knows way too much about how the lber library works!
1220          */
1221         ber_int_t       along;
1222         ber_tag_t       tag;
1223         ber_tag_t       rtag;
1224         ber_int_t       ver;
1225         ber_int_t       scope;
1226         int             rc;
1227         BerElement      tmpber, *ber;
1228         struct berval           orig_dn;
1229         char            *dn;
1230
1231         Debug( LDAP_DEBUG_TRACE,
1232             "re_encode_request: new msgid %ld, new dn <%s>\n",
1233             (long) msgid,
1234                 ( srv == NULL || srv->lud_dn == NULL) ? "NONE" : srv->lud_dn, 0 );
1235
1236         tmpber = *origber;
1237
1238         /*
1239          * all LDAP requests are sequences that start with a message id.
1240          * For all except delete, this is followed by a sequence that is
1241          * tagged with the operation code.  For delete, the provided DN
1242          * is not wrapped by a sequence.
1243          */
1244         rtag = ber_scanf( &tmpber, "{it", /*}*/ &along, &tag );
1245
1246         if ( rtag == LBER_ERROR ) {
1247                 ld->ld_errno = LDAP_DECODING_ERROR;
1248                 return( NULL );
1249         }
1250
1251         assert( tag != 0);
1252         if ( tag == LDAP_REQ_BIND ) {
1253                 /* bind requests have a version number before the DN & other stuff */
1254                 rtag = ber_scanf( &tmpber, "{im" /*}*/, &ver, &orig_dn );
1255
1256         } else if ( tag == LDAP_REQ_DELETE ) {
1257                 /* delete requests don't have a DN wrapping sequence */
1258                 rtag = ber_scanf( &tmpber, "m", &orig_dn );
1259
1260         } else if ( tag == LDAP_REQ_SEARCH ) {
1261                 /* search requests need to be re-scope-ed */
1262                 rtag = ber_scanf( &tmpber, "{me" /*"}"*/, &orig_dn, &scope );
1263
1264                 if( srv->lud_scope != LDAP_SCOPE_DEFAULT ) {
1265                         /* use the scope provided in reference */
1266                         scope = srv->lud_scope;
1267
1268                 } else if ( sref ) {
1269                         /* use scope implied by previous operation
1270                          *   base -> base
1271                          *   one -> base
1272                          *   subtree -> subtree
1273                          *   subordinate -> subtree
1274                          */
1275                         switch( scope ) {
1276                         default:
1277                         case LDAP_SCOPE_BASE:
1278                         case LDAP_SCOPE_ONELEVEL:
1279                                 scope = LDAP_SCOPE_BASE;
1280                                 break;
1281                         case LDAP_SCOPE_SUBTREE:
1282 #ifdef LDAP_SCOPE_SUBORDINATE
1283                         case LDAP_SCOPE_SUBORDINATE:
1284 #endif
1285                                 scope = LDAP_SCOPE_SUBTREE;
1286                                 break;
1287                         }
1288                 }
1289
1290         } else {
1291                 rtag = ber_scanf( &tmpber, "{m" /*}*/, &orig_dn );
1292         }
1293
1294         if( rtag == LBER_ERROR ) {
1295                 ld->ld_errno = LDAP_DECODING_ERROR;
1296                 return NULL;
1297         }
1298
1299         if (( ber = ldap_alloc_ber_with_options( ld )) == NULL ) {
1300                 return NULL;
1301         }
1302
1303         if ( srv->lud_dn == NULL ) {
1304                 dn = orig_dn.bv_val;
1305         } else {
1306                 dn = srv->lud_dn;
1307         }
1308
1309         if ( tag == LDAP_REQ_BIND ) {
1310                 rc = ber_printf( ber, "{it{is" /*}}*/, msgid, tag, ver, dn );
1311         } else if ( tag == LDAP_REQ_DELETE ) {
1312                 rc = ber_printf( ber, "{itsN}", msgid, tag, dn );
1313         } else if ( tag == LDAP_REQ_SEARCH ) {
1314                 rc = ber_printf( ber, "{it{se" /*}}*/, msgid, tag, dn, scope );
1315         } else {
1316                 rc = ber_printf( ber, "{it{s" /*}}*/, msgid, tag, dn );
1317         }
1318
1319         if ( rc == -1 ) {
1320                 ld->ld_errno = LDAP_ENCODING_ERROR;
1321                 ber_free( ber, 1 );
1322                 return NULL;
1323         }
1324
1325         if ( tag != LDAP_REQ_DELETE && (
1326                 ber_write(ber, tmpber.ber_ptr, ( tmpber.ber_end - tmpber.ber_ptr ), 0)
1327                 != ( tmpber.ber_end - tmpber.ber_ptr ) ||
1328             ber_printf( ber, /*{{*/ "N}N}" ) == -1 ) )
1329         {
1330                 ld->ld_errno = LDAP_ENCODING_ERROR;
1331                 ber_free( ber, 1 );
1332                 return NULL;
1333         }
1334
1335 #ifdef LDAP_DEBUG
1336         if ( ldap_debug & LDAP_DEBUG_PACKETS ) {
1337                 Debug( LDAP_DEBUG_ANY, "re_encode_request new request is:\n",
1338                     0, 0, 0 );
1339                 ber_log_dump( LDAP_DEBUG_BER, ldap_debug, ber, 0 );
1340         }
1341 #endif /* LDAP_DEBUG */
1342
1343         *type = tag;    /* return request type */
1344         return ber;
1345 }
1346
1347
1348 LDAPRequest *
1349 ldap_find_request_by_msgid( LDAP *ld, ber_int_t msgid )
1350 {
1351         LDAPRequest     *lr;
1352
1353 #ifdef LDAP_R_COMPILE
1354         ldap_pvt_thread_mutex_lock( &ld->ld_req_mutex );
1355 #endif
1356         for ( lr = ld->ld_requests; lr != NULL; lr = lr->lr_next ) {
1357                 if( lr->lr_status == LDAP_REQST_COMPLETED ) {
1358                         continue;       /* Skip completed requests */
1359                 }
1360                 if ( msgid == lr->lr_msgid ) {
1361                         break;
1362                 }
1363         }
1364 #ifdef LDAP_R_COMPILE
1365         ldap_pvt_thread_mutex_unlock( &ld->ld_req_mutex );
1366 #endif
1367
1368         return( lr );
1369 }
1370
1371