1
//! The stream reactor.
2

            
3
use crate::circuit::circhop::CircHopOutbound;
4
use crate::circuit::metrics::CircuitMetrics;
5
use crate::circuit::reactor::macros::derive_deftly_template_CircuitReactor;
6
use crate::circuit::{CircHopSyncView, UniqId};
7
use crate::congestion::{CongestionControl, sendme};
8
use crate::memquota::{CircuitAccount, SpecificAccount as _, StreamAccount};
9
use crate::stream::CloseStreamBehavior;
10
use crate::stream::cmdcheck::StreamStatus;
11
use crate::stream::flow_ctrl::state::WithSidechannelMitigations;
12
use crate::streammap;
13
use crate::util::err::ReactorError;
14
use crate::{Error, HopNum};
15

            
16
#[cfg(any(feature = "hs-service", feature = "relay"))]
17
use crate::stream::incoming::{
18
    InboundDataCmdChecker, IncomingStreamRequest, IncomingStreamRequestContext,
19
    IncomingStreamRequestDisposition, IncomingStreamRequestHandler, StreamReqInfo,
20
};
21

            
22
use tor_async_utils::{SinkTrySend as _, SinkTrySendError as _};
23
use tor_cell::chancell::CircId;
24
use tor_cell::relaycell::flow_ctrl::XonKBpsEwma;
25
use tor_cell::relaycell::msg::{AnyRelayMsg, Begin, BeginDir, End, EndReason, Resolve};
26
use tor_cell::relaycell::{
27
    AnyRelayMsgOuter, RelayCellFormat, RelayCmd, StreamId, UnparsedRelayMsg,
28
};
29
use tor_error::{internal, into_internal};
30
use tor_log_ratelim::log_ratelim;
31
use tor_rtcompat::{DynTimeProvider, Runtime, SleepProvider as _};
32

            
33
use derive_deftly::Deftly;
34
use futures::SinkExt;
35
use futures::channel::mpsc;
36
use futures::{FutureExt as _, StreamExt as _, future, select_biased};
37
use tracing::{debug, trace};
38

            
39
use std::pin::Pin;
40
use std::result::Result as StdResult;
41
use std::sync::{Arc, Mutex};
42
use std::task::{Poll, ready};
43
use std::time::Duration;
44

            
45
/// Trait for customizing the behavior of the stream reactor.
46
///
47
/// Used for plugging in the implementation-dependent (client vs relay)
48
/// parts of the implementation into the generic one.
49
pub(crate) trait StreamHandler: Send + Sync + 'static {
50
    /// Return the amount of time a newly closed stream
51
    /// should be kept in the stream map for.
52
    ///
53
    /// This is the amount of time we are willing to wait for
54
    /// an END ack before removing the half-stream from the map.
55
    fn halfstream_expiry(&self, hop: &CircHopOutbound) -> Duration;
56

            
57
    /// Whether sidechannel mitigations should be enabled for incoming streams.
58
    fn flowctrl_sidechannel_mitigations(&self) -> WithSidechannelMitigations;
