]> git.sur5r.net Git - openldap/blob - servers/slapd/result.c
ITS#6111 connection_state_closing() -> connection_valid()
[openldap] / servers / slapd / result.c
1 /* result.c - routines to send ldap results, errors, and referrals */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 1998-2009 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) 1995 Regents of the University of Michigan.
17  * All rights reserved.
18  *
19  * Redistribution and use in source and binary forms are permitted
20  * provided that this notice is preserved and that due credit is given
21  * to the University of Michigan at Ann Arbor. The name of the University
22  * may not be used to endorse or promote products derived from this
23  * software without specific prior written permission. This software
24  * is provided ``as is'' without express or implied warranty.
25  */
26
27 #include "portable.h"
28
29 #include <stdio.h>
30
31 #include <ac/socket.h>
32 #include <ac/errno.h>
33 #include <ac/string.h>
34 #include <ac/ctype.h>
35 #include <ac/time.h>
36 #include <ac/unistd.h>
37
38 #include "slap.h"
39
40 const struct berval slap_dummy_bv = BER_BVNULL;
41
42 int slap_null_cb( Operation *op, SlapReply *rs )
43 {
44         return 0;
45 }
46
47 int slap_freeself_cb( Operation *op, SlapReply *rs )
48 {
49         assert( op->o_callback != NULL );
50
51         op->o_tmpfree( op->o_callback, op->o_tmpmemctx );
52         op->o_callback = NULL;
53
54         return SLAP_CB_CONTINUE;
55 }
56
57 static char *v2ref( BerVarray ref, const char *text )
58 {
59         size_t len = 0, i = 0;
60         char *v2;
61
62         if(ref == NULL) {
63                 if (text) {
64                         return ch_strdup(text);
65                 } else {
66                         return NULL;
67                 }
68         }
69         
70         if ( text != NULL ) {
71                 len = strlen( text );
72                 if (text[len-1] != '\n') {
73                     i = 1;
74                 }
75         }
76
77         v2 = ch_malloc( len+i+sizeof("Referral:") );
78
79         if( text != NULL ) {
80                 strcpy(v2, text);
81                 if( i ) {
82                         v2[len++] = '\n';
83                 }
84         }
85         strcpy( v2+len, "Referral:" );
86         len += sizeof("Referral:");
87
88         for( i=0; ref[i].bv_val != NULL; i++ ) {
89                 v2 = ch_realloc( v2, len + ref[i].bv_len + 1 );
90                 v2[len-1] = '\n';
91                 AC_MEMCPY(&v2[len], ref[i].bv_val, ref[i].bv_len );
92                 len += ref[i].bv_len;
93                 if (ref[i].bv_val[ref[i].bv_len-1] != '/') {
94                         ++len;
95                 }
96         }
97
98         v2[len-1] = '\0';
99         return v2;
100 }
101
102 ber_tag_t
103 slap_req2res( ber_tag_t tag )
104 {
105         switch( tag ) {
106         case LDAP_REQ_ADD:
107         case LDAP_REQ_BIND:
108         case LDAP_REQ_COMPARE:
109         case LDAP_REQ_EXTENDED:
110         case LDAP_REQ_MODIFY:
111         case LDAP_REQ_MODRDN:
112                 tag++;
113                 break;
114
115         case LDAP_REQ_DELETE:
116                 tag = LDAP_RES_DELETE;
117                 break;
118
119         case LDAP_REQ_ABANDON:
120         case LDAP_REQ_UNBIND:
121                 tag = LBER_SEQUENCE;
122                 break;
123
124         case LDAP_REQ_SEARCH:
125                 tag = LDAP_RES_SEARCH_RESULT;
126                 break;
127
128         default:
129                 tag = LBER_SEQUENCE;
130         }
131
132         return tag;
133 }
134
135 static long send_ldap_ber(
136         Operation *op,
137         BerElement *ber )
138 {
139         Connection *conn = op->o_conn;
140         ber_len_t bytes;
141         long ret = 0;
142         int closing = 0;
143
144         ber_get_option( ber, LBER_OPT_BER_BYTES_TO_WRITE, &bytes );
145
146         /* write only one pdu at a time - wait til it's our turn */
147         ldap_pvt_thread_mutex_lock( &conn->c_write1_mutex );
148         if (( op->o_abandon && !op->o_cancel ) || !connection_valid( conn )) {
149                 ldap_pvt_thread_mutex_unlock( &conn->c_write1_mutex );
150                 return 0;
151         }
152         while ( conn->c_writers > 0 ) {
153                 ldap_pvt_thread_cond_wait( &conn->c_write1_cv, &conn->c_write1_mutex );
154         }
155         /* connection was closed under us */
156         if ( conn->c_writers < 0 ) {
157                 closing = 1;
158                 /* we're the last waiter, let the closer continue */
159                 if ( conn->c_writers == -1 )
160                         ldap_pvt_thread_cond_signal( &conn->c_write1_cv );
161         }
162
163         conn->c_writers++;
164
165         if ( closing ) {
166                 ldap_pvt_thread_mutex_unlock( &conn->c_write1_mutex );
167                 return 0;
168         }
169
170         /* write the pdu */
171         while( 1 ) {
172                 int err;
173
174                 /* lock the connection */ 
175                 if ( ldap_pvt_thread_mutex_trylock( &conn->c_mutex )) {
176                         ldap_pvt_thread_mutex_unlock( &conn->c_write1_mutex );
177                         ldap_pvt_thread_mutex_lock( &conn->c_write1_mutex );
178                         if ( conn->c_writers < 0 ) {
179                                 ret = 0;
180                                 break;
181                         }
182                         continue;
183                 }
184
185                 if ( ber_flush2( conn->c_sb, ber, LBER_FLUSH_FREE_NEVER ) == 0 ) {
186                         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
187                         ret = bytes;
188                         break;
189                 }
190
191                 err = sock_errno();
192
193                 /*
194                  * we got an error.  if it's ewouldblock, we need to
195                  * wait on the socket being writable.  otherwise, figure
196                  * it's a hard error and return.
197                  */
198
199                 Debug( LDAP_DEBUG_CONNS, "ber_flush2 failed errno=%d reason=\"%s\"\n",
200                     err, sock_errstr(err), 0 );
201
202                 if ( err != EWOULDBLOCK && err != EAGAIN ) {
203                         conn->c_writers--;
204                         ldap_pvt_thread_mutex_unlock( &conn->c_write1_mutex );
205                         connection_closing( conn, "connection lost on write" );
206
207                         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
208                         return -1;
209                 }
210
211                 /* wait for socket to be write-ready */
212                 ldap_pvt_thread_mutex_lock( &conn->c_write2_mutex );
213                 conn->c_writewaiter = 1;
214                 slapd_set_write( conn->c_sd, 2 );
215
216                 ldap_pvt_thread_mutex_unlock( &conn->c_write1_mutex );
217                 ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
218                 ldap_pvt_thread_cond_wait( &conn->c_write2_cv, &conn->c_write2_mutex );
219                 conn->c_writewaiter = 0;
220                 ldap_pvt_thread_mutex_unlock( &conn->c_write2_mutex );
221                 ldap_pvt_thread_mutex_lock( &conn->c_write1_mutex );
222                 if ( conn->c_writers < 0 ) {
223                         ret = 0;
224                         break;
225                 }
226         }
227
228         if ( conn->c_writers < 0 ) {
229                 conn->c_writers++;
230                 if ( !conn->c_writers )
231                         ldap_pvt_thread_cond_signal( &conn->c_write1_cv );
232         } else {
233                 conn->c_writers--;
234                 ldap_pvt_thread_cond_signal( &conn->c_write1_cv );
235         }
236         ldap_pvt_thread_mutex_unlock( &conn->c_write1_mutex );
237
238         return ret;
239 }
240
241 static int
242 send_ldap_control( BerElement *ber, LDAPControl *c )
243 {
244         int rc;
245
246         assert( c != NULL );
247
248         rc = ber_printf( ber, "{s" /*}*/, c->ldctl_oid );
249
250         if( c->ldctl_iscritical ) {
251                 rc = ber_printf( ber, "b",
252                         (ber_int_t) c->ldctl_iscritical ) ;
253                 if( rc == -1 ) return rc;
254         }
255
256         if( c->ldctl_value.bv_val != NULL ) {
257                 rc = ber_printf( ber, "O", &c->ldctl_value ); 
258                 if( rc == -1 ) return rc;
259         }
260
261         rc = ber_printf( ber, /*{*/"N}" );
262         if( rc == -1 ) return rc;
263
264         return 0;
265 }
266
267 static int
268 send_ldap_controls( Operation *o, BerElement *ber, LDAPControl **c )
269 {
270         int rc;
271
272         if( c == NULL )
273                 return 0;
274
275         rc = ber_printf( ber, "t{"/*}*/, LDAP_TAG_CONTROLS );
276         if( rc == -1 ) return rc;
277
278         for( ; *c != NULL; c++) {
279                 rc = send_ldap_control( ber, *c );
280                 if( rc == -1 ) return rc;
281         }
282
283 #ifdef SLAP_CONTROL_X_SORTEDRESULTS
284         /* this is a hack to avoid having to modify op->s_ctrls */
285         if( o->o_sortedresults ) {
286                 BerElementBuffer berbuf;
287                 BerElement *sber = (BerElement *) &berbuf;
288                 LDAPControl sorted;
289                 BER_BVZERO( &sorted.ldctl_value );
290                 sorted.ldctl_oid = LDAP_CONTROL_SORTRESPONSE;
291                 sorted.ldctl_iscritical = 0;
292
293                 ber_init2( sber, NULL, LBER_USE_DER );
294
295                 ber_printf( sber, "{e}", LDAP_UNWILLING_TO_PERFORM );
296
297                 if( ber_flatten2( ber, &sorted.ldctl_value, 0 ) == -1 ) {
298                         return -1;
299                 }
300
301                 (void) ber_free_buf( ber );
302
303                 rc = send_ldap_control( ber, &sorted );
304                 if( rc == -1 ) return rc;
305         }
306 #endif
307
308         rc = ber_printf( ber, /*{*/"N}" );
309
310         return rc;
311 }
312
313 /*
314  * slap_response_play()
315  *
316  * plays the callback list; rationale: a callback can
317  *   - remove itself from the list, by setting op->o_callback = NULL;
318  *     malloc()'ed callbacks should free themselves from inside the
319  *     sc_response() function.
320  *   - replace itself with another (list of) callback(s), by setting
321  *     op->o_callback = a new (list of) callback(s); in this case, it
322  *     is the callback's responsibility to to append existing subsequent
323  *     callbacks to the end of the list that is passed to the sc_response()
324  *     function.
325  *   - modify the list of subsequent callbacks by modifying the value
326  *     of the sc_next field from inside the sc_response() function; this
327  *     case does not require any handling from inside slap_response_play()
328  *
329  * To stop execution of the playlist, the sc_response() function must return
330  * a value different from SLAP_SC_CONTINUE.
331  *
332  * The same applies to slap_cleanup_play(); only, there is no means to stop
333  * execution of the playlist, since all cleanup functions must be called.
334  */
335 static int
336 slap_response_play(
337         Operation *op,
338         SlapReply *rs )
339 {
340         int rc;
341
342         slap_callback   *sc = op->o_callback, **scp;
343
344         rc = SLAP_CB_CONTINUE;
345         for ( scp = &sc; *scp; ) {
346                 slap_callback *sc_next = (*scp)->sc_next, **sc_nextp = &(*scp)->sc_next;
347
348                 op->o_callback = *scp;
349                 if ( op->o_callback->sc_response ) {
350                         rc = op->o_callback->sc_response( op, rs );
351                         if ( op->o_callback == NULL ) {
352                                 /* the callback has been removed;
353                                  * repair the list */
354                                 *scp = sc_next;
355                                 sc_nextp = scp;
356
357                         } else if ( op->o_callback != *scp ) {
358                                 /* a new callback has been inserted
359                                  * in place of the existing one; repair the list */
360                                 *scp = op->o_callback;
361                                 sc_nextp = scp;
362                         }
363                         if ( rc != SLAP_CB_CONTINUE ) break;
364                 }
365                 scp = sc_nextp;
366         }
367
368         op->o_callback = sc;
369         return rc;
370 }
371
372 static int
373 slap_cleanup_play(
374         Operation *op,
375         SlapReply *rs )
376 {
377         slap_callback   *sc = op->o_callback, **scp;
378
379         for ( scp = &sc; *scp; ) {
380                 slap_callback *sc_next = (*scp)->sc_next, **sc_nextp = &(*scp)->sc_next;
381
382                 op->o_callback = *scp;
383                 if ( op->o_callback->sc_cleanup ) {
384                         (void)op->o_callback->sc_cleanup( op, rs );
385                         if ( op->o_callback == NULL ) {
386                                 /* the callback has been removed;
387                                  * repair the list */
388                                 *scp = sc_next;
389                                 sc_nextp = scp;
390
391                         } else if ( op->o_callback != *scp ) {
392                                 /* a new callback has been inserted
393                                  * after the existing one; repair the list */
394                                 /* a new callback has been inserted
395                                  * in place of the existing one; repair the list */
396                                 *scp = op->o_callback;
397                                 sc_nextp = scp;
398                         }
399                         /* don't care about the result; do all cleanup */
400                 }
401                 scp = sc_nextp;
402         }
403
404         op->o_callback = sc;
405         return LDAP_SUCCESS;
406 }
407
408 static int
409 send_ldap_response(
410         Operation *op,
411         SlapReply *rs )
412 {
413         BerElementBuffer berbuf;
414         BerElement      *ber = (BerElement *) &berbuf;
415         int             rc = LDAP_SUCCESS;
416         long    bytes;
417
418         if (( rs->sr_err == SLAPD_ABANDON || op->o_abandon ) && !op->o_cancel ) {
419                 rc = SLAPD_ABANDON;
420                 goto clean2;
421         }
422
423         if ( op->o_callback ) {
424                 rc = slap_response_play( op, rs );
425                 if ( rc != SLAP_CB_CONTINUE ) {
426                         goto clean2;
427                 }
428         }
429
430 #ifdef LDAP_CONNECTIONLESS
431         if (op->o_conn && op->o_conn->c_is_udp)
432                 ber = op->o_res_ber;
433         else
434 #endif
435         {
436                 ber_init_w_nullc( ber, LBER_USE_DER );
437                 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
438         }
439
440         rc = rs->sr_err;
441         if ( rc == SLAPD_ABANDON && op->o_cancel )
442                 rc = LDAP_CANCELLED;
443
444         Debug( LDAP_DEBUG_TRACE,
445                 "send_ldap_response: msgid=%d tag=%lu err=%d\n",
446                 rs->sr_msgid, rs->sr_tag, rc );
447
448         if( rs->sr_ref ) {
449                 Debug( LDAP_DEBUG_ARGS, "send_ldap_response: ref=\"%s\"\n",
450                         rs->sr_ref[0].bv_val ? rs->sr_ref[0].bv_val : "NULL",
451                         NULL, NULL );
452         }
453
454 #ifdef LDAP_CONNECTIONLESS
455         if (op->o_conn && op->o_conn->c_is_udp &&
456                 op->o_protocol == LDAP_VERSION2 )
457         {
458                 rc = ber_printf( ber, "t{ess" /*"}"*/,
459                         rs->sr_tag, rs->sr_err,
460                 rs->sr_matched == NULL ? "" : rs->sr_matched,
461                 rs->sr_text == NULL ? "" : rs->sr_text );
462         } else 
463 #endif
464         if ( rs->sr_type == REP_INTERMEDIATE ) {
465             rc = ber_printf( ber, "{it{" /*"}}"*/,
466                         rs->sr_msgid, rs->sr_tag );
467
468         } else {
469             rc = ber_printf( ber, "{it{ess" /*"}}"*/,
470                 rs->sr_msgid, rs->sr_tag, rc,
471                 rs->sr_matched == NULL ? "" : rs->sr_matched,
472                 rs->sr_text == NULL ? "" : rs->sr_text );
473         }
474
475         if( rc != -1 ) {
476                 if ( rs->sr_ref != NULL ) {
477                         assert( rs->sr_err == LDAP_REFERRAL );
478                         rc = ber_printf( ber, "t{W}",
479                                 LDAP_TAG_REFERRAL, rs->sr_ref );
480                 } else {
481                         assert( rs->sr_err != LDAP_REFERRAL );
482                 }
483         }
484
485         if( rc != -1 && rs->sr_type == REP_SASL && rs->sr_sasldata != NULL ) {
486                 rc = ber_printf( ber, "tO",
487                         LDAP_TAG_SASL_RES_CREDS, rs->sr_sasldata );
488         }
489
490         if( rc != -1 &&
491                 ( rs->sr_type == REP_EXTENDED || rs->sr_type == REP_INTERMEDIATE ))
492         {
493                 if ( rs->sr_rspoid != NULL ) {
494                         rc = ber_printf( ber, "ts",
495                                 rs->sr_type == REP_EXTENDED
496                                         ? LDAP_TAG_EXOP_RES_OID : LDAP_TAG_IM_RES_OID,
497                                 rs->sr_rspoid );
498                 }
499                 if( rc != -1 && rs->sr_rspdata != NULL ) {
500                         rc = ber_printf( ber, "tO",
501                                 rs->sr_type == REP_EXTENDED
502                                         ? LDAP_TAG_EXOP_RES_VALUE : LDAP_TAG_IM_RES_VALUE,
503                                 rs->sr_rspdata );
504                 }
505         }
506
507         if( rc != -1 ) {
508                 rc = ber_printf( ber, /*"{"*/ "N}" );
509         }
510
511         if( rc != -1 ) {
512                 rc = send_ldap_controls( op, ber, rs->sr_ctrls );
513         }
514
515         if( rc != -1 ) {
516                 rc = ber_printf( ber, /*"{"*/ "N}" );
517         }
518
519 #ifdef LDAP_CONNECTIONLESS
520         if( op->o_conn && op->o_conn->c_is_udp && op->o_protocol == LDAP_VERSION2
521                 && rc != -1 )
522         {
523                 rc = ber_printf( ber, /*"{"*/ "N}" );
524         }
525 #endif
526                 
527         if ( rc == -1 ) {
528                 Debug( LDAP_DEBUG_ANY, "ber_printf failed\n", 0, 0, 0 );
529
530 #ifdef LDAP_CONNECTIONLESS
531                 if (!op->o_conn || op->o_conn->c_is_udp == 0)
532 #endif
533                 {
534                         ber_free_buf( ber );
535                 }
536                 goto cleanup;
537         }
538
539         /* send BER */
540         bytes = send_ldap_ber( op, ber );
541 #ifdef LDAP_CONNECTIONLESS
542         if (!op->o_conn || op->o_conn->c_is_udp == 0)
543 #endif
544         {
545                 ber_free_buf( ber );
546         }
547
548         if ( bytes < 0 ) {
549                 Debug( LDAP_DEBUG_ANY,
550                         "send_ldap_response: ber write failed\n",
551                         0, 0, 0 );
552
553                 goto cleanup;
554         }
555
556         ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex );
557         ldap_pvt_mp_add_ulong( op->o_counters->sc_pdu, 1 );
558         ldap_pvt_mp_add_ulong( op->o_counters->sc_bytes, (unsigned long)bytes );
559         ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex );
560
561 cleanup:;
562         /* Tell caller that we did this for real, as opposed to being
563          * overridden by a callback
564          */
565         rc = SLAP_CB_CONTINUE;
566
567 clean2:;
568         if ( op->o_callback ) {
569                 (void)slap_cleanup_play( op, rs );
570         }
571
572         if ( rs->sr_flags & REP_MATCHED_MUSTBEFREED ) {
573                 rs->sr_flags ^= REP_MATCHED_MUSTBEFREED; /* paranoia */
574                 if ( rs->sr_matched ) {
575                         free( (char *)rs->sr_matched );
576                         rs->sr_matched = NULL;
577                 }
578         }
579
580         if ( rs->sr_flags & REP_REF_MUSTBEFREED ) {
581                 rs->sr_flags ^= REP_REF_MUSTBEFREED; /* paranoia */
582                 if ( rs->sr_ref ) {
583                         ber_bvarray_free( rs->sr_ref );
584                         rs->sr_ref = NULL;
585                 }
586         }
587
588         if ( rs->sr_flags & REP_CTRLS_MUSTBEFREED ) {
589                 rs->sr_flags ^= REP_CTRLS_MUSTBEFREED; /* paranoia */
590                 if ( rs->sr_ctrls ) {
591                         slap_free_ctrls( op, rs->sr_ctrls );
592                         rs->sr_ctrls = NULL;
593                 }
594         }
595
596         return rc;
597 }
598
599
600 void
601 send_ldap_disconnect( Operation *op, SlapReply *rs )
602 {
603 #define LDAP_UNSOLICITED_ERROR(e) \
604         (  (e) == LDAP_PROTOCOL_ERROR \
605         || (e) == LDAP_STRONG_AUTH_REQUIRED \
606         || (e) == LDAP_UNAVAILABLE )
607
608         assert( LDAP_UNSOLICITED_ERROR( rs->sr_err ) );
609
610         rs->sr_type = REP_EXTENDED;
611
612         Debug( LDAP_DEBUG_TRACE,
613                 "send_ldap_disconnect %d:%s\n",
614                 rs->sr_err, rs->sr_text ? rs->sr_text : "", NULL );
615
616         if ( op->o_protocol < LDAP_VERSION3 ) {
617                 rs->sr_rspoid = NULL;
618                 rs->sr_tag = slap_req2res( op->o_tag );
619                 rs->sr_msgid = (rs->sr_tag != LBER_SEQUENCE) ? op->o_msgid : 0;
620
621         } else {
622                 rs->sr_rspoid = LDAP_NOTICE_DISCONNECT;
623                 rs->sr_tag = LDAP_RES_EXTENDED;
624                 rs->sr_msgid = LDAP_RES_UNSOLICITED;
625         }
626
627         if ( send_ldap_response( op, rs ) == SLAP_CB_CONTINUE ) {
628                 Statslog( LDAP_DEBUG_STATS,
629                         "%s DISCONNECT tag=%lu err=%d text=%s\n",
630                         op->o_log_prefix, rs->sr_tag, rs->sr_err,
631                         rs->sr_text ? rs->sr_text : "", 0 );
632         }
633 }
634
635 void
636 slap_send_ldap_result( Operation *op, SlapReply *rs )
637 {
638         char *tmp = NULL;
639         const char *otext = rs->sr_text;
640         BerVarray oref = rs->sr_ref;
641
642         rs->sr_type = REP_RESULT;
643
644         /* Propagate Abandons so that cleanup callbacks can be processed */
645         if ( rs->sr_err == SLAPD_ABANDON || op->o_abandon )
646                 goto abandon;
647
648         assert( !LDAP_API_ERROR( rs->sr_err ) );
649
650         Debug( LDAP_DEBUG_TRACE,
651                 "send_ldap_result: %s p=%d\n",
652                 op->o_log_prefix, op->o_protocol, 0 );
653
654         Debug( LDAP_DEBUG_ARGS,
655                 "send_ldap_result: err=%d matched=\"%s\" text=\"%s\"\n",
656                 rs->sr_err, rs->sr_matched ? rs->sr_matched : "",
657                 rs->sr_text ? rs->sr_text : "" );
658
659
660         if( rs->sr_ref ) {
661                 Debug( LDAP_DEBUG_ARGS,
662                         "send_ldap_result: referral=\"%s\"\n",
663                         rs->sr_ref[0].bv_val ? rs->sr_ref[0].bv_val : "NULL",
664                         NULL, NULL );
665         }
666
667         assert( rs->sr_err != LDAP_PARTIAL_RESULTS );
668
669         if ( rs->sr_err == LDAP_REFERRAL ) {
670                 if( op->o_domain_scope ) rs->sr_ref = NULL;
671
672                 if( rs->sr_ref == NULL ) {
673                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
674                 } else if ( op->o_protocol < LDAP_VERSION3 ) {
675                         rs->sr_err = LDAP_PARTIAL_RESULTS;
676                 }
677         }
678
679         if ( op->o_protocol < LDAP_VERSION3 ) {
680                 tmp = v2ref( rs->sr_ref, rs->sr_text );
681                 rs->sr_text = tmp;
682                 rs->sr_ref = NULL;
683         }
684
685 abandon:
686         rs->sr_tag = slap_req2res( op->o_tag );
687         rs->sr_msgid = (rs->sr_tag != LBER_SEQUENCE) ? op->o_msgid : 0;
688
689         if ( rs->sr_flags & REP_REF_MUSTBEFREED ) {
690                 if ( rs->sr_ref == NULL ) {
691                         rs->sr_flags ^= REP_REF_MUSTBEFREED;
692                         ber_bvarray_free( oref );
693                 }
694                 oref = NULL; /* send_ldap_response() will free rs->sr_ref if != NULL */
695         }
696
697         if ( send_ldap_response( op, rs ) == SLAP_CB_CONTINUE ) {
698                 if ( op->o_tag == LDAP_REQ_SEARCH ) {
699                         Statslog( LDAP_DEBUG_STATS,
700                                 "%s SEARCH RESULT tag=%lu err=%d nentries=%d text=%s\n",
701                                 op->o_log_prefix, rs->sr_tag, rs->sr_err,
702                                 rs->sr_nentries, rs->sr_text ? rs->sr_text : "" );
703                 } else {
704                         Statslog( LDAP_DEBUG_STATS,
705                                 "%s RESULT tag=%lu err=%d text=%s\n",
706                                 op->o_log_prefix, rs->sr_tag, rs->sr_err,
707                                 rs->sr_text ? rs->sr_text : "", 0 );
708                 }
709         }
710
711         if( tmp != NULL ) ch_free(tmp);
712         rs->sr_text = otext;
713         rs->sr_ref = oref;
714 }
715
716 void
717 send_ldap_sasl( Operation *op, SlapReply *rs )
718 {
719         rs->sr_type = REP_SASL;
720         Debug( LDAP_DEBUG_TRACE, "send_ldap_sasl: err=%d len=%ld\n",
721                 rs->sr_err,
722                 rs->sr_sasldata ? (long) rs->sr_sasldata->bv_len : -1, NULL );
723
724         rs->sr_tag = slap_req2res( op->o_tag );
725         rs->sr_msgid = (rs->sr_tag != LBER_SEQUENCE) ? op->o_msgid : 0;
726
727         if ( send_ldap_response( op, rs ) == SLAP_CB_CONTINUE ) {
728                 Statslog( LDAP_DEBUG_STATS,
729                         "%s RESULT tag=%lu err=%d text=%s\n",
730                         op->o_log_prefix, rs->sr_tag, rs->sr_err,
731                         rs->sr_text ? rs->sr_text : "", 0 );
732         }
733 }
734
735 void
736 slap_send_ldap_extended( Operation *op, SlapReply *rs )
737 {
738         rs->sr_type = REP_EXTENDED;
739
740         Debug( LDAP_DEBUG_TRACE,
741                 "send_ldap_extended: err=%d oid=%s len=%ld\n",
742                 rs->sr_err,
743                 rs->sr_rspoid ? rs->sr_rspoid : "",
744                 rs->sr_rspdata != NULL ? rs->sr_rspdata->bv_len : 0 );
745
746         rs->sr_tag = slap_req2res( op->o_tag );
747         rs->sr_msgid = (rs->sr_tag != LBER_SEQUENCE) ? op->o_msgid : 0;
748
749         if ( send_ldap_response( op, rs ) == SLAP_CB_CONTINUE ) {
750                 Statslog( LDAP_DEBUG_STATS,
751                         "%s RESULT oid=%s err=%d text=%s\n",
752                         op->o_log_prefix, rs->sr_rspoid ? rs->sr_rspoid : "",
753                         rs->sr_err, rs->sr_text ? rs->sr_text : "", 0 );
754         }
755 }
756
757 void
758 slap_send_ldap_intermediate( Operation *op, SlapReply *rs )
759 {
760         rs->sr_type = REP_INTERMEDIATE;
761         Debug( LDAP_DEBUG_TRACE,
762                 "send_ldap_intermediate: err=%d oid=%s len=%ld\n",
763                 rs->sr_err,
764                 rs->sr_rspoid ? rs->sr_rspoid : "",
765                 rs->sr_rspdata != NULL ? rs->sr_rspdata->bv_len : 0 );
766         rs->sr_tag = LDAP_RES_INTERMEDIATE;
767         rs->sr_msgid = op->o_msgid;
768         if ( send_ldap_response( op, rs ) == SLAP_CB_CONTINUE ) {
769                 Statslog( LDAP_DEBUG_STATS2,
770                         "%s INTERM oid=%s\n",
771                         op->o_log_prefix,
772                         rs->sr_rspoid ? rs->sr_rspoid : "", 0, 0, 0 );
773         }
774 }
775
776 /*
777  * returns:
778  *
779  * LDAP_SUCCESS                 entry sent
780  * LDAP_OTHER                   entry not sent (other)
781  * LDAP_INSUFFICIENT_ACCESS     entry not sent (ACL)
782  * LDAP_UNAVAILABLE             entry not sent (connection closed)
783  * LDAP_SIZELIMIT_EXCEEDED      entry not sent (caller must send sizelimitExceeded)
784  */
785
786 int
787 slap_send_search_entry( Operation *op, SlapReply *rs )
788 {
789         BerElementBuffer berbuf;
790         BerElement      *ber = (BerElement *) &berbuf;
791         Attribute       *a;
792         int             i, j, rc = LDAP_UNAVAILABLE, bytes;
793         int             userattrs;
794         AccessControlState acl_state = ACL_STATE_INIT;
795         int                      attrsonly;
796         AttributeDescription *ad_entry = slap_schema.si_ad_entry;
797
798         /* a_flags: array of flags telling if the i-th element will be
799          *          returned or filtered out
800          * e_flags: array of a_flags
801          */
802         char **e_flags = NULL;
803
804         if ( op->ors_slimit >= 0 && rs->sr_nentries >= op->ors_slimit ) {
805                 return LDAP_SIZELIMIT_EXCEEDED;
806         }
807
808         /* Every 64 entries, check for thread pool pause */
809         if ( ( ( rs->sr_nentries & 0x3f ) == 0x3f ) &&
810                 ldap_pvt_thread_pool_pausing( &connection_pool ) > 0 )
811         {
812                 return LDAP_BUSY;
813         }
814
815         rs->sr_type = REP_SEARCH;
816
817         /* eventually will loop through generated operational attribute types
818          * currently implemented types include:
819          *      entryDN, subschemaSubentry, and hasSubordinates */
820         /* NOTE: moved before overlays callback circling because
821          * they may modify entry and other stuff in rs */
822         /* check for special all operational attributes ("+") type */
823         /* FIXME: maybe we could set this flag at the operation level;
824          * however, in principle the caller of send_search_entry() may
825          * change the attribute list at each call */
826         rs->sr_attr_flags = slap_attr_flags( rs->sr_attrs );
827
828         rc = backend_operational( op, rs );
829         if ( rc ) {
830                 goto error_return;
831         }
832
833         if ( op->o_callback ) {
834                 rc = slap_response_play( op, rs );
835                 if ( rc != SLAP_CB_CONTINUE ) {
836                         goto error_return;
837                 }
838         }
839
840         Debug( LDAP_DEBUG_TRACE, "=> send_search_entry: conn %lu dn=\"%s\"%s\n",
841                 op->o_connid, rs->sr_entry->e_name.bv_val,
842                 op->ors_attrsonly ? " (attrsOnly)" : "" );
843
844         attrsonly = op->ors_attrsonly;
845
846         if ( !access_allowed( op, rs->sr_entry, ad_entry, NULL, ACL_READ, NULL )) {
847                 Debug( LDAP_DEBUG_ACL,
848                         "send_search_entry: conn %lu access to entry (%s) not allowed\n", 
849                         op->o_connid, rs->sr_entry->e_name.bv_val, 0 );
850
851                 rc = LDAP_INSUFFICIENT_ACCESS;
852                 goto error_return;
853         }
854
855         if ( op->o_res_ber ) {
856                 /* read back control or LDAP_CONNECTIONLESS */
857             ber = op->o_res_ber;
858         } else {
859                 struct berval   bv;
860
861                 bv.bv_len = entry_flatsize( rs->sr_entry, 0 );
862                 bv.bv_val = op->o_tmpalloc( bv.bv_len, op->o_tmpmemctx );
863
864                 ber_init2( ber, &bv, LBER_USE_DER );
865                 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
866         }
867
868 #ifdef LDAP_CONNECTIONLESS
869         if ( op->o_conn && op->o_conn->c_is_udp ) {
870                 /* CONNECTIONLESS */
871                 if ( op->o_protocol == LDAP_VERSION2 ) {
872                 rc = ber_printf(ber, "t{O{" /*}}*/,
873                                 LDAP_RES_SEARCH_ENTRY, &rs->sr_entry->e_name );
874                 } else {
875                 rc = ber_printf( ber, "{it{O{" /*}}}*/, op->o_msgid,
876                                 LDAP_RES_SEARCH_ENTRY, &rs->sr_entry->e_name );
877                 }
878         } else
879 #endif
880         if ( op->o_res_ber ) {
881                 /* read back control */
882             rc = ber_printf( ber, "{O{" /*}}*/, &rs->sr_entry->e_name );
883         } else {
884             rc = ber_printf( ber, "{it{O{" /*}}}*/, op->o_msgid,
885                         LDAP_RES_SEARCH_ENTRY, &rs->sr_entry->e_name );
886         }
887
888         if ( rc == -1 ) {
889                 Debug( LDAP_DEBUG_ANY, 
890                         "send_search_entry: conn %lu  ber_printf failed\n", 
891                         op->o_connid, 0, 0 );
892
893                 if ( op->o_res_ber == NULL ) ber_free_buf( ber );
894                 send_ldap_error( op, rs, LDAP_OTHER, "encoding DN error" );
895                 rc = rs->sr_err;
896                 goto error_return;
897         }
898
899         /* check for special all user attributes ("*") type */
900         userattrs = SLAP_USERATTRS( rs->sr_attr_flags );
901
902         /* create an array of arrays of flags. Each flag corresponds
903          * to particular value of attribute and equals 1 if value matches
904          * to ValuesReturnFilter or 0 if not
905          */     
906         if ( op->o_vrFilter != NULL ) {
907                 int     k = 0;
908                 size_t  size;
909
910                 for ( a = rs->sr_entry->e_attrs, i=0; a != NULL; a = a->a_next, i++ ) {
911                         for ( j = 0; a->a_vals[j].bv_val != NULL; j++ ) k++;
912                 }
913
914                 size = i * sizeof(char *) + k;
915                 if ( size > 0 ) {
916                         char    *a_flags;
917                         e_flags = slap_sl_calloc ( 1, i * sizeof(char *) + k, op->o_tmpmemctx );
918                         if( e_flags == NULL ) {
919                         Debug( LDAP_DEBUG_ANY, 
920                                         "send_search_entry: conn %lu slap_sl_calloc failed\n",
921                                         op->o_connid ? op->o_connid : 0, 0, 0 );
922                                 ber_free( ber, 1 );
923         
924                                 send_ldap_error( op, rs, LDAP_OTHER, "out of memory" );
925                                 goto error_return;
926                         }
927                         a_flags = (char *)(e_flags + i);
928                         memset( a_flags, 0, k );
929                         for ( a=rs->sr_entry->e_attrs, i=0; a != NULL; a=a->a_next, i++ ) {
930                                 for ( j = 0; a->a_vals[j].bv_val != NULL; j++ );
931                                 e_flags[i] = a_flags;
932                                 a_flags += j;
933                         }
934         
935                         rc = filter_matched_values(op, rs->sr_entry->e_attrs, &e_flags) ; 
936                         if ( rc == -1 ) {
937                                 Debug( LDAP_DEBUG_ANY, "send_search_entry: "
938                                         "conn %lu matched values filtering failed\n",
939                                         op->o_connid ? op->o_connid : 0, 0, 0 );
940                                 if ( op->o_res_ber == NULL ) ber_free_buf( ber );
941                                 send_ldap_error( op, rs, LDAP_OTHER,
942                                         "matched values filtering error" );
943                                 rc = rs->sr_err;
944                                 goto error_return;
945                         }
946                 }
947         }
948
949         for ( a = rs->sr_entry->e_attrs, j = 0; a != NULL; a = a->a_next, j++ ) {
950                 AttributeDescription *desc = a->a_desc;
951                 int finish = 0;
952
953                 if ( rs->sr_attrs == NULL ) {
954                         /* all user attrs request, skip operational attributes */
955                         if( is_at_operational( desc->ad_type ) ) {
956                                 continue;
957                         }
958
959                 } else {
960                         /* specific attrs requested */
961                         if ( is_at_operational( desc->ad_type ) ) {
962                                 /* if not explicitly requested */
963                                 if ( !ad_inlist( desc, rs->sr_attrs )) {
964                                         /* if not all op attrs requested, skip */
965                                         if ( !SLAP_OPATTRS( rs->sr_attr_flags ))
966                                                 continue;
967                                         /* if DSA-specific and replicating, skip */
968                                         if ( op->o_sync != SLAP_CONTROL_NONE &&
969                                                 desc->ad_type->sat_usage == LDAP_SCHEMA_DSA_OPERATION )
970                                                 continue;
971                                 }
972                         } else {
973                                 if ( !userattrs && !ad_inlist( desc, rs->sr_attrs ) ) {
974                                         continue;
975                                 }
976                         }
977                 }
978
979                 if ( attrsonly ) {
980                         if ( ! access_allowed( op, rs->sr_entry, desc, NULL,
981                                 ACL_READ, &acl_state ) )
982                         {
983                                 Debug( LDAP_DEBUG_ACL, "send_search_entry: "
984                                         "conn %lu access to attribute %s not allowed\n",
985                                         op->o_connid, desc->ad_cname.bv_val, 0 );
986                                 continue;
987                         }
988
989                         if (( rc = ber_printf( ber, "{O[" /*]}*/ , &desc->ad_cname )) == -1 ) {
990                                 Debug( LDAP_DEBUG_ANY, 
991                                         "send_search_entry: conn %lu  ber_printf failed\n", 
992                                         op->o_connid, 0, 0 );
993
994                                 if ( op->o_res_ber == NULL ) ber_free_buf( ber );
995                                 send_ldap_error( op, rs, LDAP_OTHER,
996                                         "encoding description error");
997                                 rc = rs->sr_err;
998                                 goto error_return;
999                         }
1000                         finish = 1;
1001
1002                 } else {
1003                         int first = 1;
1004                         for ( i = 0; a->a_nvals[i].bv_val != NULL; i++ ) {
1005                                 if ( ! access_allowed( op, rs->sr_entry,
1006                                         desc, &a->a_nvals[i], ACL_READ, &acl_state ) )
1007                                 {
1008                                         Debug( LDAP_DEBUG_ACL,
1009                                                 "send_search_entry: conn %lu "
1010                                                 "access to attribute %s, value #%d not allowed\n",
1011                                                 op->o_connid, desc->ad_cname.bv_val, i );
1012
1013                                         continue;
1014                                 }
1015
1016                                 if ( op->o_vrFilter && e_flags[j][i] == 0 ){
1017                                         continue;
1018                                 }
1019
1020                                 if ( first ) {
1021                                         first = 0;
1022                                         finish = 1;
1023                                         if (( rc = ber_printf( ber, "{O[" /*]}*/ , &desc->ad_cname )) == -1 ) {
1024                                                 Debug( LDAP_DEBUG_ANY,
1025                                                         "send_search_entry: conn %lu  ber_printf failed\n", 
1026                                                         op->o_connid, 0, 0 );
1027
1028                                                 if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1029                                                 send_ldap_error( op, rs, LDAP_OTHER,
1030                                                         "encoding description error");
1031                                                 rc = rs->sr_err;
1032                                                 goto error_return;
1033                                         }
1034                                 }
1035                                 if (( rc = ber_printf( ber, "O", &a->a_vals[i] )) == -1 ) {
1036                                         Debug( LDAP_DEBUG_ANY,
1037                                                 "send_search_entry: conn %lu  "
1038                                                 "ber_printf failed.\n", op->o_connid, 0, 0 );
1039
1040                                         if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1041                                         send_ldap_error( op, rs, LDAP_OTHER,
1042                                                 "encoding values error" );
1043                                         rc = rs->sr_err;
1044                                         goto error_return;
1045                                 }
1046                         }
1047                 }
1048
1049                 if ( finish && ( rc = ber_printf( ber, /*{[*/ "]N}" )) == -1 ) {
1050                         Debug( LDAP_DEBUG_ANY,
1051                                 "send_search_entry: conn %lu ber_printf failed\n", 
1052                                 op->o_connid, 0, 0 );
1053
1054                         if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1055                         send_ldap_error( op, rs, LDAP_OTHER, "encode end error" );
1056                         rc = rs->sr_err;
1057                         goto error_return;
1058                 }
1059         }
1060
1061         /* NOTE: moved before overlays callback circling because
1062          * they may modify entry and other stuff in rs */
1063         if ( rs->sr_operational_attrs != NULL && op->o_vrFilter != NULL ) {
1064                 int     k = 0;
1065                 size_t  size;
1066
1067                 for ( a = rs->sr_operational_attrs, i=0; a != NULL; a = a->a_next, i++ ) {
1068                         for ( j = 0; a->a_vals[j].bv_val != NULL; j++ ) k++;
1069                 }
1070
1071                 size = i * sizeof(char *) + k;
1072                 if ( size > 0 ) {
1073                         char    *a_flags, **tmp;
1074                 
1075                         /*
1076                          * Reuse previous memory - we likely need less space
1077                          * for operational attributes
1078                          */
1079                         tmp = slap_sl_realloc( e_flags, i * sizeof(char *) + k,
1080                                 op->o_tmpmemctx );
1081                         if ( tmp == NULL ) {
1082                                 Debug( LDAP_DEBUG_ANY,
1083                                         "send_search_entry: conn %lu "
1084                                         "not enough memory "
1085                                         "for matched values filtering\n",
1086                                         op->o_connid, 0, 0 );
1087                                 if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1088                                 send_ldap_error( op, rs, LDAP_OTHER,
1089                                         "not enough memory for matched values filtering" );
1090                                 goto error_return;
1091                         }
1092                         e_flags = tmp;
1093                         a_flags = (char *)(e_flags + i);
1094                         memset( a_flags, 0, k );
1095                         for ( a = rs->sr_operational_attrs, i=0; a != NULL; a = a->a_next, i++ ) {
1096                                 for ( j = 0; a->a_vals[j].bv_val != NULL; j++ );
1097                                 e_flags[i] = a_flags;
1098                                 a_flags += j;
1099                         }
1100                         rc = filter_matched_values(op, rs->sr_operational_attrs, &e_flags) ; 
1101                     
1102                         if ( rc == -1 ) {
1103                                 Debug( LDAP_DEBUG_ANY,
1104                                         "send_search_entry: conn %lu "
1105                                         "matched values filtering failed\n", 
1106                                         op->o_connid ? op->o_connid : 0, 0, 0);
1107                                 if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1108                                 send_ldap_error( op, rs, LDAP_OTHER,
1109                                         "matched values filtering error" );
1110                                 rc = rs->sr_err;
1111                                 goto error_return;
1112                         }
1113                 }
1114         }
1115
1116         for (a = rs->sr_operational_attrs, j=0; a != NULL; a = a->a_next, j++ ) {
1117                 AttributeDescription *desc = a->a_desc;
1118
1119                 if ( rs->sr_attrs == NULL ) {
1120                         /* all user attrs request, skip operational attributes */
1121                         if( is_at_operational( desc->ad_type ) ) {
1122                                 continue;
1123                         }
1124
1125                 } else {
1126                         /* specific attrs requested */
1127                         if( is_at_operational( desc->ad_type ) ) {
1128                                 if ( !SLAP_OPATTRS( rs->sr_attr_flags ) && 
1129                                         !ad_inlist( desc, rs->sr_attrs ) )
1130                                 {
1131                                         continue;
1132                                 }
1133                         } else {
1134                                 if ( !userattrs && !ad_inlist( desc, rs->sr_attrs ) ) {
1135                                         continue;
1136                                 }
1137                         }
1138                 }
1139
1140                 if ( ! access_allowed( op, rs->sr_entry, desc, NULL,
1141                         ACL_READ, &acl_state ) )
1142                 {
1143                         Debug( LDAP_DEBUG_ACL,
1144                                 "send_search_entry: conn %lu "
1145                                 "access to attribute %s not allowed\n",
1146                                 op->o_connid, desc->ad_cname.bv_val, 0 );
1147
1148                         continue;
1149                 }
1150
1151                 rc = ber_printf( ber, "{O[" /*]}*/ , &desc->ad_cname );
1152                 if ( rc == -1 ) {
1153                         Debug( LDAP_DEBUG_ANY,
1154                                 "send_search_entry: conn %lu  "
1155                                 "ber_printf failed\n", op->o_connid, 0, 0 );
1156
1157                         if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1158                         send_ldap_error( op, rs, LDAP_OTHER,
1159                                 "encoding description error" );
1160                         rc = rs->sr_err;
1161                         goto error_return;
1162                 }
1163
1164                 if ( ! attrsonly ) {
1165                         for ( i = 0; a->a_vals[i].bv_val != NULL; i++ ) {
1166                                 if ( ! access_allowed( op, rs->sr_entry,
1167                                         desc, &a->a_vals[i], ACL_READ, &acl_state ) )
1168                                 {
1169                                         Debug( LDAP_DEBUG_ACL,
1170                                                 "send_search_entry: conn %lu "
1171                                                 "access to %s, value %d not allowed\n",
1172                                                 op->o_connid, desc->ad_cname.bv_val, i );
1173
1174                                         continue;
1175                                 }
1176
1177                                 if ( op->o_vrFilter && e_flags[j][i] == 0 ){
1178                                         continue;
1179                                 }
1180
1181                                 if (( rc = ber_printf( ber, "O", &a->a_vals[i] )) == -1 ) {
1182                                         Debug( LDAP_DEBUG_ANY,
1183                                                 "send_search_entry: conn %lu  ber_printf failed\n", 
1184                                                 op->o_connid, 0, 0 );
1185
1186                                         if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1187                                         send_ldap_error( op, rs, LDAP_OTHER,
1188                                                 "encoding values error" );
1189                                         rc = rs->sr_err;
1190                                         goto error_return;
1191                                 }
1192                         }
1193                 }
1194
1195                 if (( rc = ber_printf( ber, /*{[*/ "]N}" )) == -1 ) {
1196                         Debug( LDAP_DEBUG_ANY,
1197                                 "send_search_entry: conn %lu  ber_printf failed\n",
1198                                 op->o_connid, 0, 0 );
1199
1200                         if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1201                         send_ldap_error( op, rs, LDAP_OTHER, "encode end error" );
1202                         rc = rs->sr_err;
1203                         goto error_return;
1204                 }
1205         }
1206
1207         /* free e_flags */
1208         if ( e_flags ) {
1209                 slap_sl_free( e_flags, op->o_tmpmemctx );
1210                 e_flags = NULL;
1211         }
1212
1213         rc = ber_printf( ber, /*{{*/ "}N}" );
1214
1215         if( rc != -1 ) {
1216                 rc = send_ldap_controls( op, ber, rs->sr_ctrls );
1217         }
1218
1219         if( rc != -1 ) {
1220 #ifdef LDAP_CONNECTIONLESS
1221                 if( op->o_conn && op->o_conn->c_is_udp ) {
1222                         if ( op->o_protocol != LDAP_VERSION2 ) {
1223                                 rc = ber_printf( ber, /*{*/ "N}" );
1224                         }
1225                 } else
1226 #endif
1227                 if ( op->o_res_ber == NULL ) {
1228                         rc = ber_printf( ber, /*{*/ "N}" );
1229                 }
1230         }
1231
1232         if ( rc == -1 ) {
1233                 Debug( LDAP_DEBUG_ANY, "ber_printf failed\n", 0, 0, 0 );
1234
1235                 if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1236                 send_ldap_error( op, rs, LDAP_OTHER, "encode entry end error" );
1237                 rc = rs->sr_err;
1238                 goto error_return;
1239         }
1240
1241         Statslog( LDAP_DEBUG_STATS2, "%s ENTRY dn=\"%s\"\n",
1242             op->o_log_prefix, rs->sr_entry->e_nname.bv_val, 0, 0, 0 );
1243
1244         if ( rs->sr_flags & REP_ENTRY_MUSTRELEASE ) {
1245                 be_entry_release_rw( op, rs->sr_entry, 0 );
1246                 rs->sr_flags ^= REP_ENTRY_MUSTRELEASE;
1247                 rs->sr_entry = NULL;
1248         }
1249
1250         if ( op->o_res_ber == NULL ) {
1251                 bytes = send_ldap_ber( op, ber );
1252                 ber_free_buf( ber );
1253
1254                 if ( bytes < 0 ) {
1255                         Debug( LDAP_DEBUG_ANY,
1256                                 "send_search_entry: conn %lu  ber write failed.\n", 
1257                                 op->o_connid, 0, 0 );
1258
1259                         rc = LDAP_UNAVAILABLE;
1260                         goto error_return;
1261                 }
1262                 rs->sr_nentries++;
1263
1264                 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex );
1265                 ldap_pvt_mp_add_ulong( op->o_counters->sc_bytes, (unsigned long)bytes );
1266                 ldap_pvt_mp_add_ulong( op->o_counters->sc_entries, 1 );
1267                 ldap_pvt_mp_add_ulong( op->o_counters->sc_pdu, 1 );
1268                 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex );
1269         }
1270
1271         Debug( LDAP_DEBUG_TRACE,
1272                 "<= send_search_entry: conn %lu exit.\n", op->o_connid, 0, 0 );
1273
1274         rc = LDAP_SUCCESS;
1275
1276 error_return:;
1277         if ( op->o_callback ) {
1278                 (void)slap_cleanup_play( op, rs );
1279         }
1280
1281         if ( e_flags ) {
1282                 slap_sl_free( e_flags, op->o_tmpmemctx );
1283         }
1284
1285         if ( rs->sr_operational_attrs ) {
1286                 attrs_free( rs->sr_operational_attrs );
1287                 rs->sr_operational_attrs = NULL;
1288         }
1289         rs->sr_attr_flags = SLAP_ATTRS_UNDEFINED;
1290
1291         /* FIXME: I think rs->sr_type should be explicitly set to
1292          * REP_SEARCH here. That's what it was when we entered this
1293          * function. send_ldap_error may have changed it, but we
1294          * should set it back so that the cleanup functions know
1295          * what they're doing.
1296          */
1297         if ( op->o_tag == LDAP_REQ_SEARCH && rs->sr_type == REP_SEARCH 
1298                 && rs->sr_entry 
1299                 && ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) ) 
1300         {
1301                 entry_free( rs->sr_entry );
1302                 rs->sr_entry = NULL;
1303                 rs->sr_flags &= ~REP_ENTRY_MUSTBEFREED;
1304         }
1305
1306         return( rc );
1307 }
1308
1309 int
1310 slap_send_search_reference( Operation *op, SlapReply *rs )
1311 {
1312         BerElementBuffer berbuf;
1313         BerElement      *ber = (BerElement *) &berbuf;
1314         int rc = 0;
1315         int bytes;
1316         char *edn = rs->sr_entry ? rs->sr_entry->e_name.bv_val : "(null)";
1317
1318         AttributeDescription *ad_ref = slap_schema.si_ad_ref;
1319         AttributeDescription *ad_entry = slap_schema.si_ad_entry;
1320
1321         rs->sr_type = REP_SEARCHREF;
1322         if ( op->o_callback ) {
1323                 rc = slap_response_play( op, rs );
1324                 if ( rc != SLAP_CB_CONTINUE ) {
1325                         goto rel;
1326                 }
1327         }
1328
1329         Debug( LDAP_DEBUG_TRACE,
1330                 "=> send_search_reference: dn=\"%s\"\n",
1331                 edn, 0, 0 );
1332
1333         if (  rs->sr_entry && ! access_allowed( op, rs->sr_entry,
1334                 ad_entry, NULL, ACL_READ, NULL ) )
1335         {
1336                 Debug( LDAP_DEBUG_ACL,
1337                         "send_search_reference: access to entry not allowed\n",
1338                     0, 0, 0 );
1339                 rc = 1;
1340                 goto rel;
1341         }
1342
1343         if ( rs->sr_entry && ! access_allowed( op, rs->sr_entry,
1344                 ad_ref, NULL, ACL_READ, NULL ) )
1345         {
1346                 Debug( LDAP_DEBUG_ACL,
1347                         "send_search_reference: access "
1348                         "to reference not allowed\n",
1349                     0, 0, 0 );
1350                 rc = 1;
1351                 goto rel;
1352         }
1353
1354         if( op->o_domain_scope ) {
1355                 Debug( LDAP_DEBUG_ANY,
1356                         "send_search_reference: domainScope control in (%s)\n", 
1357                         edn, 0, 0 );
1358                 rc = 0;
1359                 goto rel;
1360         }
1361
1362         if( rs->sr_ref == NULL ) {
1363                 Debug( LDAP_DEBUG_ANY,
1364                         "send_search_reference: null ref in (%s)\n", 
1365                         edn, 0, 0 );
1366                 rc = 1;
1367                 goto rel;
1368         }
1369
1370         if( op->o_protocol < LDAP_VERSION3 ) {
1371                 rc = 0;
1372                 /* save the references for the result */
1373                 if( rs->sr_ref[0].bv_val != NULL ) {
1374                         if( value_add( &rs->sr_v2ref, rs->sr_ref ) )
1375                                 rc = LDAP_OTHER;
1376                 }
1377                 goto rel;
1378         }
1379
1380 #ifdef LDAP_CONNECTIONLESS
1381         if( op->o_conn && op->o_conn->c_is_udp ) {
1382                 ber = op->o_res_ber;
1383         } else
1384 #endif
1385         {
1386                 ber_init_w_nullc( ber, LBER_USE_DER );
1387                 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
1388         }
1389
1390         rc = ber_printf( ber, "{it{W}" /*"}"*/ , op->o_msgid,
1391                 LDAP_RES_SEARCH_REFERENCE, rs->sr_ref );
1392
1393         if( rc != -1 ) {
1394                 rc = send_ldap_controls( op, ber, rs->sr_ctrls );
1395         }
1396
1397         if( rc != -1 ) {
1398                 rc = ber_printf( ber, /*"{"*/ "N}" );
1399         }
1400
1401         if ( rc == -1 ) {
1402                 Debug( LDAP_DEBUG_ANY,
1403                         "send_search_reference: ber_printf failed\n", 0, 0, 0 );
1404
1405 #ifdef LDAP_CONNECTIONLESS
1406                 if (!op->o_conn || op->o_conn->c_is_udp == 0)
1407 #endif
1408                 ber_free_buf( ber );
1409                 send_ldap_error( op, rs, LDAP_OTHER, "encode DN error" );
1410                 goto rel;
1411         }
1412
1413         rc = 0;
1414         if ( rs->sr_flags & REP_ENTRY_MUSTRELEASE ) {
1415                 assert( rs->sr_entry != NULL );
1416                 be_entry_release_rw( op, rs->sr_entry, 0 );
1417                 rs->sr_flags ^= REP_ENTRY_MUSTRELEASE;
1418                 rs->sr_entry = NULL;
1419         }
1420
1421 #ifdef LDAP_CONNECTIONLESS
1422         if (!op->o_conn || op->o_conn->c_is_udp == 0) {
1423 #endif
1424         bytes = send_ldap_ber( op, ber );
1425         ber_free_buf( ber );
1426
1427         if ( bytes < 0 ) {
1428                 rc = LDAP_UNAVAILABLE;
1429         } else {
1430                 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex );
1431                 ldap_pvt_mp_add_ulong( op->o_counters->sc_bytes, (unsigned long)bytes );
1432                 ldap_pvt_mp_add_ulong( op->o_counters->sc_refs, 1 );
1433                 ldap_pvt_mp_add_ulong( op->o_counters->sc_pdu, 1 );
1434                 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex );
1435         }
1436 #ifdef LDAP_CONNECTIONLESS
1437         }
1438 #endif
1439         if ( rs->sr_ref != NULL ) {
1440                 int     r;
1441
1442                 for ( r = 0; !BER_BVISNULL( &rs->sr_ref[ r ] ); r++ ) {
1443                         Statslog( LDAP_DEBUG_STATS2, "%s REF #%d \"%s\"\n",
1444                                 op->o_log_prefix, r, rs->sr_ref[0].bv_val,
1445                                 0, 0 );
1446                 }
1447
1448         } else {
1449                 Statslog( LDAP_DEBUG_STATS2, "%s REF \"(null)\"\n",
1450                         op->o_log_prefix, 0, 0, 0, 0 );
1451         }
1452
1453         Debug( LDAP_DEBUG_TRACE, "<= send_search_reference\n", 0, 0, 0 );
1454
1455 rel:
1456         if ( op->o_callback ) {
1457                 (void)slap_cleanup_play( op, rs );
1458         }
1459
1460         return rc;
1461 }
1462
1463 int
1464 str2result(
1465     char        *s,
1466     int         *code,
1467     char        **matched,
1468     char        **info )
1469 {
1470         int     rc;
1471         char    *c;
1472
1473         *code = LDAP_SUCCESS;
1474         *matched = NULL;
1475         *info = NULL;
1476
1477         if ( strncasecmp( s, "RESULT", STRLENOF( "RESULT" ) ) != 0 ) {
1478                 Debug( LDAP_DEBUG_ANY, "str2result (%s) expecting \"RESULT\"\n",
1479                     s, 0, 0 );
1480
1481                 return( -1 );
1482         }
1483
1484         rc = 0;
1485         while ( (s = strchr( s, '\n' )) != NULL ) {
1486                 *s++ = '\0';
1487                 if ( *s == '\0' ) {
1488                         break;
1489                 }
1490                 if ( (c = strchr( s, ':' )) != NULL ) {
1491                         c++;
1492                 }
1493
1494                 if ( strncasecmp( s, "code", STRLENOF( "code" ) ) == 0 ) {
1495                         char    *next = NULL;
1496                         long    retcode;
1497
1498                         if ( c == NULL ) {
1499                                 Debug( LDAP_DEBUG_ANY, "str2result (%s) missing value\n",
1500                                     s, 0, 0 );
1501                                 rc = -1;
1502                                 continue;
1503                         }
1504
1505                         while ( isspace( (unsigned char) c[ 0 ] ) ) c++;
1506                         if ( c[ 0 ] == '\0' ) {
1507                                 Debug( LDAP_DEBUG_ANY, "str2result (%s) missing or empty value\n",
1508                                     s, 0, 0 );
1509                                 rc = -1;
1510                                 continue;
1511                         }
1512
1513                         retcode = strtol( c, &next, 10 );
1514                         if ( next == NULL || next == c ) {
1515                                 Debug( LDAP_DEBUG_ANY, "str2result (%s) unable to parse value\n",
1516                                     s, 0, 0 );
1517                                 rc = -1;
1518                                 continue;
1519                         }
1520
1521                         while ( isspace( (unsigned char) next[ 0 ] ) ) next++;
1522                         if ( next[ 0 ] != '\0' ) {
1523                                 Debug( LDAP_DEBUG_ANY, "str2result (%s) extra cruft after value\n",
1524                                     s, 0, 0 );
1525                                 rc = -1;
1526                                 continue;
1527                         }
1528
1529                         /* FIXME: what if it's larger that max int? */
1530                         *code = (int)retcode;
1531
1532                 } else if ( strncasecmp( s, "matched", STRLENOF( "matched" ) ) == 0 ) {
1533                         if ( c != NULL ) {
1534                                 *matched = c;
1535                         }
1536                 } else if ( strncasecmp( s, "info", STRLENOF( "info" ) ) == 0 ) {
1537                         if ( c != NULL ) {
1538                                 *info = c;
1539                         }
1540                 } else {
1541                         Debug( LDAP_DEBUG_ANY, "str2result (%s) unknown\n",
1542                             s, 0, 0 );
1543
1544                         rc = -1;
1545                 }
1546         }
1547
1548         return( rc );
1549 }
1550
1551 int slap_read_controls(
1552         Operation *op,
1553         SlapReply *rs,
1554         Entry *e,
1555         const struct berval *oid,
1556         LDAPControl **ctrl )
1557 {
1558         int rc;
1559         struct berval bv;
1560         BerElementBuffer berbuf;
1561         BerElement *ber = (BerElement *) &berbuf;
1562         LDAPControl c;
1563         Operation myop;
1564
1565         Debug( LDAP_DEBUG_ANY, "%s slap_read_controls: (%s) %s\n",
1566                 op->o_log_prefix, oid->bv_val, e->e_dn );
1567
1568         rs->sr_entry = e;
1569         rs->sr_attrs = ( oid == &slap_pre_read_bv ) ?
1570                 op->o_preread_attrs : op->o_postread_attrs; 
1571
1572         bv.bv_len = entry_flatsize( rs->sr_entry, 0 );
1573         bv.bv_val = op->o_tmpalloc( bv.bv_len, op->o_tmpmemctx );
1574
1575         ber_init2( ber, &bv, LBER_USE_DER );
1576         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
1577
1578         /* create new operation */
1579         myop = *op;
1580         /* FIXME: o_bd needed for ACL */
1581         myop.o_bd = op->o_bd;
1582         myop.o_res_ber = ber;
1583         myop.o_callback = NULL;
1584         myop.ors_slimit = 1;
1585
1586         rc = slap_send_search_entry( &myop, rs );
1587         if( rc ) return rc;
1588
1589         rc = ber_flatten2( ber, &c.ldctl_value, 0 );
1590
1591         if( rc == -1 ) return LDAP_OTHER;
1592
1593         c.ldctl_oid = oid->bv_val;
1594         c.ldctl_iscritical = 0;
1595
1596         if ( *ctrl == NULL ) {
1597                 /* first try */
1598                 *ctrl = (LDAPControl *) slap_sl_calloc( 1, sizeof(LDAPControl), NULL );
1599         } else {
1600                 /* retry: free previous try */
1601                 slap_sl_free( (*ctrl)->ldctl_value.bv_val, op->o_tmpmemctx );
1602         }
1603
1604         **ctrl = c;
1605         return LDAP_SUCCESS;
1606 }
1607
1608 /* Map API errors to protocol errors... */
1609 int
1610 slap_map_api2result( SlapReply *rs )
1611 {
1612         switch(rs->sr_err) {
1613         case LDAP_SERVER_DOWN:
1614                 return LDAP_UNAVAILABLE;
1615         case LDAP_LOCAL_ERROR:
1616                 return LDAP_OTHER;
1617         case LDAP_ENCODING_ERROR:
1618         case LDAP_DECODING_ERROR:
1619                 return LDAP_PROTOCOL_ERROR;
1620         case LDAP_TIMEOUT:
1621                 return LDAP_UNAVAILABLE;
1622         case LDAP_AUTH_UNKNOWN:
1623                 return LDAP_AUTH_METHOD_NOT_SUPPORTED;
1624         case LDAP_FILTER_ERROR:
1625                 rs->sr_text = "Filter error";
1626                 return LDAP_OTHER;
1627         case LDAP_USER_CANCELLED:
1628                 rs->sr_text = "User cancelled";
1629                 return LDAP_OTHER;
1630         case LDAP_PARAM_ERROR:
1631                 return LDAP_PROTOCOL_ERROR;
1632         case LDAP_NO_MEMORY:
1633                 return LDAP_OTHER;
1634         case LDAP_CONNECT_ERROR:
1635                 return LDAP_UNAVAILABLE;
1636         case LDAP_NOT_SUPPORTED:
1637                 return LDAP_UNWILLING_TO_PERFORM;
1638         case LDAP_CONTROL_NOT_FOUND:
1639                 return LDAP_PROTOCOL_ERROR;
1640         case LDAP_NO_RESULTS_RETURNED:
1641                 return LDAP_NO_SUCH_OBJECT;
1642         case LDAP_MORE_RESULTS_TO_RETURN:
1643                 rs->sr_text = "More results to return";
1644                 return LDAP_OTHER;
1645         case LDAP_CLIENT_LOOP:
1646         case LDAP_REFERRAL_LIMIT_EXCEEDED:
1647                 return LDAP_LOOP_DETECT;
1648         default:
1649                 if ( LDAP_API_ERROR(rs->sr_err) ) return LDAP_OTHER;
1650                 return rs->sr_err;
1651         }
1652 }
1653
1654
1655 slap_mask_t
1656 slap_attr_flags( AttributeName *an )
1657 {
1658         slap_mask_t     flags = SLAP_ATTRS_UNDEFINED;
1659
1660         if ( an == NULL ) {
1661                 flags |= ( SLAP_OPATTRS_NO | SLAP_USERATTRS_YES );
1662
1663         } else {
1664                 flags |= an_find( an, slap_bv_all_operational_attrs )
1665                         ? SLAP_OPATTRS_YES : SLAP_OPATTRS_NO;
1666                 flags |= an_find( an, slap_bv_all_user_attrs )
1667                         ? SLAP_USERATTRS_YES : SLAP_USERATTRS_NO;
1668         }
1669
1670         return flags;
1671 }
1672