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