]> git.sur5r.net Git - openldap/blob - libraries/libldap/result.c
44c0e98ef4ee74ce10bc24b26390e1b9247e87f8
[openldap] / libraries / libldap / result.c
1 /* result.c - wait for an ldap result */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 1998-2004 The OpenLDAP Foundation.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted only as authorized by the OpenLDAP
10  * Public License.
11  *
12  * A copy of this license is available in the file LICENSE in the
13  * top-level directory of the distribution or, alternatively, at
14  * <http://www.OpenLDAP.org/license.html>.
15  */
16 /* Portions Copyright (c) 1990 Regents of the University of Michigan.
17  * All rights reserved.
18  */
19 /* This notice applies to changes, created by or for Novell, Inc.,
20  * to preexisting works for which notices appear elsewhere in this file.
21  *
22  * Copyright (C) 1999, 2000 Novell, Inc. All Rights Reserved.
23  *
24  * THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND TREATIES.
25  * USE, MODIFICATION, AND REDISTRIBUTION OF THIS WORK IS SUBJECT TO VERSION
26  * 2.0.1 OF THE OPENLDAP PUBLIC LICENSE, A COPY OF WHICH IS AVAILABLE AT
27  * HTTP://WWW.OPENLDAP.ORG/LICENSE.HTML OR IN THE FILE "LICENSE" IN THE
28  * TOP-LEVEL DIRECTORY OF THE DISTRIBUTION. ANY USE OR EXPLOITATION OF THIS
29  * WORK OTHER THAN AS AUTHORIZED IN VERSION 2.0.1 OF THE OPENLDAP PUBLIC
30  * LICENSE, OR OTHER PRIOR WRITTEN CONSENT FROM NOVELL, COULD SUBJECT THE
31  * PERPETRATOR TO CRIMINAL AND CIVIL LIABILITY. 
32  *---
33  * Modification to OpenLDAP source by Novell, Inc.
34  * April 2000 sfs Add code to process V3 referrals and search results
35  *---
36  * Note: A verbatim copy of version 2.0.1 of the OpenLDAP Public License 
37  * can be found in the file "build/LICENSE-2.0.1" in this distribution
38  * of OpenLDAP Software.
39  */
40 /* Portions Copyright (C) The Internet Society (1997)
41  * ASN.1 fragments are from RFC 2251; see RFC for full legal notices.
42  */
43
44 /*
45  * LDAPv3 (RFC2251)
46  *      LDAPResult ::= SEQUENCE {
47  *              resultCode              ENUMERATED { ... },
48  *              matchedDN               LDAPDN,
49  *              errorMessage    LDAPString,
50  *              referral                Referral OPTIONAL
51  *      }
52  *      Referral ::= SEQUENCE OF LDAPURL        (one or more)
53  *      LDAPURL ::= LDAPString                          (limited to URL chars)
54  */
55
56 #include "portable.h"
57
58 #include <stdio.h>
59
60 #include <ac/stdlib.h>
61
62 #include <ac/errno.h>
63 #include <ac/socket.h>
64 #include <ac/string.h>
65 #include <ac/time.h>
66 #include <ac/unistd.h>
67
68 #include "ldap-int.h"
69 #include "ldap_log.h"
70
71 static int ldap_abandoned LDAP_P(( LDAP *ld, ber_int_t msgid ));
72 static int ldap_mark_abandoned LDAP_P(( LDAP *ld, ber_int_t msgid ));
73 static int wait4msg LDAP_P(( LDAP *ld, ber_int_t msgid, int all, struct timeval *timeout,
74         LDAPMessage **result ));
75 static ber_tag_t try_read1msg LDAP_P(( LDAP *ld, ber_int_t msgid,
76         int all, Sockbuf *sb, LDAPConn **lc, LDAPMessage **result ));
77 static ber_tag_t build_result_ber LDAP_P(( LDAP *ld, BerElement **bp, LDAPRequest *lr ));
78 static void merge_error_info LDAP_P(( LDAP *ld, LDAPRequest *parentr, LDAPRequest *lr ));
79 static LDAPMessage * chkResponseList LDAP_P(( LDAP *ld, int msgid, int all));
80
81
82 /*
83  * ldap_result - wait for an ldap result response to a message from the
84  * ldap server.  If msgid is LDAP_RES_ANY (-1), any message will be
85  * accepted.  If msgid is LDAP_RES_UNSOLICITED (0), any unsolicited
86  * message is accepted.  Otherwise ldap_result will wait for a response
87  * with msgid.  If all is LDAP_MSG_ONE (0) the first message with id
88  * msgid will be accepted, otherwise, ldap_result will wait for all
89  * responses with id msgid and then return a pointer to the entire list
90  * of messages.  In general, this is only useful for search responses,
91  * which can be of three message types (zero or more entries, zero or
92  * search references, followed by an ldap result).  An extension to
93  * LDAPv3 allows partial extended responses to be returned in response
94  * to any request.  The type of the first message received is returned.
95  * When waiting, any messages that have been abandoned are discarded.
96  *
97  * Example:
98  *      ldap_result( s, msgid, all, timeout, result )
99  */
100 int
101 ldap_result(
102         LDAP *ld,
103         int msgid,
104         int all,
105         struct timeval *timeout,
106         LDAPMessage **result )
107 {
108         LDAPMessage     *lm;
109         int     rc;
110
111         assert( ld != NULL );
112         assert( result != NULL );
113
114         Debug( LDAP_DEBUG_TRACE, "ldap_result msgid %d\n", msgid, 0, 0 );
115
116 #ifdef LDAP_R_COMPILE
117         ldap_pvt_thread_mutex_lock( &ld->ld_res_mutex );
118 #endif
119         lm = chkResponseList(ld, msgid, all);
120
121         if ( lm == NULL ) {
122                 rc = wait4msg( ld, msgid, all, timeout, result );
123         } else {
124                 *result = lm;
125                 ld->ld_errno = LDAP_SUCCESS;
126                 rc = lm->lm_msgtype;
127         }
128 #ifdef LDAP_R_COMPILE
129         ldap_pvt_thread_mutex_unlock( &ld->ld_res_mutex );
130 #endif
131         return( rc );
132 }
133
134 static LDAPMessage *
135 chkResponseList(
136         LDAP *ld,
137         int msgid,
138         int all)
139 {
140         LDAPMessage     *lm, *lastlm, *nextlm;
141     /*
142          * Look through the list of responses we have received on
143          * this association and see if the response we're interested in
144          * is there.  If it is, return it.  If not, call wait4msg() to
145          * wait until it arrives or timeout occurs.
146          */
147
148         Debug( LDAP_DEBUG_TRACE,
149                 "ldap_chkResponseList for msgid=%d, all=%d\n",
150             msgid, all, 0 );
151         lastlm = NULL;
152         for ( lm = ld->ld_responses; lm != NULL; lm = nextlm ) {
153                 nextlm = lm->lm_next;
154
155                 if ( ldap_abandoned( ld, lm->lm_msgid ) ) {
156                         Debug( LDAP_DEBUG_TRACE,
157                                 "ldap_chkResponseList msg abandoned, msgid %d\n",
158                             msgid, 0, 0 );
159                         ldap_mark_abandoned( ld, lm->lm_msgid );
160
161                         if ( lastlm == NULL ) {
162                                 /* Remove first entry in list */
163                                 ld->ld_responses = lm->lm_next;
164                         } else {
165                                 lastlm->lm_next = nextlm;
166                         }
167
168                         ldap_msgfree( lm );
169
170                         continue;
171                 }
172
173                 if ( msgid == LDAP_RES_ANY || lm->lm_msgid == msgid ) {
174                         LDAPMessage     *tmp;
175
176                         if ( all == LDAP_MSG_ONE || msgid == LDAP_RES_UNSOLICITED ) {
177                                 break;
178                         }
179
180                         for ( tmp = lm; tmp != NULL; tmp = tmp->lm_chain ) {
181                                 if ( tmp->lm_msgtype != LDAP_RES_SEARCH_ENTRY
182                                     && tmp->lm_msgtype != LDAP_RES_SEARCH_REFERENCE
183                                         && tmp->lm_msgtype != LDAP_RES_INTERMEDIATE )
184                                 {
185                                         break;
186                                 }
187                         }
188
189                         if ( tmp == NULL ) {
190                                 lm = NULL;
191                         }
192
193                         break;
194                 }
195                 lastlm = lm;
196         }
197
198     if ( lm != NULL ) {
199                 /* Found an entry, remove it from the list */
200             if ( lastlm == NULL ) {
201                     ld->ld_responses = (all == LDAP_MSG_ONE && lm->lm_chain != NULL
202                         ? lm->lm_chain : lm->lm_next);
203             } else {
204                     lastlm->lm_next = (all == LDAP_MSG_ONE && lm->lm_chain != NULL
205                         ? lm->lm_chain : lm->lm_next);
206             }
207             if ( all == LDAP_MSG_ONE && lm->lm_chain != NULL ) {
208                     lm->lm_chain->lm_next = lm->lm_next;
209                     lm->lm_chain = NULL;
210             }
211             lm->lm_next = NULL;
212     }
213
214 #ifdef LDAP_DEBUG
215         if( lm == NULL) {
216                 Debug( LDAP_DEBUG_TRACE,
217                         "ldap_chkResponseList returns NULL\n", 0, 0, 0);
218         } else {
219                 Debug( LDAP_DEBUG_TRACE,
220                         "ldap_chkResponseList returns msgid %d, type 0x%02lu\n",
221                         lm->lm_msgid, (unsigned long) lm->lm_msgtype, 0);
222         }
223 #endif
224     return lm;
225 }
226
227 static int
228 wait4msg(
229         LDAP *ld,
230         ber_int_t msgid,
231         int all,
232         struct timeval *timeout,
233         LDAPMessage **result )
234 {
235         int             rc;
236         struct timeval  tv, *tvp;
237         time_t          start_time = 0;
238         time_t          tmp_time;
239         LDAPConn        *lc, *nextlc;
240
241         assert( ld != NULL );
242         assert( result != NULL );
243
244 #ifdef LDAP_DEBUG
245         if ( timeout == NULL ) {
246                 Debug( LDAP_DEBUG_TRACE,
247                         "wait4msg (infinite timeout), msgid %d\n",
248                         msgid, 0, 0 );
249         } else {
250                 Debug( LDAP_DEBUG_TRACE,
251                         "wait4msg (timeout %ld sec, %ld usec), msgid %d\n",
252                         (long) timeout->tv_sec, (long) timeout->tv_usec, msgid );
253         }
254 #endif /* LDAP_DEBUG */
255
256         if ( timeout == NULL ) {
257                 tvp = NULL;
258         } else {
259                 tv = *timeout;
260                 tvp = &tv;
261                 start_time = time( NULL );
262         }
263                     
264         rc = -2;
265         while ( rc == -2 ) {
266 #ifdef LDAP_DEBUG
267                 Debug( LDAP_DEBUG_TRACE, "wait4msg continue, msgid %d, all %d\n",
268                     msgid, all, 0 );
269                 if ( ldap_debug & LDAP_DEBUG_TRACE ) {
270                         ldap_dump_connection( ld, ld->ld_conns, 1 );
271                         ldap_dump_requests_and_responses( ld );
272                 }
273 #endif /* LDAP_DEBUG */
274
275         if( (*result = chkResponseList(ld, msgid, all)) != NULL ) {
276             rc = (*result)->lm_msgtype;
277         } else {
278                         int lc_ready = 0;
279
280                         for ( lc = ld->ld_conns; lc != NULL; lc = nextlc ) {
281                                 nextlc = lc->lconn_next;
282                                 if ( ber_sockbuf_ctrl( lc->lconn_sb,
283                                                 LBER_SB_OPT_DATA_READY, NULL ) ) {
284                                         rc = try_read1msg( ld, msgid, all, lc->lconn_sb,
285                                                 &lc, result );
286                                         lc_ready = 1;
287                                     break;
288                                 }
289                 }
290
291                     if ( !lc_ready ) {
292                             rc = ldap_int_select( ld, tvp );
293 #ifdef LDAP_DEBUG
294                             if ( rc == -1 ) {
295                                 Debug( LDAP_DEBUG_TRACE,
296                                         "ldap_int_select returned -1: errno %d\n",
297                                         errno, 0, 0 );
298                             }
299 #endif
300
301                             if ( rc == 0 || ( rc == -1 && (
302                                     !LDAP_BOOL_GET(&ld->ld_options, LDAP_BOOL_RESTART)
303                                     || errno != EINTR )))
304                             {
305                                     ld->ld_errno = (rc == -1 ? LDAP_SERVER_DOWN :
306                                         LDAP_TIMEOUT);
307                                     return -1;
308                             }
309
310                             if ( rc == -1 ) {
311                                     rc = -2;    /* select interrupted: loop */
312                             } else {
313                                     rc = -2;
314 #ifdef LDAP_R_COMPILE
315                                     ldap_pvt_thread_mutex_lock( &ld->ld_req_mutex );
316 #endif
317                                     if ( ld->ld_requests &&
318                                                 ld->ld_requests->lr_status == LDAP_REQST_WRITING &&
319                                                 ldap_is_write_ready( ld,
320                                                         ld->ld_requests->lr_conn->lconn_sb ) ) {
321                                                 ldap_int_flush_request( ld, ld->ld_requests );
322                                         }
323 #ifdef LDAP_R_COMPILE
324                                     ldap_pvt_thread_mutex_unlock( &ld->ld_req_mutex );
325 #endif
326                                     for ( lc = ld->ld_conns; rc == -2 && lc != NULL;
327                                         lc = nextlc ) {
328                                             nextlc = lc->lconn_next;
329                                             if ( lc->lconn_status ==
330                                                 LDAP_CONNST_CONNECTED &&
331                                                 ldap_is_read_ready( ld,
332                                                 lc->lconn_sb )) {
333                                                     rc = try_read1msg( ld, msgid, all,
334                                                         lc->lconn_sb, &lc, result );
335                                                         if ( lc == NULL ) lc = nextlc;
336                                             }
337                                     }
338                             }
339                     }
340                 }
341
342                 if ( rc == -2 && tvp != NULL ) {
343                         tmp_time = time( NULL );
344                         if (( tv.tv_sec -=  ( tmp_time - start_time )) <= 0 ) {
345                                 rc = 0; /* timed out */
346                                 ld->ld_errno = LDAP_TIMEOUT;
347                                 break;
348                         }
349
350                         Debug( LDAP_DEBUG_TRACE, "wait4msg:  %ld secs to go\n",
351                                (long) tv.tv_sec, 0, 0 );
352                         start_time = tmp_time;
353                 }
354         }
355
356         return rc;
357 }
358
359
360 static ber_tag_t
361 try_read1msg(
362         LDAP *ld,
363         ber_int_t msgid,
364         int all,
365         Sockbuf *sb,
366         LDAPConn **lcp,
367         LDAPMessage **result )
368 {
369         BerElement      *ber;
370         LDAPMessage     *new, *l, *prev, *tmp;
371         ber_int_t       id;
372         ber_tag_t       tag;
373         ber_len_t       len;
374         int             foundit = 0;
375         LDAPRequest     *lr, *tmplr;
376         LDAPConn        *lc;
377         BerElement      tmpber;
378         int             rc, refer_cnt, hadref, simple_request;
379         ber_int_t       lderr;
380 #ifdef LDAP_CONNECTIONLESS
381         int             firstmsg = 1, moremsgs = 0, isv2 = 0;
382 #endif
383         /*
384          * v3ref = flag for V3 referral / search reference
385          * 0 = not a ref, 1 = sucessfully chased ref, -1 = pass ref to application
386          */
387         int     v3ref;
388
389         assert( ld != NULL );
390         assert( lcp != NULL );
391         assert( *lcp != NULL );
392         
393         Debug( LDAP_DEBUG_TRACE, "read1msg: msgid %d, all %d\n", msgid, all, 0 );
394
395         lc = *lcp;
396
397 retry:
398         if ( lc->lconn_ber == NULL ) {
399                 lc->lconn_ber = ldap_alloc_ber_with_options(ld);
400
401                 if( lc->lconn_ber == NULL ) {
402                         return -1;
403                 }
404         }
405
406         ber = lc->lconn_ber;
407         assert( LBER_VALID (ber) );
408
409         /* get the next message */
410         errno = 0;
411 #ifdef LDAP_CONNECTIONLESS
412         if ( LDAP_IS_UDP(ld) ) {
413                 struct sockaddr from;
414                 ber_int_sb_read(sb, &from, sizeof(struct sockaddr));
415                 if (ld->ld_options.ldo_version == LDAP_VERSION2) isv2=1;
416         }
417 nextresp3:
418 #endif
419         tag = ber_get_next( sb, &len, ber );
420         if ( tag == LDAP_TAG_MESSAGE ) {
421                 /*
422                  * We read a complete message.
423                  * The connection should no longer need this ber.
424                  */
425                 lc->lconn_ber = NULL;
426         }
427         if ( tag != LDAP_TAG_MESSAGE ) {
428                 if ( tag == LBER_DEFAULT) {
429 #ifdef LDAP_DEBUG                  
430                         Debug( LDAP_DEBUG_CONNS,
431                               "ber_get_next failed.\n", 0, 0, 0 );
432 #endif             
433 #ifdef EWOULDBLOCK                      
434                         if (errno==EWOULDBLOCK) return -2;
435 #endif
436 #ifdef EAGAIN
437                         if (errno == EAGAIN) return -2;
438 #endif
439                         ld->ld_errno = LDAP_SERVER_DOWN;
440                         return -1;
441                 }
442                 ld->ld_errno = LDAP_LOCAL_ERROR;
443                 return -1;
444         }
445
446         /* message id */
447         if ( ber_get_int( ber, &id ) == LBER_ERROR ) {
448                 ber_free( ber, 1 );
449                 ld->ld_errno = LDAP_DECODING_ERROR;
450                 return( -1 );
451         }
452
453         /* if it's been abandoned, toss it */
454         if ( ldap_abandoned( ld, id ) ) {
455                 Debug( LDAP_DEBUG_ANY, "abandoned\n", 0, 0, 0);
456 retry_ber:
457                 ber_free( ber, 1 );
458                 if ( ber_sockbuf_ctrl( sb, LBER_SB_OPT_DATA_READY, NULL ) ) {
459                         goto retry;
460                 }
461                 return( -2 );   /* continue looking */
462         }
463
464         if (( lr = ldap_find_request_by_msgid( ld, id )) == NULL ) {
465                 Debug( LDAP_DEBUG_ANY,
466                     "no request for response with msgid %ld (tossing)\n",
467                     (long) id, 0, 0 );
468                 goto retry_ber;
469         }
470 #ifdef LDAP_CONNECTIONLESS
471         if (LDAP_IS_UDP(ld) && isv2) {
472                 ber_scanf(ber, "x{");
473         }
474 nextresp2:
475 #endif
476         /* the message type */
477         if ( (tag = ber_peek_tag( ber, &len )) == LBER_ERROR ) {
478                 ld->ld_errno = LDAP_DECODING_ERROR;
479                 ber_free( ber, 1 );
480                 return( -1 );
481         }
482
483         Debug( LDAP_DEBUG_TRACE,
484                 "ldap_read: message type %s msgid %ld, original id %ld\n",
485             ldap_int_msgtype2str( tag ),
486                 (long) lr->lr_msgid, (long) lr->lr_origid );
487
488         id = lr->lr_origid;
489         refer_cnt = 0;
490         hadref = simple_request = 0;
491         rc = -2;        /* default is to keep looking (no response found) */
492         lr->lr_res_msgtype = tag;
493
494         /*
495          * This code figures out if we are going to chase a
496          * referral / search reference, or pass it back to the application
497          */
498         v3ref = 0;      /* Assume not a V3 search reference or referral */
499         if( (tag != LDAP_RES_SEARCH_ENTRY) && (ld->ld_version > LDAP_VERSION2) ) {
500                 BerElement      tmpber = *ber;  /* struct copy */
501                 char **refs = NULL;
502
503                 if( tag == LDAP_RES_SEARCH_REFERENCE) {
504                         /* This is a V3 search reference */
505                         /* Assume we do not chase the reference, but pass it to application */
506                         v3ref = -1;
507                         if( LDAP_BOOL_GET(&ld->ld_options, LDAP_BOOL_REFERRALS) ||
508                                         (lr->lr_parent != NULL) )
509                         {
510                                 /* Get the referral list */
511                                 if ( ber_scanf( &tmpber, "{v}", &refs ) == LBER_ERROR ) {
512                                         rc = LDAP_DECODING_ERROR;
513                                 } else {
514                                         /* Note: refs arrary is freed by ldap_chase_v3referrals */
515                                         refer_cnt = ldap_chase_v3referrals( ld, lr, refs,
516                                             1, &lr->lr_res_error, &hadref );
517                                         if ( refer_cnt > 0 ) {  /* sucessfully chased reference */
518                                                 /* If haven't got end search, set chasing referrals */
519                                                 if( lr->lr_status != LDAP_REQST_COMPLETED) {
520                                                         lr->lr_status = LDAP_REQST_CHASINGREFS;
521                                                         Debug( LDAP_DEBUG_TRACE,
522                                                             "read1msg:  search ref chased, mark request chasing refs, id = %d\n",
523                                                             lr->lr_msgid, 0, 0);
524                                                 }
525                                                 v3ref = 1;      /* We sucessfully chased the reference */
526                                         }
527                                 }
528                         }
529                 } else {
530                         /* Check for V3 referral */
531                         ber_len_t len;
532                         if ( ber_scanf( &tmpber, "{iaa",/*}*/ &lderr,
533                                     &lr->lr_res_matched, &lr->lr_res_error )
534                                     != LBER_ERROR ) {
535                                 /* Check if V3 referral */
536                                 if( ber_peek_tag( &tmpber, &len) == LDAP_TAG_REFERRAL ) {
537                                         /* We have a V3 referral, assume we cannot chase it */
538                                         v3ref = -1;
539                                         if( LDAP_BOOL_GET(&ld->ld_options, LDAP_BOOL_REFERRALS)
540                                                          || (lr->lr_parent != NULL) )
541                                         {
542                                                 v3ref = -1;  /* Assume referral not chased and return it to app */
543                                                 /* Get the referral list */
544                                                 if( ber_scanf( &tmpber, "{v}", &refs) == LBER_ERROR) {
545                                                         rc = LDAP_DECODING_ERROR;
546                                                         lr->lr_status = LDAP_REQST_COMPLETED;
547                                                         Debug( LDAP_DEBUG_TRACE,
548                                                             "read1msg: referral decode error, mark request completed, id = %d\n",
549                                                                     lr->lr_msgid, 0, 0);
550                                                 } else {
551                                                         /* Chase the referral 
552                                                          * Note: refs arrary is freed by ldap_chase_v3referrals
553                                                          */
554                                                         refer_cnt = ldap_chase_v3referrals( ld, lr, refs,
555                                                             0, &lr->lr_res_error, &hadref );
556                                                         lr->lr_status = LDAP_REQST_COMPLETED;
557                                                         Debug( LDAP_DEBUG_TRACE,
558                                                             "read1msg:  referral chased, mark request completed, id = %d\n",
559                                                             lr->lr_msgid, 0, 0);
560                                                         if( refer_cnt > 0) {
561                                                                 v3ref = 1;  /* Referral successfully chased */
562                                                         }
563                                                 }
564                                         }
565                                 }
566
567                                 if( lr->lr_res_matched != NULL ) {
568                                         LDAP_FREE( lr->lr_res_matched );
569                                         lr->lr_res_matched = NULL;
570                                 }
571                                 if( lr->lr_res_error != NULL ) {
572                                         LDAP_FREE( lr->lr_res_error );
573                                         lr->lr_res_error = NULL;
574                                 }
575                         }
576                 }
577         }
578
579         /* All results that just return a status, i.e. don't return data
580          * go through the following code.  This code also chases V2 referrals
581          * and checks if all referrals have been chased.
582          */
583         if ( (tag != LDAP_RES_SEARCH_ENTRY) && (v3ref > -1) &&
584                 (tag != LDAP_RES_INTERMEDIATE ))
585         {
586                 /* For a v3 search referral/reference, only come here if already chased it */
587                 if ( ld->ld_version >= LDAP_VERSION2 &&
588                         ( lr->lr_parent != NULL ||
589                         LDAP_BOOL_GET(&ld->ld_options, LDAP_BOOL_REFERRALS) ) )
590                 {
591                         tmpber = *ber;  /* struct copy */
592                         if ( v3ref == 1 ) {
593                                 /* V3 search reference or V3 referral
594                                  * sucessfully chased. If this message
595                                  * is a search result, then it has no more
596                                  * outstanding referrals.
597                                  */
598                                 if ( tag == LDAP_RES_SEARCH_RESULT )
599                                         refer_cnt = 0;
600                         } else if ( ber_scanf( &tmpber, "{iaa}", &lderr,
601                             &lr->lr_res_matched, &lr->lr_res_error )
602                             != LBER_ERROR ) {
603                                 if ( lderr != LDAP_SUCCESS ) {
604                                         /* referrals are in error string */
605                                         refer_cnt = ldap_chase_referrals( ld, lr,
606                                                 &lr->lr_res_error, -1, &hadref );
607                                         lr->lr_status = LDAP_REQST_COMPLETED;
608                                         Debug( LDAP_DEBUG_TRACE,
609                                             "read1msg:  V2 referral chased, mark request completed, id = %d\n", lr->lr_msgid, 0, 0);
610                                 }
611
612                                 /* save errno, message, and matched string */
613                                 if ( !hadref || lr->lr_res_error == NULL ) {
614                                         lr->lr_res_errno = ( lderr ==
615                                         LDAP_PARTIAL_RESULTS ) ? LDAP_SUCCESS
616                                         : lderr;
617                                 } else if ( ld->ld_errno != LDAP_SUCCESS ) {
618                                         lr->lr_res_errno = ld->ld_errno;
619                                 } else {
620                                         lr->lr_res_errno = LDAP_PARTIAL_RESULTS;
621                                 }
622 Debug( LDAP_DEBUG_TRACE,
623     "new result:  res_errno: %d, res_error: <%s>, res_matched: <%s>\n",
624     lr->lr_res_errno, lr->lr_res_error ? lr->lr_res_error : "",
625     lr->lr_res_matched ? lr->lr_res_matched : "" );
626                         }
627                 }
628
629                 Debug( LDAP_DEBUG_TRACE,
630                     "read1msg:  %d new referrals\n", refer_cnt, 0, 0 );
631
632                 if ( refer_cnt != 0 ) { /* chasing referrals */
633                         ber_free( ber, 1 );
634                         ber = NULL;
635                         if ( refer_cnt < 0 ) {
636                                 return( -1 );   /* fatal error */
637                         }
638                         lr->lr_res_errno = LDAP_SUCCESS; /* sucessfully chased referral */
639                 } else {
640                         if ( lr->lr_outrefcnt <= 0 && lr->lr_parent == NULL ) {
641                                 /* request without any referrals */
642                                 simple_request = ( hadref ? 0 : 1 );
643                         } else {
644                                 /* request with referrals or child request */
645                                 ber_free( ber, 1 );
646                                 ber = NULL;
647                         }
648
649                         lr->lr_status = LDAP_REQST_COMPLETED; /* declare this request done */
650                         Debug( LDAP_DEBUG_TRACE,
651                             "read1msg:  mark request completed, id = %d\n", lr->lr_msgid, 0, 0);
652                         while ( lr->lr_parent != NULL ) {
653                                 merge_error_info( ld, lr->lr_parent, lr );
654
655                                 lr = lr->lr_parent;
656                                 if ( --lr->lr_outrefcnt > 0 ) {
657                                         break;  /* not completely done yet */
658                                 }
659                         }
660
661                         /* Check if all requests are finished, lr is now parent */
662                         tmplr = lr;
663                         if (tmplr->lr_status == LDAP_REQST_COMPLETED) {
664                                 for(tmplr=lr->lr_child; tmplr != NULL; tmplr=tmplr->lr_refnext) {
665                                 if( tmplr->lr_status != LDAP_REQST_COMPLETED) {
666                                         break;
667                                         }
668                                 }
669                         }
670
671                         /* This is the parent request if the request has referrals */
672                         if ( lr->lr_outrefcnt <= 0 && lr->lr_parent == NULL && tmplr == NULL ) {
673                                 id = lr->lr_msgid;
674                                 tag = lr->lr_res_msgtype;
675                                 Debug( LDAP_DEBUG_ANY, "request %ld done\n",
676                                     (long) id, 0, 0 );
677 Debug( LDAP_DEBUG_TRACE,
678 "res_errno: %d, res_error: <%s>, res_matched: <%s>\n",
679 lr->lr_res_errno, lr->lr_res_error ? lr->lr_res_error : "",
680 lr->lr_res_matched ? lr->lr_res_matched : "" );
681                                 if ( !simple_request ) {
682                                         ber_free( ber, 1 );
683                                         ber = NULL;
684                                         if ( build_result_ber( ld, &ber, lr )
685                                             == LBER_ERROR ) {
686                                                 rc = -1; /* fatal error */
687                                         }
688                                 }
689
690                                 ldap_free_request( ld, lr );
691                         }
692
693                         if ( lc != NULL ) {
694                                 ldap_free_connection( ld, lc, 0, 1 );
695                                 *lcp = NULL;
696                         }
697                 }
698         }
699
700         if ( ber == NULL ) {
701                 return( rc );
702         }
703
704         /* make a new ldap message */
705         if ( (new = (LDAPMessage *) LDAP_CALLOC( 1, sizeof(LDAPMessage) ))
706             == NULL ) {
707                 ld->ld_errno = LDAP_NO_MEMORY;
708                 return( -1 );
709         }
710         new->lm_msgid = (int)id;
711         new->lm_msgtype = tag;
712         new->lm_ber = ber;
713
714 #ifdef LDAP_CONNECTIONLESS
715         /* CLDAP replies all fit in a single datagram. In LDAPv2 RFC1798
716          * the responses are all a sequence wrapped in one message. In
717          * LDAPv3 each response is in its own message. The datagram must
718          * end with a SearchResult. We can't just parse each response in
719          * separate calls to try_read1msg because the header info is only
720          * present at the beginning of the datagram, not at the beginning
721          * of each response. So parse all the responses at once and queue
722          * them up, then pull off the first response to return to the
723          * caller when all parsing is complete.
724          */
725         if ( LDAP_IS_UDP(ld) ) {
726                 /* If not a result, look for more */
727                 if ( tag != LDAP_RES_SEARCH_RESULT ) {
728                         int ok = 0;
729                         moremsgs = 1;
730                         if (isv2) {
731                                 /* LDAPv2: dup the current ber, skip past the current
732                                  * response, and see if there are any more after it.
733                                  */
734                                 ber = ber_dup( ber );
735                                 ber_scanf( ber, "x" );
736                                 if (ber_peek_tag(ber, &len) != LBER_DEFAULT) {
737                                         /* There's more - dup the ber buffer so they can all be
738                                          * individually freed by ldap_msgfree.
739                                          */
740                                         struct berval bv;
741                                         ber_get_option(ber, LBER_OPT_BER_REMAINING_BYTES, &len);
742                                         bv.bv_val = LDAP_MALLOC(len);
743                                         if (bv.bv_val) {
744                                                 ok=1;
745                                                 ber_read(ber, bv.bv_val, len);
746                                                 bv.bv_len = len;
747                                                 ber_init2(ber, &bv, ld->ld_lberoptions );
748                                         }
749                                 }
750                         } else {
751                                 /* LDAPv3: Just allocate a new ber. Since this is a buffered
752                                  * datagram, if the sockbuf is readable we still have data
753                                  * to parse.
754                                  */
755                                 ber = ldap_alloc_ber_with_options(ld);
756                                 if (ber_sockbuf_ctrl(sb, LBER_SB_OPT_DATA_READY, NULL)) ok=1;
757                         }
758                         /* set up response chain */
759                         if ( firstmsg ) {
760                                 firstmsg = 0;
761                                 new->lm_next = ld->ld_responses;
762                                 ld->ld_responses = new;
763                         } else {
764                                 tmp->lm_chain = new;
765                         }
766                         tmp = new;
767                         /* "ok" means there's more to parse */
768                         if (ok) {
769                                 if (isv2) goto nextresp2;
770                                 else goto nextresp3;
771                         } else {
772                                 /* got to end of datagram without a SearchResult. Free
773                                  * our dup'd ber, but leave any buffer alone. For v2 case,
774                                  * the previous response is still using this buffer. For v3,
775                                  * the new ber has no buffer to free yet.
776                                  */
777                                 ber_free(ber, 0);
778                                 return -1;
779                         }
780                 } else if ( moremsgs ) {
781                 /* got search result, and we had multiple responses in 1 datagram.
782                  * stick the result onto the end of the chain, and then pull the
783                  * first response off the head of the chain.
784                  */
785                         tmp->lm_chain = new;
786                         *result = chkResponseList( ld, msgid, all );
787                         ld->ld_errno = LDAP_SUCCESS;
788                         return( (*result)->lm_msgtype );
789                 }
790         }
791 #endif
792
793         /* is this the one we're looking for? */
794         if ( msgid == LDAP_RES_ANY || id == msgid ) {
795                 if ( all == LDAP_MSG_ONE
796                     || (new->lm_msgtype != LDAP_RES_SEARCH_RESULT
797                     && new->lm_msgtype != LDAP_RES_SEARCH_ENTRY
798                     && new->lm_msgtype != LDAP_RES_SEARCH_REFERENCE) ) {
799                         *result = new;
800                         ld->ld_errno = LDAP_SUCCESS;
801                         return( tag );
802                 } else if ( new->lm_msgtype == LDAP_RES_SEARCH_RESULT) {
803                         foundit = 1;    /* return the chain later */
804                 }
805         }
806
807         /* 
808          * if not, we must add it to the list of responses.  if
809          * the msgid is already there, it must be part of an existing
810          * search response.
811          */
812
813         prev = NULL;
814         for ( l = ld->ld_responses; l != NULL; l = l->lm_next ) {
815                 if ( l->lm_msgid == new->lm_msgid )
816                         break;
817                 prev = l;
818         }
819
820         /* not part of an existing search response */
821         if ( l == NULL ) {
822                 if ( foundit ) {
823                         *result = new;
824                         goto exit;
825                 }
826
827                 new->lm_next = ld->ld_responses;
828                 ld->ld_responses = new;
829                 goto exit;
830         }
831
832         Debug( LDAP_DEBUG_TRACE, "adding response id %ld type %ld:\n",
833             (long) new->lm_msgid, (long) new->lm_msgtype, 0 );
834
835         /* part of a search response - add to end of list of entries */
836         for ( tmp = l; (tmp->lm_chain != NULL) &&
837                 ((tmp->lm_chain->lm_msgtype == LDAP_RES_SEARCH_ENTRY) ||
838                  (tmp->lm_chain->lm_msgtype == LDAP_RES_SEARCH_REFERENCE) ||
839                          (tmp->lm_chain->lm_msgtype == LDAP_RES_INTERMEDIATE ));
840             tmp = tmp->lm_chain )
841                 ;       /* NULL */
842         tmp->lm_chain = new;
843
844         /* return the whole chain if that's what we were looking for */
845         if ( foundit ) {
846                 if ( prev == NULL )
847                         ld->ld_responses = l->lm_next;
848                 else
849                         prev->lm_next = l->lm_next;
850                 *result = l;
851         }
852
853 exit:
854         if ( foundit ) {
855                 ld->ld_errno = LDAP_SUCCESS;
856                 return( tag );
857         }
858         if ( ber_sockbuf_ctrl( sb, LBER_SB_OPT_DATA_READY, NULL ) ) {
859                 goto retry;
860         }
861         return( -2 );   /* continue looking */
862 }
863
864
865 static ber_tag_t
866 build_result_ber( LDAP *ld, BerElement **bp, LDAPRequest *lr )
867 {
868         ber_len_t       len;
869         ber_tag_t       tag;
870         ber_int_t       along;
871         BerElement *ber;
872
873         *bp = NULL;
874         ber = ldap_alloc_ber_with_options( ld );
875
876         if( ber == NULL ) {
877                 ld->ld_errno = LDAP_NO_MEMORY;
878                 return LBER_ERROR;
879         }
880
881         if ( ber_printf( ber, "{it{ess}}", lr->lr_msgid,
882             lr->lr_res_msgtype, lr->lr_res_errno,
883             lr->lr_res_matched ? lr->lr_res_matched : "",
884             lr->lr_res_error ? lr->lr_res_error : "" ) == -1 ) {
885
886                 ld->ld_errno = LDAP_ENCODING_ERROR;
887                 ber_free(ber, 1);
888                 return( LBER_ERROR );
889         }
890
891         ber_reset( ber, 1 );
892
893         if ( ber_skip_tag( ber, &len ) == LBER_ERROR ) {
894                 ld->ld_errno = LDAP_DECODING_ERROR;
895                 ber_free(ber, 1);
896                 return( LBER_ERROR );
897         }
898
899         if ( ber_get_int( ber, &along ) == LBER_ERROR ) {
900                 ld->ld_errno = LDAP_DECODING_ERROR;
901                 ber_free(ber, 1);
902                 return( LBER_ERROR );
903         }
904
905         tag = ber_peek_tag( ber, &len );
906
907         if ( tag == LBER_ERROR ) {
908                 ld->ld_errno = LDAP_DECODING_ERROR;
909                 ber_free(ber, 1);
910                 return( LBER_ERROR );
911         }
912
913         *bp = ber;
914         return tag;
915 }
916
917
918 static void
919 merge_error_info( LDAP *ld, LDAPRequest *parentr, LDAPRequest *lr )
920 {
921 /*
922  * Merge error information in "lr" with "parentr" error code and string.
923  */
924         if ( lr->lr_res_errno == LDAP_PARTIAL_RESULTS ) {
925                 parentr->lr_res_errno = lr->lr_res_errno;
926                 if ( lr->lr_res_error != NULL ) {
927                         (void)ldap_append_referral( ld, &parentr->lr_res_error,
928                             lr->lr_res_error );
929                 }
930         } else if ( lr->lr_res_errno != LDAP_SUCCESS &&
931             parentr->lr_res_errno == LDAP_SUCCESS ) {
932                 parentr->lr_res_errno = lr->lr_res_errno;
933                 if ( parentr->lr_res_error != NULL ) {
934                         LDAP_FREE( parentr->lr_res_error );
935                 }
936                 parentr->lr_res_error = lr->lr_res_error;
937                 lr->lr_res_error = NULL;
938                 if ( LDAP_NAME_ERROR( lr->lr_res_errno )) {
939                         if ( parentr->lr_res_matched != NULL ) {
940                                 LDAP_FREE( parentr->lr_res_matched );
941                         }
942                         parentr->lr_res_matched = lr->lr_res_matched;
943                         lr->lr_res_matched = NULL;
944                 }
945         }
946
947         Debug( LDAP_DEBUG_TRACE, "merged parent (id %d) error info:  ",
948             parentr->lr_msgid, 0, 0 );
949         Debug( LDAP_DEBUG_TRACE, "result errno %d, error <%s>, matched <%s>\n",
950             parentr->lr_res_errno, parentr->lr_res_error ?
951             parentr->lr_res_error : "", parentr->lr_res_matched ?
952             parentr->lr_res_matched : "" );
953 }
954
955
956
957 int
958 ldap_msgtype( LDAPMessage *lm )
959 {
960         assert( lm != NULL );
961         return ( lm != NULL ) ? lm->lm_msgtype : -1;
962 }
963
964
965 int
966 ldap_msgid( LDAPMessage *lm )
967 {
968         assert( lm != NULL );
969
970         return ( lm != NULL ) ? lm->lm_msgid : -1;
971 }
972
973
974 char * ldap_int_msgtype2str( ber_tag_t tag )
975 {
976         switch( tag ) {
977         case LDAP_RES_ADD: return "add";
978         case LDAP_RES_BIND: return "bind";
979         case LDAP_RES_COMPARE: return "compare";
980         case LDAP_RES_DELETE: return "delete";
981         case LDAP_RES_EXTENDED: return "extended-result";
982         case LDAP_RES_INTERMEDIATE: return "intermediate";
983         case LDAP_RES_MODIFY: return "modify";
984         case LDAP_RES_RENAME: return "rename";
985         case LDAP_RES_SEARCH_ENTRY: return "search-entry";
986         case LDAP_RES_SEARCH_REFERENCE: return "search-reference";
987         case LDAP_RES_SEARCH_RESULT: return "search-result";
988         }
989         return "unknown";
990 }
991
992 int
993 ldap_msgfree( LDAPMessage *lm )
994 {
995         LDAPMessage     *next;
996         int             type = 0;
997
998         Debug( LDAP_DEBUG_TRACE, "ldap_msgfree\n", 0, 0, 0 );
999
1000         for ( ; lm != NULL; lm = next ) {
1001                 next = lm->lm_chain;
1002                 type = lm->lm_msgtype;
1003                 ber_free( lm->lm_ber, 1 );
1004                 LDAP_FREE( (char *) lm );
1005         }
1006
1007         return( type );
1008 }
1009
1010 /*
1011  * ldap_msgdelete - delete a message.  It returns:
1012  *      0       if the entire message was deleted
1013  *      -1      if the message was not found, or only part of it was found
1014  */
1015 int
1016 ldap_msgdelete( LDAP *ld, int msgid )
1017 {
1018         LDAPMessage     *lm, *prev;
1019         int rc = 0;
1020
1021         assert( ld != NULL );
1022
1023         Debug( LDAP_DEBUG_TRACE, "ldap_msgdelete\n", 0, 0, 0 );
1024
1025         prev = NULL;
1026 #ifdef LDAP_R_COMPILE
1027         ldap_pvt_thread_mutex_lock( &ld->ld_res_mutex );
1028 #endif
1029         for ( lm = ld->ld_responses; lm != NULL; lm = lm->lm_next ) {
1030                 if ( lm->lm_msgid == msgid )
1031                         break;
1032                 prev = lm;
1033         }
1034
1035         if ( lm == NULL ) {
1036                 rc = -1;
1037         } else {
1038                 if ( prev == NULL )
1039                         ld->ld_responses = lm->lm_next;
1040                 else
1041                         prev->lm_next = lm->lm_next;
1042         }
1043 #ifdef LDAP_R_COMPILE
1044         ldap_pvt_thread_mutex_unlock( &ld->ld_res_mutex );
1045 #endif
1046         if ( lm && ldap_msgfree( lm ) == LDAP_RES_SEARCH_ENTRY )
1047                 rc = -1;
1048
1049         return( rc );
1050 }
1051
1052
1053 /*
1054  * return 1 if message msgid is waiting to be abandoned, 0 otherwise
1055  */
1056 static int
1057 ldap_abandoned( LDAP *ld, ber_int_t msgid )
1058 {
1059         int     i;
1060
1061         if ( ld->ld_abandoned == NULL )
1062                 return( 0 );
1063
1064         for ( i = 0; ld->ld_abandoned[i] != -1; i++ )
1065                 if ( ld->ld_abandoned[i] == msgid )
1066                         return( 1 );
1067
1068         return( 0 );
1069 }
1070
1071
1072 static int
1073 ldap_mark_abandoned( LDAP *ld, ber_int_t msgid )
1074 {
1075         int     i;
1076
1077         if ( ld->ld_abandoned == NULL )
1078                 return( -1 );
1079
1080         for ( i = 0; ld->ld_abandoned[i] != -1; i++ )
1081                 if ( ld->ld_abandoned[i] == msgid )
1082                         break;
1083
1084         if ( ld->ld_abandoned[i] == -1 )
1085                 return( -1 );
1086
1087         for ( ; ld->ld_abandoned[i] != -1; i++ ) {
1088                 ld->ld_abandoned[i] = ld->ld_abandoned[i + 1];
1089         }
1090
1091         return( 0 );
1092 }