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