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