]> git.sur5r.net Git - openldap/blob - libraries/libldap/result.c
Fix encoding
[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-2006 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 #define LDAP_MSG_X_KEEP_LOOKING         (-2)
82
83
84 /*
85  * ldap_result - wait for an ldap result response to a message from the
86  * ldap server.  If msgid is LDAP_RES_ANY (-1), any message will be
87  * accepted.  If msgid is LDAP_RES_UNSOLICITED (0), any unsolicited
88  * message is accepted.  Otherwise ldap_result will wait for a response
89  * with msgid.  If all is LDAP_MSG_ONE (0) the first message with id
90  * msgid will be accepted, otherwise, ldap_result will wait for all
91  * responses with id msgid and then return a pointer to the entire list
92  * of messages.  In general, this is only useful for search responses,
93  * which can be of three message types (zero or more entries, zero or
94  * search references, followed by an ldap result).  An extension to
95  * LDAPv3 allows partial extended responses to be returned in response
96  * to any request.  The type of the first message received is returned.
97  * When waiting, any messages that have been abandoned are discarded.
98  *
99  * Example:
100  *      ldap_result( s, msgid, all, timeout, result )
101  */
102 int
103 ldap_result(
104         LDAP *ld,
105         int msgid,
106         int all,
107         struct timeval *timeout,
108         LDAPMessage **result )
109 {
110         LDAPMessage     *lm;
111         int     rc;
112
113         assert( ld != NULL );
114         assert( result != NULL );
115
116         Debug( LDAP_DEBUG_TRACE, "ldap_result ld %p msgid %d\n", (void *)ld, msgid, 0 );
117
118 #ifdef LDAP_R_COMPILE
119         ldap_pvt_thread_mutex_lock( &ld->ld_res_mutex );
120 #endif
121         lm = chkResponseList(ld, msgid, all);
122
123         if ( lm == NULL ) {
124                 rc = wait4msg( ld, msgid, all, timeout, result );
125         } else {
126                 *result = lm;
127                 ld->ld_errno = LDAP_SUCCESS;
128                 rc = lm->lm_msgtype;
129         }
130 #ifdef LDAP_R_COMPILE
131         ldap_pvt_thread_mutex_unlock( &ld->ld_res_mutex );
132 #endif
133         return( rc );
134 }
135
136 static LDAPMessage *
137 chkResponseList(
138         LDAP *ld,
139         int msgid,
140         int all)
141 {
142         LDAPMessage     *lm, **lastlm, *nextlm;
143     /*
144          * Look through the list of responses we have received on
145          * this association and see if the response we're interested in
146          * is there.  If it is, return it.  If not, call wait4msg() to
147          * wait until it arrives or timeout occurs.
148          */
149
150         Debug( LDAP_DEBUG_TRACE,
151                 "ldap_chkResponseList ld %p msgid %d all %d\n",
152                 (void *)ld, msgid, all );
153         lastlm = &ld->ld_responses;
154         for ( lm = ld->ld_responses; lm != NULL; lm = nextlm ) {
155                 nextlm = lm->lm_next;
156
157                 if ( ldap_abandoned( ld, lm->lm_msgid ) ) {
158                         Debug( LDAP_DEBUG_TRACE,
159                                 "ldap_chkResponseList msg abandoned, msgid %d\n",
160                             msgid, 0, 0 );
161                         ldap_mark_abandoned( ld, lm->lm_msgid );
162
163                         /* Remove this entry from list */
164                         *lastlm = nextlm;
165
166                         ldap_msgfree( lm );
167
168                         continue;
169                 }
170
171                 if ( msgid == LDAP_RES_ANY || lm->lm_msgid == msgid ) {
172                         LDAPMessage     *tmp;
173
174                         if ( all == LDAP_MSG_ONE || all == LDAP_MSG_RECEIVED ||
175                                 msgid == LDAP_RES_UNSOLICITED ) {
176                                 break;
177                         }
178
179                         tmp = lm->lm_chain_tail;
180                         if ((tmp->lm_msgtype == LDAP_RES_SEARCH_ENTRY) ||
181                                 (tmp->lm_msgtype == LDAP_RES_SEARCH_REFERENCE) ||
182                                 (tmp->lm_msgtype == LDAP_RES_INTERMEDIATE)) {
183                                 tmp = NULL;
184                         }
185
186                         if ( tmp == NULL ) {
187                                 lm = NULL;
188                         }
189
190                         break;
191                 }
192                 lastlm = &lm->lm_next;
193         }
194
195     if ( lm != NULL ) {
196                 /* Found an entry, remove it from the list */
197             if ( all == LDAP_MSG_ONE && lm->lm_chain != NULL ) {
198                         *lastlm = lm->lm_chain;
199                         lm->lm_chain->lm_next = lm->lm_next;
200                         lm->lm_chain->lm_chain_tail = ( lm->lm_chain_tail != lm ) ? lm->lm_chain_tail : lm->lm_chain;
201                         lm->lm_chain = NULL;
202                         lm->lm_chain_tail = NULL;
203             } else {
204                         *lastlm = lm->lm_next;
205                 }
206             lm->lm_next = NULL;
207     }
208
209 #ifdef LDAP_DEBUG
210         if( lm == NULL) {
211                 Debug( LDAP_DEBUG_TRACE,
212                         "ldap_chkResponseList returns ld %p NULL\n", (void *)ld, 0, 0);
213         } else {
214                 Debug( LDAP_DEBUG_TRACE,
215                         "ldap_chkResponseList returns ld %p msgid %d, type 0x%02lu\n",
216                         (void *)ld, lm->lm_msgid, (unsigned long) lm->lm_msgtype);
217         }
218 #endif
219     return lm;
220 }
221
222 static int
223 wait4msg(
224         LDAP *ld,
225         ber_int_t msgid,
226         int all,
227         struct timeval *timeout,
228         LDAPMessage **result )
229 {
230         int             rc;
231         struct timeval  tv = { 0 },
232                         tv0 = { 0 },
233                         *tvp;
234         time_t          start_time = 0;
235         time_t          tmp_time;
236         LDAPConn        *lc, *nextlc;
237
238         assert( ld != NULL );
239         assert( result != NULL );
240
241 #ifdef LDAP_DEBUG
242         if ( timeout == NULL ) {
243                 Debug( LDAP_DEBUG_TRACE, "wait4msg ld %p msgid %d (infinite timeout)\n",
244                         (void *)ld, msgid, 0 );
245         } else {
246                 Debug( LDAP_DEBUG_TRACE, "wait4msg ld %p msgid %d (timeout %ld usec)\n",
247                         (void *)ld, msgid, (long)timeout->tv_sec * 1000000 + timeout->tv_usec );
248         }
249 #endif /* LDAP_DEBUG */
250
251         if ( timeout == NULL ) {
252                 tvp = NULL;
253         } else {
254                 tv0 = *timeout;
255                 tv = *timeout;
256                 tvp = &tv;
257                 start_time = time( NULL );
258         }
259                     
260         rc = LDAP_MSG_X_KEEP_LOOKING;
261         while ( rc == LDAP_MSG_X_KEEP_LOOKING ) {
262 #ifdef LDAP_DEBUG
263                 if ( ldap_debug & LDAP_DEBUG_TRACE ) {
264                         Debug( LDAP_DEBUG_TRACE, "wait4msg continue ld %p msgid %d all %d\n",
265                                 (void *)ld, msgid, all );
266                         ldap_dump_connection( ld, ld->ld_conns, 1 );
267                         ldap_dump_requests_and_responses( ld );
268                 }
269 #endif /* LDAP_DEBUG */
270
271                 if ( (*result = chkResponseList(ld, msgid, all)) != NULL ) {
272                         rc = (*result)->lm_msgtype;
273
274                 } else {
275                         int lc_ready = 0;
276
277 #ifdef LDAP_R_COMPILE
278                         ldap_pvt_thread_mutex_lock( &ld->ld_conn_mutex );
279 #endif
280                         for ( lc = ld->ld_conns; lc != NULL; lc = nextlc ) {
281                                 nextlc = lc->lconn_next;
282                                 if ( ber_sockbuf_ctrl( lc->lconn_sb,
283                                                 LBER_SB_OPT_DATA_READY, NULL ) ) {
284 #ifdef LDAP_R_COMPILE
285                                         ldap_pvt_thread_mutex_unlock( &ld->ld_conn_mutex );
286 #endif
287                                         rc = try_read1msg( ld, msgid, all, lc->lconn_sb,
288                                                 &lc, result );
289 #ifdef LDAP_R_COMPILE
290                                         ldap_pvt_thread_mutex_lock( &ld->ld_conn_mutex );
291 #endif
292                                         lc_ready = 1;
293                                         break;
294                                 }
295                         }
296 #ifdef LDAP_R_COMPILE
297                         ldap_pvt_thread_mutex_unlock( &ld->ld_conn_mutex );
298 #endif
299
300                         if ( !lc_ready ) {
301                                 rc = ldap_int_select( ld, tvp );
302 #ifdef LDAP_DEBUG
303                                 if ( rc == -1 ) {
304                                         Debug( LDAP_DEBUG_TRACE,
305                                                 "ldap_int_select returned -1: errno %d\n",
306                                                 errno, 0, 0 );
307                                 }
308 #endif
309
310                                 if ( rc == 0 || ( rc == -1 && (
311                                         !LDAP_BOOL_GET(&ld->ld_options, LDAP_BOOL_RESTART)
312                                                 || errno != EINTR )))
313                                 {
314                                         ld->ld_errno = (rc == -1 ? LDAP_SERVER_DOWN :
315                                                 LDAP_TIMEOUT);
316                                         return( rc );
317                                 }
318
319                                 if ( rc == -1 ) {
320                                         rc = LDAP_MSG_X_KEEP_LOOKING;   /* select interrupted: loop */
321                                 } else {
322                                         rc = LDAP_MSG_X_KEEP_LOOKING;
323 #ifdef LDAP_R_COMPILE
324                                         ldap_pvt_thread_mutex_lock( &ld->ld_req_mutex );
325 #endif
326                                         if ( ld->ld_requests &&
327                                                 ld->ld_requests->lr_status == LDAP_REQST_WRITING &&
328                                                 ldap_is_write_ready( ld,
329                                                         ld->ld_requests->lr_conn->lconn_sb ) )
330                                         {
331                                                 ldap_int_flush_request( ld, ld->ld_requests );
332                                         }
333 #ifdef LDAP_R_COMPILE
334                                         ldap_pvt_thread_mutex_unlock( &ld->ld_req_mutex );
335                                         ldap_pvt_thread_mutex_lock( &ld->ld_conn_mutex );
336 #endif
337                                         for ( lc = ld->ld_conns; rc == LDAP_MSG_X_KEEP_LOOKING && lc != NULL;
338                                                 lc = nextlc )
339                                         {
340                                                 nextlc = lc->lconn_next;
341                                                 if ( lc->lconn_status == LDAP_CONNST_CONNECTED &&
342                                                         ldap_is_read_ready( ld, lc->lconn_sb ))
343                                                 {
344 #ifdef LDAP_R_COMPILE
345                                                         ldap_pvt_thread_mutex_unlock( &ld->ld_conn_mutex );
346 #endif
347                                                         rc = try_read1msg( ld, msgid, all,
348                                                                 lc->lconn_sb, &lc, result );
349                                                                 if ( lc == NULL ) lc = nextlc;
350 #ifdef LDAP_R_COMPILE
351                                                         ldap_pvt_thread_mutex_lock( &ld->ld_conn_mutex );
352 #endif
353                                                 }
354                                         }
355 #ifdef LDAP_R_COMPILE
356                                         ldap_pvt_thread_mutex_unlock( &ld->ld_conn_mutex );
357 #endif
358                                 }
359                         }
360                 }
361
362                 if ( rc == LDAP_MSG_X_KEEP_LOOKING && tvp != NULL ) {
363                         tmp_time = time( NULL );
364                         tv0.tv_sec -= ( tmp_time - start_time );
365                         if ( tv0.tv_sec <= 0 ) {
366                                 rc = 0; /* timed out */
367                                 ld->ld_errno = LDAP_TIMEOUT;
368                                 break;
369                         }
370                         tv.tv_sec = tv0.tv_sec;
371
372                         Debug( LDAP_DEBUG_TRACE, "wait4msg ld %p %ld secs to go\n",
373                                 (void *)ld, (long) tv.tv_sec, 0 );
374                         start_time = tmp_time;
375                 }
376         }
377
378         return( rc );
379 }
380
381
382 static ber_tag_t
383 try_read1msg(
384         LDAP *ld,
385         ber_int_t msgid,
386         int all,
387         Sockbuf *sb,
388         LDAPConn **lcp,
389         LDAPMessage **result )
390 {
391         BerElement      *ber;
392         LDAPMessage     *newmsg, *l, *prev;
393         ber_int_t       id;
394         ber_tag_t       tag;
395         ber_len_t       len;
396         int             foundit = 0;
397         LDAPRequest     *lr, *tmplr;
398         LDAPConn        *lc;
399         BerElement      tmpber;
400         int             rc, refer_cnt, hadref, simple_request;
401         ber_int_t       lderr;
402
403 #ifdef LDAP_CONNECTIONLESS
404         LDAPMessage     *tmp = NULL, *chain_head = NULL;
405         int             moremsgs = 0, isv2 = 0;
406 #endif
407
408         /*
409          * v3ref = flag for V3 referral / search reference
410          * 0 = not a ref, 1 = sucessfully chased ref, -1 = pass ref to application
411          */
412         enum {
413                 V3REF_NOREF     = 0,
414                 V3REF_SUCCESS   = 1,
415                 V3REF_TOAPP     = -1
416         }       v3ref;
417
418         assert( ld != NULL );
419         assert( lcp != NULL );
420         assert( *lcp != NULL );
421         
422         Debug( LDAP_DEBUG_TRACE, "read1msg: ld %p msgid %d all %d\n",
423                 (void *)ld, msgid, all );
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 LDAP_MSG_X_KEEP_LOOKING;
465 #endif
466 #ifdef EAGAIN
467                         if (errno == EAGAIN) return LDAP_MSG_X_KEEP_LOOKING;
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 ld %p msgid %ld\n",
486                         (void *)ld, (long) id, 0);
487 retry_ber:
488                 ber_free( ber, 1 );
489                 if ( ber_sockbuf_ctrl( sb, LBER_SB_OPT_DATA_READY, NULL ) ) {
490                         goto retry;
491                 }
492                 return( LDAP_MSG_X_KEEP_LOOKING );      /* continue looking */
493         }
494
495         lr = ldap_find_request_by_msgid( ld, id );
496         if ( lr == NULL ) {
497                 Debug( LDAP_DEBUG_ANY,
498                         "no request for response on ld %p msgid %ld (tossing)\n",
499                         (void *)ld, (long) id, 0 );
500                 goto retry_ber;
501         }
502 #ifdef LDAP_CONNECTIONLESS
503         if (LDAP_IS_UDP(ld) && isv2) {
504                 ber_scanf(ber, "x{");
505         }
506 nextresp2:
507 #endif
508         /* the message type */
509         if ( (tag = ber_peek_tag( ber, &len )) == LBER_ERROR ) {
510                 ld->ld_errno = LDAP_DECODING_ERROR;
511                 ber_free( ber, 1 );
512                 return( -1 );
513         }
514
515         Debug( LDAP_DEBUG_TRACE,
516                 "read1msg: ld %p msgid %ld message type %s\n",
517                 (void *)ld, (long) lr->lr_msgid, ldap_int_msgtype2str( tag ));
518
519         id = lr->lr_origid;
520         refer_cnt = 0;
521         hadref = simple_request = 0;
522         rc = LDAP_MSG_X_KEEP_LOOKING;   /* 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                                         {
577                                                 if ( lr->lr_res_error != NULL ) {
578                                                         (void)ldap_append_referral( ld, &lr->lr_res_error, lr_res_error );
579                                                         LDAP_FREE( (char *)lr_res_error );
580
581                                                 } else {
582                                                         lr->lr_res_error = lr_res_error;
583                                                 }
584                                         }
585                                         lr_res_error = NULL;
586                                 }
587
588                                 /* Check if V3 referral */
589                                 if ( ber_peek_tag( &tmpber, &len ) == LDAP_TAG_REFERRAL ) {
590                                         /* We have a V3 referral, assume we cannot chase it */
591                                         v3ref = V3REF_TOAPP;
592                                         if( LDAP_BOOL_GET(&ld->ld_options, LDAP_BOOL_REFERRALS)
593                                                          || (lr->lr_parent != NULL) )
594                                         {
595                                                 /* Assume referral not chased and return it to app */
596                                                 v3ref = V3REF_TOAPP;
597
598                                                 /* Get the referral list */
599                                                 if( ber_scanf( &tmpber, "{v}", &refs) == LBER_ERROR) {
600                                                         rc = LDAP_DECODING_ERROR;
601                                                         lr->lr_status = LDAP_REQST_COMPLETED;
602                                                         Debug( LDAP_DEBUG_TRACE,
603                                                                 "read1msg: referral decode error, mark request completed, ld %p msgid %d\n",
604                                                                 (void *)ld, lr->lr_msgid, 0);
605                                                 } else {
606                                                         /* Chase the referral 
607                                                          * Note: refs arrary is freed by ldap_chase_v3referrals
608                                                          */
609                                                         refer_cnt = ldap_chase_v3referrals( ld, lr, refs,
610                                                             0, &lr->lr_res_error, &hadref );
611                                                         lr->lr_status = LDAP_REQST_COMPLETED;
612                                                         Debug( LDAP_DEBUG_TRACE,
613                                                                 "read1msg: referral chased, mark request completed, ld %p msgid %d\n",
614                                                                 (void *)ld, lr->lr_msgid, 0);
615                                                         if( refer_cnt > 0) {
616                                                                 /* Referral successfully chased */
617                                                                 v3ref = V3REF_SUCCESS;
618                                                         }
619                                                 }
620                                         }
621                                 }
622
623                                 if( lr->lr_res_matched != NULL ) {
624                                         LDAP_FREE( lr->lr_res_matched );
625                                         lr->lr_res_matched = NULL;
626                                 }
627                                 if( lr->lr_res_error != NULL ) {
628                                         LDAP_FREE( lr->lr_res_error );
629                                         lr->lr_res_error = NULL;
630                                 }
631                         }
632                 }
633         }
634
635         /* All results that just return a status, i.e. don't return data
636          * go through the following code.  This code also chases V2 referrals
637          * and checks if all referrals have been chased.
638          */
639         if ( (tag != LDAP_RES_SEARCH_ENTRY) && (v3ref != V3REF_TOAPP) &&
640                 (tag != LDAP_RES_INTERMEDIATE ))
641         {
642                 /* For a v3 search referral/reference, only come here if already chased it */
643                 if ( ld->ld_version >= LDAP_VERSION2 &&
644                         ( lr->lr_parent != NULL ||
645                         LDAP_BOOL_GET(&ld->ld_options, LDAP_BOOL_REFERRALS) ) )
646                 {
647                         char            *lr_res_error = NULL;
648
649                         tmpber = *ber;  /* struct copy */
650                         if ( v3ref == V3REF_SUCCESS ) {
651                                 /* V3 search reference or V3 referral
652                                  * sucessfully chased. If this message
653                                  * is a search result, then it has no more
654                                  * outstanding referrals.
655                                  */
656                                 if ( tag == LDAP_RES_SEARCH_RESULT )
657                                         refer_cnt = 0;
658                         } else if ( ber_scanf( &tmpber, "{eAA}", &lderr,
659                                 &lr->lr_res_matched, &lr_res_error )
660                                 != LBER_ERROR )
661                         {
662                                 if ( lr_res_error != NULL ) {
663                                         {
664                                                 if ( lr->lr_res_error != NULL ) {
665                                                         (void)ldap_append_referral( ld, &lr->lr_res_error, lr_res_error );
666                                                         LDAP_FREE( (char *)lr_res_error );
667                                                 } else {
668                                                         lr->lr_res_error = lr_res_error;
669                                                 }
670                                         }
671                                         lr_res_error = NULL;
672                                 }
673
674                                 switch ( lderr ) {
675                                 case LDAP_SUCCESS:
676                                 case LDAP_COMPARE_TRUE:
677                                 case LDAP_COMPARE_FALSE:
678                                         break;
679
680                                 default:
681                                         if ( lr->lr_res_error == NULL
682                                                 || lr->lr_res_error[ 0 ] == '\0' )
683                                         {
684                                                 break;
685                                         }
686
687                                         /* referrals are in error string */
688                                         refer_cnt = ldap_chase_referrals( ld, lr,
689                                                 &lr->lr_res_error, -1, &hadref );
690                                         lr->lr_status = LDAP_REQST_COMPLETED;
691                                         Debug( LDAP_DEBUG_TRACE,
692                                                 "read1msg:  V2 referral chased, "
693                                                 "mark request completed, id = %d\n",
694                                                 lr->lr_msgid, 0, 0 );
695                                         break;
696                                 }
697
698                                 /* save errno, message, and matched string */
699                                 if ( !hadref || lr->lr_res_error == NULL ) {
700                                         lr->lr_res_errno = ( lderr ==
701                                         LDAP_PARTIAL_RESULTS ) ? LDAP_SUCCESS
702                                         : lderr;
703                                 } else if ( ld->ld_errno != LDAP_SUCCESS ) {
704                                         lr->lr_res_errno = ld->ld_errno;
705                                 } else {
706                                         lr->lr_res_errno = LDAP_PARTIAL_RESULTS;
707                                 }
708
709                                 Debug( LDAP_DEBUG_TRACE, "new result:  "
710                                         "res_errno: %d, "
711                                         "res_error: <%s>, "
712                                         "res_matched: <%s>\n",
713                                         lr->lr_res_errno,
714                                         lr->lr_res_error ? lr->lr_res_error : "",
715                                         lr->lr_res_matched ? lr->lr_res_matched : "" );
716                         }
717
718                         /* in any case, don't leave any lr_res_error 'round */
719                         if ( lr_res_error ) {
720                                 LDAP_FREE( lr_res_error );
721                         }
722                 }
723
724                 Debug( LDAP_DEBUG_TRACE,
725                         "read1msg: ld %p %d new referrals\n",
726                         (void *)ld, refer_cnt, 0 );
727
728                 if ( refer_cnt != 0 ) { /* chasing referrals */
729                         ber_free( ber, 1 );
730                         ber = NULL;
731                         if ( refer_cnt < 0 ) {
732                                 return( -1 );   /* fatal error */
733                         }
734                         lr->lr_res_errno = LDAP_SUCCESS; /* sucessfully chased referral */
735                 } else {
736                         if ( lr->lr_outrefcnt <= 0 && lr->lr_parent == NULL ) {
737                                 /* request without any referrals */
738                                 simple_request = ( hadref ? 0 : 1 );
739                         } else {
740                                 /* request with referrals or child request */
741                                 ber_free( ber, 1 );
742                                 ber = NULL;
743                         }
744
745                         lr->lr_status = LDAP_REQST_COMPLETED; /* declare this request done */
746                         Debug( LDAP_DEBUG_TRACE,
747                                 "read1msg:  mark request completed, ld %p msgid %d\n",
748                                 (void *)ld, lr->lr_msgid, 0);
749                         while ( lr->lr_parent != NULL ) {
750                                 merge_error_info( ld, lr->lr_parent, lr );
751
752                                 lr = lr->lr_parent;
753                                 if ( --lr->lr_outrefcnt > 0 ) {
754                                         break;  /* not completely done yet */
755                                 }
756                         }
757
758                         /* Check if all requests are finished, lr is now parent */
759                         tmplr = lr;
760                         if (tmplr->lr_status == LDAP_REQST_COMPLETED) {
761                                 for ( tmplr=lr->lr_child;
762                                         tmplr != NULL;
763                                         tmplr=tmplr->lr_refnext)
764                                 {
765                                         if( tmplr->lr_status != LDAP_REQST_COMPLETED) break;
766                                 }
767                         }
768
769                         /* This is the parent request if the request has referrals */
770                         if ( lr->lr_outrefcnt <= 0 && lr->lr_parent == NULL &&
771                                 tmplr == NULL )
772                         {
773                                 id = lr->lr_msgid;
774                                 tag = lr->lr_res_msgtype;
775                                 Debug( LDAP_DEBUG_ANY, "request done: ld %p msgid %ld\n",
776                                         (void *)ld, (long) id, 0 );
777 Debug( LDAP_DEBUG_TRACE,
778 "res_errno: %d, res_error: <%s>, res_matched: <%s>\n",
779 lr->lr_res_errno, lr->lr_res_error ? lr->lr_res_error : "",
780 lr->lr_res_matched ? lr->lr_res_matched : "" );
781                                 if ( !simple_request ) {
782                                         ber_free( ber, 1 );
783                                         ber = NULL;
784                                         if ( build_result_ber( ld, &ber, lr )
785                                             == LBER_ERROR ) {
786                                                 rc = -1; /* fatal error */
787                                         }
788                                 }
789
790 #ifdef LDAP_R_COMPILE
791                                 ldap_pvt_thread_mutex_lock( &ld->ld_req_mutex );
792 #endif
793                                 ldap_free_request( ld, lr );
794 #ifdef LDAP_R_COMPILE
795                                 ldap_pvt_thread_mutex_unlock( &ld->ld_req_mutex );
796 #endif
797                         }
798
799                         if ( lc != NULL ) {
800 #ifdef LDAP_R_COMPILE
801                                 ldap_pvt_thread_mutex_lock( &ld->ld_req_mutex );
802 #endif
803                                 ldap_free_connection( ld, lc, 0, 1 );
804 #ifdef LDAP_R_COMPILE
805                                 ldap_pvt_thread_mutex_unlock( &ld->ld_req_mutex );
806 #endif
807                                 *lcp = NULL;
808                         }
809                 }
810         }
811
812         if ( ber == NULL ) {
813                 return( rc );
814         }
815
816         /* make a new ldap message */
817         newmsg = (LDAPMessage *) LDAP_CALLOC( 1, sizeof(LDAPMessage) );
818         if ( newmsg == NULL ) {
819                 ld->ld_errno = LDAP_NO_MEMORY;
820                 return( -1 );
821         }
822         newmsg->lm_msgid = (int)id;
823         newmsg->lm_msgtype = tag;
824         newmsg->lm_ber = ber;
825         newmsg->lm_chain_tail = newmsg;
826
827 #ifdef LDAP_CONNECTIONLESS
828         /* CLDAP replies all fit in a single datagram. In LDAPv2 RFC1798
829          * the responses are all a sequence wrapped in one message. In
830          * LDAPv3 each response is in its own message. The datagram must
831          * end with a SearchResult. We can't just parse each response in
832          * separate calls to try_read1msg because the header info is only
833          * present at the beginning of the datagram, not at the beginning
834          * of each response. So parse all the responses at once and queue
835          * them up, then pull off the first response to return to the
836          * caller when all parsing is complete.
837          */
838         if ( LDAP_IS_UDP(ld) ) {
839                 /* If not a result, look for more */
840                 if ( tag != LDAP_RES_SEARCH_RESULT ) {
841                         int ok = 0;
842                         moremsgs = 1;
843                         if (isv2) {
844                                 /* LDAPv2: dup the current ber, skip past the current
845                                  * response, and see if there are any more after it.
846                                  */
847                                 ber = ber_dup( ber );
848                                 ber_scanf( ber, "x" );
849                                 if (ber_peek_tag(ber, &len) != LBER_DEFAULT) {
850                                         /* There's more - dup the ber buffer so they can all be
851                                          * individually freed by ldap_msgfree.
852                                          */
853                                         struct berval bv;
854                                         ber_get_option(ber, LBER_OPT_BER_REMAINING_BYTES, &len);
855                                         bv.bv_val = LDAP_MALLOC(len);
856                                         if (bv.bv_val) {
857                                                 ok=1;
858                                                 ber_read(ber, bv.bv_val, len);
859                                                 bv.bv_len = len;
860                                                 ber_init2(ber, &bv, ld->ld_lberoptions );
861                                         }
862                                 }
863                         } else {
864                                 /* LDAPv3: Just allocate a new ber. Since this is a buffered
865                                  * datagram, if the sockbuf is readable we still have data
866                                  * to parse.
867                                  */
868                                 ber = ldap_alloc_ber_with_options(ld);
869                                 if (ber_sockbuf_ctrl(sb, LBER_SB_OPT_DATA_READY, NULL)) ok=1;
870                         }
871                         /* set up response chain */
872                         if ( tmp == NULL ) {
873                                 newmsg->lm_next = ld->ld_responses;
874                                 ld->ld_responses = newmsg;
875                                 chain_head = newmsg;
876                         } else {
877                                 tmp->lm_chain = newmsg;
878                         }
879                         chain_head->lm_chain_tail = newmsg;
880                         tmp = newmsg;
881                         /* "ok" means there's more to parse */
882                         if (ok) {
883                                 if (isv2) goto nextresp2;
884                                 else goto nextresp3;
885                         } else {
886                                 /* got to end of datagram without a SearchResult. Free
887                                  * our dup'd ber, but leave any buffer alone. For v2 case,
888                                  * the previous response is still using this buffer. For v3,
889                                  * the new ber has no buffer to free yet.
890                                  */
891                                 ber_free(ber, 0);
892                                 return -1;
893                         }
894                 } else if ( moremsgs ) {
895                 /* got search result, and we had multiple responses in 1 datagram.
896                  * stick the result onto the end of the chain, and then pull the
897                  * first response off the head of the chain.
898                  */
899                         tmp->lm_chain = newmsg;
900                         chain_head->lm_chain_tail = newmsg;
901                         *result = chkResponseList( ld, msgid, all );
902                         ld->ld_errno = LDAP_SUCCESS;
903                         return( (*result)->lm_msgtype );
904                 }
905         }
906 #endif /* LDAP_CONNECTIONLESS */
907
908         /* is this the one we're looking for? */
909         if ( msgid == LDAP_RES_ANY || id == msgid ) {
910                 if ( all == LDAP_MSG_ONE
911                     || (newmsg->lm_msgtype != LDAP_RES_SEARCH_RESULT
912                     && newmsg->lm_msgtype != LDAP_RES_SEARCH_ENTRY
913                     && newmsg->lm_msgtype != LDAP_RES_SEARCH_REFERENCE) ) {
914                         *result = newmsg;
915                         ld->ld_errno = LDAP_SUCCESS;
916                         return( tag );
917                 } else if ( newmsg->lm_msgtype == LDAP_RES_SEARCH_RESULT) {
918                         foundit = 1;    /* return the chain later */
919                 }
920         }
921
922         /* 
923          * if not, we must add it to the list of responses.  if
924          * the msgid is already there, it must be part of an existing
925          * search response.
926          */
927
928         prev = NULL;
929         for ( l = ld->ld_responses; l != NULL; l = l->lm_next ) {
930                 if ( l->lm_msgid == newmsg->lm_msgid )
931                         break;
932                 prev = l;
933         }
934
935         /* not part of an existing search response */
936         if ( l == NULL ) {
937                 if ( foundit ) {
938                         *result = newmsg;
939                         goto exit;
940                 }
941
942                 newmsg->lm_next = ld->ld_responses;
943                 ld->ld_responses = newmsg;
944                 goto exit;
945         }
946
947         Debug( LDAP_DEBUG_TRACE, "adding response ld %p msgid %ld type %ld:\n",
948                 (void *)ld, (long) newmsg->lm_msgid, (long) newmsg->lm_msgtype );
949
950         /* part of a search response - add to end of list of entries */
951         l->lm_chain_tail->lm_chain = newmsg;
952         l->lm_chain_tail = newmsg;
953
954         /* return the whole chain if that's what we were looking for */
955         if ( foundit ) {
956                 if ( prev == NULL )
957                         ld->ld_responses = l->lm_next;
958                 else
959                         prev->lm_next = l->lm_next;
960                 *result = l;
961         }
962
963 exit:
964         if ( foundit ) {
965                 ld->ld_errno = LDAP_SUCCESS;
966                 return( tag );
967         }
968         if ( ber_sockbuf_ctrl( sb, LBER_SB_OPT_DATA_READY, NULL ) ) {
969                 goto retry;
970         }
971         return( LDAP_MSG_X_KEEP_LOOKING );      /* continue looking */
972 }
973
974
975 static ber_tag_t
976 build_result_ber( LDAP *ld, BerElement **bp, LDAPRequest *lr )
977 {
978         ber_len_t       len;
979         ber_tag_t       tag;
980         ber_int_t       along;
981         BerElement *ber;
982
983         *bp = NULL;
984         ber = ldap_alloc_ber_with_options( ld );
985
986         if( ber == NULL ) {
987                 ld->ld_errno = LDAP_NO_MEMORY;
988                 return LBER_ERROR;
989         }
990
991         if ( ber_printf( ber, "{it{ess}}", lr->lr_msgid,
992                 lr->lr_res_msgtype, lr->lr_res_errno,
993                 lr->lr_res_matched ? lr->lr_res_matched : "",
994                 lr->lr_res_error ? lr->lr_res_error : "" ) == -1 )
995         {
996                 ld->ld_errno = LDAP_ENCODING_ERROR;
997                 ber_free(ber, 1);
998                 return( LBER_ERROR );
999         }
1000
1001         ber_reset( ber, 1 );
1002
1003         if ( ber_skip_tag( ber, &len ) == LBER_ERROR ) {
1004                 ld->ld_errno = LDAP_DECODING_ERROR;
1005                 ber_free(ber, 1);
1006                 return( LBER_ERROR );
1007         }
1008
1009         if ( ber_get_enum( ber, &along ) == LBER_ERROR ) {
1010                 ld->ld_errno = LDAP_DECODING_ERROR;
1011                 ber_free(ber, 1);
1012                 return( LBER_ERROR );
1013         }
1014
1015         tag = ber_peek_tag( ber, &len );
1016
1017         if ( tag == LBER_ERROR ) {
1018                 ld->ld_errno = LDAP_DECODING_ERROR;
1019                 ber_free(ber, 1);
1020                 return( LBER_ERROR );
1021         }
1022
1023         *bp = ber;
1024         return tag;
1025 }
1026
1027
1028 static void
1029 merge_error_info( LDAP *ld, LDAPRequest *parentr, LDAPRequest *lr )
1030 {
1031 /*
1032  * Merge error information in "lr" with "parentr" error code and string.
1033  */
1034         if ( lr->lr_res_errno == LDAP_PARTIAL_RESULTS ) {
1035                 parentr->lr_res_errno = lr->lr_res_errno;
1036                 if ( lr->lr_res_error != NULL ) {
1037                         (void)ldap_append_referral( ld, &parentr->lr_res_error,
1038                             lr->lr_res_error );
1039                 }
1040         } else if ( lr->lr_res_errno != LDAP_SUCCESS &&
1041                 parentr->lr_res_errno == LDAP_SUCCESS )
1042         {
1043                 parentr->lr_res_errno = lr->lr_res_errno;
1044                 if ( parentr->lr_res_error != NULL ) {
1045                         LDAP_FREE( parentr->lr_res_error );
1046                 }
1047                 parentr->lr_res_error = lr->lr_res_error;
1048                 lr->lr_res_error = NULL;
1049                 if ( LDAP_NAME_ERROR( lr->lr_res_errno ) ) {
1050                         if ( parentr->lr_res_matched != NULL ) {
1051                                 LDAP_FREE( parentr->lr_res_matched );
1052                         }
1053                         parentr->lr_res_matched = lr->lr_res_matched;
1054                         lr->lr_res_matched = NULL;
1055                 }
1056         }
1057
1058         Debug( LDAP_DEBUG_TRACE, "merged parent (id %d) error info:  ",
1059             parentr->lr_msgid, 0, 0 );
1060         Debug( LDAP_DEBUG_TRACE, "result errno %d, error <%s>, matched <%s>\n",
1061             parentr->lr_res_errno, parentr->lr_res_error ?
1062             parentr->lr_res_error : "", parentr->lr_res_matched ?
1063             parentr->lr_res_matched : "" );
1064 }
1065
1066
1067
1068 int
1069 ldap_msgtype( LDAPMessage *lm )
1070 {
1071         assert( lm != NULL );
1072         return ( lm != NULL ) ? (int)lm->lm_msgtype : -1;
1073 }
1074
1075
1076 int
1077 ldap_msgid( LDAPMessage *lm )
1078 {
1079         assert( lm != NULL );
1080
1081         return ( lm != NULL ) ? lm->lm_msgid : -1;
1082 }
1083
1084
1085 char * ldap_int_msgtype2str( ber_tag_t tag )
1086 {
1087         switch( tag ) {
1088         case LDAP_RES_ADD: return "add";
1089         case LDAP_RES_BIND: return "bind";
1090         case LDAP_RES_COMPARE: return "compare";
1091         case LDAP_RES_DELETE: return "delete";
1092         case LDAP_RES_EXTENDED: return "extended-result";
1093         case LDAP_RES_INTERMEDIATE: return "intermediate";
1094         case LDAP_RES_MODIFY: return "modify";
1095         case LDAP_RES_RENAME: return "rename";
1096         case LDAP_RES_SEARCH_ENTRY: return "search-entry";
1097         case LDAP_RES_SEARCH_REFERENCE: return "search-reference";
1098         case LDAP_RES_SEARCH_RESULT: return "search-result";
1099         }
1100         return "unknown";
1101 }
1102
1103 int
1104 ldap_msgfree( LDAPMessage *lm )
1105 {
1106         LDAPMessage     *next;
1107         int             type = 0;
1108
1109         Debug( LDAP_DEBUG_TRACE, "ldap_msgfree\n", 0, 0, 0 );
1110
1111         for ( ; lm != NULL; lm = next ) {
1112                 next = lm->lm_chain;
1113                 type = lm->lm_msgtype;
1114                 ber_free( lm->lm_ber, 1 );
1115                 LDAP_FREE( (char *) lm );
1116         }
1117
1118         return( type );
1119 }
1120
1121 /*
1122  * ldap_msgdelete - delete a message.  It returns:
1123  *      0       if the entire message was deleted
1124  *      -1      if the message was not found, or only part of it was found
1125  */
1126 int
1127 ldap_msgdelete( LDAP *ld, int msgid )
1128 {
1129         LDAPMessage     *lm, *prev;
1130         int rc = 0;
1131
1132         assert( ld != NULL );
1133
1134         Debug( LDAP_DEBUG_TRACE, "ldap_msgdelete\n", 0, 0, 0 );
1135
1136         prev = NULL;
1137 #ifdef LDAP_R_COMPILE
1138         ldap_pvt_thread_mutex_lock( &ld->ld_res_mutex );
1139 #endif
1140         for ( lm = ld->ld_responses; lm != NULL; lm = lm->lm_next ) {
1141                 if ( lm->lm_msgid == msgid )
1142                         break;
1143                 prev = lm;
1144         }
1145
1146         if ( lm == NULL ) {
1147                 rc = -1;
1148         } else {
1149                 if ( prev == NULL )
1150                         ld->ld_responses = lm->lm_next;
1151                 else
1152                         prev->lm_next = lm->lm_next;
1153         }
1154 #ifdef LDAP_R_COMPILE
1155         ldap_pvt_thread_mutex_unlock( &ld->ld_res_mutex );
1156 #endif
1157         if ( lm && ldap_msgfree( lm ) == LDAP_RES_SEARCH_ENTRY )
1158                 rc = -1;
1159
1160         return( rc );
1161 }
1162
1163
1164 /*
1165  * return 1 if message msgid is waiting to be abandoned, 0 otherwise
1166  */
1167 static int
1168 ldap_abandoned( LDAP *ld, ber_int_t msgid )
1169 {
1170         int     i;
1171
1172         if ( ld->ld_abandoned == NULL )
1173                 return( 0 );
1174
1175         for ( i = 0; ld->ld_abandoned[i] != -1; i++ )
1176                 if ( ld->ld_abandoned[i] == msgid )
1177                         return( 1 );
1178
1179         return( 0 );
1180 }
1181
1182
1183 static int
1184 ldap_mark_abandoned( LDAP *ld, ber_int_t msgid )
1185 {
1186         int     i;
1187
1188         if ( ld->ld_abandoned == NULL )
1189                 return( -1 );
1190
1191         for ( i = 0; ld->ld_abandoned[i] != -1; i++ )
1192                 if ( ld->ld_abandoned[i] == msgid )
1193                         break;
1194
1195         if ( ld->ld_abandoned[i] == -1 )
1196                 return( -1 );
1197
1198         for ( ; ld->ld_abandoned[i] != -1; i++ ) {
1199                 ld->ld_abandoned[i] = ld->ld_abandoned[i + 1];
1200         }
1201
1202         return( 0 );
1203 }