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