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