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