59
}
60

            
61
/// The stream reactor for a given hop.
62
///
63
/// Drives the application streams.
64
///
65
/// This reactor accepts [`CtrlMsg`]s from the decrypting reactor over its [`Self::cell_rx`]
66
/// MPSC channel, and delivers them to the corresponding stream entries in the stream map.
67
///
68
/// The local streams are polled from the main loop, and any ready messages are sent
69
/// to the encrypting reactor over the `enc_tx` MPSC channel for packaging and delivery.
70
///
71
/// Shuts downs down if an error occurs, or if the sending end
72
/// of the `cell_rx` MPSC channel, i.e. the decrypting reactor, closes.
73
#[derive(Deftly)]
74
#[derive_deftly(CircuitReactor)]
75
#[deftly(reactor_name = "stream reactor")]
76
#[deftly(run_inner_fn = "Self::run_once")]
77
#[must_use = "If you don't call run() on a reactor, the circuit won't work."]
78
pub(crate) struct StreamReactor {
79
    /// The hop this stream reactor is for.
80
    ///
81
    /// This is `None` for relays.
82
    hopnum: Option<HopNum>,
83
    /// The state of this circuit hop.
84
    hop: CircHopOutbound,
85
    /// The time provider.
86
    time_provider: DynTimeProvider,
87
    /// An identifier for logging about this reactor's circuit.
88
    unique_id: UniqId,
89
    /// The circuit identifier on the inbound Tor channel.
90
    circ_id: CircId,
91
    /// Receiver for Tor stream data that need to be delivered to a Tor stream.
92
    ///
93
    /// The sender is in the [`CircuitState`](super::circ_state::CircuitState) of the
94
    /// [`DecryptingReactor`](super::DecryptingReactor), which will forward all cells
95
    /// carrying Tor stream data to us.
96
    ///
97
    /// This serves a dual purpose:
98
    ///
99
    ///   * it enables the `DecryptingReactor` to deliver Tor stream data received from the client
100
    ///   * it lets the `StreamReactor` know if the `DecryptingReactor` has shut down:
101
    ///     we select! on this MPSC channel in the main loop, so if the `DecryptingReactor`
102
    ///     shuts down, we will get EOS upon calling `.next()`)
103
    ///
104
    /// NOTE: The channel should have relatively little buffering in order
105
    /// for XON/XOFF-based flow control to work correctly.
106
    /// This flow control requires us to know how many incoming messages are
107
    /// buffered on each stream so that we can send an XOFF when appropriate.
108
    /// If adding more than a relatively small amount of buffering,
109
    /// we'll need to consider that buffering in the flow control code somehow.
110
    cell_rx: mpsc::Receiver<CtrlMsg>,
111
    /// Sender for sending Tor stream data to [`EncryptingReactor`](super::EncryptingReactor).
112
    enc_tx: mpsc::Sender<ReadyStreamMsg>,
113
    /// A handler for incoming streams.
114
    ///
115
    /// Set to `None` if incoming streams are not allowed on this circuit.
116
    ///
117
    /// This handler is shared with the [`CircuitState`](super::circ_state::CircuitState) of this reactor,
118
    /// which can install a new handler at runtime (for example, in response to a CtrlMsg).
119
    /// The ability to update the handler after the reactor is launched is needed
120
    /// for onion services, where the incoming stream request handler only gets installed
121
    /// after the virtual hop is created.
122
    #[cfg(any(feature = "hs-service", feature = "relay"))]
123
    incoming: Arc<Mutex<Option<IncomingStreamRequestHandler>>>,
124
    /// A handler for customizing the stream reactor behavior.
125
    inner: Arc<dyn StreamHandler>,
126
    /// Memory quota account
127
    memquota: CircuitAccount,
128
    /// The circuit metrics.
129
    metrics: Arc<CircuitMetrics>,
130
}
131

            
132
impl StreamReactor {
133
    /// Create a new [`StreamReactor`].
134
    #[allow(clippy::too_many_arguments)] // TODO
135
8
    pub(crate) fn new<R: Runtime>(
136
8
        runtime: R,
137
8
        hopnum: Option<HopNum>,
138
8
        hop: CircHopOutbound,
139
8
        unique_id: UniqId,
140
8
        circ_id: CircId,
141
8
        cell_rx: mpsc::Receiver<CtrlMsg>,
142
8
        enc_tx: mpsc::Sender<ReadyStreamMsg>,
143
8
        inner: Arc<dyn StreamHandler>,
144
8
        #[cfg(any(feature = "hs-service", feature = "relay"))] //
145
8
        incoming: Arc<Mutex<Option<IncomingStreamRequestHandler>>>,
146
8
        memquota: CircuitAccount,
147
8
        metrics: Arc<CircuitMetrics>,
148
8
    ) -> Self {
149
8
        Self {
150
8
            hopnum,
151
8
            hop,
152
8
            time_provider: DynTimeProvider::new(runtime),
153
8
            unique_id,
154
8
            circ_id,
155
8
            #[cfg(any(feature = "hs-service", feature = "relay"))]
156
8
            incoming,
157
8
            cell_rx,
158
8
            enc_tx,
159
8
            inner,
160
8
            memquota,
161
8
            metrics,
162
8
        }
163
8
    }
164

            
165
    /// Helper for [`run`](Self::run).
166
    ///
167
    /// Polls the stream map for messages
168
    /// that need to be delivered to the other endpoint,
169
    /// and the `cells_rx` MPSC stream for stream messages received
170
    /// from the `DecryptingReactor` that need to be delivered to the application streams.
171
26
    async fn run_once(&mut self) -> StdResult<(), ReactorError> {
172
        // Garbage-collect all halfstreams that have expired.
173
        //
174
        // Note: this will iterate over the closed streams of this hop.
175
        // If we think this will cause perf issues, one idea would be to make
176
        // StreamMap::closed_streams into a min-heap, and add a branch to the
177
        // select_biased! below to sleep until the first expiry is due
178
        // (but my gut feeling is that iterating is cheaper)
179
26
        self.hop
180
26
            .stream_map()
181
26
            .lock()
182
26
            .expect("poisoned lock")
183
26
            .remove_expired_halfstreams(self.time_provider.now());
184

            
185
26
        let streams = Arc::clone(self.hop.stream_map());
186
26
        let ccontrol = Arc::clone(self.hop.ccontrol());
187
26
        let ready_streams_fut = future::poll_fn(move |cx| {
188
            // We can't send anything on this hop that counts towards SENDME windows.
189
            //
190
            // Note: this does not block outgoing flow-control messages:
191
            //
192
            //   * circuit SENDMEs are initiated by the decrypting reactor,
193
            //     by sending a EncryptingReactorCmd::SendRelayMsg to ENC,
194
            //   * stream SENDMEs will be initiated by StreamTarget::send_sendme(),
195
            //     by sending a control message to the reactor
196
            //     (TODO(relay): not yet implemented)
197
            //   * XOFFs are sent in response to messages on streams
198
            //     (i.e. RELAY messages with non-zero stream IDs).
199
            //     These messages are delivered to us by the decrypting reactor
200
            //     inside EncryptingReactorCmd::HandleMsg
201
            //   * XON will be initiated by StreamTarget::drain_rate_update(),
202
            //     by sending a control message to the reactor
203
            //     (TODO(relay): not yet implemented)
204
            //
205
            // We'll be woken up via `cx.waker()` once we get a SENDME.
206
21
            ready!(ccontrol.lock().expect("poisoned lock").poll_can_send(cx));
207

            
208
21
            let mut streams = streams.lock().expect("lock poisoned");
209
21
            let Some((sid, msg)) = streams.poll_ready_streams_iter(cx).next() else {
210
                // No ready streams
211
                //
212
                // TODO(flushing): if there are no ready Tor streams, we might want to defer
213
                // flushing until stream data becomes available (or until a timeout elapses).
214
                // The deferred flushing approach should enable us to send
215
                // more than one message at a time to the channel reactor.
216
17
                return Poll::Pending;
217
            };
218

            
219
4
            if msg.is_none() {
220
                // This means the local sender has been dropped,
221
                // which presumably can only happen if an error occurs,
222
                // or if the Tor stream ends. In both cases, we're going to
223
                // want to send an END to the client to let them know,
224
                // and to remove the stream from the stream map.
225
                //
226
                // TODO(relay): the local sender part is not implemented yet
227
2
                return Poll::Ready(StreamEvent::ApplicationStreamClosed(sid));
228
2
            };
229

            
230
2
            let msg = streams.take_ready_msg(sid).expect("msg disappeared");
231

            
232
2
            Poll::Ready(StreamEvent::ReadyMsg { sid, msg })
233
21
        });
234

            
235
26
        select_biased! {
236
26
            res = self.cell_rx.next().fuse() => {
237
22
                let Some(cmd) = res else {
238
                    // The decrypting reactor has shut down
239
4
                    return Err(ReactorError::Shutdown);
240
                };
241

            
242
18
                self.handle_reactor_cmd(cmd).await?;
243
            }
244
26
            event = ready_streams_fut.fuse() => {
245
4
                self.handle_stream_event(event).await?;
246
            }
247
        }
248

            
249
18
        Ok(())
250
26
    }
251

            
252
    /// Handle a stream message sent to us by the decrypting reactor.
253
    ///
254
    /// Delivers the message to its corresponding application stream.
255
18
    async fn handle_reactor_cmd(&mut self, msg: CtrlMsg) -> StdResult<(), ReactorError> {
256
18
        match msg {
257
            CtrlMsg::DeliverStreamMsg {
258
                sid,
259
                msg,
260
                cell_counts_toward_windows,
261
            } => {
262
14
                self.deliver_message_to_stream(sid, msg, cell_counts_toward_windows)
263
14
                    .await
264
            }
265
            #[cfg(any(feature = "hs-service", feature = "relay"))]
266
            CtrlMsg::ClosePendingStream { stream_id, behav } => {
267
4
                self.close_stream(stream_id, behav, streammap::TerminateReason::ExplicitEnd)
268
4
                    .await
269
            }
270
            CtrlMsg::DrainRateUpdate { stream_id, rate } => {
271
                self.maybe_send_xon(stream_id, rate).await
272
            }
273
        }
274
18
    }
275

            
276
    /// Maybe send an XON for the `stream_id` with the given `rate`.
277
    async fn maybe_send_xon(
278
        &mut self,
279
        stream_id: StreamId,
280
        rate: XonKBpsEwma,
281
    ) -> StdResult<(), ReactorError> {
282
        let Some(xon) = self.hop.maybe_send_xon(rate, stream_id)? else {
283
            // Nothing to do. This can happen if stream is closed, XON/XOFF are not in
284
            // use or or the stream is still above its XOFF limit.
285
            return Ok(());
286
        };
287

            
288
        trace!(
289
            circ_id = %self.unique_id,
290
            stream_id = %stream_id,
291
            "Sending XON with rate {rate}",
292
        );
293

            
294
        // Deliver the XON to the encrypting reactor which will send it back to the client
295
        // (if we're a relay), or exit (if we're a client).
296
        let msg = AnyRelayMsgOuter::new(Some(stream_id), xon.into());
297
        self.send_msg_to_bwd(msg).await
298
    }
299

            
300
    /// Deliver `msg` to the specified stream
301
14
    async fn deliver_message_to_stream(
302
14
        &mut self,
303
14
        sid: StreamId,
304
14
        msg: UnparsedRelayMsg,
305
14
        cell_counts_toward_windows: bool,
306
14
    ) -> StdResult<(), ReactorError> {
307
        // We need to apply stream-level flow control *before* encoding the message.
308
        // May optionally return a message that needs to be sent back to the client.
309
14
        let enc_msg = self.handle_msg(sid, msg, cell_counts_toward_windows)?;
310

            
311
10
        if let Some(enc_msg) = enc_msg {
312
            self.send_msg_to_bwd(enc_msg).await?;
313
10
        }
314

            
315
10
        Ok(())
316
14
    }
317

            
318
    /// Handle a RELAY message that has a non-zero stream ID.
319
    ///
320
    /// A returned message is one that we need to send back to the client.
321
    //
322
    // TODO(relay): this is very similar to the client impl from
323
    // Circuit::handle_in_order_relay_msg()
324
14
    fn handle_msg(
325
14
        &mut self,
326
14
        streamid: StreamId,
327
14
        msg: UnparsedRelayMsg,
328
14
        cell_counts_toward_windows: bool,
329
14
    ) -> StdResult<Option<AnyRelayMsgOuter>, ReactorError> {
330
14
        let cmd = msg.cmd();
331
2
        let possible_proto_violation_err = move |streamid: StreamId| {
332
2
            Error::StreamProto(format!(
333
2
                "Unexpected {cmd:?} message on unknown stream {streamid}"
334
2
            ))
335
2
        };
336
14
        let now = self.time_provider.now();
337

            
338
        // Check if any of our already-open streams want this message
339
14
        let res = self.hop.handle_msg(
340
14
            possible_proto_violation_err,
341
14
            cell_counts_toward_windows,
342
14
            streamid,
343
14
            msg,
344
14
            now,
345
14
        )?;
346

            
347
        // If it was an incoming stream request, we don't need to worry about
348
        // sending an XOFF as there's no stream data within this message.
349
12
        if let Some(msg) = res {
350
            cfg_if::cfg_if! {
351
                if #[cfg(any(feature = "hs-service", feature = "relay"))] {
352
10
                    return self.handle_incoming_stream_request(streamid, msg);
353
                } else {
354
                    return Err(
355
                        Error::CircProto(format!("Cannot handle {} cells on this circuit", msg.cmd())).into(),
356
                    );
357
                }
358
            }
359
2
        }
360

            
361
        // We may want to send an XOFF if the incoming buffer is too large.
362
2
        if let Some(cell) = self.hop.maybe_send_xoff(streamid)? {
363
            let cell = AnyRelayMsgOuter::new(Some(streamid), cell.into());
364
            return Ok(Some(cell));
365
2
        }
366

            
367
2
        Ok(None)
368
14
    }
