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