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