369

            
370
    /// A helper for handling incoming stream requests.
371
    ///
372
    /// Accepts the specified incoming stream request,
373
    /// by adding a new entry to our stream map.
374
    ///
375
    /// Returns the cell we need to send back to the client,
376
    /// if an error occurred and the stream cannot be opened.
377
    ///
378
    /// Returns None if everything went well
379
    /// (the CONNECTED response only comes if the external
380
    /// consumer of our [Stream](futures::Stream) of incoming Tor streams
381
    /// is able to actually establish the connection to the address
382
    /// specified in the BEGIN).
383
    ///
384
    /// Any error returned from this function will shut down the reactor.
385
    #[cfg(any(feature = "hs-service", feature = "relay"))]
386
10
    fn handle_incoming_stream_request(
387
10
        &mut self,
388
10
        sid: StreamId,
389
10
        msg: UnparsedRelayMsg,
390
10
    ) -> StdResult<Option<AnyRelayMsgOuter>, ReactorError> {
391
10
        let mut lock = self.incoming.lock().expect("poisoned lock");
392
10
        let Some(handler) = lock.as_mut() else {
393
            return Err(Error::CircProto(format!(
394
                "Cannot handle {} cells on this circuit",
395
                msg.cmd()
396
            ))
397
            .into());
398
        };
399

            
400
10
        if self.hopnum != handler.hop_num {
401
            let expected_hopnum = match handler.hop_num {
402
                Some(hopnum) => hopnum.display().to_string(),
403
                None => "client".to_string(),
404
            };
405

            
406
            let actual_hopnum = match self.hopnum {
407
                Some(hopnum) => hopnum.display().to_string(),
408
                None => "None".to_string(),
409
            };
410

            
411
            return Err(Error::CircProto(format!(
412
                "Expecting incoming streams from {}, but received {} cell from unexpected hop {}",
413
                expected_hopnum,
414
                msg.cmd(),
415
                actual_hopnum,
416
            ))
417
            .into());
418
10
        }
419

            
420
10
        let message_closes_stream = handler.cmd_checker.check_msg(&msg)? == StreamStatus::Closed;
421

            
422
8
        if message_closes_stream {
423
            self.hop
424
                .stream_map()
425
                .lock()
426
                .expect("poisoned lock")
427
                .ending_msg_received(sid)?;
428

            
429
            return Ok(None);
430
8
        }
431

            
432
8
        let req = parse_incoming_stream_req(msg)?;
433
8
        self.metrics.increment_stream_requests(&req);
434

            
435
8
        let view = CircHopSyncView::new(&self.hop);
436

            
437
8
        if let Some(reject) = Self::should_reject_incoming(handler, sid, &req, &view)? {
438
            // We can't honor this request, so we bail by sending an END.
439
            return Ok(Some(reject));
440
8
        };
441

            
442
        let memquota =
443
8
            StreamAccount::new(&self.memquota).map_err(|e| ReactorError::Err(e.into()))?;
444

            
445
8
        let cmd_checker = InboundDataCmdChecker::new_connected();
446
8
        let stream_components = self.hop.add_ent_with_id(
447
8
            &self.time_provider,
448
8
            sid,
449
8
            cmd_checker,
450
8
            self.inner.flowctrl_sidechannel_mitigations(),
451
8
            &memquota,
452
8
        )?;
453

            
454
8
        let outcome = Pin::new(&mut handler.incoming_sender).try_send(StreamReqInfo {
455
8
            req,
456
8
            stream_id: sid,
457
8
            hop: None,
458
8
            stream_components,
459
8
            memquota,
460
8
            relay_cell_format: self.hop.relay_cell_format(),
461
8
        });
462

            
463
8
        log_ratelim!("Delivering message to incoming stream handler"; outcome);
464

            
465
8
        if let Err(e) = outcome {
466
            if e.is_full() {
467
                // The IncomingStreamRequestHandler's stream is full; it isn't
468
                // handling requests fast enough. So instead, we reply with an
469
                // END cell.
470
                let end_msg = AnyRelayMsgOuter::new(
471
                    Some(sid),
472
                    End::new_with_reason(EndReason::RESOURCELIMIT).into(),
473
                );
474

            
475
                return Ok(Some(end_msg));
476
            } else if e.is_disconnected() {
477
                // The IncomingStreamRequestHandler's stream has been dropped.
478
                // In the Tor protocol as it stands, this always means that the
479
                // circuit itself is out-of-use and should be closed.
480
                //
481
                // Note that we will _not_ reach this point immediately after
482
                // the IncomingStreamRequestHandler is dropped; we won't hit it
483
                // until we next get an incoming request.  Thus, if we later
484
                // want to add early detection for a dropped
485
                // IncomingStreamRequestHandler, we need to do it elsewhere, in
486
                // a different way.
487
                debug!(
488
                    circ_uniq_id = %self.unique_id,
489
                    backward_circ_id = %self.circ_id,
490
                    "Incoming stream request receiver dropped",
491
                );
492
                // This will _cause_ the circuit to get closed.
493
                return Err(ReactorError::Err(Error::CircuitClosed));
494
            } else {
495
                // There are no errors like this with the current design of
496
                // futures::mpsc, but we shouldn't just ignore the possibility
497
                // that they'll be added later.
498
                return Err(
499
                    Error::from((into_internal!("try_send failed unexpectedly"))(e)).into(),
500
                );
501
            }
502
8
        }
503

            
504
8
        Ok(None)
505
10
    }
