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