]> git.sur5r.net Git - openldap/blob - servers/slapd/result.c
Silence warning. Also avoids pointless umask(0) when umask already is 0.
[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( ber, &sorted.ldctl_value, 0 ) == -1 ) {
306                         return -1;
307                 }
308
309                 (void) ber_free_buf( ber );
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
620         Debug( LDAP_DEBUG_TRACE,
621                 "send_ldap_disconnect %d:%s\n",
622                 rs->sr_err, rs->sr_text ? rs->sr_text : "", NULL );
623
624         if ( op->o_protocol < LDAP_VERSION3 ) {
625                 rs->sr_rspoid = NULL;
626                 rs->sr_tag = slap_req2res( op->o_tag );
627                 rs->sr_msgid = (rs->sr_tag != LBER_SEQUENCE) ? op->o_msgid : 0;
628
629         } else {
630                 rs->sr_rspoid = LDAP_NOTICE_DISCONNECT;
631                 rs->sr_tag = LDAP_RES_EXTENDED;
632                 rs->sr_msgid = LDAP_RES_UNSOLICITED;
633         }
634
635         if ( send_ldap_response( op, rs ) == SLAP_CB_CONTINUE ) {
636                 Statslog( LDAP_DEBUG_STATS,
637                         "%s DISCONNECT tag=%lu err=%d text=%s\n",
638                         op->o_log_prefix, rs->sr_tag, rs->sr_err,
639                         rs->sr_text ? rs->sr_text : "", 0 );
640         }
641 }
642
643 void
644 slap_send_ldap_result( Operation *op, SlapReply *rs )
645 {
646         char *tmp = NULL;
647         const char *otext = rs->sr_text;
648         BerVarray oref = rs->sr_ref;
649
650         rs->sr_type = REP_RESULT;
651
652         /* Propagate Abandons so that cleanup callbacks can be processed */
653         if ( rs->sr_err == SLAPD_ABANDON || op->o_abandon )
654                 goto abandon;
655
656         assert( !LDAP_API_ERROR( rs->sr_err ) );
657
658         Debug( LDAP_DEBUG_TRACE,
659                 "send_ldap_result: %s p=%d\n",
660                 op->o_log_prefix, op->o_protocol, 0 );
661
662         Debug( LDAP_DEBUG_ARGS,
663                 "send_ldap_result: err=%d matched=\"%s\" text=\"%s\"\n",
664                 rs->sr_err, rs->sr_matched ? rs->sr_matched : "",
665                 rs->sr_text ? rs->sr_text : "" );
666
667
668         if( rs->sr_ref ) {
669                 Debug( LDAP_DEBUG_ARGS,
670                         "send_ldap_result: referral=\"%s\"\n",
671                         rs->sr_ref[0].bv_val ? rs->sr_ref[0].bv_val : "NULL",
672                         NULL, NULL );
673         }
674
675         assert( rs->sr_err != LDAP_PARTIAL_RESULTS );
676
677         if ( rs->sr_err == LDAP_REFERRAL ) {
678                 if( op->o_domain_scope ) rs->sr_ref = NULL;
679
680                 if( rs->sr_ref == NULL ) {
681                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
682                 } else if ( op->o_protocol < LDAP_VERSION3 ) {
683                         rs->sr_err = LDAP_PARTIAL_RESULTS;
684                 }
685         }
686
687         if ( op->o_protocol < LDAP_VERSION3 ) {
688                 tmp = v2ref( rs->sr_ref, rs->sr_text );
689                 rs->sr_text = tmp;
690                 rs->sr_ref = NULL;
691         }
692
693 abandon:
694         rs->sr_tag = slap_req2res( op->o_tag );
695         rs->sr_msgid = (rs->sr_tag != LBER_SEQUENCE) ? op->o_msgid : 0;
696
697         if ( rs->sr_flags & REP_REF_MUSTBEFREED ) {
698                 if ( rs->sr_ref == NULL ) {
699                         rs->sr_flags ^= REP_REF_MUSTBEFREED;
700                         ber_bvarray_free( oref );
701                 }
702                 oref = NULL; /* send_ldap_response() will free rs->sr_ref if != NULL */
703         }
704
705         if ( send_ldap_response( op, rs ) == SLAP_CB_CONTINUE ) {
706                 if ( op->o_tag == LDAP_REQ_SEARCH ) {
707                         Statslog( LDAP_DEBUG_STATS,
708                                 "%s SEARCH RESULT tag=%lu err=%d nentries=%d text=%s\n",
709                                 op->o_log_prefix, rs->sr_tag, rs->sr_err,
710                                 rs->sr_nentries, rs->sr_text ? rs->sr_text : "" );
711                 } else {
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         if( tmp != NULL ) ch_free(tmp);
720         rs->sr_text = otext;
721         rs->sr_ref = oref;
722 }
723
724 void
725 send_ldap_sasl( Operation *op, SlapReply *rs )
726 {
727         rs->sr_type = REP_SASL;
728         Debug( LDAP_DEBUG_TRACE, "send_ldap_sasl: err=%d len=%ld\n",
729                 rs->sr_err,
730                 rs->sr_sasldata ? (long) rs->sr_sasldata->bv_len : -1, NULL );
731
732         rs->sr_tag = slap_req2res( op->o_tag );
733         rs->sr_msgid = (rs->sr_tag != LBER_SEQUENCE) ? op->o_msgid : 0;
734
735         if ( send_ldap_response( op, rs ) == SLAP_CB_CONTINUE ) {
736                 Statslog( LDAP_DEBUG_STATS,
737                         "%s RESULT tag=%lu err=%d text=%s\n",
738                         op->o_log_prefix, rs->sr_tag, rs->sr_err,
739                         rs->sr_text ? rs->sr_text : "", 0 );
740         }
741 }
742
743 void
744 slap_send_ldap_extended( Operation *op, SlapReply *rs )
745 {
746         rs->sr_type = REP_EXTENDED;
747
748         Debug( LDAP_DEBUG_TRACE,
749                 "send_ldap_extended: err=%d oid=%s len=%ld\n",
750                 rs->sr_err,
751                 rs->sr_rspoid ? rs->sr_rspoid : "",
752                 rs->sr_rspdata != NULL ? rs->sr_rspdata->bv_len : 0 );
753
754         rs->sr_tag = slap_req2res( op->o_tag );
755         rs->sr_msgid = (rs->sr_tag != LBER_SEQUENCE) ? op->o_msgid : 0;
756
757         if ( send_ldap_response( op, rs ) == SLAP_CB_CONTINUE ) {
758                 Statslog( LDAP_DEBUG_STATS,
759                         "%s RESULT oid=%s err=%d text=%s\n",
760                         op->o_log_prefix, rs->sr_rspoid ? rs->sr_rspoid : "",
761                         rs->sr_err, rs->sr_text ? rs->sr_text : "", 0 );
762         }
763 }
764
765 void
766 slap_send_ldap_intermediate( Operation *op, SlapReply *rs )
767 {
768         rs->sr_type = REP_INTERMEDIATE;
769         Debug( LDAP_DEBUG_TRACE,
770                 "send_ldap_intermediate: err=%d oid=%s len=%ld\n",
771                 rs->sr_err,
772                 rs->sr_rspoid ? rs->sr_rspoid : "",
773                 rs->sr_rspdata != NULL ? rs->sr_rspdata->bv_len : 0 );
774         rs->sr_tag = LDAP_RES_INTERMEDIATE;
775         rs->sr_msgid = op->o_msgid;
776         if ( send_ldap_response( op, rs ) == SLAP_CB_CONTINUE ) {
777                 Statslog( LDAP_DEBUG_STATS2,
778                         "%s INTERM oid=%s\n",
779                         op->o_log_prefix,
780                         rs->sr_rspoid ? rs->sr_rspoid : "", 0, 0, 0 );
781         }
782 }
783
784 /*
785  * returns:
786  *
787  * LDAP_SUCCESS                 entry sent
788  * LDAP_OTHER                   entry not sent (other)
789  * LDAP_INSUFFICIENT_ACCESS     entry not sent (ACL)
790  * LDAP_UNAVAILABLE             entry not sent (connection closed)
791  * LDAP_SIZELIMIT_EXCEEDED      entry not sent (caller must send sizelimitExceeded)
792  */
793
794 int
795 slap_send_search_entry( Operation *op, SlapReply *rs )
796 {
797         BerElementBuffer berbuf;
798         BerElement      *ber = (BerElement *) &berbuf;
799         Attribute       *a;
800         int             i, j, rc = LDAP_UNAVAILABLE, bytes;
801         int             userattrs;
802         AccessControlState acl_state = ACL_STATE_INIT;
803         int                      attrsonly;
804         AttributeDescription *ad_entry = slap_schema.si_ad_entry;
805
806         /* a_flags: array of flags telling if the i-th element will be
807          *          returned or filtered out
808          * e_flags: array of a_flags
809          */
810         char **e_flags = NULL;
811
812         if ( op->ors_slimit >= 0 && rs->sr_nentries >= op->ors_slimit ) {
813                 return LDAP_SIZELIMIT_EXCEEDED;
814         }
815
816         /* Every 64 entries, check for thread pool pause */
817         if ( ( ( rs->sr_nentries & 0x3f ) == 0x3f ) &&
818                 ldap_pvt_thread_pool_pausing( &connection_pool ) > 0 )
819         {
820                 return LDAP_BUSY;
821         }
822
823         rs->sr_type = REP_SEARCH;
824
825         /* eventually will loop through generated operational attribute types
826          * currently implemented types include:
827          *      entryDN, subschemaSubentry, and hasSubordinates */
828         /* NOTE: moved before overlays callback circling because
829          * they may modify entry and other stuff in rs */
830         /* check for special all operational attributes ("+") type */
831         /* FIXME: maybe we could set this flag at the operation level;
832          * however, in principle the caller of send_search_entry() may
833          * change the attribute list at each call */
834         rs->sr_attr_flags = slap_attr_flags( rs->sr_attrs );
835
836         rc = backend_operational( op, rs );
837         if ( rc ) {
838                 goto error_return;
839         }
840
841         if ( op->o_callback ) {
842                 rc = slap_response_play( op, rs );
843                 if ( rc != SLAP_CB_CONTINUE ) {
844                         goto error_return;
845                 }
846         }
847
848         Debug( LDAP_DEBUG_TRACE, "=> send_search_entry: conn %lu dn=\"%s\"%s\n",
849                 op->o_connid, rs->sr_entry->e_name.bv_val,
850                 op->ors_attrsonly ? " (attrsOnly)" : "" );
851
852         attrsonly = op->ors_attrsonly;
853
854         if ( !access_allowed( op, rs->sr_entry, ad_entry, NULL, ACL_READ, NULL )) {
855                 Debug( LDAP_DEBUG_ACL,
856                         "send_search_entry: conn %lu access to entry (%s) not allowed\n", 
857                         op->o_connid, rs->sr_entry->e_name.bv_val, 0 );
858
859                 rc = LDAP_INSUFFICIENT_ACCESS;
860                 goto error_return;
861         }
862
863         if ( op->o_res_ber ) {
864                 /* read back control or LDAP_CONNECTIONLESS */
865             ber = op->o_res_ber;
866         } else {
867                 struct berval   bv;
868
869                 bv.bv_len = entry_flatsize( rs->sr_entry, 0 );
870                 bv.bv_val = op->o_tmpalloc( bv.bv_len, op->o_tmpmemctx );
871
872                 ber_init2( ber, &bv, LBER_USE_DER );
873                 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
874         }
875
876 #ifdef LDAP_CONNECTIONLESS
877         if ( op->o_conn && op->o_conn->c_is_udp ) {
878                 /* CONNECTIONLESS */
879                 if ( op->o_protocol == LDAP_VERSION2 ) {
880                 rc = ber_printf(ber, "t{O{" /*}}*/,
881                                 LDAP_RES_SEARCH_ENTRY, &rs->sr_entry->e_name );
882                 } else {
883                 rc = ber_printf( ber, "{it{O{" /*}}}*/, op->o_msgid,
884                                 LDAP_RES_SEARCH_ENTRY, &rs->sr_entry->e_name );
885                 }
886         } else
887 #endif
888         if ( op->o_res_ber ) {
889                 /* read back control */
890             rc = ber_printf( ber, "{O{" /*}}*/, &rs->sr_entry->e_name );
891         } else {
892             rc = ber_printf( ber, "{it{O{" /*}}}*/, op->o_msgid,
893                         LDAP_RES_SEARCH_ENTRY, &rs->sr_entry->e_name );
894         }
895
896         if ( rc == -1 ) {
897                 Debug( LDAP_DEBUG_ANY, 
898                         "send_search_entry: conn %lu  ber_printf failed\n", 
899                         op->o_connid, 0, 0 );
900
901                 if ( op->o_res_ber == NULL ) ber_free_buf( ber );
902                 send_ldap_error( op, rs, LDAP_OTHER, "encoding DN error" );
903                 rc = rs->sr_err;
904                 goto error_return;
905         }
906
907         /* check for special all user attributes ("*") type */
908         userattrs = SLAP_USERATTRS( rs->sr_attr_flags );
909
910         /* create an array of arrays of flags. Each flag corresponds
911          * to particular value of attribute and equals 1 if value matches
912          * to ValuesReturnFilter or 0 if not
913          */     
914         if ( op->o_vrFilter != NULL ) {
915                 int     k = 0;
916                 size_t  size;
917
918                 for ( a = rs->sr_entry->e_attrs, i=0; a != NULL; a = a->a_next, i++ ) {
919                         for ( j = 0; a->a_vals[j].bv_val != NULL; j++ ) k++;
920                 }
921
922                 size = i * sizeof(char *) + k;
923                 if ( size > 0 ) {
924                         char    *a_flags;
925                         e_flags = slap_sl_calloc ( 1, i * sizeof(char *) + k, op->o_tmpmemctx );
926                         if( e_flags == NULL ) {
927                         Debug( LDAP_DEBUG_ANY, 
928                                         "send_search_entry: conn %lu slap_sl_calloc failed\n",
929                                         op->o_connid ? op->o_connid : 0, 0, 0 );
930                                 ber_free( ber, 1 );
931         
932                                 send_ldap_error( op, rs, LDAP_OTHER, "out of memory" );
933                                 goto error_return;
934                         }
935                         a_flags = (char *)(e_flags + i);
936                         memset( a_flags, 0, k );
937                         for ( a=rs->sr_entry->e_attrs, i=0; a != NULL; a=a->a_next, i++ ) {
938                                 for ( j = 0; a->a_vals[j].bv_val != NULL; j++ );
939                                 e_flags[i] = a_flags;
940                                 a_flags += j;
941                         }
942         
943                         rc = filter_matched_values(op, rs->sr_entry->e_attrs, &e_flags) ; 
944                         if ( rc == -1 ) {
945                                 Debug( LDAP_DEBUG_ANY, "send_search_entry: "
946                                         "conn %lu matched values filtering failed\n",
947                                         op->o_connid ? op->o_connid : 0, 0, 0 );
948                                 if ( op->o_res_ber == NULL ) ber_free_buf( ber );
949                                 send_ldap_error( op, rs, LDAP_OTHER,
950                                         "matched values filtering error" );
951                                 rc = rs->sr_err;
952                                 goto error_return;
953                         }
954                 }
955         }
956
957         for ( a = rs->sr_entry->e_attrs, j = 0; a != NULL; a = a->a_next, j++ ) {
958                 AttributeDescription *desc = a->a_desc;
959                 int finish = 0;
960
961                 if ( rs->sr_attrs == NULL ) {
962                         /* all user attrs request, skip operational attributes */
963                         if( is_at_operational( desc->ad_type ) ) {
964                                 continue;
965                         }
966
967                 } else {
968                         /* specific attrs requested */
969                         if ( is_at_operational( desc->ad_type ) ) {
970                                 /* if not explicitly requested */
971                                 if ( !ad_inlist( desc, rs->sr_attrs )) {
972                                         /* if not all op attrs requested, skip */
973                                         if ( !SLAP_OPATTRS( rs->sr_attr_flags ))
974                                                 continue;
975                                         /* if DSA-specific and replicating, skip */
976                                         if ( op->o_sync != SLAP_CONTROL_NONE &&
977                                                 desc->ad_type->sat_usage == LDAP_SCHEMA_DSA_OPERATION )
978                                                 continue;
979                                 }
980                         } else {
981                                 if ( !userattrs && !ad_inlist( desc, rs->sr_attrs ) ) {
982                                         continue;
983                                 }
984                         }
985                 }
986
987                 if ( attrsonly ) {
988                         if ( ! access_allowed( op, rs->sr_entry, desc, NULL,
989                                 ACL_READ, &acl_state ) )
990                         {
991                                 Debug( LDAP_DEBUG_ACL, "send_search_entry: "
992                                         "conn %lu access to attribute %s not allowed\n",
993                                         op->o_connid, desc->ad_cname.bv_val, 0 );
994                                 continue;
995                         }
996
997                         if (( rc = ber_printf( ber, "{O[" /*]}*/ , &desc->ad_cname )) == -1 ) {
998                                 Debug( LDAP_DEBUG_ANY, 
999                                         "send_search_entry: conn %lu  ber_printf failed\n", 
1000                                         op->o_connid, 0, 0 );
1001
1002                                 if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1003                                 send_ldap_error( op, rs, LDAP_OTHER,
1004                                         "encoding description error");
1005                                 rc = rs->sr_err;
1006                                 goto error_return;
1007                         }
1008                         finish = 1;
1009
1010                 } else {
1011                         int first = 1;
1012                         for ( i = 0; a->a_nvals[i].bv_val != NULL; i++ ) {
1013                                 if ( ! access_allowed( op, rs->sr_entry,
1014                                         desc, &a->a_nvals[i], ACL_READ, &acl_state ) )
1015                                 {
1016                                         Debug( LDAP_DEBUG_ACL,
1017                                                 "send_search_entry: conn %lu "
1018                                                 "access to attribute %s, value #%d not allowed\n",
1019                                                 op->o_connid, desc->ad_cname.bv_val, i );
1020
1021                                         continue;
1022                                 }
1023
1024                                 if ( op->o_vrFilter && e_flags[j][i] == 0 ){
1025                                         continue;
1026                                 }
1027
1028                                 if ( first ) {
1029                                         first = 0;
1030                                         finish = 1;
1031                                         if (( rc = ber_printf( ber, "{O[" /*]}*/ , &desc->ad_cname )) == -1 ) {
1032                                                 Debug( LDAP_DEBUG_ANY,
1033                                                         "send_search_entry: conn %lu  ber_printf failed\n", 
1034                                                         op->o_connid, 0, 0 );
1035
1036                                                 if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1037                                                 send_ldap_error( op, rs, LDAP_OTHER,
1038                                                         "encoding description error");
1039                                                 rc = rs->sr_err;
1040                                                 goto error_return;
1041                                         }
1042                                 }
1043                                 if (( rc = ber_printf( ber, "O", &a->a_vals[i] )) == -1 ) {
1044                                         Debug( LDAP_DEBUG_ANY,
1045                                                 "send_search_entry: conn %lu  "
1046                                                 "ber_printf failed.\n", op->o_connid, 0, 0 );
1047
1048                                         if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1049                                         send_ldap_error( op, rs, LDAP_OTHER,
1050                                                 "encoding values error" );
1051                                         rc = rs->sr_err;
1052                                         goto error_return;
1053                                 }
1054                         }
1055                 }
1056
1057                 if ( finish && ( rc = ber_printf( ber, /*{[*/ "]N}" )) == -1 ) {
1058                         Debug( LDAP_DEBUG_ANY,
1059                                 "send_search_entry: conn %lu ber_printf failed\n", 
1060                                 op->o_connid, 0, 0 );
1061
1062                         if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1063                         send_ldap_error( op, rs, LDAP_OTHER, "encode end error" );
1064                         rc = rs->sr_err;
1065                         goto error_return;
1066                 }
1067         }
1068
1069         /* NOTE: moved before overlays callback circling because
1070          * they may modify entry and other stuff in rs */
1071         if ( rs->sr_operational_attrs != NULL && op->o_vrFilter != NULL ) {
1072                 int     k = 0;
1073                 size_t  size;
1074
1075                 for ( a = rs->sr_operational_attrs, i=0; a != NULL; a = a->a_next, i++ ) {
1076                         for ( j = 0; a->a_vals[j].bv_val != NULL; j++ ) k++;
1077                 }
1078
1079                 size = i * sizeof(char *) + k;
1080                 if ( size > 0 ) {
1081                         char    *a_flags, **tmp;
1082                 
1083                         /*
1084                          * Reuse previous memory - we likely need less space
1085                          * for operational attributes
1086                          */
1087                         tmp = slap_sl_realloc( e_flags, i * sizeof(char *) + k,
1088                                 op->o_tmpmemctx );
1089                         if ( tmp == NULL ) {
1090                                 Debug( LDAP_DEBUG_ANY,
1091                                         "send_search_entry: conn %lu "
1092                                         "not enough memory "
1093                                         "for matched values filtering\n",
1094                                         op->o_connid, 0, 0 );
1095                                 if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1096                                 send_ldap_error( op, rs, LDAP_OTHER,
1097                                         "not enough memory for matched values filtering" );
1098                                 goto error_return;
1099                         }
1100                         e_flags = tmp;
1101                         a_flags = (char *)(e_flags + i);
1102                         memset( a_flags, 0, k );
1103                         for ( a = rs->sr_operational_attrs, i=0; a != NULL; a = a->a_next, i++ ) {
1104                                 for ( j = 0; a->a_vals[j].bv_val != NULL; j++ );
1105                                 e_flags[i] = a_flags;
1106                                 a_flags += j;
1107                         }
1108                         rc = filter_matched_values(op, rs->sr_operational_attrs, &e_flags) ; 
1109                     
1110                         if ( rc == -1 ) {
1111                                 Debug( LDAP_DEBUG_ANY,
1112                                         "send_search_entry: conn %lu "
1113                                         "matched values filtering failed\n", 
1114                                         op->o_connid ? op->o_connid : 0, 0, 0);
1115                                 if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1116                                 send_ldap_error( op, rs, LDAP_OTHER,
1117                                         "matched values filtering error" );
1118                                 rc = rs->sr_err;
1119                                 goto error_return;
1120                         }
1121                 }
1122         }
1123
1124         for (a = rs->sr_operational_attrs, j=0; a != NULL; a = a->a_next, j++ ) {
1125                 AttributeDescription *desc = a->a_desc;
1126
1127                 if ( rs->sr_attrs == NULL ) {
1128                         /* all user attrs request, skip operational attributes */
1129                         if( is_at_operational( desc->ad_type ) ) {
1130                                 continue;
1131                         }
1132
1133                 } else {
1134                         /* specific attrs requested */
1135                         if( is_at_operational( desc->ad_type ) ) {
1136                                 if ( !SLAP_OPATTRS( rs->sr_attr_flags ) && 
1137                                         !ad_inlist( desc, rs->sr_attrs ) )
1138                                 {
1139                                         continue;
1140                                 }
1141                         } else {
1142                                 if ( !userattrs && !ad_inlist( desc, rs->sr_attrs ) ) {
1143                                         continue;
1144                                 }
1145                         }
1146                 }
1147
1148                 if ( ! access_allowed( op, rs->sr_entry, desc, NULL,
1149                         ACL_READ, &acl_state ) )
1150                 {
1151                         Debug( LDAP_DEBUG_ACL,
1152                                 "send_search_entry: conn %lu "
1153                                 "access to attribute %s not allowed\n",
1154                                 op->o_connid, desc->ad_cname.bv_val, 0 );
1155
1156                         continue;
1157                 }
1158
1159                 rc = ber_printf( ber, "{O[" /*]}*/ , &desc->ad_cname );
1160                 if ( rc == -1 ) {
1161                         Debug( LDAP_DEBUG_ANY,
1162                                 "send_search_entry: conn %lu  "
1163                                 "ber_printf failed\n", op->o_connid, 0, 0 );
1164
1165                         if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1166                         send_ldap_error( op, rs, LDAP_OTHER,
1167                                 "encoding description error" );
1168                         rc = rs->sr_err;
1169                         goto error_return;
1170                 }
1171
1172                 if ( ! attrsonly ) {
1173                         for ( i = 0; a->a_vals[i].bv_val != NULL; i++ ) {
1174                                 if ( ! access_allowed( op, rs->sr_entry,
1175                                         desc, &a->a_vals[i], ACL_READ, &acl_state ) )
1176                                 {
1177                                         Debug( LDAP_DEBUG_ACL,
1178                                                 "send_search_entry: conn %lu "
1179                                                 "access to %s, value %d not allowed\n",
1180                                                 op->o_connid, desc->ad_cname.bv_val, i );
1181
1182                                         continue;
1183                                 }
1184
1185                                 if ( op->o_vrFilter && e_flags[j][i] == 0 ){
1186                                         continue;
1187                                 }
1188
1189                                 if (( rc = ber_printf( ber, "O", &a->a_vals[i] )) == -1 ) {
1190                                         Debug( LDAP_DEBUG_ANY,
1191                                                 "send_search_entry: conn %lu  ber_printf failed\n", 
1192                                                 op->o_connid, 0, 0 );
1193
1194                                         if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1195                                         send_ldap_error( op, rs, LDAP_OTHER,
1196                                                 "encoding values error" );
1197                                         rc = rs->sr_err;
1198                                         goto error_return;
1199                                 }
1200                         }
1201                 }
1202
1203                 if (( rc = ber_printf( ber, /*{[*/ "]N}" )) == -1 ) {
1204                         Debug( LDAP_DEBUG_ANY,
1205                                 "send_search_entry: conn %lu  ber_printf failed\n",
1206                                 op->o_connid, 0, 0 );
1207
1208                         if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1209                         send_ldap_error( op, rs, LDAP_OTHER, "encode end error" );
1210                         rc = rs->sr_err;
1211                         goto error_return;
1212                 }
1213         }
1214
1215         /* free e_flags */
1216         if ( e_flags ) {
1217                 slap_sl_free( e_flags, op->o_tmpmemctx );
1218                 e_flags = NULL;
1219         }
1220
1221         rc = ber_printf( ber, /*{{*/ "}N}" );
1222
1223         if( rc != -1 ) {
1224                 rc = send_ldap_controls( op, ber, rs->sr_ctrls );
1225         }
1226
1227         if( rc != -1 ) {
1228 #ifdef LDAP_CONNECTIONLESS
1229                 if( op->o_conn && op->o_conn->c_is_udp ) {
1230                         if ( op->o_protocol != LDAP_VERSION2 ) {
1231                                 rc = ber_printf( ber, /*{*/ "N}" );
1232                         }
1233                 } else
1234 #endif
1235                 if ( op->o_res_ber == NULL ) {
1236                         rc = ber_printf( ber, /*{*/ "N}" );
1237                 }
1238         }
1239
1240         if ( rc == -1 ) {
1241                 Debug( LDAP_DEBUG_ANY, "ber_printf failed\n", 0, 0, 0 );
1242
1243                 if ( op->o_res_ber == NULL ) ber_free_buf( ber );
1244                 send_ldap_error( op, rs, LDAP_OTHER, "encode entry end error" );
1245                 rc = rs->sr_err;
1246                 goto error_return;
1247         }
1248
1249         Statslog( LDAP_DEBUG_STATS2, "%s ENTRY dn=\"%s\"\n",
1250             op->o_log_prefix, rs->sr_entry->e_nname.bv_val, 0, 0, 0 );
1251
1252         if ( rs->sr_flags & REP_ENTRY_MUSTRELEASE ) {
1253                 be_entry_release_rw( op, rs->sr_entry, 0 );
1254                 rs->sr_flags ^= REP_ENTRY_MUSTRELEASE;
1255                 rs->sr_entry = NULL;
1256         }
1257
1258         if ( op->o_res_ber == NULL ) {
1259                 bytes = send_ldap_ber( op, ber );
1260                 ber_free_buf( ber );
1261
1262                 if ( bytes < 0 ) {
1263                         Debug( LDAP_DEBUG_ANY,
1264                                 "send_search_entry: conn %lu  ber write failed.\n", 
1265                                 op->o_connid, 0, 0 );
1266
1267                         rc = LDAP_UNAVAILABLE;
1268                         goto error_return;
1269                 }
1270                 rs->sr_nentries++;
1271
1272                 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex );
1273                 ldap_pvt_mp_add_ulong( op->o_counters->sc_bytes, (unsigned long)bytes );
1274                 ldap_pvt_mp_add_ulong( op->o_counters->sc_entries, 1 );
1275                 ldap_pvt_mp_add_ulong( op->o_counters->sc_pdu, 1 );
1276                 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex );
1277         }
1278
1279         Debug( LDAP_DEBUG_TRACE,
1280                 "<= send_search_entry: conn %lu exit.\n", op->o_connid, 0, 0 );
1281
1282         rc = LDAP_SUCCESS;
1283
1284 error_return:;
1285         if ( op->o_callback ) {
1286                 (void)slap_cleanup_play( op, rs );
1287         }
1288
1289         if ( e_flags ) {
1290                 slap_sl_free( e_flags, op->o_tmpmemctx );
1291         }
1292
1293         if ( rs->sr_operational_attrs ) {
1294                 attrs_free( rs->sr_operational_attrs );
1295                 rs->sr_operational_attrs = NULL;
1296         }
1297         rs->sr_attr_flags = SLAP_ATTRS_UNDEFINED;
1298
1299         /* FIXME: I think rs->sr_type should be explicitly set to
1300          * REP_SEARCH here. That's what it was when we entered this
1301          * function. send_ldap_error may have changed it, but we
1302          * should set it back so that the cleanup functions know
1303          * what they're doing.
1304          */
1305         if ( op->o_tag == LDAP_REQ_SEARCH && rs->sr_type == REP_SEARCH 
1306                 && rs->sr_entry 
1307                 && ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) ) 
1308         {
1309                 entry_free( rs->sr_entry );
1310                 rs->sr_entry = NULL;
1311                 rs->sr_flags &= ~REP_ENTRY_MUSTBEFREED;
1312         }
1313
1314         return( rc );
1315 }
1316
1317 int
1318 slap_send_search_reference( Operation *op, SlapReply *rs )
1319 {
1320         BerElementBuffer berbuf;
1321         BerElement      *ber = (BerElement *) &berbuf;
1322         int rc = 0;
1323         int bytes;
1324         char *edn = rs->sr_entry ? rs->sr_entry->e_name.bv_val : "(null)";
1325
1326         AttributeDescription *ad_ref = slap_schema.si_ad_ref;
1327         AttributeDescription *ad_entry = slap_schema.si_ad_entry;
1328
1329         rs->sr_type = REP_SEARCHREF;
1330         if ( op->o_callback ) {
1331                 rc = slap_response_play( op, rs );
1332                 if ( rc != SLAP_CB_CONTINUE ) {
1333                         goto rel;
1334                 }
1335         }
1336
1337         Debug( LDAP_DEBUG_TRACE,
1338                 "=> send_search_reference: dn=\"%s\"\n",
1339                 edn, 0, 0 );
1340
1341         if (  rs->sr_entry && ! access_allowed( op, rs->sr_entry,
1342                 ad_entry, NULL, ACL_READ, NULL ) )
1343         {
1344                 Debug( LDAP_DEBUG_ACL,
1345                         "send_search_reference: access to entry not allowed\n",
1346                     0, 0, 0 );
1347                 rc = 1;
1348                 goto rel;
1349         }
1350
1351         if ( rs->sr_entry && ! access_allowed( op, rs->sr_entry,
1352                 ad_ref, NULL, ACL_READ, NULL ) )
1353         {
1354                 Debug( LDAP_DEBUG_ACL,
1355                         "send_search_reference: access "
1356                         "to reference not allowed\n",
1357                     0, 0, 0 );
1358                 rc = 1;
1359                 goto rel;
1360         }
1361
1362         if( op->o_domain_scope ) {
1363                 Debug( LDAP_DEBUG_ANY,
1364                         "send_search_reference: domainScope control in (%s)\n", 
1365                         edn, 0, 0 );
1366                 rc = 0;
1367                 goto rel;
1368         }
1369
1370         if( rs->sr_ref == NULL ) {
1371                 Debug( LDAP_DEBUG_ANY,
1372                         "send_search_reference: null ref in (%s)\n", 
1373                         edn, 0, 0 );
1374                 rc = 1;
1375                 goto rel;
1376         }
1377
1378         if( op->o_protocol < LDAP_VERSION3 ) {
1379                 rc = 0;
1380                 /* save the references for the result */
1381                 if( rs->sr_ref[0].bv_val != NULL ) {
1382                         if( value_add( &rs->sr_v2ref, rs->sr_ref ) )
1383                                 rc = LDAP_OTHER;
1384                 }
1385                 goto rel;
1386         }
1387
1388 #ifdef LDAP_CONNECTIONLESS
1389         if( op->o_conn && op->o_conn->c_is_udp ) {
1390                 ber = op->o_res_ber;
1391         } else
1392 #endif
1393         {
1394                 ber_init_w_nullc( ber, LBER_USE_DER );
1395                 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
1396         }
1397
1398         rc = ber_printf( ber, "{it{W}" /*"}"*/ , op->o_msgid,
1399                 LDAP_RES_SEARCH_REFERENCE, rs->sr_ref );
1400
1401         if( rc != -1 ) {
1402                 rc = send_ldap_controls( op, ber, rs->sr_ctrls );
1403         }
1404
1405         if( rc != -1 ) {
1406                 rc = ber_printf( ber, /*"{"*/ "N}" );
1407         }
1408
1409         if ( rc == -1 ) {
1410                 Debug( LDAP_DEBUG_ANY,
1411                         "send_search_reference: ber_printf failed\n", 0, 0, 0 );
1412
1413 #ifdef LDAP_CONNECTIONLESS
1414                 if (!op->o_conn || op->o_conn->c_is_udp == 0)
1415 #endif
1416                 ber_free_buf( ber );
1417                 send_ldap_error( op, rs, LDAP_OTHER, "encode DN error" );
1418                 goto rel;
1419         }
1420
1421         rc = 0;
1422         if ( rs->sr_flags & REP_ENTRY_MUSTRELEASE ) {
1423                 assert( rs->sr_entry != NULL );
1424                 be_entry_release_rw( op, rs->sr_entry, 0 );
1425                 rs->sr_flags ^= REP_ENTRY_MUSTRELEASE;
1426                 rs->sr_entry = NULL;
1427         }
1428
1429 #ifdef LDAP_CONNECTIONLESS
1430         if (!op->o_conn || op->o_conn->c_is_udp == 0) {
1431 #endif
1432         bytes = send_ldap_ber( op, ber );
1433         ber_free_buf( ber );
1434
1435         if ( bytes < 0 ) {
1436                 rc = LDAP_UNAVAILABLE;
1437         } else {
1438                 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex );
1439                 ldap_pvt_mp_add_ulong( op->o_counters->sc_bytes, (unsigned long)bytes );
1440                 ldap_pvt_mp_add_ulong( op->o_counters->sc_refs, 1 );
1441                 ldap_pvt_mp_add_ulong( op->o_counters->sc_pdu, 1 );
1442                 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex );
1443         }
1444 #ifdef LDAP_CONNECTIONLESS
1445         }
1446 #endif
1447         if ( rs->sr_ref != NULL ) {
1448                 int     r;
1449
1450                 for ( r = 0; !BER_BVISNULL( &rs->sr_ref[ r ] ); r++ ) {
1451                         Statslog( LDAP_DEBUG_STATS2, "%s REF #%d \"%s\"\n",
1452                                 op->o_log_prefix, r, rs->sr_ref[0].bv_val,
1453                                 0, 0 );
1454                 }
1455
1456         } else {
1457                 Statslog( LDAP_DEBUG_STATS2, "%s REF \"(null)\"\n",
1458                         op->o_log_prefix, 0, 0, 0, 0 );
1459         }
1460
1461         Debug( LDAP_DEBUG_TRACE, "<= send_search_reference\n", 0, 0, 0 );
1462
1463 rel:
1464         if ( op->o_callback ) {
1465                 (void)slap_cleanup_play( op, rs );
1466         }
1467
1468         return rc;
1469 }
1470
1471 int
1472 str2result(
1473     char        *s,
1474     int         *code,
1475     char        **matched,
1476     char        **info )
1477 {
1478         int     rc;
1479         char    *c;
1480
1481         *code = LDAP_SUCCESS;
1482         *matched = NULL;
1483         *info = NULL;
1484
1485         if ( strncasecmp( s, "RESULT", STRLENOF( "RESULT" ) ) != 0 ) {
1486                 Debug( LDAP_DEBUG_ANY, "str2result (%s) expecting \"RESULT\"\n",
1487                     s, 0, 0 );
1488
1489                 return( -1 );
1490         }
1491
1492         rc = 0;
1493         while ( (s = strchr( s, '\n' )) != NULL ) {
1494                 *s++ = '\0';
1495                 if ( *s == '\0' ) {
1496                         break;
1497                 }
1498                 if ( (c = strchr( s, ':' )) != NULL ) {
1499                         c++;
1500                 }
1501
1502                 if ( strncasecmp( s, "code", STRLENOF( "code" ) ) == 0 ) {
1503                         char    *next = NULL;
1504                         long    retcode;
1505
1506                         if ( c == NULL ) {
1507                                 Debug( LDAP_DEBUG_ANY, "str2result (%s) missing value\n",
1508                                     s, 0, 0 );
1509                                 rc = -1;
1510                                 continue;
1511                         }
1512
1513                         while ( isspace( (unsigned char) c[ 0 ] ) ) c++;
1514                         if ( c[ 0 ] == '\0' ) {
1515                                 Debug( LDAP_DEBUG_ANY, "str2result (%s) missing or empty value\n",
1516                                     s, 0, 0 );
1517                                 rc = -1;
1518                                 continue;
1519                         }
1520
1521                         retcode = strtol( c, &next, 10 );
1522                         if ( next == NULL || next == c ) {
1523                                 Debug( LDAP_DEBUG_ANY, "str2result (%s) unable to parse value\n",
1524                                     s, 0, 0 );
1525                                 rc = -1;
1526                                 continue;
1527                         }
1528
1529                         while ( isspace( (unsigned char) next[ 0 ] ) ) next++;
1530                         if ( next[ 0 ] != '\0' ) {
1531                                 Debug( LDAP_DEBUG_ANY, "str2result (%s) extra cruft after value\n",
1532                                     s, 0, 0 );
1533                                 rc = -1;
1534                                 continue;
1535                         }
1536
1537                         /* FIXME: what if it's larger that max int? */
1538                         *code = (int)retcode;
1539
1540                 } else if ( strncasecmp( s, "matched", STRLENOF( "matched" ) ) == 0 ) {
1541                         if ( c != NULL ) {
1542                                 *matched = c;
1543                         }
1544                 } else if ( strncasecmp( s, "info", STRLENOF( "info" ) ) == 0 ) {
1545                         if ( c != NULL ) {
1546                                 *info = c;
1547                         }
1548                 } else {
1549                         Debug( LDAP_DEBUG_ANY, "str2result (%s) unknown\n",
1550                             s, 0, 0 );
1551
1552                         rc = -1;
1553                 }
1554         }
1555
1556         return( rc );
1557 }
1558
1559 int slap_read_controls(
1560         Operation *op,
1561         SlapReply *rs,
1562         Entry *e,
1563         const struct berval *oid,
1564         LDAPControl **ctrl )
1565 {
1566         int rc;
1567         struct berval bv;
1568         BerElementBuffer berbuf;
1569         BerElement *ber = (BerElement *) &berbuf;
1570         LDAPControl c;
1571         Operation myop;
1572
1573         Debug( LDAP_DEBUG_ANY, "%s slap_read_controls: (%s) %s\n",
1574                 op->o_log_prefix, oid->bv_val, e->e_dn );
1575
1576         rs->sr_entry = e;
1577         rs->sr_attrs = ( oid == &slap_pre_read_bv ) ?
1578                 op->o_preread_attrs : op->o_postread_attrs; 
1579
1580         bv.bv_len = entry_flatsize( rs->sr_entry, 0 );
1581         bv.bv_val = op->o_tmpalloc( bv.bv_len, op->o_tmpmemctx );
1582
1583         ber_init2( ber, &bv, LBER_USE_DER );
1584         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
1585
1586         /* create new operation */
1587         myop = *op;
1588         /* FIXME: o_bd needed for ACL */
1589         myop.o_bd = op->o_bd;
1590         myop.o_res_ber = ber;
1591         myop.o_callback = NULL;
1592         myop.ors_slimit = 1;
1593
1594         rc = slap_send_search_entry( &myop, rs );
1595         if( rc ) return rc;
1596
1597         rc = ber_flatten2( ber, &c.ldctl_value, 0 );
1598
1599         if( rc == -1 ) return LDAP_OTHER;
1600
1601         c.ldctl_oid = oid->bv_val;
1602         c.ldctl_iscritical = 0;
1603
1604         if ( *ctrl == NULL ) {
1605                 /* first try */
1606                 *ctrl = (LDAPControl *) slap_sl_calloc( 1, sizeof(LDAPControl), NULL );
1607         } else {
1608                 /* retry: free previous try */
1609                 slap_sl_free( (*ctrl)->ldctl_value.bv_val, op->o_tmpmemctx );
1610         }
1611
1612         **ctrl = c;
1613         return LDAP_SUCCESS;
1614 }
1615
1616 /* Map API errors to protocol errors... */
1617 int
1618 slap_map_api2result( SlapReply *rs )
1619 {
1620         switch(rs->sr_err) {
1621         case LDAP_SERVER_DOWN:
1622                 return LDAP_UNAVAILABLE;
1623         case LDAP_LOCAL_ERROR:
1624                 return LDAP_OTHER;
1625         case LDAP_ENCODING_ERROR:
1626         case LDAP_DECODING_ERROR:
1627                 return LDAP_PROTOCOL_ERROR;
1628         case LDAP_TIMEOUT:
1629                 return LDAP_UNAVAILABLE;
1630         case LDAP_AUTH_UNKNOWN:
1631                 return LDAP_AUTH_METHOD_NOT_SUPPORTED;
1632         case LDAP_FILTER_ERROR:
1633                 rs->sr_text = "Filter error";
1634                 return LDAP_OTHER;
1635         case LDAP_USER_CANCELLED:
1636                 rs->sr_text = "User cancelled";
1637                 return LDAP_OTHER;
1638         case LDAP_PARAM_ERROR:
1639                 return LDAP_PROTOCOL_ERROR;
1640         case LDAP_NO_MEMORY:
1641                 return LDAP_OTHER;
1642         case LDAP_CONNECT_ERROR:
1643                 return LDAP_UNAVAILABLE;
1644         case LDAP_NOT_SUPPORTED:
1645                 return LDAP_UNWILLING_TO_PERFORM;
1646         case LDAP_CONTROL_NOT_FOUND:
1647                 return LDAP_PROTOCOL_ERROR;
1648         case LDAP_NO_RESULTS_RETURNED:
1649                 return LDAP_NO_SUCH_OBJECT;
1650         case LDAP_MORE_RESULTS_TO_RETURN:
1651                 rs->sr_text = "More results to return";
1652                 return LDAP_OTHER;
1653         case LDAP_CLIENT_LOOP:
1654         case LDAP_REFERRAL_LIMIT_EXCEEDED:
1655                 return LDAP_LOOP_DETECT;
1656         default:
1657                 if ( LDAP_API_ERROR(rs->sr_err) ) return LDAP_OTHER;
1658                 return rs->sr_err;
1659         }
1660 }
1661
1662
1663 slap_mask_t
1664 slap_attr_flags( AttributeName *an )
1665 {
1666         slap_mask_t     flags = SLAP_ATTRS_UNDEFINED;
1667
1668         if ( an == NULL ) {
1669                 flags |= ( SLAP_OPATTRS_NO | SLAP_USERATTRS_YES );
1670
1671         } else {
1672                 flags |= an_find( an, slap_bv_all_operational_attrs )
1673                         ? SLAP_OPATTRS_YES : SLAP_OPATTRS_NO;
1674                 flags |= an_find( an, slap_bv_all_user_attrs )
1675                         ? SLAP_USERATTRS_YES : SLAP_USERATTRS_NO;
1676         }
1677
1678         return flags;
1679 }