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