Skip to main content

tor_proto/circuit/reactor/
stream.rs

1//! The stream reactor.
2
3use crate::circuit::circhop::CircHopOutbound;
4use crate::circuit::reactor::macros::derive_deftly_template_CircuitReactor;
5use crate::circuit::{CircHopSyncView, UniqId};
6use crate::congestion::{CongestionControl, sendme};
7use crate::memquota::{CircuitAccount, SpecificAccount as _, StreamAccount};
8use crate::stream::CloseStreamBehavior;
9use crate::stream::cmdcheck::StreamStatus;
10use crate::stream::flow_ctrl::state::WithSidechannelMitigations;
11use crate::streammap;
12use crate::util::err::ReactorError;
13use crate::{Error, HopNum};
14
15#[cfg(any(feature = "hs-service", feature = "relay"))]
16use crate::stream::incoming::{
17    InboundDataCmdChecker, IncomingStreamRequest, IncomingStreamRequestContext,
18    IncomingStreamRequestDisposition, IncomingStreamRequestHandler, StreamReqInfo,
19};
20
21use tor_async_utils::{SinkTrySend as _, SinkTrySendError as _};
22use tor_cell::chancell::CircId;
23use tor_cell::relaycell::flow_ctrl::XonKBpsEwma;
24use tor_cell::relaycell::msg::{AnyRelayMsg, Begin, BeginDir, End, EndReason, Resolve};
25use tor_cell::relaycell::{
26    AnyRelayMsgOuter, RelayCellFormat, RelayCmd, StreamId, UnparsedRelayMsg,
27};
28use tor_error::{internal, into_internal};
29use tor_log_ratelim::log_ratelim;
30use tor_rtcompat::{DynTimeProvider, Runtime, SleepProvider as _};
31
32use derive_deftly::Deftly;
33use futures::SinkExt;
34use futures::channel::mpsc;
35use futures::{FutureExt as _, StreamExt as _, future, select_biased};
36use tracing::{debug, trace};
37
38use std::pin::Pin;
39use std::result::Result as StdResult;
40use std::sync::{Arc, Mutex};
41use std::task::{Poll, ready};
42use std::time::Duration;
43
44/// Trait for customizing the behavior of the stream reactor.
45///
46/// Used for plugging in the implementation-dependent (client vs relay)
47/// parts of the implementation into the generic one.
48pub(crate) trait StreamHandler: Send + Sync + 'static {
49    /// Return the amount of time a newly closed stream
50    /// should be kept in the stream map for.
51    ///
52    /// This is the amount of time we are willing to wait for
53    /// an END ack before removing the half-stream from the map.
54    fn halfstream_expiry(&self, hop: &CircHopOutbound) -> Duration;
55
56    /// Whether sidechannel mitigations should be enabled for incoming streams.
57    fn flowctrl_sidechannel_mitigations(&self) -> WithSidechannelMitigations;
58}
59
60/// The stream reactor for a given hop.
61///
62/// Drives the application streams.
63///
64/// This reactor accepts [`CtrlMsg`]s from the forward reactor over its [`Self::cell_rx`]
65/// MPSC channel, and delivers them to the corresponding stream entries in the stream map.
66///
67/// The local streams are polled from the main loop, and any ready messages are sent
68/// to the backward reactor over the `bwd_tx` MPSC channel for packaging and delivery.
69///
70/// Shuts downs down if an error occurs, or if the sending end
71/// of the `cell_rx` MPSC channel, i.e. the forward reactor, closes.
72#[derive(Deftly)]
73#[derive_deftly(CircuitReactor)]
74#[deftly(reactor_name = "stream reactor")]
75#[deftly(run_inner_fn = "Self::run_once")]
76#[must_use = "If you don't call run() on a reactor, the circuit won't work."]
77pub(crate) struct StreamReactor {
78    /// The hop this stream reactor is for.
79    ///
80    /// This is `None` for relays.
81    hopnum: Option<HopNum>,
82    /// The state of this circuit hop.
83    hop: CircHopOutbound,
84    /// The time provider.
85    time_provider: DynTimeProvider,
86    /// An identifier for logging about this reactor's circuit.
87    unique_id: UniqId,
88    /// The circuit identifier on the inbound Tor channel.
89    circ_id: CircId,
90    /// Receiver for Tor stream data that need to be delivered to a Tor stream.
91    ///
92    /// The sender is in the [`HopMgr`](super::hop_mgr::HopMgr) of the
93    /// [`ForwardReactor`](super::ForwardReactor), which will forward all cells
94    /// carrying Tor stream data to us.
95    ///
96    /// This serves a dual purpose:
97    ///
98    ///   * it enables the `ForwardReactor` to deliver Tor stream data received from the client
99    ///   * it lets the `StreamReactor` know if the `ForwardReactor` has shut down:
100    ///     we select! on this MPSC channel in the main loop, so if the `ForwardReactor`
101    ///     shuts down, we will get EOS upon calling `.next()`)
102    ///
103    /// NOTE: The channel should have relatively little buffering in order
104    /// for XON/XOFF-based flow control to work correctly.
105    /// This flow control requires us to know how many incoming messages are
106    /// buffered on each stream so that we can send an XOFF when appropriate.
107    /// If adding more than a relatively small amount of buffering,
108    /// we'll need to consider that buffering in the flow control code somehow.
109    cell_rx: mpsc::Receiver<CtrlMsg>,
110    /// Sender for sending Tor stream data to [`BackwardReactor`](super::BackwardReactor).
111    bwd_tx: mpsc::Sender<ReadyStreamMsg>,
112    /// A handler for incoming streams.
113    ///
114    /// Set to `None` if incoming streams are not allowed on this circuit.
115    ///
116    /// This handler is shared with the [`HopMgr`](super::hop_mgr::HopMgr) of this reactor,
117    /// which can install a new handler at runtime (for example, in response to a CtrlMsg).
118    /// The ability to update the handler after the reactor is launched is needed
119    /// for onion services, where the incoming stream request handler only gets installed
120    /// after the virtual hop is created.
121    #[cfg(any(feature = "hs-service", feature = "relay"))]
122    incoming: Arc<Mutex<Option<IncomingStreamRequestHandler>>>,
123    /// A handler for customizing the stream reactor behavior.
124    inner: Arc<dyn StreamHandler>,
125    /// Memory quota account
126    memquota: CircuitAccount,
127}
128
129impl StreamReactor {
130    /// Create a new [`StreamReactor`].
131    #[allow(clippy::too_many_arguments)] // TODO
132    pub(crate) fn new<R: Runtime>(
133        runtime: R,
134        hopnum: Option<HopNum>,
135        hop: CircHopOutbound,
136        unique_id: UniqId,
137        circ_id: CircId,
138        cell_rx: mpsc::Receiver<CtrlMsg>,
139        bwd_tx: mpsc::Sender<ReadyStreamMsg>,
140        inner: Arc<dyn StreamHandler>,
141        #[cfg(any(feature = "hs-service", feature = "relay"))] //
142        incoming: Arc<Mutex<Option<IncomingStreamRequestHandler>>>,
143        memquota: CircuitAccount,
144    ) -> Self {
145        Self {
146            hopnum,
147            hop,
148            time_provider: DynTimeProvider::new(runtime),
149            unique_id,
150            circ_id,
151            #[cfg(any(feature = "hs-service", feature = "relay"))]
152            incoming,
153            cell_rx,
154            bwd_tx,
155            inner,
156            memquota,
157        }
158    }
159
160    /// Helper for [`run`](Self::run).
161    ///
162    /// Polls the stream map for messages
163    /// that need to be delivered to the other endpoint,
164    /// and the `cells_rx` MPSC stream for stream messages received
165    /// from the `ForwardReactor` that need to be delivered to the application streams.
166    async fn run_once(&mut self) -> StdResult<(), ReactorError> {
167        // Garbage-collect all halfstreams that have expired.
168        //
169        // Note: this will iterate over the closed streams of this hop.
170        // If we think this will cause perf issues, one idea would be to make
171        // StreamMap::closed_streams into a min-heap, and add a branch to the
172        // select_biased! below to sleep until the first expiry is due
173        // (but my gut feeling is that iterating is cheaper)
174        self.hop
175            .stream_map()
176            .lock()
177            .expect("poisoned lock")
178            .remove_expired_halfstreams(self.time_provider.now());
179
180        let streams = Arc::clone(self.hop.stream_map());
181        let ccontrol = Arc::clone(self.hop.ccontrol());
182        let ready_streams_fut = future::poll_fn(move |cx| {
183            // We can't send anything on this hop that counts towards SENDME windows.
184            //
185            // Note: this does not block outgoing flow-control messages:
186            //
187            //   * circuit SENDMEs are initiated by the forward reactor,
188            //     by sending a BackwardReactorCmd::SendRelayMsg to BWD,
189            //   * stream SENDMEs will be initiated by StreamTarget::send_sendme(),
190            //     by sending a control message to the reactor
191            //     (TODO(relay): not yet implemented)
192            //   * XOFFs are sent in response to messages on streams
193            //     (i.e. RELAY messages with non-zero stream IDs).
194            //     These messages are delivered to us by the forward reactor
195            //     inside BackwardReactorCmd::HandleMsg
196            //   * XON will be initiated by StreamTarget::drain_rate_update(),
197            //     by sending a control message to the reactor
198            //     (TODO(relay): not yet implemented)
199            //
200            // We'll be woken up via `cx.waker()` once we get a SENDME.
201            ready!(ccontrol.lock().expect("poisoned lock").poll_can_send(cx));
202
203            let mut streams = streams.lock().expect("lock poisoned");
204            let Some((sid, msg)) = streams.poll_ready_streams_iter(cx).next() else {
205                // No ready streams
206                //
207                // TODO(flushing): if there are no ready Tor streams, we might want to defer
208                // flushing until stream data becomes available (or until a timeout elapses).
209                // The deferred flushing approach should enable us to send
210                // more than one message at a time to the channel reactor.
211                return Poll::Pending;
212            };
213
214            if msg.is_none() {
215                // This means the local sender has been dropped,
216                // which presumably can only happen if an error occurs,
217                // or if the Tor stream ends. In both cases, we're going to
218                // want to send an END to the client to let them know,
219                // and to remove the stream from the stream map.
220                //
221                // TODO(relay): the local sender part is not implemented yet
222                return Poll::Ready(StreamEvent::ApplicationStreamClosed(sid));
223            };
224
225            let msg = streams.take_ready_msg(sid).expect("msg disappeared");
226
227            Poll::Ready(StreamEvent::ReadyMsg { sid, msg })
228        });
229
230        select_biased! {
231            res = self.cell_rx.next().fuse() => {
232                let Some(cmd) = res else {
233                    // The forward reactor has shut down
234                    return Err(ReactorError::Shutdown);
235                };
236
237                self.handle_reactor_cmd(cmd).await?;
238            }
239            event = ready_streams_fut.fuse() => {
240                self.handle_stream_event(event).await?;
241            }
242        }
243
244        Ok(())
245    }
246
247    /// Handle a stream message sent to us by the forward reactor.
248    ///
249    /// Delivers the message to its corresponding application stream.
250    async fn handle_reactor_cmd(&mut self, msg: CtrlMsg) -> StdResult<(), ReactorError> {
251        match msg {
252            CtrlMsg::DeliverStreamMsg {
253                sid,
254                msg,
255                cell_counts_toward_windows,
256            } => {
257                self.deliver_message_to_stream(sid, msg, cell_counts_toward_windows)
258                    .await
259            }
260            #[cfg(any(feature = "hs-service", feature = "relay"))]
261            CtrlMsg::ClosePendingStream { stream_id, behav } => {
262                self.close_stream(stream_id, behav, streammap::TerminateReason::ExplicitEnd)
263                    .await
264            }
265            CtrlMsg::DrainRateUpdate { stream_id, rate } => {
266                self.maybe_send_xon(stream_id, rate).await
267            }
268        }
269    }
270
271    /// Maybe send an XON for the `stream_id` with the given `rate`.
272    async fn maybe_send_xon(
273        &mut self,
274        stream_id: StreamId,
275        rate: XonKBpsEwma,
276    ) -> StdResult<(), ReactorError> {
277        let Some(xon) = self.hop.maybe_send_xon(rate, stream_id)? else {
278            // Nothing to do. This can happen if stream is closed, XON/XOFF are not in
279            // use or or the stream is still above its XOFF limit.
280            return Ok(());
281        };
282
283        trace!(
284            circ_id = %self.unique_id,
285            stream_id = %stream_id,
286            "Sending XON with rate {rate}",
287        );
288
289        // Deliver the XON to the backward reactor which will send it back to the client
290        // (if we're a relay), or exit (if we're a client).
291        let msg = AnyRelayMsgOuter::new(Some(stream_id), xon.into());
292        self.send_msg_to_bwd(msg).await
293    }
294
295    /// Deliver `msg` to the specified stream
296    async fn deliver_message_to_stream(
297        &mut self,
298        sid: StreamId,
299        msg: UnparsedRelayMsg,
300        cell_counts_toward_windows: bool,
301    ) -> StdResult<(), ReactorError> {
302        // We need to apply stream-level flow control *before* encoding the message.
303        // May optionally return a message that needs to be sent back to the client.
304        let bwd_msg = self.handle_msg(sid, msg, cell_counts_toward_windows)?;
305
306        if let Some(bwd_msg) = bwd_msg {
307            self.send_msg_to_bwd(bwd_msg).await?;
308        }
309
310        Ok(())
311    }
312
313    /// Handle a RELAY message that has a non-zero stream ID.
314    ///
315    /// A returned message is one that we need to send back to the client.
316    //
317    // TODO(relay): this is very similar to the client impl from
318    // Circuit::handle_in_order_relay_msg()
319    fn handle_msg(
320        &mut self,
321        streamid: StreamId,
322        msg: UnparsedRelayMsg,
323        cell_counts_toward_windows: bool,
324    ) -> StdResult<Option<AnyRelayMsgOuter>, ReactorError> {
325        let cmd = msg.cmd();
326        let possible_proto_violation_err = move |streamid: StreamId| {
327            Error::StreamProto(format!(
328                "Unexpected {cmd:?} message on unknown stream {streamid}"
329            ))
330        };
331        let now = self.time_provider.now();
332
333        // Check if any of our already-open streams want this message
334        let res = self.hop.handle_msg(
335            possible_proto_violation_err,
336            cell_counts_toward_windows,
337            streamid,
338            msg,
339            now,
340        )?;
341
342        // If it was an incoming stream request, we don't need to worry about
343        // sending an XOFF as there's no stream data within this message.
344        if let Some(msg) = res {
345            cfg_if::cfg_if! {
346                if #[cfg(any(feature = "hs-service", feature = "relay"))] {
347                    return self.handle_incoming_stream_request(streamid, msg);
348                } else {
349                    return Err(
350                        Error::CircProto(format!("Cannot handle {} cells on this circuit", msg.cmd())).into(),
351                    );
352                }
353            }
354        }
355
356        // We may want to send an XOFF if the incoming buffer is too large.
357        if let Some(cell) = self.hop.maybe_send_xoff(streamid)? {
358            let cell = AnyRelayMsgOuter::new(Some(streamid), cell.into());
359            return Ok(Some(cell));
360        }
361
362        Ok(None)
363    }
364
365    /// A helper for handling incoming stream requests.
366    ///
367    /// Accepts the specified incoming stream request,
368    /// by adding a new entry to our stream map.
369    ///
370    /// Returns the cell we need to send back to the client,
371    /// if an error occurred and the stream cannot be opened.
372    ///
373    /// Returns None if everything went well
374    /// (the CONNECTED response only comes if the external
375    /// consumer of our [Stream](futures::Stream) of incoming Tor streams
376    /// is able to actually establish the connection to the address
377    /// specified in the BEGIN).
378    ///
379    /// Any error returned from this function will shut down the reactor.
380    #[cfg(any(feature = "hs-service", feature = "relay"))]
381    fn handle_incoming_stream_request(
382        &mut self,
383        sid: StreamId,
384        msg: UnparsedRelayMsg,
385    ) -> StdResult<Option<AnyRelayMsgOuter>, ReactorError> {
386        let mut lock = self.incoming.lock().expect("poisoned lock");
387        let Some(handler) = lock.as_mut() else {
388            return Err(Error::CircProto(format!(
389                "Cannot handle {} cells on this circuit",
390                msg.cmd()
391            ))
392            .into());
393        };
394
395        if self.hopnum != handler.hop_num {
396            let expected_hopnum = match handler.hop_num {
397                Some(hopnum) => hopnum.display().to_string(),
398                None => "client".to_string(),
399            };
400
401            let actual_hopnum = match self.hopnum {
402                Some(hopnum) => hopnum.display().to_string(),
403                None => "None".to_string(),
404            };
405
406            return Err(Error::CircProto(format!(
407                "Expecting incoming streams from {}, but received {} cell from unexpected hop {}",
408                expected_hopnum,
409                msg.cmd(),
410                actual_hopnum,
411            ))
412            .into());
413        }
414
415        let message_closes_stream = handler.cmd_checker.check_msg(&msg)? == StreamStatus::Closed;
416
417        if message_closes_stream {
418            self.hop
419                .stream_map()
420                .lock()
421                .expect("poisoned lock")
422                .ending_msg_received(sid)?;
423
424            return Ok(None);
425        }
426
427        let req = parse_incoming_stream_req(msg)?;
428        let view = CircHopSyncView::new(&self.hop);
429
430        if let Some(reject) = Self::should_reject_incoming(handler, sid, &req, &view)? {
431            // We can't honor this request, so we bail by sending an END.
432            return Ok(Some(reject));
433        };
434
435        let memquota =
436            StreamAccount::new(&self.memquota).map_err(|e| ReactorError::Err(e.into()))?;
437
438        let cmd_checker = InboundDataCmdChecker::new_connected();
439        let stream_components = self.hop.add_ent_with_id(
440            &self.time_provider,
441            sid,
442            cmd_checker,
443            self.inner.flowctrl_sidechannel_mitigations(),
444            &memquota,
445        )?;
446
447        let outcome = Pin::new(&mut handler.incoming_sender).try_send(StreamReqInfo {
448            req,
449            stream_id: sid,
450            hop: None,
451            stream_components,
452            memquota,
453            relay_cell_format: self.hop.relay_cell_format(),
454        });
455
456        log_ratelim!("Delivering message to incoming stream handler"; outcome);
457
458        if let Err(e) = outcome {
459            if e.is_full() {
460                // The IncomingStreamRequestHandler's stream is full; it isn't
461                // handling requests fast enough. So instead, we reply with an
462                // END cell.
463                let end_msg = AnyRelayMsgOuter::new(
464                    Some(sid),
465                    End::new_with_reason(EndReason::RESOURCELIMIT).into(),
466                );
467
468                return Ok(Some(end_msg));
469            } else if e.is_disconnected() {
470                // The IncomingStreamRequestHandler's stream has been dropped.
471                // In the Tor protocol as it stands, this always means that the
472                // circuit itself is out-of-use and should be closed.
473                //
474                // Note that we will _not_ reach this point immediately after
475                // the IncomingStreamRequestHandler is dropped; we won't hit it
476                // until we next get an incoming request.  Thus, if we later
477                // want to add early detection for a dropped
478                // IncomingStreamRequestHandler, we need to do it elsewhere, in
479                // a different way.
480                debug!(
481                    circ_uniq_id = %self.unique_id,
482                    backward_circ_id = %self.circ_id,
483                    "Incoming stream request receiver dropped",
484                );
485                // This will _cause_ the circuit to get closed.
486                return Err(ReactorError::Err(Error::CircuitClosed));
487            } else {
488                // There are no errors like this with the current design of
489                // futures::mpsc, but we shouldn't just ignore the possibility
490                // that they'll be added later.
491                return Err(
492                    Error::from((into_internal!("try_send failed unexpectedly"))(e)).into(),
493                );
494            }
495        }
496
497        Ok(None)
498    }
499
500    /// Check if we should reject this incoming stream request or not.
501    ///
502    /// Returns a cell we need to send back to the client if we must reject the request,
503    /// or `None` if we are allowed to accept it.
504    ///`
505    /// Any error returned from this function will shut down the reactor.
506    #[cfg(any(feature = "hs-service", feature = "relay"))]
507    fn should_reject_incoming<'a>(
508        handler: &mut IncomingStreamRequestHandler,
509        sid: StreamId,
510        request: &IncomingStreamRequest,
511        view: &CircHopSyncView<'a>,
512    ) -> StdResult<Option<AnyRelayMsgOuter>, ReactorError> {
513        use IncomingStreamRequestDisposition::*;
514
515        let ctx = IncomingStreamRequestContext { request };
516
517        // Run the externally provided filter to check if we should
518        // open the stream or not.
519        match handler.filter.as_mut().disposition(&ctx, view)? {
520            Accept => {
521                // All is well, we can accept the stream request
522                Ok(None)
523            }
524            CloseCircuit => Err(ReactorError::Shutdown),
525            RejectRequest(end) => {
526                let end_msg = AnyRelayMsgOuter::new(Some(sid), end.into());
527
528                Ok(Some(end_msg))
529            }
530        }
531    }
532
533    /// Handle a [`StreamEvent`].
534    async fn handle_stream_event(&mut self, event: StreamEvent) -> StdResult<(), ReactorError> {
535        match event {
536            StreamEvent::ApplicationStreamClosed(sid) => {
537                self.close_stream(
538                    sid,
539                    CloseStreamBehavior::default(),
540                    streammap::TerminateReason::StreamTargetClosed,
541                )
542                .await
543            }
544            StreamEvent::ReadyMsg { sid, msg } => {
545                self.send_msg_to_bwd(AnyRelayMsgOuter::new(Some(sid), msg))
546                    .await
547            }
548        }
549    }
550
551    /// Close the stream that has the specified `sid`.
552    ///
553    /// The `behav` controls whether an `END` will be sent or not.
554    ///
555    /// This calls [`CircHopOutbound::close_stream`] under the hood,
556    /// which removes the stream from the stream map,
557    /// and returns an optional `END` cell to send back to the other party.
558    async fn close_stream(
559        &mut self,
560        sid: StreamId,
561        behav: CloseStreamBehavior,
562        reason: streammap::TerminateReason,
563    ) -> StdResult<(), ReactorError> {
564        let timeout = self.inner.halfstream_expiry(&self.hop);
565        let expire_at = self.time_provider.now() + timeout;
566        let res = self.hop.close_stream(
567            self.unique_id,
568            self.circ_id,
569            sid,
570            None,
571            behav,
572            reason,
573            expire_at,
574        )?;
575        let Some(msg) = res else {
576            // We may not need to send anything at all...
577            return Ok(());
578        };
579
580        self.send_msg_to_bwd(msg.cell).await
581    }
582
583    /// Wrap `msg` in [`ReadyStreamMsg`], and send it to the backward reactor.
584    async fn send_msg_to_bwd(&mut self, msg: AnyRelayMsgOuter) -> StdResult<(), ReactorError> {
585        // TODO(DEDUP): this contains parts of Circuit::send_relay_cell_inner()
586
587        // We might be out of capacity entirely; see if we are about to hit a limit.
588        //
589        // TODO: If we ever add a notion of _recoverable_ errors below, we'll
590        // need a way to restore this limit, and similarly for about_to_send().
591        self.hop.decrement_cell_limit()?;
592
593        // We need to apply stream-level flow control *before* encoding the message
594        // (the BWD handles the encoding)
595        if sendme::cmd_counts_towards_windows(msg.cmd()) {
596            if let Some(stream_id) = msg.stream_id() {
597                self.hop
598                    .about_to_send(self.unique_id, self.circ_id, stream_id, msg.msg())?;
599            }
600        }
601
602        // NOTE: on the client side, we call note_data_sent()
603        // just before writing the cell to the channel.
604        // We can't do that here, because we're not the ones
605        // encoding the cell, so we don't have the SENDME tag
606        // which is needed for note_data_sent().
607        //
608        // Instead, we notify the CC algorithm in the BWD,
609        // right after we've finished sending the cell.
610
611        let msg = ReadyStreamMsg {
612            hop: self.hopnum,
613            relay_cell_format: self.hop.relay_cell_format(),
614            ccontrol: Arc::clone(self.hop.ccontrol()),
615            msg,
616        };
617
618        self.bwd_tx
619            .send(msg)
620            .await
621            .map_err(|_| ReactorError::Shutdown)?;
622
623        Ok(())
624    }
625}
626
627/// A Tor stream-related event.
628enum StreamEvent {
629    /// An application stream was closed.
630    ///
631    /// The corresponding entry needs to be removed from the reactor's stream map.
632    ApplicationStreamClosed(StreamId),
633    /// A stream has a ready message.
634    ReadyMsg {
635        /// The ID of the stream to close.
636        sid: StreamId,
637        /// The message.
638        msg: AnyRelayMsg,
639    },
640}
641
642/// Convert an incoming stream request message (BEGIN, BEGIN_DIR, RESOLVE, etc.)
643/// to an [`IncomingStreamRequest`]
644///
645// TODO(dedup): when we rewrite the client reactor in the multi-reactor register,
646// we should rethink this part a bit: ideally, onion services shouldn't even
647// try to parse BEGIN_DIR, RESOLVE.
648//
649// We will likely need an implementation-specific hook for this,
650// similar to the `{Forward,Backward}Handler` implementation-specific handlers
651// we have for the FWD and BWD reactors.
652//
653// See https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/4188#note_3432579
654#[cfg(any(feature = "hs-service", feature = "relay"))]
655fn parse_incoming_stream_req(msg: UnparsedRelayMsg) -> crate::Result<IncomingStreamRequest> {
656    /// Helper for parsing an incoming stream request
657    /// (BEGIN, BEGIN_DIR, or RESOLVE)
658    macro_rules! parse_stream_req {
659        ($msg:expr, $type:tt) => {{
660            let req = $msg
661                .decode::<$type>()
662                .map_err(|e| {
663                    Error::from_bytes_err(e, concat!("Invalid ", stringify!($type), " message"))
664                })?
665                .into_msg();
666
667            IncomingStreamRequest::$type(req)
668        }};
669    }
670
671    let req = match msg.cmd() {
672        RelayCmd::BEGIN => parse_stream_req!(msg, Begin),
673        RelayCmd::BEGIN_DIR => parse_stream_req!(msg, BeginDir),
674        RelayCmd::RESOLVE => parse_stream_req!(msg, Resolve),
675        cmd => {
676            // It's a bug if we reach this point, because CircHopOutbound::handle_msg()
677            // should have consumed the message (by forwarding it to the appropriate stream
678            // in its stream map)
679            return Err(internal!("{cmd} is not an incoming stream request").into());
680        }
681    };
682
683    Ok(req)
684}
685
686/// A stream message to be sent to the backward reactor for delivery.
687pub(crate) struct ReadyStreamMsg {
688    /// The hop number, or `None` if we are a relay.
689    pub(crate) hop: Option<HopNum>,
690    /// The message to send.
691    pub(crate) msg: AnyRelayMsgOuter,
692    /// The cell format used with the hop the message should be sent to.
693    pub(crate) relay_cell_format: RelayCellFormat,
694    /// The CC object to use.
695    pub(crate) ccontrol: Arc<Mutex<CongestionControl>>,
696}
697
698/// A control message
699/// that needs to be handled by [`StreamReactor`].
700pub(crate) enum CtrlMsg {
701    /// Stream data received from the other endpoint
702    /// that needs to be delivered to a Tor stream
703    DeliverStreamMsg {
704        /// The ID of the stream this message is for.
705        sid: StreamId,
706        /// The message.
707        msg: UnparsedRelayMsg,
708        /// Whether the cell this message came from counts towards flow-control windows.
709        cell_counts_toward_windows: bool,
710    },
711
712    /// Close the specified pending incoming stream, sending the provided END message.
713    #[cfg(any(feature = "hs-service", feature = "relay"))]
714    ClosePendingStream {
715        /// The stream ID to send the END for.
716        stream_id: StreamId,
717        /// The END message to send, if any.
718        behav: CloseStreamBehavior,
719    },
720
721    /// Indicate that the drain rate of a specific stream has changed to the given value.
722    DrainRateUpdate {
723        /// The stream ID to send the XON on.
724        stream_id: StreamId,
725        /// The drain rate to advertise in the XON.
726        rate: XonKBpsEwma,
727    },
728}