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