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