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