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