506

            
507
    /// Check if we should reject this incoming stream request or not.
508
    ///
509
    /// Returns a cell we need to send back to the client if we must reject the request,
510
    /// or `None` if we are allowed to accept it.
511
    ///`
512
    /// Any error returned from this function will shut down the reactor.
513
    #[cfg(any(feature = "hs-service", feature = "relay"))]
514
8
    fn should_reject_incoming<'a>(
515
8
        handler: &mut IncomingStreamRequestHandler,
516
8
        sid: StreamId,
517
8
        request: &IncomingStreamRequest,
518
8
        view: &CircHopSyncView<'a>,
519
8
    ) -> StdResult<Option<AnyRelayMsgOuter>, ReactorError> {
520
        use IncomingStreamRequestDisposition::*;
521

            
522
8
        let ctx = IncomingStreamRequestContext { request };
523

            
524
        // Run the externally provided filter to check if we should
525
        // open the stream or not.
526
8
        match handler.filter.as_mut().disposition(&ctx, view)? {
527
            Accept => {
528
                // All is well, we can accept the stream request
529
8
                Ok(None)
530
            }
531
            CloseCircuit => Err(ReactorError::Shutdown),
532
            RejectRequest(end) => {
533
                let end_msg = AnyRelayMsgOuter::new(Some(sid), end.into());
534

            
535
                Ok(Some(end_msg))
536
            }
537
        }
538
8
    }
