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