]> git.sur5r.net Git - openldap/blob - libraries/libldap/result.c
4180c31a320879c98a2c58d41fd21d48fdce5ec7
[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-2005 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                         if ( lm->lm_chain == NULL ) {
181                                 assert(lm->lm_chain_tail == lm);
182                                 if ((lm->lm_msgtype == LDAP_RES_SEARCH_ENTRY) ||
183                                         (lm->lm_msgtype == LDAP_RES_SEARCH_REFERENCE) ||
184                                         (lm->lm_msgtype == LDAP_RES_INTERMEDIATE)) {
185                                         tmp = NULL;
186                                 } else {
187                                         tmp = lm;
188                                 }
189                         } else {
190                                 assert(lm->lm_chain_tail);
191                                 assert(lm->lm_chain_tail->lm_chain);
192                                 if ((lm->lm_chain_tail->lm_chain->lm_msgtype
193                                                 == LDAP_RES_SEARCH_ENTRY) ||
194                                         (lm->lm_chain_tail->lm_chain->lm_msgtype
195                                                 == LDAP_RES_SEARCH_REFERENCE) ||
196                                         (lm->lm_chain_tail->lm_chain->lm_msgtype
197                                                 == LDAP_RES_INTERMEDIATE)) {
198                                         tmp = NULL;
199                                 } else {
200                                         tmp = lm->lm_chain_tail->lm_chain;
201                                 }
202                         }
203
204                         if ( tmp == NULL ) {
205                                 lm = NULL;
206                         }
207
208                         break;
209                 }
210                 lastlm = lm;
211         }
212
213     if ( lm != NULL ) {
214                 /* Found an entry, remove it from the list */
215             if ( lastlm == NULL ) {
216                     ld->ld_responses = (all == LDAP_MSG_ONE && lm->lm_chain != NULL
217                         ? lm->lm_chain : lm->lm_next);
218             } else {
219                     lastlm->lm_next = (all == LDAP_MSG_ONE && lm->lm_chain != NULL
220                         ? lm->lm_chain : lm->lm_next);
221             }
222             if ( all == LDAP_MSG_ONE && lm->lm_chain != NULL ) {
223                         lm->lm_chain->lm_next = lm->lm_next;
224                         lm->lm_chain->lm_chain_tail = ( lm->lm_chain_tail != lm ) ? lm->lm_chain_tail : lm->lm_chain;
225                         assert(lm->lm_chain->lm_chain_tail);
226                         lm->lm_chain = NULL;
227                         lm->lm_chain_tail = NULL;
228             }
229             lm->lm_next = NULL;
230     }
231
232 #ifdef LDAP_DEBUG
233         if( lm == NULL) {
234                 Debug( LDAP_DEBUG_TRACE,
235                         "ldap_chkResponseList returns NULL\n", 0, 0, 0);
236         } else {
237                 Debug( LDAP_DEBUG_TRACE,
238                         "ldap_chkResponseList returns msgid %d, type 0x%02lu\n",
239                         lm->lm_msgid, (unsigned long) lm->lm_msgtype, 0);
240         }
241 #endif
242     return lm;
243 }
244
245 static int
246 wait4msg(
247         LDAP *ld,
248         ber_int_t msgid,
249         int all,
250         struct timeval *timeout,
251         LDAPMessage **result )
252 {
253         int             rc;
254         struct timeval  tv, tv0, *tvp;
255         time_t          start_time = 0;
256         time_t          tmp_time;
257         LDAPConn        *lc, *nextlc;
258
259         assert( ld != NULL );
260         assert( result != NULL );
261
262 #ifdef LDAP_DEBUG
263         if ( timeout == NULL ) {
264                 Debug( LDAP_DEBUG_TRACE, "wait4msg (infinite timeout), msgid %d\n",
265                     msgid, 0, 0 );
266         } else {
267                 Debug( LDAP_DEBUG_TRACE, "wait4msg (timeout %ld sec, %ld usec), msgid %d\n",
268                        (long) timeout->tv_sec, (long) timeout->tv_usec, msgid );
269         }
270 #endif /* LDAP_DEBUG */
271
272         if ( timeout == NULL ) {
273                 tvp = NULL;
274         } else {
275                 tv0 = *timeout;
276                 tv = *timeout;
277                 tvp = &tv;
278                 start_time = time( NULL );
279         }
280                     
281         rc = -2;
282         while ( rc == -2 ) {
283 #ifdef LDAP_DEBUG
284                 Debug( LDAP_DEBUG_TRACE, "wait4msg continue, msgid %d, all %d\n",
285                     msgid, all, 0 );
286                 if ( ldap_debug & LDAP_DEBUG_TRACE ) {
287                         ldap_dump_connection( ld, ld->ld_conns, 1 );
288                         ldap_dump_requests_and_responses( ld );
289                 }
290 #endif /* LDAP_DEBUG */
291
292                 if ( (*result = chkResponseList(ld, msgid, all)) != NULL ) {
293                         rc = (*result)->lm_msgtype;
294
295                 } else {
296                         int lc_ready = 0;
297
298                         for ( lc = ld->ld_conns; lc != NULL; lc = nextlc ) {
299                                 nextlc = lc->lconn_next;
300                                 if ( ber_sockbuf_ctrl( lc->lconn_sb,
301                                                 LBER_SB_OPT_DATA_READY, NULL ) ) {
302                                         rc = try_read1msg( ld, msgid, all, lc->lconn_sb,
303                                                 &lc, result );
304                                         lc_ready = 1;
305                                         break;
306                                 }
307                         }
308
309                         if ( !lc_ready ) {
310                             rc = ldap_int_select( ld, tvp );
311 #ifdef LDAP_DEBUG
312                             if ( rc == -1 ) {
313                                 Debug( LDAP_DEBUG_TRACE,
314                                         "ldap_int_select returned -1: errno %d\n",
315                                         errno, 0, 0 );
316                             }
317 #endif
318
319                             if ( rc == 0 || ( rc == -1 && (
320                                     !LDAP_BOOL_GET(&ld->ld_options, LDAP_BOOL_RESTART)
321                                     || errno != EINTR )))
322                             {
323                                     ld->ld_errno = (rc == -1 ? LDAP_SERVER_DOWN :
324                                         LDAP_TIMEOUT);
325                                     return( rc );
326                             }
327
328                             if ( rc == -1 ) {
329                                     rc = -2;    /* select interrupted: loop */
330                             } else {
331                                     rc = -2;
332 #ifdef LDAP_R_COMPILE
333                                     ldap_pvt_thread_mutex_lock( &ld->ld_req_mutex );
334 #endif
335                                     if ( ld->ld_requests &&
336                                                 ld->ld_requests->lr_status == LDAP_REQST_WRITING &&
337                                                 ldap_is_write_ready( ld,
338                                                         ld->ld_requests->lr_conn->lconn_sb ) ) {
339                                                 ldap_int_flush_request( ld, ld->ld_requests );
340                                         }
341 #ifdef LDAP_R_COMPILE
342                                     ldap_pvt_thread_mutex_unlock( &ld->ld_req_mutex );
343 #endif
344                                     for ( lc = ld->ld_conns; rc == -2 && lc != NULL;
345                                         lc = nextlc ) {
346                                             nextlc = lc->lconn_next;
347                                             if ( lc->lconn_status ==
348                                                 LDAP_CONNST_CONNECTED &&
349                                                 ldap_is_read_ready( ld,
350                                                 lc->lconn_sb )) {
351                                                     rc = try_read1msg( ld, msgid, all,
352                                                         lc->lconn_sb, &lc, result );
353                                                         if ( lc == NULL ) lc = nextlc;
354                                             }
355                                     }
356                             }
357                     }
358                 }
359
360                 if ( rc == -2 && tvp != NULL ) {
361                         tmp_time = time( NULL );
362                         if (( tv0.tv_sec -=  ( tmp_time - start_time )) <= 0 ) {
363                                 rc = 0; /* timed out */
364                                 ld->ld_errno = LDAP_TIMEOUT;
365                                 break;
366                         }
367                         tv.tv_sec = tv0.tv_sec;
368
369                         Debug( LDAP_DEBUG_TRACE, "wait4msg:  %ld secs to go\n",
370                                (long) tv.tv_sec, 0, 0 );
371                         start_time = tmp_time;
372                 }
373         }
374
375         return( rc );
376 }
377
378
379 static ber_tag_t
380 try_read1msg(
381         LDAP *ld,
382         ber_int_t msgid,
383         int all,
384         Sockbuf *sb,
385         LDAPConn **lcp,
386         LDAPMessage **result )
387 {
388         BerElement      *ber;
389         LDAPMessage     *new, *l, *prev;
390         ber_int_t       id;
391         ber_tag_t       tag;
392         ber_len_t       len;
393         int             foundit = 0;
394         LDAPRequest     *lr, *tmplr;
395         LDAPConn        *lc;
396         BerElement      tmpber;
397         int             rc, refer_cnt, hadref, simple_request;
398         ber_int_t       lderr;
399 #ifdef LDAP_CONNECTIONLESS
400         LDAPMessage     *tmp, *chain_head;
401         int             firstmsg = 1, moremsgs = 0, isv2 = 0;
402 #endif
403         /*
404          * v3ref = flag for V3 referral / search reference
405          * 0 = not a ref, 1 = sucessfully chased ref, -1 = pass ref to application
406          */
407         int     v3ref;
408
409         assert( ld != NULL );
410         assert( lcp != NULL );
411         assert( *lcp != NULL );
412         
413         Debug( LDAP_DEBUG_TRACE, "read1msg: msgid %d, all %d\n", msgid, all, 0 );
414
415         lc = *lcp;
416
417 retry:
418         if ( lc->lconn_ber == NULL ) {
419                 lc->lconn_ber = ldap_alloc_ber_with_options(ld);
420
421                 if( lc->lconn_ber == NULL ) {
422                         return -1;
423                 }
424         }
425
426         ber = lc->lconn_ber;
427         assert( LBER_VALID (ber) );
428
429         /* get the next message */
430         errno = 0;
431 #ifdef LDAP_CONNECTIONLESS
432         if ( LDAP_IS_UDP(ld) ) {
433                 struct sockaddr from;
434                 ber_int_sb_read(sb, &from, sizeof(struct sockaddr));
435                 if (ld->ld_options.ldo_version == LDAP_VERSION2) isv2=1;
436         }
437 nextresp3:
438 #endif
439         tag = ber_get_next( sb, &len, ber );
440         if ( tag == LDAP_TAG_MESSAGE ) {
441                 /*
442                  * We read a complete message.
443                  * The connection should no longer need this ber.
444                  */
445                 lc->lconn_ber = NULL;
446         }
447         if ( tag != LDAP_TAG_MESSAGE ) {
448                 if ( tag == LBER_DEFAULT) {
449 #ifdef LDAP_DEBUG                  
450                         Debug( LDAP_DEBUG_CONNS,
451                               "ber_get_next failed.\n", 0, 0, 0 );
452 #endif             
453 #ifdef EWOULDBLOCK                      
454                         if (errno==EWOULDBLOCK) return -2;
455 #endif
456 #ifdef EAGAIN
457                         if (errno == EAGAIN) return -2;
458 #endif
459                         ld->ld_errno = LDAP_SERVER_DOWN;
460                         return -1;
461                 }
462                 ld->ld_errno = LDAP_LOCAL_ERROR;
463                 return -1;
464         }
465
466         /* message id */
467         if ( ber_get_int( ber, &id ) == LBER_ERROR ) {
468                 ber_free( ber, 1 );
469                 ld->ld_errno = LDAP_DECODING_ERROR;
470                 return( -1 );
471         }
472
473         /* if it's been abandoned, toss it */
474         if ( ldap_abandoned( ld, id ) ) {
475                 Debug( LDAP_DEBUG_ANY, "abandoned\n", 0, 0, 0);
476 retry_ber:
477                 ber_free( ber, 1 );
478                 if ( ber_sockbuf_ctrl( sb, LBER_SB_OPT_DATA_READY, NULL ) ) {
479                         goto retry;
480                 }
481                 return( -2 );   /* continue looking */
482         }
483
484         if (( lr = ldap_find_request_by_msgid( ld, id )) == NULL ) {
485                 Debug( LDAP_DEBUG_ANY,
486                     "no request for response with msgid %ld (tossing)\n",
487                     (long) id, 0, 0 );
488                 goto retry_ber;
489         }
490 #ifdef LDAP_CONNECTIONLESS
491         if (LDAP_IS_UDP(ld) && isv2) {
492                 ber_scanf(ber, "x{");
493         }
494 nextresp2:
495 #endif
496         /* the message type */
497         if ( (tag = ber_peek_tag( ber, &len )) == LBER_ERROR ) {
498                 ld->ld_errno = LDAP_DECODING_ERROR;
499                 ber_free( ber, 1 );
500                 return( -1 );
501         }
502
503         Debug( LDAP_DEBUG_TRACE,
504                 "ldap_read: message type %s msgid %ld, original id %ld\n",
505             ldap_int_msgtype2str( tag ),
506                 (long) lr->lr_msgid, (long) lr->lr_origid );
507
508         id = lr->lr_origid;
509         refer_cnt = 0;
510         hadref = simple_request = 0;
511         rc = -2;        /* default is to keep looking (no response found) */
512         lr->lr_res_msgtype = tag;
513
514         /*
515          * This code figures out if we are going to chase a
516          * referral / search reference, or pass it back to the application
517          */
518         v3ref = 0;      /* Assume not a V3 search reference or referral */
519         if( (tag != LDAP_RES_SEARCH_ENTRY) && (ld->ld_version > LDAP_VERSION2) ) {
520                 BerElement      tmpber = *ber;  /* struct copy */
521                 char **refs = NULL;
522
523                 if( tag == LDAP_RES_SEARCH_REFERENCE) {
524                         /* This is a V3 search reference */
525                         /* Assume we do not chase the reference, but pass it to application */
526                         v3ref = -1;
527                         if( LDAP_BOOL_GET(&ld->ld_options, LDAP_BOOL_REFERRALS) ||
528                                         (lr->lr_parent != NULL) )
529                         {
530                                 /* Get the referral list */
531                                 if ( ber_scanf( &tmpber, "{v}", &refs ) == LBER_ERROR ) {
532                                         rc = LDAP_DECODING_ERROR;
533                                 } else {
534                                         /* Note: refs arrary is freed by ldap_chase_v3referrals */
535                                         refer_cnt = ldap_chase_v3referrals( ld, lr, refs,
536                                             1, &lr->lr_res_error, &hadref );
537                                         if ( refer_cnt > 0 ) {  /* sucessfully chased reference */
538                                                 /* If haven't got end search, set chasing referrals */
539                                                 if( lr->lr_status != LDAP_REQST_COMPLETED) {
540                                                         lr->lr_status = LDAP_REQST_CHASINGREFS;
541                                                         Debug( LDAP_DEBUG_TRACE,
542                                                             "read1msg:  search ref chased, mark request chasing refs, id = %d\n",
543                                                             lr->lr_msgid, 0, 0);
544                                                 }
545                                                 v3ref = 1;      /* We sucessfully chased the reference */
546                                         }
547                                 }
548                         }
549                 } else {
550                         /* Check for V3 referral */
551                         ber_len_t len;
552                         if ( ber_scanf( &tmpber, "{iaa",/*}*/ &lderr,
553                                     &lr->lr_res_matched, &lr->lr_res_error )
554                                     != LBER_ERROR ) {
555                                 /* Check if V3 referral */
556                                 if( ber_peek_tag( &tmpber, &len) == LDAP_TAG_REFERRAL ) {
557                                         /* We have a V3 referral, assume we cannot chase it */
558                                         v3ref = -1;
559                                         if( LDAP_BOOL_GET(&ld->ld_options, LDAP_BOOL_REFERRALS)
560                                                          || (lr->lr_parent != NULL) )
561                                         {
562                                                 v3ref = -1;  /* Assume referral not chased and return it to app */
563                                                 /* Get the referral list */
564                                                 if( ber_scanf( &tmpber, "{v}", &refs) == LBER_ERROR) {
565                                                         rc = LDAP_DECODING_ERROR;
566                                                         lr->lr_status = LDAP_REQST_COMPLETED;
567                                                         Debug( LDAP_DEBUG_TRACE,
568                                                             "read1msg: referral decode error, mark request completed, id = %d\n",
569                                                                     lr->lr_msgid, 0, 0);
570                                                 } else {
571                                                         /* Chase the referral 
572                                                          * Note: refs arrary is freed by ldap_chase_v3referrals
573                                                          */
574                                                         refer_cnt = ldap_chase_v3referrals( ld, lr, refs,
575                                                             0, &lr->lr_res_error, &hadref );
576                                                         lr->lr_status = LDAP_REQST_COMPLETED;
577                                                         Debug( LDAP_DEBUG_TRACE,
578                                                             "read1msg:  referral chased, mark request completed, id = %d\n",
579                                                             lr->lr_msgid, 0, 0);
580                                                         if( refer_cnt > 0) {
581                                                                 v3ref = 1;  /* Referral successfully chased */
582                                                         }
583                                                 }
584                                         }
585                                 }
586
587                                 if( lr->lr_res_matched != NULL ) {
588                                         LDAP_FREE( lr->lr_res_matched );
589                                         lr->lr_res_matched = NULL;
590                                 }
591                                 if( lr->lr_res_error != NULL ) {
592                                         LDAP_FREE( lr->lr_res_error );
593                                         lr->lr_res_error = NULL;
594                                 }
595                         }
596                 }
597         }
598
599         /* All results that just return a status, i.e. don't return data
600          * go through the following code.  This code also chases V2 referrals
601          * and checks if all referrals have been chased.
602          */
603         if ( (tag != LDAP_RES_SEARCH_ENTRY) && (v3ref > -1) &&
604                 (tag != LDAP_RES_INTERMEDIATE ))
605         {
606                 /* For a v3 search referral/reference, only come here if already chased it */
607                 if ( ld->ld_version >= LDAP_VERSION2 &&
608                         ( lr->lr_parent != NULL ||
609                         LDAP_BOOL_GET(&ld->ld_options, LDAP_BOOL_REFERRALS) ) )
610                 {
611                         tmpber = *ber;  /* struct copy */
612                         if ( v3ref == 1 ) {
613                                 /* V3 search reference or V3 referral
614                                  * sucessfully chased. If this message
615                                  * is a search result, then it has no more
616                                  * outstanding referrals.
617                                  */
618                                 if ( tag == LDAP_RES_SEARCH_RESULT )
619                                         refer_cnt = 0;
620                         } else if ( ber_scanf( &tmpber, "{iaa}", &lderr,
621                             &lr->lr_res_matched, &lr->lr_res_error )
622                             != LBER_ERROR ) {
623                                 if ( lderr != LDAP_SUCCESS ) {
624                                         /* referrals are in error string */
625                                         refer_cnt = ldap_chase_referrals( ld, lr,
626                                                 &lr->lr_res_error, -1, &hadref );
627                                         lr->lr_status = LDAP_REQST_COMPLETED;
628                                         Debug( LDAP_DEBUG_TRACE,
629                                             "read1msg:  V2 referral chased, mark request completed, id = %d\n", lr->lr_msgid, 0, 0);
630                                 }
631
632                                 /* save errno, message, and matched string */
633                                 if ( !hadref || lr->lr_res_error == NULL ) {
634                                         lr->lr_res_errno = ( lderr ==
635                                         LDAP_PARTIAL_RESULTS ) ? LDAP_SUCCESS
636                                         : lderr;
637                                 } else if ( ld->ld_errno != LDAP_SUCCESS ) {
638                                         lr->lr_res_errno = ld->ld_errno;
639                                 } else {
640                                         lr->lr_res_errno = LDAP_PARTIAL_RESULTS;
641                                 }
642 Debug( LDAP_DEBUG_TRACE,
643     "new result:  res_errno: %d, res_error: <%s>, res_matched: <%s>\n",
644     lr->lr_res_errno, lr->lr_res_error ? lr->lr_res_error : "",
645     lr->lr_res_matched ? lr->lr_res_matched : "" );
646                         }
647                 }
648
649                 Debug( LDAP_DEBUG_TRACE,
650                     "read1msg:  %d new referrals\n", refer_cnt, 0, 0 );
651
652                 if ( refer_cnt != 0 ) { /* chasing referrals */
653                         ber_free( ber, 1 );
654                         ber = NULL;
655                         if ( refer_cnt < 0 ) {
656                                 return( -1 );   /* fatal error */
657                         }
658                         lr->lr_res_errno = LDAP_SUCCESS; /* sucessfully chased referral */
659                 } else {
660                         if ( lr->lr_outrefcnt <= 0 && lr->lr_parent == NULL ) {
661                                 /* request without any referrals */
662                                 simple_request = ( hadref ? 0 : 1 );
663                         } else {
664                                 /* request with referrals or child request */
665                                 ber_free( ber, 1 );
666                                 ber = NULL;
667                         }
668
669                         lr->lr_status = LDAP_REQST_COMPLETED; /* declare this request done */
670                         Debug( LDAP_DEBUG_TRACE,
671                             "read1msg:  mark request completed, id = %d\n", lr->lr_msgid, 0, 0);
672                         while ( lr->lr_parent != NULL ) {
673                                 merge_error_info( ld, lr->lr_parent, lr );
674
675                                 lr = lr->lr_parent;
676                                 if ( --lr->lr_outrefcnt > 0 ) {
677                                         break;  /* not completely done yet */
678                                 }
679                         }
680
681                         /* Check if all requests are finished, lr is now parent */
682                         tmplr = lr;
683                         if (tmplr->lr_status == LDAP_REQST_COMPLETED) {
684                                 for ( tmplr=lr->lr_child;
685                                         tmplr != NULL;
686                                         tmplr=tmplr->lr_refnext)
687                                 {
688                                         if( tmplr->lr_status != LDAP_REQST_COMPLETED) break;
689                                 }
690                         }
691
692                         /* This is the parent request if the request has referrals */
693                         if ( lr->lr_outrefcnt <= 0 && lr->lr_parent == NULL &&
694                                 tmplr == NULL )
695                         {
696                                 id = lr->lr_msgid;
697                                 tag = lr->lr_res_msgtype;
698                                 Debug( LDAP_DEBUG_ANY, "request %ld done\n",
699                                     (long) id, 0, 0 );
700 Debug( LDAP_DEBUG_TRACE,
701 "res_errno: %d, res_error: <%s>, res_matched: <%s>\n",
702 lr->lr_res_errno, lr->lr_res_error ? lr->lr_res_error : "",
703 lr->lr_res_matched ? lr->lr_res_matched : "" );
704                                 if ( !simple_request ) {
705                                         ber_free( ber, 1 );
706                                         ber = NULL;
707                                         if ( build_result_ber( ld, &ber, lr )
708                                             == LBER_ERROR ) {
709                                                 rc = -1; /* fatal error */
710                                         }
711                                 }
712
713                                 ldap_free_request( ld, lr );
714                         }
715
716                         if ( lc != NULL ) {
717                                 ldap_free_connection( ld, lc, 0, 1 );
718                                 *lcp = NULL;
719                         }
720                 }
721         }
722
723         if ( ber == NULL ) {
724                 return( rc );
725         }
726
727         /* make a new ldap message */
728         if ( (new = (LDAPMessage *) LDAP_CALLOC( 1, sizeof(LDAPMessage) ))
729             == NULL ) {
730                 ld->ld_errno = LDAP_NO_MEMORY;
731                 return( -1 );
732         }
733         new->lm_msgid = (int)id;
734         new->lm_msgtype = tag;
735         new->lm_ber = ber;
736
737 #ifdef LDAP_CONNECTIONLESS
738         /* CLDAP replies all fit in a single datagram. In LDAPv2 RFC1798
739          * the responses are all a sequence wrapped in one message. In
740          * LDAPv3 each response is in its own message. The datagram must
741          * end with a SearchResult. We can't just parse each response in
742          * separate calls to try_read1msg because the header info is only
743          * present at the beginning of the datagram, not at the beginning
744          * of each response. So parse all the responses at once and queue
745          * them up, then pull off the first response to return to the
746          * caller when all parsing is complete.
747          */
748         if ( LDAP_IS_UDP(ld) ) {
749                 /* If not a result, look for more */
750                 if ( tag != LDAP_RES_SEARCH_RESULT ) {
751                         int ok = 0;
752                         moremsgs = 1;
753                         if (isv2) {
754                                 /* LDAPv2: dup the current ber, skip past the current
755                                  * response, and see if there are any more after it.
756                                  */
757                                 ber = ber_dup( ber );
758                                 ber_scanf( ber, "x" );
759                                 if (ber_peek_tag(ber, &len) != LBER_DEFAULT) {
760                                         /* There's more - dup the ber buffer so they can all be
761                                          * individually freed by ldap_msgfree.
762                                          */
763                                         struct berval bv;
764                                         ber_get_option(ber, LBER_OPT_BER_REMAINING_BYTES, &len);
765                                         bv.bv_val = LDAP_MALLOC(len);
766                                         if (bv.bv_val) {
767                                                 ok=1;
768                                                 ber_read(ber, bv.bv_val, len);
769                                                 bv.bv_len = len;
770                                                 ber_init2(ber, &bv, ld->ld_lberoptions );
771                                         }
772                                 }
773                         } else {
774                                 /* LDAPv3: Just allocate a new ber. Since this is a buffered
775                                  * datagram, if the sockbuf is readable we still have data
776                                  * to parse.
777                                  */
778                                 ber = ldap_alloc_ber_with_options(ld);
779                                 if (ber_sockbuf_ctrl(sb, LBER_SB_OPT_DATA_READY, NULL)) ok=1;
780                         }
781                         /* set up response chain */
782                         if ( firstmsg ) {
783                                 firstmsg = 0;
784                                 new->lm_next = ld->ld_responses;
785                                 ld->ld_responses = new;
786                                 new->lm_chain_tail = new;
787                                 chain_head = new;
788                         } else {
789                                 tmp->lm_chain = new;
790                                 chain_head->lm_chain_tail = tmp;
791                         }
792                         tmp = new;
793                         /* "ok" means there's more to parse */
794                         if (ok) {
795                                 if (isv2) goto nextresp2;
796                                 else goto nextresp3;
797                         } else {
798                                 /* got to end of datagram without a SearchResult. Free
799                                  * our dup'd ber, but leave any buffer alone. For v2 case,
800                                  * the previous response is still using this buffer. For v3,
801                                  * the new ber has no buffer to free yet.
802                                  */
803                                 ber_free(ber, 0);
804                                 return -1;
805                         }
806                 } else if ( moremsgs ) {
807                 /* got search result, and we had multiple responses in 1 datagram.
808                  * stick the result onto the end of the chain, and then pull the
809                  * first response off the head of the chain.
810                  */
811                         tmp->lm_chain = new;
812                         chain_head->lm_chain_tail = tmp;
813                         *result = chkResponseList( ld, msgid, all );
814                         ld->ld_errno = LDAP_SUCCESS;
815                         return( (*result)->lm_msgtype );
816                 }
817         }
818 #endif
819
820         /* is this the one we're looking for? */
821         if ( msgid == LDAP_RES_ANY || id == msgid ) {
822                 if ( all == LDAP_MSG_ONE
823                     || (new->lm_msgtype != LDAP_RES_SEARCH_RESULT
824                     && new->lm_msgtype != LDAP_RES_SEARCH_ENTRY
825                     && new->lm_msgtype != LDAP_RES_SEARCH_REFERENCE) ) {
826                         *result = new;
827                         ld->ld_errno = LDAP_SUCCESS;
828                         return( tag );
829                 } else if ( new->lm_msgtype == LDAP_RES_SEARCH_RESULT) {
830                         foundit = 1;    /* return the chain later */
831                 }
832         }
833
834         /* 
835          * if not, we must add it to the list of responses.  if
836          * the msgid is already there, it must be part of an existing
837          * search response.
838          */
839
840         prev = NULL;
841         for ( l = ld->ld_responses; l != NULL; l = l->lm_next ) {
842                 if ( l->lm_msgid == new->lm_msgid )
843                         break;
844                 prev = l;
845         }
846
847         /* not part of an existing search response */
848         if ( l == NULL ) {
849                 if ( foundit ) {
850                         *result = new;
851                         goto exit;
852                 }
853
854                 new->lm_next = ld->ld_responses;
855                 ld->ld_responses = new;
856                 new->lm_chain_tail = new;
857                 goto exit;
858         }
859
860         Debug( LDAP_DEBUG_TRACE, "adding response id %ld type %ld:\n",
861             (long) new->lm_msgid, (long) new->lm_msgtype, 0 );
862
863         /* part of a search response - add to end of list of entries */
864         if (l->lm_chain == NULL) {
865                 assert(l->lm_chain_tail == l);
866                 l->lm_chain = new;
867         } else {
868                 assert(l->lm_chain_tail);
869                 assert(l->lm_chain_tail->lm_chain);
870                 if ((l->lm_chain_tail->lm_chain->lm_msgtype
871                                 == LDAP_RES_SEARCH_ENTRY) ||
872                         (l->lm_chain_tail->lm_chain->lm_msgtype
873                                 == LDAP_RES_SEARCH_REFERENCE) ||
874                         (l->lm_chain_tail->lm_chain->lm_msgtype
875                                 == LDAP_RES_INTERMEDIATE)) {
876                         l->lm_chain_tail->lm_chain->lm_chain = new;
877                         l->lm_chain_tail = l->lm_chain_tail->lm_chain;
878                 } else {
879                         /*FIXME: ldap_msgfree( l->lm_chain_tail->lm_chain );*/
880                         l->lm_chain_tail->lm_chain = new;
881                 }
882         }
883
884         /* return the whole chain if that's what we were looking for */
885         if ( foundit ) {
886                 if ( prev == NULL )
887                         ld->ld_responses = l->lm_next;
888                 else
889                         prev->lm_next = l->lm_next;
890                 *result = l;
891         }
892
893 exit:
894         if ( foundit ) {
895                 ld->ld_errno = LDAP_SUCCESS;
896                 return( tag );
897         }
898         if ( ber_sockbuf_ctrl( sb, LBER_SB_OPT_DATA_READY, NULL ) ) {
899                 goto retry;
900         }
901         return( -2 );   /* continue looking */
902 }
903
904
905 static ber_tag_t
906 build_result_ber( LDAP *ld, BerElement **bp, LDAPRequest *lr )
907 {
908         ber_len_t       len;
909         ber_tag_t       tag;
910         ber_int_t       along;
911         BerElement *ber;
912
913         *bp = NULL;
914         ber = ldap_alloc_ber_with_options( ld );
915
916         if( ber == NULL ) {
917                 ld->ld_errno = LDAP_NO_MEMORY;
918                 return LBER_ERROR;
919         }
920
921         if ( ber_printf( ber, "{it{ess}}", lr->lr_msgid,
922             lr->lr_res_msgtype, lr->lr_res_errno,
923             lr->lr_res_matched ? lr->lr_res_matched : "",
924             lr->lr_res_error ? lr->lr_res_error : "" ) == -1 ) {
925
926                 ld->ld_errno = LDAP_ENCODING_ERROR;
927                 ber_free(ber, 1);
928                 return( LBER_ERROR );
929         }
930
931         ber_reset( ber, 1 );
932
933         if ( ber_skip_tag( ber, &len ) == LBER_ERROR ) {
934                 ld->ld_errno = LDAP_DECODING_ERROR;
935                 ber_free(ber, 1);
936                 return( LBER_ERROR );
937         }
938
939         if ( ber_get_int( ber, &along ) == LBER_ERROR ) {
940                 ld->ld_errno = LDAP_DECODING_ERROR;
941                 ber_free(ber, 1);
942                 return( LBER_ERROR );
943         }
944
945         tag = ber_peek_tag( ber, &len );
946
947         if ( tag == LBER_ERROR ) {
948                 ld->ld_errno = LDAP_DECODING_ERROR;
949                 ber_free(ber, 1);
950                 return( LBER_ERROR );
951         }
952
953         *bp = ber;
954         return tag;
955 }
956
957
958 static void
959 merge_error_info( LDAP *ld, LDAPRequest *parentr, LDAPRequest *lr )
960 {
961 /*
962  * Merge error information in "lr" with "parentr" error code and string.
963  */
964         if ( lr->lr_res_errno == LDAP_PARTIAL_RESULTS ) {
965                 parentr->lr_res_errno = lr->lr_res_errno;
966                 if ( lr->lr_res_error != NULL ) {
967                         (void)ldap_append_referral( ld, &parentr->lr_res_error,
968                             lr->lr_res_error );
969                 }
970         } else if ( lr->lr_res_errno != LDAP_SUCCESS &&
971             parentr->lr_res_errno == LDAP_SUCCESS ) {
972                 parentr->lr_res_errno = lr->lr_res_errno;
973                 if ( parentr->lr_res_error != NULL ) {
974                         LDAP_FREE( parentr->lr_res_error );
975                 }
976                 parentr->lr_res_error = lr->lr_res_error;
977                 lr->lr_res_error = NULL;
978                 if ( LDAP_NAME_ERROR( lr->lr_res_errno )) {
979                         if ( parentr->lr_res_matched != NULL ) {
980                                 LDAP_FREE( parentr->lr_res_matched );
981                         }
982                         parentr->lr_res_matched = lr->lr_res_matched;
983                         lr->lr_res_matched = NULL;
984                 }
985         }
986
987         Debug( LDAP_DEBUG_TRACE, "merged parent (id %d) error info:  ",
988             parentr->lr_msgid, 0, 0 );
989         Debug( LDAP_DEBUG_TRACE, "result errno %d, error <%s>, matched <%s>\n",
990             parentr->lr_res_errno, parentr->lr_res_error ?
991             parentr->lr_res_error : "", parentr->lr_res_matched ?
992             parentr->lr_res_matched : "" );
993 }
994
995
996
997 int
998 ldap_msgtype( LDAPMessage *lm )
999 {
1000         assert( lm != NULL );
1001         return ( lm != NULL ) ? lm->lm_msgtype : -1;
1002 }
1003
1004
1005 int
1006 ldap_msgid( LDAPMessage *lm )
1007 {
1008         assert( lm != NULL );
1009
1010         return ( lm != NULL ) ? lm->lm_msgid : -1;
1011 }
1012
1013
1014 char * ldap_int_msgtype2str( ber_tag_t tag )
1015 {
1016         switch( tag ) {
1017         case LDAP_RES_ADD: return "add";
1018         case LDAP_RES_BIND: return "bind";
1019         case LDAP_RES_COMPARE: return "compare";
1020         case LDAP_RES_DELETE: return "delete";
1021         case LDAP_RES_EXTENDED: return "extended-result";
1022         case LDAP_RES_INTERMEDIATE: return "intermediate";
1023         case LDAP_RES_MODIFY: return "modify";
1024         case LDAP_RES_RENAME: return "rename";
1025         case LDAP_RES_SEARCH_ENTRY: return "search-entry";
1026         case LDAP_RES_SEARCH_REFERENCE: return "search-reference";
1027         case LDAP_RES_SEARCH_RESULT: return "search-result";
1028         }
1029         return "unknown";
1030 }
1031
1032 int
1033 ldap_msgfree( LDAPMessage *lm )
1034 {
1035         LDAPMessage     *next;
1036         int             type = 0;
1037
1038         Debug( LDAP_DEBUG_TRACE, "ldap_msgfree\n", 0, 0, 0 );
1039
1040         for ( ; lm != NULL; lm = next ) {
1041                 next = lm->lm_chain;
1042                 type = lm->lm_msgtype;
1043                 ber_free( lm->lm_ber, 1 );
1044                 LDAP_FREE( (char *) lm );
1045         }
1046
1047         return( type );
1048 }
1049
1050 /*
1051  * ldap_msgdelete - delete a message.  It returns:
1052  *      0       if the entire message was deleted
1053  *      -1      if the message was not found, or only part of it was found
1054  */
1055 int
1056 ldap_msgdelete( LDAP *ld, int msgid )
1057 {
1058         LDAPMessage     *lm, *prev;
1059         int rc = 0;
1060
1061         assert( ld != NULL );
1062
1063         Debug( LDAP_DEBUG_TRACE, "ldap_msgdelete\n", 0, 0, 0 );
1064
1065         prev = NULL;
1066 #ifdef LDAP_R_COMPILE
1067         ldap_pvt_thread_mutex_lock( &ld->ld_res_mutex );
1068 #endif
1069         for ( lm = ld->ld_responses; lm != NULL; lm = lm->lm_next ) {
1070                 if ( lm->lm_msgid == msgid )
1071                         break;
1072                 prev = lm;
1073         }
1074
1075         if ( lm == NULL ) {
1076                 rc = -1;
1077         } else {
1078                 if ( prev == NULL )
1079                         ld->ld_responses = lm->lm_next;
1080                 else
1081                         prev->lm_next = lm->lm_next;
1082         }
1083 #ifdef LDAP_R_COMPILE
1084         ldap_pvt_thread_mutex_unlock( &ld->ld_res_mutex );
1085 #endif
1086         if ( lm && ldap_msgfree( lm ) == LDAP_RES_SEARCH_ENTRY )
1087                 rc = -1;
1088
1089         return( rc );
1090 }
1091
1092
1093 /*
1094  * return 1 if message msgid is waiting to be abandoned, 0 otherwise
1095  */
1096 static int
1097 ldap_abandoned( LDAP *ld, ber_int_t msgid )
1098 {
1099         int     i;
1100
1101         if ( ld->ld_abandoned == NULL )
1102                 return( 0 );
1103
1104         for ( i = 0; ld->ld_abandoned[i] != -1; i++ )
1105                 if ( ld->ld_abandoned[i] == msgid )
1106                         return( 1 );
1107
1108         return( 0 );
1109 }
1110
1111
1112 static int
1113 ldap_mark_abandoned( LDAP *ld, ber_int_t msgid )
1114 {
1115         int     i;
1116
1117         if ( ld->ld_abandoned == NULL )
1118                 return( -1 );
1119
1120         for ( i = 0; ld->ld_abandoned[i] != -1; i++ )
1121                 if ( ld->ld_abandoned[i] == msgid )
1122                         break;
1123
1124         if ( ld->ld_abandoned[i] == -1 )
1125                 return( -1 );
1126
1127         for ( ; ld->ld_abandoned[i] != -1; i++ ) {
1128                 ld->ld_abandoned[i] = ld->ld_abandoned[i + 1];
1129         }
1130
1131         return( 0 );
1132 }