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