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