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