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