539

            
540
    /// Handle a [`StreamEvent`].
541
4
    async fn handle_stream_event(&mut self, event: StreamEvent) -> StdResult<(), ReactorError> {
542
4
        match event {
543
            StreamEvent::ApplicationStreamClosed(sid) => {
544
2
                self.close_stream(
545
2
                    sid,
546
2
                    CloseStreamBehavior::default(),
547
2
                    streammap::TerminateReason::StreamTargetClosed,
548
2
                )
549
2
                .await
550
            }
551
            StreamEvent::ReadyMsg { sid, msg } => {
552
2
                self.send_msg_to_bwd(AnyRelayMsgOuter::new(Some(sid), msg))
553
2
                    .await
554
            }
555
        }
556
4
    }
557

            
558
    /// Close the stream that has the specified `sid`.
559
    ///
560
    /// The `behav` controls whether an `END` will be sent or not.
561
    ///
562
    /// This calls [`CircHopOutbound::close_stream`] under the hood,
563
    /// which removes the stream from the stream map,
564
    /// and returns an optional `END` cell to send back to the other party.
565
6
    async fn close_stream(
566
6
        &mut self,
567
6
        sid: StreamId,
568
6
        behav: CloseStreamBehavior,
569
6
        reason: streammap::TerminateReason,
570
6
    ) -> StdResult<(), ReactorError> {
571
6
        let timeout = self.inner.halfstream_expiry(&self.hop);
572
6
        let expire_at = self.time_provider.now() + timeout;
573
6
        let res = self.hop.close_stream(
574
6
            self.unique_id,
575
6
            self.circ_id,
576
6
            sid,
577
6
            None,
578
6
            behav,
579
6
            reason,
580
6
            expire_at,
581
6
        )?;
582
6
        let Some(msg) = res else {
583
            // We may not need to send anything at all...
584
            return Ok(());
585
        };
586

            
587
6
        self.send_msg_to_bwd(msg.cell).await
588
6
    }
