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