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