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