589

            
590
    /// Wrap `msg` in [`ReadyStreamMsg`], and send it to the encrypting reactor.
591
8
    async fn send_msg_to_bwd(&mut self, msg: AnyRelayMsgOuter) -> StdResult<(), ReactorError> {
592
        // TODO(DEDUP): this contains parts of Circuit::send_relay_cell_inner()
593

            
594
        // We might be out of capacity entirely; see if we are about to hit a limit.
595
        //
596
        // TODO: If we ever add a notion of _recoverable_ errors below, we'll
597
        // need a way to restore this limit, and similarly for about_to_send().
598
8
        self.hop.decrement_cell_limit()?;
599

            
600
        // We need to apply stream-level flow control *before* encoding the message
601
        // (the ENC handles the encoding)
602
8
        if sendme::cmd_counts_towards_windows(msg.cmd()) {
603
            if let Some(stream_id) = msg.stream_id() {
604
                self.hop
605
                    .about_to_send(self.unique_id, self.circ_id, stream_id, msg.msg())?;
606
            }
607
8
        }
608

            
609
        // NOTE: on the client side, we call note_data_sent()
610
        // just before writing the cell to the channel.
611
        // We can't do that here, because we're not the ones
612
        // encoding the cell, so we don't have the SENDME tag
613
        // which is needed for note_data_sent().
614
        //
615
        // Instead, we notify the CC algorithm in the ENC,
616
        // right after we've finished sending the cell.
617

            
618
8
        let msg = ReadyStreamMsg {
619
8
            hop: self.hopnum,
620
8
            relay_cell_format: self.hop.relay_cell_format(),
621
8
            ccontrol: Arc::clone(self.hop.ccontrol()),
622
8
            msg,
623
8
        };
624

            
625
8
        self.enc_tx
626
8
            .send(msg)
627
8
            .await
628
            .map_err(|_| ReactorError::Shutdown)?;
629

            
630
8
        Ok(())
631
8
    }
