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