]> git.sur5r.net Git - openldap/blob - libraries/libldap/request.c
cabdaca6b3dc6cd4522bbf608c0049476fe7aa7f
[openldap] / libraries / libldap / request.c
1 /* $OpenLDAP$ */
2 /*
3  * Copyright 1998-2000 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
49 static BerElement *re_encode_request LDAP_P((
50         LDAP *ld,
51         BerElement *origber,
52     ber_int_t msgid,
53         char **dnp,
54         int      *type));
55
56
57 BerElement *
58 ldap_alloc_ber_with_options( LDAP *ld )
59 {
60         BerElement      *ber;
61
62     if (( ber = ber_alloc_t( ld->ld_lberoptions )) == NULL ) {
63                 ld->ld_errno = LDAP_NO_MEMORY;
64         }
65
66         return( ber );
67 }
68
69
70 void
71 ldap_set_ber_options( LDAP *ld, BerElement *ber )
72 {
73         ber->ber_options = ld->ld_lberoptions;
74 }
75
76
77 ber_int_t
78 ldap_send_initial_request(
79         LDAP *ld,
80         ber_tag_t msgtype,
81         const char *dn,
82         BerElement *ber )
83 {
84         LDAPURLDesc     *servers;
85         int rc;
86
87         Debug( LDAP_DEBUG_TRACE, "ldap_send_initial_request\n", 0, 0, 0 );
88
89         if ( ber_sockbuf_ctrl( ld->ld_sb, LBER_SB_OPT_GET_FD, NULL ) == -1 ) {
90                 /* not connected yet */
91                 int rc = ldap_open_defconn( ld );
92
93                 if( rc < 0 ) {
94                         ber_free( ber, 1 );
95                         return( -1 );
96                 }
97
98                 Debug( LDAP_DEBUG_TRACE,
99                         "ldap_delayed_open successful, ld_host is %s\n",
100                         ( ld->ld_host == NULL ) ? "(null)" : ld->ld_host, 0, 0 );
101         }
102
103         {
104                 /*
105                  * use of DNS is turned off or this is an X.500 DN...
106                  * use our default connection
107                  */
108                 servers = NULL;
109         }       
110
111         rc = ldap_send_server_request( ld, ber, ld->ld_msgid, NULL,
112                                                                         servers, NULL, NULL );
113         if (servers)
114                 ldap_free_urllist(servers);
115         return(rc);
116 }
117
118
119
120 int
121 ldap_send_server_request(
122         LDAP *ld,
123         BerElement *ber,
124         ber_int_t msgid,
125         LDAPRequest *parentreq,
126         LDAPURLDesc *srvlist,
127         LDAPConn *lc,
128         LDAPreqinfo *bind )
129 {
130         LDAPRequest     *lr;
131         int incparent;
132
133         Debug( LDAP_DEBUG_TRACE, "ldap_send_server_request\n", 0, 0, 0 );
134
135         incparent = 0;
136         ld->ld_errno = LDAP_SUCCESS;    /* optimistic */
137
138         if ( lc == NULL ) {
139                 if ( srvlist == NULL ) {
140                         lc = ld->ld_defconn;
141                 } else {
142                         if (( lc = find_connection( ld, srvlist, 1 )) ==
143                             NULL ) {
144                                 if ( (bind != NULL) && (parentreq != NULL) ) {
145                                         /* Remember the bind in the parent */
146                                         incparent = 1;
147                                         ++parentreq->lr_outrefcnt;
148                                 }
149                                 lc = ldap_new_connection( ld, srvlist, 0, 1, bind );
150                         }
151                 }
152         }
153
154         if ( lc == NULL || lc->lconn_status != LDAP_CONNST_CONNECTED ) {
155                 ber_free( ber, 1 );
156                 if ( ld->ld_errno == LDAP_SUCCESS ) {
157                         ld->ld_errno = LDAP_SERVER_DOWN;
158                 }
159                 if ( incparent ) {
160                         /* Forget about the bind */
161                         --parentreq->lr_outrefcnt; 
162                 }
163                 return( -1 );
164         }
165
166         use_connection( ld, lc );
167         if (( lr = (LDAPRequest *)LDAP_CALLOC( 1, sizeof( LDAPRequest ))) ==
168             NULL ) {
169                 ld->ld_errno = LDAP_NO_MEMORY;
170                 ldap_free_connection( ld, lc, 0, 0 );
171                 ber_free( ber, 1 );
172                 if ( incparent ) {
173                         /* Forget about the bind */
174                         --parentreq->lr_outrefcnt; 
175                 }
176                 return( -1 );
177         } 
178         lr->lr_msgid = msgid;
179         lr->lr_status = LDAP_REQST_INPROGRESS;
180         lr->lr_res_errno = LDAP_SUCCESS;        /* optimistic */
181         lr->lr_ber = ber;
182         lr->lr_conn = lc;
183         if ( parentreq != NULL ) {      /* sub-request */
184                 if ( !incparent ) { 
185                         /* Increment if we didn't do it before the bind */
186                         ++parentreq->lr_outrefcnt;
187                 }
188                 lr->lr_origid = parentreq->lr_origid;
189                 lr->lr_parentcnt = parentreq->lr_parentcnt + 1;
190                 lr->lr_parent = parentreq;
191                 lr->lr_refnext = parentreq->lr_refnext;
192                 parentreq->lr_refnext = lr;
193         } else {                        /* original request */
194                 lr->lr_origid = lr->lr_msgid;
195         }
196
197         if (( lr->lr_next = ld->ld_requests ) != NULL ) {
198                 lr->lr_next->lr_prev = lr;
199         }
200         ld->ld_requests = lr;
201         lr->lr_prev = NULL;
202
203         if ( ber_flush( lc->lconn_sb, ber, 0 ) != 0 ) {
204 #ifdef notyet
205                 if ( errno == EWOULDBLOCK ) {
206                         /* need to continue write later */
207                         lr->lr_status = LDAP_REQST_WRITING;
208                         ldap_mark_select_write( ld, lc->lconn_sb );
209                 } else {
210 #else /* notyet */
211                         ld->ld_errno = LDAP_SERVER_DOWN;
212                         ldap_free_request( ld, lr );
213                         ldap_free_connection( ld, lc, 0, 0 );
214                         return( -1 );
215 #endif /* notyet */
216 #ifdef notyet
217                 }
218 #endif /* notyet */
219         } else {
220                 if ( parentreq == NULL ) {
221                         ber->ber_end = ber->ber_ptr;
222                         ber->ber_ptr = ber->ber_buf;
223                 }
224
225                 /* sent -- waiting for a response */
226                 ldap_mark_select_read( ld, lc->lconn_sb );
227         }
228
229         ld->ld_errno = LDAP_SUCCESS;
230         return( msgid );
231 }
232
233 LDAPConn *
234 ldap_new_connection( LDAP *ld, LDAPURLDesc *srvlist, int use_ldsb,
235         int connect, LDAPreqinfo *bind )
236 {
237         LDAPConn        *lc;
238         LDAPURLDesc     *srv;
239         Sockbuf         *sb;
240
241         Debug( LDAP_DEBUG_TRACE, "ldap_new_connection\n", 0, 0, 0 );
242         /*
243          * make a new LDAP server connection
244          * XXX open connection synchronously for now
245          */
246         if (( lc = (LDAPConn *)LDAP_CALLOC( 1, sizeof( LDAPConn ))) == NULL ||
247             ( !use_ldsb && ( (sb = ber_sockbuf_alloc()) == NULL ))) {
248                 if ( lc != NULL ) {
249                         LDAP_FREE( (char *)lc );
250                 }
251                 ld->ld_errno = LDAP_NO_MEMORY;
252                 return( NULL );
253         }
254
255         lc->lconn_sb = ( use_ldsb ) ? ld->ld_sb : sb;
256
257         if ( connect ) {
258                 for ( srv = srvlist; srv != NULL; srv = srv->lud_next ) {
259                         if ( open_ldap_connection( ld, lc->lconn_sb,
260                                         srv, &lc->lconn_krbinstance, 0 ) != -1 )
261                         {
262                                 break;
263                         }
264                 }
265
266                 if ( srv == NULL ) {
267                         if ( !use_ldsb ) {
268                                 ber_sockbuf_free( lc->lconn_sb );
269                         }
270                     LDAP_FREE( (char *)lc );
271                     ld->ld_errno = LDAP_SERVER_DOWN;
272                     return( NULL );
273                 }
274
275                 lc->lconn_server = ldap_url_dup(srv);
276         }
277
278         lc->lconn_status = LDAP_CONNST_CONNECTED;
279         lc->lconn_next = ld->ld_conns;
280         ld->ld_conns = lc;
281
282         /*
283          * XXX for now, we always do a synchronous bind.  This will have
284          * to change in the long run...
285          */
286         if ( bind != NULL) {
287                 int             err = 0;
288                 LDAPConn        *savedefconn;
289
290                 /* Set flag to prevent additional referrals from being processed on this
291                  * connection until the bind has completed
292                  */
293                 lc->lconn_rebind_inprogress = 1;
294                 /* V3 rebind function */
295                 if ( ld->ld_rebindproc != NULL) {
296                         LDAPURLDesc     *srvfunc;
297                         if( ( srvfunc = ldap_url_dup( srvlist)) == NULL) {
298                                 ld->ld_errno = LDAP_NO_MEMORY;
299                                 err = -1;
300                         } else {
301                                 savedefconn = ld->ld_defconn;
302                                 ++lc->lconn_refcnt;     /* avoid premature free */
303                                 ld->ld_defconn = lc;
304
305                                 Debug( LDAP_DEBUG_TRACE, "Call application rebindproc\n", 0, 0, 0);
306                                 err = (*ld->ld_rebindproc)( ld, bind->ri_url, bind->ri_request, bind->ri_msgid);
307
308                                 ld->ld_defconn = savedefconn;
309                                 --lc->lconn_refcnt;
310
311                                 if( err != 0) {
312                                 err = -1;
313                                         ldap_free_connection( ld, lc, 1, 0 );
314                                         lc = NULL;
315                         }
316                                 ldap_free_urldesc( srvfunc);
317                 }
318                 } else {
319                         savedefconn = ld->ld_defconn;
320                         ++lc->lconn_refcnt;     /* avoid premature free */
321                         ld->ld_defconn = lc;
322
323                         Debug( LDAP_DEBUG_TRACE, "anonymous rebind via ldap_bind_s\n", 0, 0, 0);
324                         if ( ldap_bind_s( ld, "", "", LDAP_AUTH_SIMPLE ) != LDAP_SUCCESS ) {
325                                 err = -1;
326                         }
327                         ld->ld_defconn = savedefconn;
328                         --lc->lconn_refcnt;
329
330                 if ( err != 0 ) {
331                         ldap_free_connection( ld, lc, 1, 0 );
332                         lc = NULL;
333                 }
334         }
335                 if( lc != NULL)
336                         lc->lconn_rebind_inprogress = 0;
337         }
338
339         return( lc );
340 }
341
342
343 static LDAPConn *
344 find_connection( LDAP *ld, LDAPURLDesc *srv, int any )
345 /*
346  * return an existing connection (if any) to the server srv
347  * if "any" is non-zero, check for any server in the "srv" chain
348  */
349 {
350         LDAPConn        *lc;
351         LDAPURLDesc     *ls;
352
353         for ( lc = ld->ld_conns; lc != NULL; lc = lc->lconn_next ) {
354                 for ( ls = srv; ls != NULL; ls = ls->lud_next ) {
355                         if ( lc->lconn_server->lud_host != NULL &&
356                             ls->lud_host != NULL && strcasecmp(
357                             ls->lud_host, lc->lconn_server->lud_host ) == 0
358                             && ls->lud_port == lc->lconn_server->lud_port ) {
359                                 return( lc );
360                         }
361                         if ( !any ) {
362                                 break;
363                         }
364                 }
365         }
366
367         return( NULL );
368 }
369
370
371
372 static void
373 use_connection( LDAP *ld, LDAPConn *lc )
374 {
375         ++lc->lconn_refcnt;
376         lc->lconn_lastused = time( NULL );
377 }
378
379
380 void
381 ldap_free_connection( LDAP *ld, LDAPConn *lc, int force, int unbind )
382 {
383         LDAPConn        *tmplc, *prevlc;
384
385         Debug( LDAP_DEBUG_TRACE, "ldap_free_connection\n", 0, 0, 0 );
386
387         if ( force || --lc->lconn_refcnt <= 0 ) {
388                 if ( lc->lconn_status == LDAP_CONNST_CONNECTED ) {
389                         ldap_mark_select_clear( ld, lc->lconn_sb );
390                         if ( unbind ) {
391                                 ldap_send_unbind( ld, lc->lconn_sb, NULL, NULL );
392                         }
393                 }
394
395                 if( lc->lconn_ber != NULL ) {
396                         ber_free( lc->lconn_ber, 1 );
397                 }
398
399                 prevlc = NULL;
400                 for ( tmplc = ld->ld_conns; tmplc != NULL;
401                     tmplc = tmplc->lconn_next ) {
402                         if ( tmplc == lc ) {
403                                 if ( prevlc == NULL ) {
404                                     ld->ld_conns = tmplc->lconn_next;
405                                 } else {
406                                     prevlc->lconn_next = tmplc->lconn_next;
407                                 }
408                                 break;
409                         }
410                         prevlc = tmplc;
411                 }
412                 ldap_free_urllist( lc->lconn_server );
413                 if ( lc->lconn_krbinstance != NULL ) {
414                         LDAP_FREE( lc->lconn_krbinstance );
415                 }
416                 if ( lc->lconn_sb != ld->ld_sb ) {
417                         ber_sockbuf_free( lc->lconn_sb );
418                 }
419                 if( lc->lconn_rebind_queue != NULL) {
420                         int i;
421                         for( i = 0; lc->lconn_rebind_queue[i] != NULL; i++) {
422                                 free_strarray(lc->lconn_rebind_queue[i]);
423                         }
424                         LDAP_FREE( lc->lconn_rebind_queue);
425                 }
426                 LDAP_FREE( lc );
427                 Debug( LDAP_DEBUG_TRACE, "ldap_free_connection: actually freed\n",
428                     0, 0, 0 );
429         } else {
430                 lc->lconn_lastused = time( NULL );
431                 Debug( LDAP_DEBUG_TRACE, "ldap_free_connection: refcnt %d\n",
432                     lc->lconn_refcnt, 0, 0 );
433         }
434 }
435
436
437 #ifdef LDAP_DEBUG
438 void
439 ldap_dump_connection( LDAP *ld, LDAPConn *lconns, int all )
440 {
441         LDAPConn        *lc;
442         char            timebuf[32];
443
444         fprintf( stderr, "** Connection%s:\n", all ? "s" : "" );
445         for ( lc = lconns; lc != NULL; lc = lc->lconn_next ) {
446                 if ( lc->lconn_server != NULL ) {
447                         fprintf( stderr, "* host: %s  port: %d%s\n",
448                             ( lc->lconn_server->lud_host == NULL ) ? "(null)"
449                             : lc->lconn_server->lud_host,
450                             lc->lconn_server->lud_port, ( lc->lconn_sb ==
451                             ld->ld_sb ) ? "  (default)" : "" );
452                 }
453                 fprintf( stderr, "  refcnt: %d  status: %s\n", lc->lconn_refcnt,
454                     ( lc->lconn_status == LDAP_CONNST_NEEDSOCKET ) ?
455                     "NeedSocket" : ( lc->lconn_status ==
456                     LDAP_CONNST_CONNECTING ) ? "Connecting" : "Connected" );
457                 fprintf( stderr, "  last used: %s",
458                     ldap_pvt_ctime( &lc->lconn_lastused, timebuf ));
459                 if( lc->lconn_rebind_inprogress ) {
460                         fprintf( stderr, "  rebind in progress\n");
461                         if( lc->lconn_rebind_queue != NULL) {
462                                 int i = 0;
463                                 for( ;lc->lconn_rebind_queue[i] != NULL; i++) {
464                                         int j = 0;
465                                         for( ;lc->lconn_rebind_queue[i][j] != 0; j++) {
466                                                 fprintf( stderr, "    queue %d entry %d - %s\n",
467                                                         i, j, lc->lconn_rebind_queue[i][j]);
468                                         }
469                                 }
470                         } else {
471                                 fprintf( stderr, "    queue is empty\n");
472                         }
473                 }
474                 fprintf(stderr, "\n");
475                 if ( !all ) {
476                         break;
477                 }
478         }
479 }
480
481
482 void
483 ldap_dump_requests_and_responses( LDAP *ld )
484 {
485         LDAPRequest     *lr;
486         LDAPMessage     *lm, *l;
487
488         fprintf( stderr, "** Outstanding Requests:\n" );
489         if (( lr = ld->ld_requests ) == NULL ) {
490                 fprintf( stderr, "   Empty\n" );
491         }
492         for ( ; lr != NULL; lr = lr->lr_next ) {
493             fprintf( stderr, " * msgid %d,  origid %d, status %s\n",
494                 lr->lr_msgid, lr->lr_origid,
495                 ( lr->lr_status == LDAP_REQST_INPROGRESS ) ? "InProgress" :
496                 ( lr->lr_status == LDAP_REQST_CHASINGREFS ) ? "ChasingRefs" :
497                 ( lr->lr_status == LDAP_REQST_NOTCONNECTED ) ? "NotConnected" :
498                 ( lr->lr_status == LDAP_REQST_WRITING) ? "Writing" :
499                 ( lr->lr_status == LDAP_REQST_COMPLETED ? "Request Completed" : "Invalid Status"));
500             fprintf( stderr, "   outstanding referrals %d, parent count %d\n",
501                     lr->lr_outrefcnt, lr->lr_parentcnt );
502         }
503
504         fprintf( stderr, "** Response Queue:\n" );
505         if (( lm = ld->ld_responses ) == NULL ) {
506                 fprintf( stderr, "   Empty\n" );
507         }
508         for ( ; lm != NULL; lm = lm->lm_next ) {
509                 fprintf( stderr, " * msgid %d,  type %lu\n",
510                     lm->lm_msgid, (unsigned long) lm->lm_msgtype );
511                 if (( l = lm->lm_chain ) != NULL ) {
512                         fprintf( stderr, "   chained responses:\n" );
513                         for ( ; l != NULL; l = l->lm_chain ) {
514                                 fprintf( stderr,
515                                     "  * msgid %d,  type %lu\n",
516                                     l->lm_msgid,
517                                     (unsigned long) l->lm_msgtype );
518                         }
519                 }
520         }
521 }
522 #endif /* LDAP_DEBUG */
523
524
525 void
526 ldap_free_request( LDAP *ld, LDAPRequest *lr )
527 {
528         LDAPRequest     *tmplr, *nextlr;
529
530         Debug( LDAP_DEBUG_TRACE, "ldap_free_request (origid %d, msgid %d)\n",
531                 lr->lr_origid, lr->lr_msgid, 0 );
532
533         if ( lr->lr_parent != NULL ) {
534                 --lr->lr_parent->lr_outrefcnt;
535         } else {
536                 /* free all referrals (child requests) */
537                 for ( tmplr = lr->lr_refnext; tmplr != NULL; tmplr = nextlr ) {
538                         nextlr = tmplr->lr_refnext;
539                         ldap_free_request( ld, tmplr );
540                 }
541         }
542
543         if ( lr->lr_prev == NULL ) {
544                 ld->ld_requests = lr->lr_next;
545         } else {
546                 lr->lr_prev->lr_next = lr->lr_next;
547         }
548
549         if ( lr->lr_next != NULL ) {
550                 lr->lr_next->lr_prev = lr->lr_prev;
551         }
552
553         if ( lr->lr_ber != NULL ) {
554                 ber_free( lr->lr_ber, 1 );
555         }
556
557         if ( lr->lr_res_error != NULL ) {
558                 LDAP_FREE( lr->lr_res_error );
559         }
560
561         if ( lr->lr_res_matched != NULL ) {
562                 LDAP_FREE( lr->lr_res_matched );
563         }
564
565         LDAP_FREE( lr );
566 }
567
568 /*
569  * Chase v3 referrals
570  *
571  * Parameters:
572  *  (IN) ld = LDAP connection handle
573  *  (IN) lr = LDAP Request structure
574  *  (IN) refs = array of pointers to referral strings that we will chase
575  *              The array will be free'd by this function when no longer needed
576  *  (OUT) errstrp = Place to return a string of referrals which could not be followed
577  *  (OUT) hadrefp = 1 if sucessfully followed referral
578  *
579  * Return value - number of referrals followed
580  */
581 LIBLDAP_F(int)
582 ldap_chase_v3referrals( LDAP *ld, LDAPRequest *lr, char **refs, char **errstrp, int *hadrefp )
583 {
584         char            *unfollowed;
585         int                      unfollowedcnt = 0;
586         LDAPRequest     *origreq;
587         LDAPURLDesc     *srv = NULL;
588         BerElement      *ber;
589         char            **refarray = NULL;
590         LDAPConn        *lc;
591         int                      rc, count, i, j;
592         LDAPreqinfo  rinfo;
593
594         ld->ld_errno = LDAP_SUCCESS;    /* optimistic */
595         *hadrefp = 0;
596
597         Debug( LDAP_DEBUG_TRACE, "ldap_chase_v3referrals\n", 0, 0, 0 );
598
599         unfollowed = NULL;
600         rc = count = 0;
601
602         /* If no referrals in array, return */
603         if ( (refs == NULL) || ( (refs)[0] == NULL) ) {
604                 rc = 0;
605                 goto done;
606         }
607
608         /* Check for hop limit exceeded */
609         if ( lr->lr_parentcnt >= ld->ld_refhoplimit ) {
610                 Debug( LDAP_DEBUG_ANY,
611                     "more than %d referral hops (dropping)\n", ld->ld_refhoplimit, 0, 0 );
612                 ld->ld_errno = LDAP_REFERRAL_LIMIT_EXCEEDED;
613             rc = -1;
614                 goto done;
615         }
616
617         /* find original request */
618         for ( origreq = lr; origreq->lr_parent != NULL; origreq = origreq->lr_parent ) {
619                 ;
620         }
621
622         refarray = refs;
623         refs = NULL;
624         /* parse out & follow referrals */
625         for( i=0; refarray[i] != NULL; i++) {
626                 /* Parse the referral URL */
627                 if (( rc = ldap_url_parse( refarray[i], &srv)) != LDAP_SUCCESS) {
628                         ld->ld_errno = rc;
629                         rc = -1;
630                         goto done;
631                 }
632
633                 /* treat ldap://hostpart and ldap://hostpart/ the same */
634                 if ( srv->lud_dn && srv->lud_dn[0] == '\0' ) {
635                         LDAP_FREE( srv->lud_dn );
636                         srv->lud_dn = NULL;
637                 }
638
639                 /* check connection for re-bind in progress */
640                 if (( lc = find_connection( ld, srv, 1 )) != NULL ) {
641                         if( lc->lconn_rebind_inprogress) {
642                                 /* We are already chasing a referral or search reference and a
643                                  * bind on that connection is in progress.  We must queue
644                                  * referrals on that connection, so we don't get a request
645                                  * going out before the bind operation completes. This happens
646                                  * if two search references come in one behind the other
647                                  * for the same server with different contexts.
648                                  */
649                                 Debug( LDAP_DEBUG_TRACE, "ldap_chase_v3referrals: queue referral \"%s\"\n",
650                                         refarray[i], 0, 0);
651                                 if( lc->lconn_rebind_queue == NULL ) {
652                                         /* Create a referral list */
653                                         if( (lc->lconn_rebind_queue = (char ***)LDAP_MALLOC( sizeof(void *) * 2)) == NULL) {
654                                                 ld->ld_errno = LDAP_NO_MEMORY;
655                                                 rc = -1;
656                                                 goto done;
657                                         }
658                                         lc->lconn_rebind_queue[0] = refarray;
659                                         lc->lconn_rebind_queue[1] = NULL;
660                                         refarray = NULL;
661                                 } else {
662                                         /* Count how many referral arrays we already have */
663                                         for( j = 0; lc->lconn_rebind_queue[j] != NULL; j++) {
664                                                 ;
665                                         }
666                                         /* Add the new referral to the list */
667                                         if( (lc->lconn_rebind_queue = (char ***)LDAP_REALLOC(
668                                                         lc->lconn_rebind_queue, sizeof(void *) * (j + 2))) == NULL) {
669                                                 ld->ld_errno = LDAP_NO_MEMORY;
670                                                 rc = -1;
671                                                 goto done;
672                                         }
673                                         lc->lconn_rebind_queue[j] = refarray;
674                                         lc->lconn_rebind_queue[j+1] = NULL;
675                                         refarray = NULL;
676                                 }
677                                 /* We have queued the referral/reference, now just return */
678                                 rc = 0;
679                                 *hadrefp = 1;
680                                 count = 1; /* Pretend we already followed referral */
681                                 goto done;
682                         }
683                 } 
684                 /* Re-encode the request with the new starting point of the search.
685                  * Note: In the future we also need to replace the filter if one
686                  * was provided with the search reference
687                  */
688                 if (( ber = re_encode_request( ld, origreq->lr_ber,
689                             ++ld->ld_msgid, &srv->lud_dn, &rinfo.ri_request )) == NULL ) {
690                         ld->ld_errno = LDAP_ENCODING_ERROR;
691                         rc = -1;
692                         goto done;
693                 }
694
695                 Debug( LDAP_DEBUG_TRACE, "ldap_chase_v3referral: msgid %d, url \"%s\"\n",
696                         lr->lr_msgid, refarray[i], 0);
697
698                 /* Send the new request to the server - may require a bind */
699                 rinfo.ri_msgid = origreq->lr_origid;
700                 rinfo.ri_url = refarray[i];
701                 if ( (rc = ldap_send_server_request( ld, ber, ld->ld_msgid,
702                         origreq, srv, NULL, &rinfo )) < 0 ) {
703                         /* Failure, try next referral in the list */
704                         Debug( LDAP_DEBUG_ANY, "Unable to chase referral \"%s\" (%s)\n", 
705                                 refarray[i], ldap_err2string( ld->ld_errno ), 0);
706                         unfollowedcnt += ldap_append_referral( ld, &unfollowed, refarray[i]);
707                         ldap_free_urllist(srv);
708                         srv = NULL;
709                 } else {
710                         /* Success, no need to try this referral list further */
711                         rc = 0;
712                         ++count;
713                         *hadrefp = 1;
714
715                         /* check if there is a queue of referrals that came in during bind */
716                         if( lc == NULL) {
717                                 if (( lc = find_connection( ld, srv, 1 )) == NULL ) {
718                                         ld->ld_errno = LDAP_OPERATIONS_ERROR;
719                                         rc = -1;
720                                         goto done;
721                                 }
722                         }
723
724                         if( lc->lconn_rebind_queue != NULL) {
725                                 /* Release resources of previous list */
726                                 free_strarray(refarray);
727                                 refarray = NULL;
728                                 ldap_free_urllist(srv);
729                                 srv = NULL;
730
731                                 /* Pull entries off end of queue so list always null terminated */
732                                 for( j = 0; lc->lconn_rebind_queue[j] != NULL; j++) {
733                                         ;
734                                 }
735                                 refarray = lc->lconn_rebind_queue[j-1];
736                                 lc->lconn_rebind_queue[j-1] = NULL;
737                                 /* we pulled off last entry from queue, free queue */
738                                 if ( j == 1 ) {
739                                         LDAP_FREE( lc->lconn_rebind_queue);
740                                         lc->lconn_rebind_queue = NULL;
741                                 }
742                                 /* restart the loop the with new referral list */
743                                 i = -1;
744                                 continue;
745                         }
746                         break; /* referral followed, break out of for loop */
747                 }
748         } /* end for loop */
749 done:
750         free_strarray(refarray);
751         ldap_free_urllist(srv);
752         LDAP_FREE( *errstrp );
753         
754         if( rc == 0) {
755                 *errstrp = NULL;
756                 LDAP_FREE( unfollowed );
757                 return count;
758         } else {
759                 ld->ld_errno = LDAP_REFERRAL;
760                 *errstrp = unfollowed;
761                 return rc;
762         }
763 }
764
765 /*
766  * XXX merging of errors in this routine needs to be improved
767  */
768 int
769 ldap_chase_referrals( LDAP *ld, LDAPRequest *lr, char **errstrp, int *hadrefp )
770 {
771         int             rc, count, len, newdn;
772         char            *p, *ports, *ref, *tmpref, *refdn, *unfollowed;
773         LDAPRequest     *origreq;
774         LDAPURLDesc     *srv;
775         BerElement      *ber;
776         LDAPreqinfo  rinfo;
777
778         Debug( LDAP_DEBUG_TRACE, "ldap_chase_referrals\n", 0, 0, 0 );
779
780         ld->ld_errno = LDAP_SUCCESS;    /* optimistic */
781         *hadrefp = 0;
782
783         if ( *errstrp == NULL ) {
784                 return( 0 );
785         }
786
787         len = strlen( *errstrp );
788         for ( p = *errstrp; len >= LDAP_REF_STR_LEN; ++p, --len ) {
789                 if (( *p == 'R' || *p == 'r' ) && strncasecmp( p,
790                     LDAP_REF_STR, LDAP_REF_STR_LEN ) == 0 ) {
791                         *p = '\0';
792                         p += LDAP_REF_STR_LEN;
793                         break;
794                 }
795         }
796
797         if ( len < LDAP_REF_STR_LEN ) {
798                 return( 0 );
799         }
800
801         if ( lr->lr_parentcnt >= ld->ld_refhoplimit ) {
802                 Debug( LDAP_DEBUG_ANY,
803                     "more than %d referral hops (dropping)\n",
804                     ld->ld_refhoplimit, 0, 0 );
805                     /* XXX report as error in ld->ld_errno? */
806                     return( 0 );
807         }
808
809         /* find original request */
810         for ( origreq = lr; origreq->lr_parent != NULL;
811              origreq = origreq->lr_parent ) {
812                 ;
813         }
814
815         unfollowed = NULL;
816         rc = count = 0;
817
818         /* parse out & follow referrals */
819         for ( ref = p; rc == 0 && ref != NULL; ref = p ) {
820
821                 if (( p = strchr( ref, '\n' )) != NULL ) {
822                         *p++ = '\0';
823                 } else {
824                         p = NULL;
825                 }
826
827                 ldap_pvt_hex_unescape( ref );
828                 len = strlen( ref );
829
830                 if ( len > LDAP_LDAP_REF_STR_LEN && strncasecmp( ref,
831                     LDAP_LDAP_REF_STR, LDAP_LDAP_REF_STR_LEN ) == 0 ) {
832                         Debug( LDAP_DEBUG_TRACE,
833                             "chasing LDAP referral: <%s>\n", ref, 0, 0 );
834                         tmpref = ref + LDAP_LDAP_REF_STR_LEN;
835                 } else {
836                         Debug( LDAP_DEBUG_TRACE,
837                             "ignoring unknown referral <%s>\n", ref, 0, 0 );
838                         rc = ldap_append_referral( ld, &unfollowed, ref );
839                         *hadrefp = 1;
840                         continue;
841                 }
842
843                 /* copy the complete referral for rebind process */
844                 rinfo.ri_url = LDAP_STRDUP( ref );
845
846                 *hadrefp = 1;
847
848                 if (( refdn = strchr( tmpref, '/' )) != NULL ) {
849                         *refdn++ = '\0';
850                         newdn = refdn[0] != '?' && refdn[0] != '\0';
851                         if( !newdn ) refdn = NULL;
852                 } else {
853                         newdn = 0;
854                 }
855
856                 if (( ber = re_encode_request( ld, origreq->lr_ber,
857                     ++ld->ld_msgid, &refdn, &rinfo.ri_request )) == NULL ) {
858                         return( -1 );
859                 }
860
861                         if (( srv = (LDAPURLDesc *)LDAP_CALLOC( 1,
862                             sizeof( LDAPURLDesc ))) == NULL ) {
863                                 ber_free( ber, 1 );
864                                 ld->ld_errno = LDAP_NO_MEMORY;
865                                 return( -1 );
866                         }
867
868                         if (( srv->lud_host = LDAP_STRDUP( tmpref )) == NULL ) {
869                                 LDAP_FREE( (char *)srv );
870                                 ber_free( ber, 1 );
871                                 ld->ld_errno = LDAP_NO_MEMORY;
872                                 return( -1 );
873                         }
874
875                         if (( ports = strchr( srv->lud_host, ':' )) != NULL ) {
876                                 *ports++ = '\0';
877                                 srv->lud_port = atoi( ports );
878                         } else {
879                                 srv->lud_port = ldap_int_global_options.ldo_defport;
880                         }
881
882                 rinfo.ri_msgid = origreq->lr_origid;
883                 if ( srv != NULL && ldap_send_server_request( ld, ber, ld->ld_msgid,
884                     lr, srv, NULL, &rinfo ) >= 0 ) {
885                         ++count;
886                 } else {
887                         Debug( LDAP_DEBUG_ANY,
888                             "Unable to chase referral (%s)\n", 
889                             ldap_err2string( ld->ld_errno ), 0, 0 );
890                         rc = ldap_append_referral( ld, &unfollowed, ref );
891                 }
892                 LDAP_FREE( rinfo.ri_url);
893
894                 if (srv != NULL)
895                         ldap_free_urllist(srv);
896
897                 if ( !newdn && refdn != NULL ) {
898                         LDAP_FREE( refdn );
899                 }
900         }
901
902         LDAP_FREE( *errstrp );
903         *errstrp = unfollowed;
904
905         return(( rc == 0 ) ? count : rc );
906 }
907
908
909 int
910 ldap_append_referral( LDAP *ld, char **referralsp, char *s )
911 {
912         int     first;
913
914         if ( *referralsp == NULL ) {
915                 first = 1;
916                 *referralsp = (char *)LDAP_MALLOC( strlen( s ) + LDAP_REF_STR_LEN
917                     + 1 );
918         } else {
919                 first = 0;
920                 *referralsp = (char *)LDAP_REALLOC( *referralsp,
921                     strlen( *referralsp ) + strlen( s ) + 2 );
922         }
923
924         if ( *referralsp == NULL ) {
925                 ld->ld_errno = LDAP_NO_MEMORY;
926                 return( -1 );
927         }
928
929         if ( first ) {
930                 strcpy( *referralsp, LDAP_REF_STR );
931         } else {
932                 strcat( *referralsp, "\n" );
933         }
934         strcat( *referralsp, s );
935
936         return( 0 );
937 }
938
939
940
941 static BerElement *
942 re_encode_request( LDAP *ld, BerElement *origber, ber_int_t msgid, char **dnp, int *type )
943 {
944 /*
945  * XXX this routine knows way too much about how the lber library works!
946  */
947         ber_int_t       along;
948         ber_tag_t       tag;
949         ber_int_t       ver;
950         int             rc;
951         BerElement      tmpber, *ber;
952         char            *orig_dn;
953
954         Debug( LDAP_DEBUG_TRACE,
955             "re_encode_request: new msgid %ld, new dn <%s>\n",
956             (long) msgid, ( *dnp == NULL ) ? "NONE" : *dnp, 0 );
957
958         tmpber = *origber;
959
960         /*
961          * all LDAP requests are sequences that start with a message id.
962          * For all except delete, this is followed by a sequence that is
963          * tagged with the operation code.  For delete, the provided DN
964          * is not wrapped by a sequence.
965          */
966         rc = ber_scanf( &tmpber, "{it", /*}*/ &along, &tag );
967
968         if ( rc == LBER_ERROR ) {
969                 ld->ld_errno = LDAP_DECODING_ERROR;
970                 return( NULL );
971         }
972
973         assert( tag != 0);
974         if ( tag == LDAP_REQ_BIND ) {
975                 /* bind requests have a version number before the DN & other stuff */
976                 rc = ber_scanf( &tmpber, "{ia" /*}*/, &ver, &orig_dn );
977
978         } else if ( tag == LDAP_REQ_DELETE ) {
979                 /* delete requests don't have a DN wrapping sequence */
980                 rc = ber_scanf( &tmpber, "a", &orig_dn );
981
982         } else {
983                 rc = ber_scanf( &tmpber, "{a" /*}*/, &orig_dn );
984         }
985
986         if( rc == LBER_ERROR ) {
987                 ld->ld_errno = LDAP_DECODING_ERROR;
988                 return NULL;
989         }
990
991         if ( *dnp == NULL ) {
992                 *dnp = orig_dn;
993         } else {
994                 LDAP_FREE( orig_dn );
995         }
996
997         if (( ber = ldap_alloc_ber_with_options( ld )) == NULL ) {
998                 return( NULL );
999         }
1000
1001         if ( tag == LDAP_REQ_BIND ) {
1002                 rc = ber_printf( ber, "{it{is" /*}}*/, msgid, tag, ver, *dnp );
1003         } else if ( tag == LDAP_REQ_DELETE ) {
1004                 rc = ber_printf( ber, "{its}", msgid, tag, *dnp );
1005         } else {
1006                 rc = ber_printf( ber, "{it{s" /*}}*/, msgid, tag, *dnp );
1007         }
1008
1009         if ( rc == -1 ) {
1010                 ld->ld_errno = LDAP_ENCODING_ERROR;
1011                 ber_free( ber, 1 );
1012                 return( NULL );
1013         }
1014
1015         if ( tag != LDAP_REQ_DELETE && (
1016                 ber_write(ber, tmpber.ber_ptr, ( tmpber.ber_end - tmpber.ber_ptr ), 0)
1017                 != ( tmpber.ber_end - tmpber.ber_ptr ) ||
1018             ber_printf( ber, /*{{*/ "}}" ) == -1 ) )
1019         {
1020                 ld->ld_errno = LDAP_ENCODING_ERROR;
1021                 ber_free( ber, 1 );
1022                 return( NULL );
1023         }
1024
1025 #ifdef LDAP_DEBUG
1026         if ( ldap_debug & LDAP_DEBUG_PACKETS ) {
1027                 Debug( LDAP_DEBUG_ANY, "re_encode_request new request is:\n",
1028                     0, 0, 0 );
1029                 ber_log_dump( LDAP_DEBUG_BER, ldap_debug, ber, 0 );
1030         }
1031 #endif /* LDAP_DEBUG */
1032
1033         *type = tag;    /* return request type */
1034         return( ber );
1035 }
1036
1037
1038 LDAPRequest *
1039 ldap_find_request_by_msgid( LDAP *ld, ber_int_t msgid )
1040 {
1041         LDAPRequest     *lr;
1042
1043         for ( lr = ld->ld_requests; lr != NULL; lr = lr->lr_next ) {
1044                 if( lr->lr_status == LDAP_REQST_COMPLETED ) {
1045                         continue;       /* Skip completed requests */
1046                 }
1047                 if ( msgid == lr->lr_msgid ) {
1048                         break;
1049                 }
1050         }
1051
1052         return( lr );
1053 }
1054
1055