632
}
633

            
634
/// A Tor stream-related event.
635
enum StreamEvent {
636
    /// An application stream was closed.
637
    ///
638
    /// The corresponding entry needs to be removed from the reactor's stream map.
639
    ApplicationStreamClosed(StreamId),
640
    /// A stream has a ready message.
641
    ReadyMsg {
642
        /// The ID of the stream to close.
643
        sid: StreamId,
644
        /// The message.
645
        msg: AnyRelayMsg,
646
    },
647
}
648

            
649
/// Convert an incoming stream request message (BEGIN, BEGIN_DIR, RESOLVE, etc.)
650
/// to an [`IncomingStreamRequest`]
651
///
652
// TODO(dedup): when we rewrite the client reactor in the multi-reactor register,
653
// we should rethink this part a bit: ideally, onion services shouldn't even
654
// try to parse BEGIN_DIR, RESOLVE.
655
//
656
// We will likely need an implementation-specific hook for this,
657
// similar to the `{Forward,Backward}Handler` implementation-specific handlers
658
// we have for the DEC and ENC reactors.
659
//
660
// See https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/4188#note_3432579
661
#[cfg(any(feature = "hs-service", feature = "relay"))]
662
8
fn parse_incoming_stream_req(msg: UnparsedRelayMsg) -> crate::Result<IncomingStreamRequest> {
663
    /// Helper for parsing an incoming stream request
664
    /// (BEGIN, BEGIN_DIR, or RESOLVE)
665
    macro_rules! parse_stream_req {
666
        ($msg:expr, $type:tt) => {{
667
            let req = $msg
668
                .decode::<$type>()
669
                .map_err(|e| {
670
                    Error::from_bytes_err(e, concat!("Invalid ", stringify!($type), " message"))
671
                })?
672
                .into_msg();
673

            
674
            IncomingStreamRequest::$type(req)
675
        }};
676
    }
677

            
678
8
    let req = match msg.cmd() {
679
4
        RelayCmd::BEGIN => parse_stream_req!(msg, Begin),
680
2
        RelayCmd::BEGIN_DIR => parse_stream_req!(msg, BeginDir),
681
2
        RelayCmd::RESOLVE => parse_stream_req!(msg, Resolve),
682
        cmd => {
683
            // It's a bug if we reach this point, because CircHopOutbound::handle_msg()
684
            // should have consumed the message (by forwarding it to the appropriate stream
685
            // in its stream map)
686
            return Err(internal!("{cmd} is not an incoming stream request").into());
687
        }
688
    };
689

            
690
8
    Ok(req)
691
8
}
692

            
693
/// A stream message to be sent to the encrypting reactor for delivery.
694
pub(crate) struct ReadyStreamMsg {
695
    /// The hop number, or `None` if we are a relay.
696
    pub(crate) hop: Option<HopNum>,
697
    /// The message to send.
698
    pub(crate) msg: AnyRelayMsgOuter,
699
    /// The cell format used with the hop the message should be sent to.
700
    pub(crate) relay_cell_format: RelayCellFormat,
701
    /// The CC object to use.
702
    pub(crate) ccontrol: Arc<Mutex<CongestionControl>>,
703
}
704

            
705
/// A control message
706
/// that needs to be handled by [`StreamReactor`].
707
pub(crate) enum CtrlMsg {
708
    /// Stream data received from the other endpoint
709
    /// that needs to be delivered to a Tor stream
710
    DeliverStreamMsg {
711
        /// The ID of the stream this message is for.
712
        sid: StreamId,
713
        /// The message.
714
        msg: UnparsedRelayMsg,
715
        /// Whether the cell this message came from counts towards flow-control windows.
716
        cell_counts_toward_windows: bool,
717
    },
718

            
719
    /// Close the specified pending incoming stream, sending the provided END message.
720
    #[cfg(any(feature = "hs-service", feature = "relay"))]
721
    ClosePendingStream {
722
        /// The stream ID to send the END for.
723
        stream_id: StreamId,
724
        /// The END message to send, if any.
725
        behav: CloseStreamBehavior,
726
    },
727

            
728
    /// Indicate that the drain rate of a specific stream has changed to the given value.
729
    DrainRateUpdate {
730
        /// The stream ID to send the XON on.
731
        stream_id: StreamId,
732
        /// The drain rate to advertise in the XON.
733
        rate: XonKBpsEwma,
734
    },
735
}