Skip to main content

tor_proto/relay/
reactor.rs

1//! Module exposing the relay circuit reactor subsystem.
2//!
3//! See [`reactor`](crate::circuit::reactor) for a description of the overall architecture.
4//!
5//! All cells moving in the forward direction (i.e. away from the client)
6//! are handled by the forward reactor, which deals with
7//!
8//!  * unrecognized RELAY* cells, by moving them in the forward direction (towards the exit)
9//!  * recognized RELAY* cells, by splitting each cell into messages, and handling
10//!    each message individually as described in the table below
11//!    (Note: since prop340 is not yet implemented, in practice there is only 1 message per cell).
12//!  * DESTROY cells, by tearing down the circuit, and causing a DESTROY to be sent forward,
13//!    to the next hop, if there is one
14//!  * PADDING_NEGOTIATE cells (**not yet implemented**)
15//!
16//! ```text
17//!
18//! Legend: `F` = "forward reactor", `B` = "backward reactor", `S` = "stream reactor"
19//! `FH` = `ForwardHandler`
20//!
21//! | RELAY cmd  | Received in | Handled in            | Description                            |
22//! |------------|-------------|-----------------------|----------------------------------------|
23//! | DROP       | F           | FH::handle_meta_msg() | Passed to PaddingController for        |
24//! |            |             |                       | validation                             |
25//! |------------|-------------|-----------------------|----------------------------------------|
26//! | EXTEND2    | F           | FH::handle_meta_msg() | Handled by the ExtendRequestHandler    |
27//! |            |             |                       | See [forward::extend_handler].         |
28//! |------------|-------------|-----------------------|----------------------------------------|
29//! | TRUNCATE   | F           | FH::handle_meta_msg() | Not supported: TRUNCATE is considered  |
30//! |            |             |                       | a protocol violation, because none of  |
31//! |            |             |                       | of our implementations send it.        |
32//! |------------|-------------|-----------------------|----------------------------------------|
33//! | SENDME     | F           | B                     | Sent to BackwardReactor for handling.  |
34//! | (sid = 0)  |             |                       | See the [crate::circuit::reactor] docs |
35//! |------------|-------------|-----------------------|----------------------------------------|
36//! | Other      | F           | FH::handle_meta_msg() | Rejected as unrecognized               |
37//! | (sid = 0)  |             |                       |                                        |
38//! |------------|-------------|-----------------------|----------------------------------------|
39//! | Other      | F           | S                     | Handled in the `StreamReactor`         |
40//! | (sid != 0) |             |                       |                                        |
41//! ```
42
43pub(crate) mod backward;
44pub(crate) mod forward;
45
46use std::sync::Arc;
47use std::time::Duration;
48
49use futures::StreamExt as _;
50use futures::channel::mpsc;
51
52use tor_cell::chancell::CircId;
53use tor_cell::relaycell::RelayCmd;
54use tor_linkspec::OwnedChanTarget;
55use tor_memquota::mq_queue::{ChannelSpec, MpscSpec};
56use tor_rtcompat::{DynTimeProvider, Runtime};
57
58use crate::channel::Channel;
59use crate::circuit::circhop::ReactorStreamComponents;
60use crate::circuit::circhop::{CircHopOutbound, HopSettings};
61use crate::circuit::reactor::Reactor as BaseReactor;
62use crate::circuit::reactor::hop_mgr::HopMgr;
63use crate::circuit::reactor::stream;
64use crate::circuit::{CircuitRxReceiver, UniqId};
65use crate::congestion::sendme::StreamRecvWindow;
66use crate::crypto::cell::{InboundRelayLayer, OutboundRelayLayer};
67use crate::memquota::{CircuitAccount, SpecificAccount};
68use crate::relay::RelayCirc;
69use crate::relay::channel_provider::ChannelProvider;
70use crate::relay::reactor::backward::Backward;
71use crate::relay::reactor::forward::Forward;
72use crate::stream::flow_ctrl::state::WithSidechannelMitigations;
73use crate::stream::flow_ctrl::xon_xoff::reader::XonXoffReaderCtrl;
74use crate::stream::incoming::{
75    IncomingCmdChecker, IncomingStream, IncomingStreamRequestFilter, IncomingStreamRequestHandler,
76    StreamReqInfo,
77};
78use crate::stream::raw::StreamReceiver;
79use crate::stream::{RECV_WINDOW_INIT, StreamComponents, StreamTarget, Tunnel};
80
81// TODO(circpad): once padding is stabilized, the padding module will be moved out of client.
82use crate::client::circuit::padding::{PaddingController, PaddingEventStream};
83
84/// Type-alias for the relay base reactor type.
85type RelayBaseReactor<R> = BaseReactor<R, Forward, Backward>;
86
87/// The entry point of the circuit reactor subsystem.
88#[must_use = "If you don't call run() on a reactor, the circuit won't work."]
89pub(crate) struct Reactor<R: Runtime>(RelayBaseReactor<R>);
90
91/// A handler customizing the relay stream reactor.
92struct StreamHandler;
93
94impl stream::StreamHandler for StreamHandler {
95    fn halfstream_expiry(&self, hop: &CircHopOutbound) -> Duration {
96        let ccontrol = hop.ccontrol();
97
98        // Note: if we have no measurements for the RTT, this will be set to 0,
99        // so the stream will be removed from the stream map immediately,
100        // and any subsequent messages arriving on it will trigger
101        // a proto violation causing the circuit to close.
102        //
103        // TODO(relay-tuning): we should make sure that this doesn't cause us to
104        // wrongly close legitimate circuits that still have in-flight stream data
105        ccontrol
106            .lock()
107            .expect("poisoned lock")
108            .rtt()
109            .max_rtt()
110            // TODO(relay): we should fallback to a non-zero default here
111            // if we don't have any RTT measurements yet
112            .unwrap_or_default()
113    }
114
115    fn flowctrl_sidechannel_mitigations(&self) -> WithSidechannelMitigations {
116        // We're a relay, so we don't want sidechannel mitigations for flow control.
117        WithSidechannelMitigations::Disabled
118    }
119}
120
121impl<R: Runtime> Reactor<R> {
122    /// Create a new circuit reactor.
123    ///
124    /// Returns the [`Reactor`], a [`RelayCirc`] handle to it,
125    /// and a [`Stream`](futures::Stream) of `IncomingStream`s.
126    ///
127    /// The reactor will send outbound messages on `channel`, receive incoming
128    /// messages on `input`, and identify this circuit by the channel-local
129    /// [`CircId`] provided.
130    ///
131    /// The internal unique identifier for this circuit will be `unique_id`.
132    ///
133    /// The returned `IncomingStream`s are exit, dns, or directory streams.
134    /// An incoming stream is automatically rejected by the reactor
135    /// if the provided `IncomingStreamRequestFilter` rejects it.
136    /// You can also explicitly reject a stream by calling [`IncomingStream::reject`].
137    /// If the `Stream` is dropped, the next incoming stream request
138    /// (`BEGIN`, `BEGIN_DIR`, or RESOLVE`)
139    /// on this circuit will cause the stream reactor to shut down,
140    /// which will trigger a shutdown of all the circuit reactors (FWD, BWD),
141    /// which causing the circuit to close.
142    ///
143    /// The streams not rejected by the `IncomingStreamRequestFilter` will
144    /// get an entry in the circuit's stream map.
145    /// Rejecting such a stream using [`IncomingStream::reject`] will remove the entry.
146    ///
147    /// The `IncomingStreamRequestFilter` should only perform inexpensive checks
148    /// that won't block the reactor.
149    /// More expensive, or blocking checks, should be handled outside of the circuit reactor,
150    /// when processing new `IncomingStream`s from the returned Rust stream.
151    ///
152    /// Data and directory streams can be accepted by calling [`IncomingStream::accept_data`].
153    /// The caller is responsible for proxying data between the resulting `DataStream`
154    /// and the local application stream.
155    ///
156    // TODO(relay): say how RESOLVE streams should be handled
157    //
158    // TODO: declare a type-alias for the impl futures::Stream return type
159    // when support for impl in type aliases gets stabilized.
160    //
161    // See issue #63063 <https://github.com/rust-lang/rust/issues/63063>
162    //
163    // TODO(DEDUP): the incoming stream handling is *very* similar
164    // to the impll from ServiceOnionServiceDataTunnel::allow_stream_requests.
165    // We should dedupe these someday, when we rewrite the client reactor
166    // to use the new multi-reactor architecture
167    #[allow(clippy::too_many_arguments)] // TODO
168    pub(crate) fn new(
169        runtime: R,
170        channel: &Arc<Channel>,
171        circ_id: CircId,
172        unique_id: UniqId,
173        input: CircuitRxReceiver,
174        crypto_in: Box<dyn InboundRelayLayer + Send>,
175        crypto_out: Box<dyn OutboundRelayLayer + Send>,
176        settings: &HopSettings,
177        chan_provider: Arc<dyn ChannelProvider<BuildSpec = OwnedChanTarget> + Send + Sync>,
178        padding_ctrl: PaddingController,
179        padding_event_stream: PaddingEventStream,
180        incoming_filter: Box<dyn IncomingStreamRequestFilter>,
181        allowed_stream_cmds: &[RelayCmd],
182        memquota: &CircuitAccount,
183    ) -> crate::Result<(
184        Self,
185        Arc<RelayCirc>,
186        impl futures::Stream<Item = IncomingStream> + use<R>,
187    )> {
188        // NOTE: not registering this channel with the memquota subsystem is okay,
189        // because it has no buffering (if ever decide to make the size of this buffer
190        // non-zero for whatever reason, we must remember to register it with memquota
191        // so that it counts towards the total memory usage for the circuit.
192        #[allow(clippy::disallowed_methods)]
193        let (stream_tx, stream_rx) = mpsc::channel(0);
194
195        /// The size of the channel receiving IncomingStreamRequestContexts.
196        ///
197        // TODO(relay-tuning): buffer size
198        //
199        // This is currently set to 2x the initial receive window,
200        // the same as the buffer size we use for onion services.
201        // This value was picked arbitrarily,
202        // and is not necessarily tuned for relay needs.
203        const INCOMING_BUFFER: usize = crate::stream::STREAM_READER_BUFFER;
204
205        let time_provider = DynTimeProvider::new(runtime.clone());
206        let (incoming_sender, incoming_receiver) = MpscSpec::new(INCOMING_BUFFER)
207            .new_mq(time_provider.clone(), memquota.as_raw_account())?;
208
209        // Our IncomingCmdChecker does not reject BEGIN, BEGIN_DIR, RESOLVE cells,
210        // but that doesn't necessarily mean the stream will be accepted.
211        // An incoming stream can still be rejected at a later stage,
212        // by the IncomingStreamRequestFilter, or directly by the consumer of the
213        // futures::Stream<Item = IncomingStream> (by calling IncomingStream::reject()).
214        let cmd_checker = IncomingCmdChecker::new_any(allowed_stream_cmds);
215        let incoming_handler = IncomingStreamRequestHandler {
216            incoming_sender,
217            hop_num: None,
218            cmd_checker,
219            filter: incoming_filter,
220        };
221        let hop_mgr = HopMgr::new_relay(
222            runtime.clone(),
223            settings.clone(),
224            unique_id,
225            circ_id,
226            StreamHandler,
227            stream_tx,
228            incoming_handler,
229            memquota.clone(),
230        );
231
232        // TODO(relay): currently we don't need buffering on this channel,
233        // but we might need it if we start using it for more than just EXTENDED2 events
234        #[allow(clippy::disallowed_methods)]
235        let (fwd_ev_tx, fwd_ev_rx) = mpsc::channel(0);
236        let forward = Forward::new(
237            channel,
238            circ_id,
239            unique_id,
240            crypto_out,
241            chan_provider,
242            fwd_ev_tx,
243            memquota.clone(),
244        );
245        let backward = Backward::new(crypto_in);
246
247        let (inner, handle) = BaseReactor::new(
248            runtime,
249            channel,
250            circ_id,
251            unique_id,
252            input,
253            forward,
254            backward,
255            hop_mgr,
256            padding_ctrl,
257            padding_event_stream,
258            stream_rx,
259            fwd_ev_rx,
260            memquota,
261        );
262
263        let reactor = Self(inner);
264        let handle = Arc::new(RelayCirc(handle));
265
266        // Note: tunnel is a bit of a misnomer for relays
267        let tunnel = Arc::clone(&handle);
268        // TODO(relay): this is more or less copy-pasta from client code
269        let stream = incoming_receiver.map(move |req_ctx| {
270            let StreamReqInfo {
271                req,
272                stream_id,
273                hop,
274                stream_components:
275                    ReactorStreamComponents {
276                        stream_inbound_rx,
277                        stream_outbound_tx,
278                        rate_limit_rx,
279                        drain_rate_request_rx,
280                    },
281                memquota,
282                relay_cell_format,
283            } = req_ctx;
284
285            // There is no originating hop if we're a relay
286            debug_assert!(hop.is_none());
287
288            let target = StreamTarget {
289                tunnel: Tunnel::Relay(Arc::clone(&tunnel)),
290                tx: stream_outbound_tx,
291                hop: None,
292                stream_id,
293                relay_cell_format,
294                rate_limit_stream: rate_limit_rx,
295            };
296
297            // can be used to build a reader that supports XON/XOFF flow control
298            let xon_xoff_reader_ctrl =
299                XonXoffReaderCtrl::new(drain_rate_request_rx, target.clone());
300
301            let reader = StreamReceiver {
302                target: target.clone(),
303                receiver: stream_inbound_rx,
304                recv_window: StreamRecvWindow::new(RECV_WINDOW_INIT),
305                ended: false,
306            };
307
308            let components = StreamComponents {
309                stream_receiver: reader,
310                target,
311                memquota,
312                xon_xoff_reader_ctrl,
313            };
314
315            IncomingStream::new(time_provider.clone(), req, components)
316        });
317
318        Ok((reactor, handle, stream))
319    }
320
321    /// Launch the reactor, and run until the circuit closes or we
322    /// encounter an error.
323    ///
324    /// Once this method returns, the circuit is dead and cannot be
325    /// used again.
326    pub(crate) async fn run(self) -> crate::Result<()> {
327        self.0.run().await
328    }
329}
330
331#[cfg(test)]
332pub(crate) mod test {
333    // @@ begin test lint list maintained by maint/add_warning @@
334    #![allow(clippy::bool_assert_comparison)]
335    #![allow(clippy::clone_on_copy)]
336    #![allow(clippy::dbg_macro)]
337    #![allow(clippy::mixed_attributes_style)]
338    #![allow(clippy::print_stderr)]
339    #![allow(clippy::print_stdout)]
340    #![allow(clippy::single_char_pattern)]
341    #![allow(clippy::unwrap_used)]
342    #![allow(clippy::unchecked_time_subtraction)]
343    #![allow(clippy::useless_vec)]
344    #![allow(clippy::needless_pass_by_value)]
345    #![allow(clippy::string_slice)] // See arti#2571
346    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
347
348    use super::*;
349    use crate::channel::ChannelMode;
350    use crate::channel::CtrlMsg;
351    use crate::channel::circmap::CircIdRange;
352    use crate::channel::test_utils::DummyChan;
353    use crate::circuit::CircParameters;
354    use crate::circuit::circ_sender;
355    use crate::circuit::reactor::test::{AllowAllStreamsFilter, rmsg_to_ccmsg};
356    use crate::circuit::test::new_circ_net_params;
357    use crate::client::circuit::padding::new_padding;
358    use crate::congestion::test_utils::params::build_cc_vegas_params;
359    use crate::crypto::cell::RelayCellBody;
360    use crate::crypto::cell::{InboundRelayLayer, OutboundRelayLayer};
361    use crate::relay::CreateRequestHandler;
362    use crate::relay::channel::test::DummyChanProvider;
363    use crate::stream::flow_ctrl::params::FlowCtrlParameters;
364    use crate::stream::incoming::{IncomingStream, IncomingStreamRequest, NoOpRequestFilter};
365
366    use futures::AsyncReadExt as _;
367    use futures::SinkExt as _;
368    use oneshot_fused_workaround as oneshot;
369    use tracing_test::traced_test;
370
371    use tor_basic_utils::test_rng::{TestingRng, testing_rng};
372    use tor_cell::chancell::{ChanCell, ChanCmd, msg as chanmsg};
373    use tor_cell::relaycell::{AnyRelayMsgOuter, RelayCellFormat, StreamId, msg as relaymsg};
374    use tor_key_forge::Keygen;
375    use tor_linkspec::{EncodedLinkSpec, HasRelayIds, LinkSpec};
376    use tor_llcrypto::pk::curve25519::StaticKeypair;
377    use tor_llcrypto::pk::ed25519::Ed25519Identity;
378    use tor_llcrypto::pk::rsa::RsaIdentity;
379    use tor_llcrypto::rng::FakeEntropicRng;
380    use tor_protover::{Protocols, named};
381    use tor_relay_crypto::pk::RelayNtorKeys;
382    use tor_rtcompat::SpawnExt;
383    use tor_rtcompat::{DynTimeProvider, Runtime};
384    use tor_rtmock::MockRuntime;
385
386    use chanmsg::{AnyChanMsg, Destroy, DestroyReason, HandshakeType};
387    use relaymsg::SendmeTag;
388
389    use std::net::IpAddr;
390    use std::sync::{Arc, Mutex, Weak, mpsc};
391    use std::task::{Context, Poll, Waker};
392
393    // An inbound encryption layer that doesn't do any crypto.
394    struct DummyInboundCrypto {}
395
396    // An outbound encryption layer that doesn't do any crypto.
397    struct DummyOutboundCrypto {
398        /// Channel for controlling whether the current cell is meant for us or not.
399        ///
400        /// Useful for tests that check if recognized/unrecognized
401        /// cells are handled/forwarded correctly.
402        recognized_rx: mpsc::Receiver<Recognized>,
403    }
404
405    const DUMMY_TAG: [u8; 20] = [1; 20];
406
407    impl InboundRelayLayer for DummyInboundCrypto {
408        fn originate(&mut self, _cmd: ChanCmd, _cell: &mut RelayCellBody) -> SendmeTag {
409            DUMMY_TAG.into()
410        }
411
412        fn encrypt_inbound(&mut self, _cmd: ChanCmd, _cell: &mut RelayCellBody) {}
413    }
414
415    impl OutboundRelayLayer for DummyOutboundCrypto {
416        fn decrypt_outbound(
417            &mut self,
418            _cmd: ChanCmd,
419            _cell: &mut RelayCellBody,
420        ) -> Option<SendmeTag> {
421            // Note: this should never block.
422            let recognized = self.recognized_rx.recv().unwrap();
423
424            match recognized {
425                Recognized::Yes => Some(DUMMY_TAG.into()),
426                Recognized::No => None,
427            }
428        }
429    }
430
431    /// A circuit reactor handle, for building circuits of the form
432    /// A -> B, and A -> B -> C, where the circuit reactor under test
433    /// "thinks" it is B.
434    ///
435    /// [`ReactorTestCtrl::new`] builds and spawns:
436    ///
437    ///   * a channel reactor for the A - B "Tor Channel"
438    ///   * a circuit reactor for B's view of the circuit
439    ///
440    /// Some of the tests in this module extend the circuit by another dummy hop,
441    /// to obtain an A -> B -> C circuit. This involves sending an EXTEND2
442    /// cell over the A -> B channel, and calling [`ReactorTestCtrl::do_create2_handshake`]
443    /// to finalize the handshake.
444    struct ReactorTestCtrl {
445        /// The relay circuit handle.
446        relay_circ: Arc<RelayCirc>,
447        /// The circuit id on our `inbound_chan`.
448        circid: CircId,
449        /// The inbound channel ("towards the client").
450        ///
451        /// This is the "Tor channel" between A and B in
452        /// a circuit of the form A -> B or A -> B -> C.
453        inbound_chan: DummyChan,
454        /// The outbound channel ("away from the client"), if any.
455        ///
456        /// Shared with the DummyChanProvider, which initializes this
457        /// when the relay reactor launches a channel to the next hop
458        /// via `get_or_launch()`.
459        ///
460        /// This is the "Tor channel" between B and C,
461        /// if our test circuit is of the form A -> B -> C
462        /// (i.e. if we have extended the "base" circuit by another mock hop, to C).
463        outbound_chan: Arc<Mutex<Option<DummyChan>>>,
464        /// MPSC channel for telling the DummyOutboundCrypto that the next
465        /// cell we're about to send to the reactor should be "recognized".
466        recognized_tx: mpsc::Sender<Recognized>,
467    }
468
469    /// Whether a forward cell to send should be "recognized"
470    /// or "unrecognized" by the relay under test.
471    enum Recognized {
472        /// Recognized
473        Yes,
474        /// Unrecognized
475        No,
476    }
477
478    /// The direction we expect the reactor to have sent a DESTROY in
479    #[allow(dead_code)] // we don't use all of these yet
480    enum DestroyDirection {
481        /// Forward ("towards the exit")
482        Forward,
483        /// Backward ("towards the client")
484        Backward,
485        /// Both forward and backward
486        Both,
487    }
488
489    /// Decode a cell, extracting the underlying message of type `expect_msg`
490    macro_rules! decode_relay_cell {
491        ($cell:expr, $expect_msg:tt) => {{
492            let rmsg = match $cell.msg() {
493                chanmsg::AnyChanMsg::Relay(r) => AnyRelayMsgOuter::decode_singleton(
494                    RelayCellFormat::V0,
495                    r.clone().into_relay_body(),
496                )
497                .unwrap(),
498                msg => panic!("unexpected forwarded {msg:?}"),
499            };
500
501            let msg = match rmsg.msg() {
502                relaymsg::AnyRelayMsg::$expect_msg(inner) => inner.clone(),
503                _ => panic!("unexpected relay message {rmsg:?}"),
504            };
505
506            (rmsg.stream_id(), msg)
507        }};
508    }
509
510    const DUMMY_ED25519_KEY: [u8; 32] = *b"32 bytes pretending to be a key!";
511    const DUMMY_RSA_KEY: [u8; 20] = *b"not really an RSA ky";
512
513    /// Helper for building a [`ChannelMode::Relay`] for our test reactor
514    fn build_channel_mode<R: Runtime>(
515        chan_provider: Arc<DummyChanProvider<R>>,
516        allowed_stream_cmds: &[RelayCmd],
517    ) -> ChannelMode {
518        let our_ed25519_id = Ed25519Identity::from_bytes(&DUMMY_ED25519_KEY).unwrap();
519        let our_rsa_id = RsaIdentity::from_bytes(&DUMMY_RSA_KEY).unwrap();
520
521        let mut rng = FakeEntropicRng::<TestingRng>(testing_rng());
522        let relay_ntor_keys = StaticKeypair::generate(&mut rng).unwrap();
523
524        // A handler that will process CREATE* requests on channels
525        //
526        // Note: in practice, this won't actually be used at all,
527        // because for the purposes of these tests, the circuit reactor is spawned manually,
528        // by ReactorTestCtrl::new(), which also hackily initializes the channel's circuit map
529        // with a circuit entry for it.
530        //
531        // This should be fine for now, but we might want to rethink it in the future
532        // (i.e. we might want to let the channel reactor spawn the circuit reactor under test,
533        // in response to CREATE*).
534        let (create_request_handler, _circuit_stream_rx) = CreateRequestHandler::new(
535            Arc::downgrade(&chan_provider) as Weak<_>,
536            new_circ_net_params(),
537            RelayNtorKeys::new(Arc::new(relay_ntor_keys.into())),
538            // Don't filter any stream requests.
539            Box::new(|| Box::new(NoOpRequestFilter) as Box<_>),
540            allowed_stream_cmds,
541        );
542        let create_request_handler = Arc::new(create_request_handler);
543
544        ChannelMode::Relay {
545            create_request_handler,
546            our_ed25519_id,
547            our_rsa_id,
548            // This doesn't actually matter for these tests
549            circ_id_range: CircIdRange::Low,
550        }
551    }
552
553    /// Prepare our "inbound" channel,
554    ///
555    /// > Note: the concept of an "inbound" channel only really makes sense
556    /// > if you think about it from a circuit perspective:
557    /// > these tests essentially simulate circuits of the form A -> B
558    /// > and A -> B -> C. The relay circuit reactor under test "thinks" it's relay B,
559    /// > and its "inbound" and "outbound" channels are the A -> B and B -> C channels,
560    /// > respectively.
561    ///
562    /// This spawns a channel reactor and creates a fake circuit entry in it,
563    /// which is wired up to the circuit Reactor under test by [`ReactorTestCtrl::new`].
564    async fn prepare_inbound_chan<R: Runtime>(
565        rt: &R,
566        mode: ChannelMode,
567    ) -> (CircId, CircuitRxReceiver, DummyChan) {
568        let mut inbound_chan = DummyChan::run(rt, mode);
569
570        let memquota = CircuitAccount::new_noop();
571        let time_provider = DynTimeProvider::new(rt.clone());
572
573        let (sender, receiver) = MpscSpec::new(128)
574            .new_mq(time_provider, memquota.as_raw_account())
575            .unwrap();
576        let (sender, receiver) = circ_sender::channel(sender, receiver);
577        let (created_sender, created_receiver) = oneshot::channel();
578
579        let (tx, rx) = oneshot::channel();
580
581        // Note: we need to make sure the circuit is in the channel reactor's
582        // circuit map, because otherwise we can't test the DESTROY behavior,
583        // (the channel reactor conditionally sends DESTROY based on whether
584        // the circuit entry is still in the circmap or not;
585        // the presence of a circuit in the circmap is a proxy for
586        // whether we have sent a DESTROY ourselves or not).
587        inbound_chan
588            .channel
589            .send_control(CtrlMsg::AllocateCircuit {
590                created_sender,
591                sender,
592                tx,
593            })
594            .unwrap();
595        let (circid, _circ_unique_id, _padding_ctrl, _padding_stream) = rx.await.unwrap().unwrap();
596
597        // Hack: AllocateCircuit puts the circuit in the "Opening" state,
598        // but in order to actually be able to send anything on this channel,
599        // we need to advance it to "Open". We do that by sending a CREATED2 cell on the channel,
600        // which is nonsensical from the perspective of the relay-specific test setup
601        // (it would make sense if this was a client channel, however).
602        // Alas, it is the only way we can advance the circuit's state to "Open"
603        // in the channel's circmap without introducing a test-only CtrlMsg for this,
604        // or without surrendering the circuit Reactor setup to the channel impl
605        // (the latter might not be so bad actually, because it would be closer to what
606        // happens in reality).
607        let handshake = vec![];
608        let created2 = chanmsg::Created2::new(handshake.clone());
609        let cell = ChanCell::new(Some(circid), created2.into());
610        inbound_chan.tx.try_send(Ok(cell)).unwrap();
611
612        // We **have** to read the CREATED2 (otherwise the channel reactor shuts down with an error)
613        let _ = created_receiver.await;
614
615        (circid, receiver, inbound_chan)
616    }
617
618    impl ReactorTestCtrl {
619        /// Spawn a relay circuit reactor, returning a `ReactorTestCtrl` for
620        /// controlling it.
621        async fn spawn_reactor<R: Runtime>(
622            rt: &R,
623            allowed_stream_cmds: &[RelayCmd],
624        ) -> (Self, impl futures::Stream<Item = IncomingStream>) {
625            let outbound_chan = Arc::new(Mutex::new(None));
626            let chan_provider = Arc::new(DummyChanProvider::new(
627                rt.clone(),
628                Arc::clone(&outbound_chan),
629            ));
630
631            let mode = build_channel_mode(Arc::clone(&chan_provider), allowed_stream_cmds);
632            let (circid, receiver, inbound_chan) = prepare_inbound_chan(rt, mode).await;
633
634            let unique_id = UniqId::new(8, 17);
635            let (padding_ctrl, padding_stream) = new_padding(DynTimeProvider::new(rt.clone()));
636            let params = CircParameters::new(
637                true,
638                build_cc_vegas_params(),
639                FlowCtrlParameters::defaults_for_tests(),
640            );
641            let settings = HopSettings::from_params_and_caps(
642                crate::circuit::circhop::HopNegotiationType::Full,
643                &params,
644                &[named::FLOWCTRL_CC].into_iter().collect::<Protocols>(),
645            )
646            .unwrap();
647
648            let (recognized_tx, recognized_rx) = mpsc::channel();
649            let (reactor, relay_circ, incoming_streams) = Reactor::new(
650                rt.clone(),
651                &Arc::clone(&inbound_chan.channel),
652                circid,
653                unique_id,
654                receiver,
655                Box::new(DummyInboundCrypto {}),
656                Box::new(DummyOutboundCrypto { recognized_rx }),
657                &settings,
658                chan_provider,
659                padding_ctrl,
660                padding_stream,
661                Box::new(AllowAllStreamsFilter),
662                allowed_stream_cmds,
663                &CircuitAccount::new_noop(),
664            )
665            .unwrap();
666
667            rt.spawn(async {
668                let _ = reactor.run().await;
669            })
670            .unwrap();
671
672            let ctrl = Self {
673                relay_circ,
674                circid,
675                recognized_tx,
676                inbound_chan,
677                outbound_chan,
678            };
679
680            (ctrl, incoming_streams)
681        }
682
683        /// Simulate the sending of a forward relay message through our relay.
684        async fn send_fwd(
685            &mut self,
686            id: Option<StreamId>,
687            msg: relaymsg::AnyRelayMsg,
688            recognized: Recognized,
689            early: bool,
690        ) {
691            // This a bit janky, but for each forward cell we send to the reactor
692            // we need to send a bit of metadata to the DummyOutboundLayer
693            // specifying whether the cell should be treated as recognized
694            // or unrecognized
695            self.recognized_tx.send(recognized).unwrap();
696            self.send_fwd_cmsg(rmsg_to_ccmsg(id, msg, early)).await;
697        }
698
699        /// Simulate the sending of a forward channel message through our relay.
700        async fn send_fwd_cmsg(&mut self, msg: chanmsg::AnyChanMsg) {
701            let cell = ChanCell::new(Some(self.circid), msg);
702            self.inbound_chan.tx.send(Ok(cell)).await.unwrap();
703        }
704
705        /// Whether the reactor opened an outbound channel
706        /// (i.e. a channel to the next relay in the circuit).
707        fn outbound_chan_launched(&self) -> bool {
708            self.outbound_chan.lock().unwrap().is_some()
709        }
710
711        /// Perform the CREATE2 handshake.
712        async fn do_create2_handshake(
713            &mut self,
714            rt: &MockRuntime,
715            expected_hs_type: HandshakeType,
716        ) -> Option<CircId> {
717            // First, check that the reactor actually sent a CREATE2 to the next hop...
718            let (circid, msg) = self.read_outbound().into_circid_and_msg();
719            let _create2 = match msg {
720                chanmsg::AnyChanMsg::Create2(c) => {
721                    assert_eq!(c.handshake_type(), expected_hs_type);
722                    c
723                }
724                _ => panic!("unexpected forwarded {msg:?}"),
725            };
726
727            let handshake = vec![];
728            let created2 = chanmsg::Created2::new(handshake.clone());
729            // ...and then finalize the handshake by pretending to be
730            // the responding relay
731            self.write_outbound(circid, chanmsg::AnyChanMsg::Created2(created2));
732            rt.advance_until_stalled().await;
733
734            // Make sure we actually did send an EXTENDED2 towards the client
735            let msg = self.read_inbound();
736
737            let (_sid, e) = decode_relay_cell!(msg, Extended2);
738            assert_eq!(e.clone().into_body(), handshake);
739
740            circid
741        }
742
743        /// Whether the circuit is closing (e.g. due to a proto violation).
744        fn is_closing(&self) -> bool {
745            self.relay_circ.is_closing()
746        }
747
748        /// Read a cell from the inbound channel
749        /// (moving towards the client).
750        ///
751        /// See [`try_read_inbound`](Self::try_read_inbound).
752        ///
753        /// Panics if there are no ready cells on the inbound MPSC channel.
754        fn read_inbound(&mut self) -> ChanCell<AnyChanMsg> {
755            self.try_read_inbound().unwrap()
756        }
757
758        /// Try to read a cell from the inbound channel
759        /// (moving towards the client).
760        ///
761        /// For example, for a circuit of the form A -> B -> C,
762        /// where B is the relay whose circuit reactor we're testing,
763        /// this function reads a channel message on the A <-> B channel,
764        /// from the perspective of A (i.e. it reads a channel message sent by B).
765        ///
766        /// Returns None if there are no ready cells on the inbound MPSC channel.
767        fn try_read_inbound(&mut self) -> Option<ChanCell<AnyChanMsg>> {
768            #[allow(deprecated)] // TODO(#2386)
769            self.inbound_chan.rx.try_next().ok().flatten()
770        }
771
772        /// Read a cell from the outbound channel
773        /// (moving towards the next hop).
774        ///
775        /// See [`try_read_outbound`](Self::try_read_outbound).
776        ///
777        /// Panics if there are no ready cells on the outbound MPSC channel,
778        /// or if there is no outbound channel.
779        fn read_outbound(&mut self) -> ChanCell<AnyChanMsg> {
780            self.try_read_outbound().unwrap()
781        }
782
783        /// Read a cell from the outbound channel
784        /// (moving towards the next hop).
785        ///
786        /// For example, for a circuit of the form A -> B -> C,
787        /// where B is the relay whose circuit reactor we're testing,
788        /// this function reads a channel message on the B <-> C channel,
789        /// from the perspective of C (i.e. it reads a channel message sent by B).
790        ///
791        /// Returns None if there are no ready cells on the outbound MPSC channel,
792        /// or if there is no outbound channel.
793        fn try_read_outbound(&mut self) -> Option<ChanCell<AnyChanMsg>> {
794            let mut lock = self.outbound_chan.lock().unwrap();
795            let chan = lock.as_mut()?;
796            #[allow(deprecated)] // TODO(#2386)
797            chan.rx.try_next().ok().flatten()
798        }
799
800        /// Write to the sending end of the outbound Tor channel.
801        ///
802        /// Simulates the receipt of a cell from the next hop.
803        ///
804        /// Panics if the outbound chan sender is full.
805        fn write_outbound(&mut self, circid: Option<CircId>, msg: chanmsg::AnyChanMsg) {
806            let mut lock = self.outbound_chan.lock().unwrap();
807            let chan = lock.as_mut().unwrap();
808            let cell = ChanCell::new(circid, msg);
809
810            chan.tx.try_send(Ok(cell)).unwrap();
811        }
812    }
813
814    fn dummy_linkspecs() -> Vec<EncodedLinkSpec> {
815        vec![
816            LinkSpec::Ed25519Id([43; 32].into()).encode().unwrap(),
817            LinkSpec::RsaId([45; 20].into()).encode().unwrap(),
818            LinkSpec::OrPort("127.0.0.1".parse::<IpAddr>().unwrap(), 999)
819                .encode()
820                .unwrap(),
821        ]
822    }
823
824    macro_rules! assert_cell_is_destroy {
825        ($cell:expr, $reason:expr) => {{
826            match $cell.msg() {
827                chanmsg::AnyChanMsg::Destroy(d) => {
828                    assert_eq!(d.reason(), $reason);
829                }
830                _ => panic!("unexpected ending {:?}", $cell),
831            }
832        }};
833    }
834
835    /// Assert that we have sent a DESTROY cell with the specified `reason`
836    /// towards the "client" and/or the "next hop".
837    ///
838    /// The test is expected to drain the inbound Tor "channel"
839    /// of any non-ending cells it might be expecting before calling this function.
840    fn assert_destroy_sent(
841        ctrl: &mut ReactorTestCtrl,
842        reason: DestroyReason,
843        direction: DestroyDirection,
844    ) {
845        assert!(ctrl.is_closing());
846
847        match direction {
848            DestroyDirection::Backward => {
849                assert_cell_is_destroy!(ctrl.read_inbound(), reason);
850                assert!(ctrl.try_read_outbound().is_none());
851            }
852            DestroyDirection::Forward => {
853                assert_cell_is_destroy!(ctrl.read_outbound(), reason);
854                assert!(ctrl.try_read_inbound().is_none());
855            }
856            DestroyDirection::Both => {
857                assert_cell_is_destroy!(ctrl.read_inbound(), reason);
858                assert_cell_is_destroy!(ctrl.read_outbound(), reason);
859            }
860        }
861    }
862
863    macro_rules! expect_cell {
864        ($cell:expr, $chanmsg:tt, $relaymsg:tt) => {{
865            let msg = match $cell.msg() {
866                chanmsg::AnyChanMsg::$chanmsg(m) => {
867                    let body = m.clone().into_relay_body();
868                    AnyRelayMsgOuter::decode_singleton(RelayCellFormat::V0, body).unwrap()
869                }
870                _ => panic!("unexpected forwarded {:?}", $cell),
871            };
872
873            match msg.msg() {
874                relaymsg::AnyRelayMsg::$relaymsg(m) => m.clone(),
875                _ => panic!("unexpected cell {msg:?}"),
876            }
877        }};
878    }
879
880    #[traced_test]
881    #[test]
882    fn reject_extend2_relay() {
883        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
884            let (mut ctrl, _incoming_streams) =
885                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
886            rt.advance_until_stalled().await;
887
888            let linkspecs = dummy_linkspecs();
889            let extend2 = relaymsg::Extend2::new(linkspecs, HandshakeType::NTOR_V3, vec![]).into();
890            ctrl.send_fwd(None, extend2, Recognized::Yes, false).await;
891            rt.advance_until_stalled().await;
892
893            assert!(logs_contain("got EXTEND2 in a RELAY cell?!"));
894            assert!(!ctrl.outbound_chan_launched());
895
896            // There is no next hop because we haven't extended the circuit,
897            // so only expect the DESTROY to be sent toward the client (Backward).
898            assert_destroy_sent(&mut ctrl, DestroyReason::NONE, DestroyDirection::Backward);
899        });
900    }
901
902    #[traced_test]
903    #[test]
904    fn reject_extend2_previous_hop() {
905        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
906            let (mut ctrl, _incoming_streams) =
907                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
908            rt.advance_until_stalled().await;
909
910            // No outbound circuits yet
911            assert!(!ctrl.outbound_chan_launched());
912
913            // Build a linkspec with the identities of the dummy channel
914            let mut linkspecs = ctrl
915                .inbound_chan
916                .channel
917                .target()
918                .identities()
919                .map(|id| LinkSpec::from(id.to_owned()).encode())
920                .collect::<Result<Vec<_>, _>>()
921                .unwrap();
922
923            // Make sure this channel actually has some identities
924            // (i.e. that it's not a client channel or something)
925            assert_eq!(linkspecs.len(), 2);
926
927            // There must be at least one IPv4 OR port address
928            linkspecs.push(
929                LinkSpec::OrPort("127.0.0.1".parse::<IpAddr>().unwrap(), 999)
930                    .encode()
931                    .unwrap(),
932            );
933            let handshake_type = HandshakeType::NTOR_V3;
934            let extend2 = relaymsg::Extend2::new(linkspecs, handshake_type, vec![]).into();
935            ctrl.send_fwd(None, extend2, Recognized::Yes, true).await;
936            rt.advance_until_stalled().await;
937
938            // The reactor handled the EXTEND2 and launched an outbound channel
939            assert!(logs_contain("Cannot extend circuit to previous hop"));
940            assert!(!ctrl.outbound_chan_launched());
941            assert!(ctrl.is_closing());
942        });
943    }
944
945    #[traced_test]
946    #[test]
947    fn extend_and_forward() {
948        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
949            let (mut ctrl, _incoming_streams) =
950                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
951            rt.advance_until_stalled().await;
952
953            // No outbound circuits yet
954            assert!(!ctrl.outbound_chan_launched());
955
956            let linkspecs = dummy_linkspecs();
957            let handshake_type = HandshakeType::NTOR_V3;
958            let extend2 = relaymsg::Extend2::new(linkspecs, handshake_type, vec![]).into();
959            ctrl.send_fwd(None, extend2, Recognized::Yes, true).await;
960            rt.advance_until_stalled().await;
961
962            // The reactor handled the EXTEND2 and launched an outbound channel
963            assert!(logs_contain(
964                "Launched channel to the next hop circ_uniq_id=Circ 8.17"
965            ));
966            assert!(ctrl.outbound_chan_launched());
967            assert!(!ctrl.is_closing());
968
969            let _circid = ctrl.do_create2_handshake(&rt, handshake_type).await;
970            assert!(logs_contain("Got CREATED2 response from next hop"));
971            assert!(logs_contain("Extended circuit to the next hop"));
972
973            // Time to forward a message to the next hop!
974            let early = false;
975            let begin = relaymsg::Begin::new("127.0.0.1", 1111, 0).unwrap();
976            ctrl.send_fwd(None, begin.clone().into(), Recognized::No, early)
977                .await;
978            rt.advance_until_stalled().await;
979
980            // Ensure the other end received the BEGIN cell
981            let cell = ctrl.read_outbound();
982            let recvd_begin = expect_cell!(cell, Relay, Begin);
983            assert_eq!(begin, recvd_begin);
984
985            // Now send the same message again, but this time in a RELAY_EARLY
986            let early = true;
987            let begin = relaymsg::Begin::new("127.0.0.1", 1111, 0).unwrap();
988            ctrl.send_fwd(None, begin.clone().into(), Recognized::No, early)
989                .await;
990            rt.advance_until_stalled().await;
991            let cell = ctrl.read_outbound();
992            let recvd_begin = expect_cell!(cell, RelayEarly, Begin);
993            assert_eq!(begin, recvd_begin);
994        });
995    }
996
997    #[traced_test]
998    #[test]
999    fn forward_before_extend() {
1000        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
1001            let (mut ctrl, _incoming_streams) =
1002                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
1003            rt.advance_until_stalled().await;
1004
1005            // Send an arbitrary unrecognized cell. The reactor should flag this as
1006            // a protocol violation, because we don't have an outbound channel to forward it on.
1007            let end = relaymsg::End::new_misc().into();
1008            ctrl.send_fwd(None, end, Recognized::No, true).await;
1009            rt.advance_until_stalled().await;
1010
1011            assert!(logs_contain(
1012                "Asked to forward cell before the circuit was extended?!"
1013            ));
1014
1015            // There is no next hop because we haven't extended the circuit,
1016            // so only expect the DESTROY to be sent toward the client (Backward).
1017            assert_destroy_sent(&mut ctrl, DestroyReason::NONE, DestroyDirection::Backward);
1018        });
1019    }
1020
1021    #[traced_test]
1022    #[test]
1023    fn reject_invalid_begin() {
1024        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
1025            let (mut ctrl, _incoming_streams) =
1026                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
1027            rt.advance_until_stalled().await;
1028
1029            let begin = relaymsg::Begin::new("127.0.0.1", 1111, 0).unwrap().into();
1030
1031            // BEGIN cells *must* have a stream ID, so expect the reactor to reject this
1032            // and close the circuit
1033            ctrl.send_fwd(None, begin, Recognized::Yes, false).await;
1034            rt.advance_until_stalled().await;
1035
1036            assert!(logs_contain(
1037                "Invalid stream ID [scrubbed] for relay command BEGIN"
1038            ));
1039
1040            // There is no next hop because we haven't extended the circuit,
1041            // so only expect the DESTROY to be sent toward the client (Backward).
1042            assert_destroy_sent(&mut ctrl, DestroyReason::NONE, DestroyDirection::Backward);
1043        });
1044    }
1045
1046    #[traced_test]
1047    #[test]
1048    fn destroy_from_client() {
1049        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
1050            let (mut ctrl, _incoming_streams) =
1051                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
1052            rt.advance_until_stalled().await;
1053
1054            // Extend the circuit by another hop
1055            let linkspecs = dummy_linkspecs();
1056            let handshake_type = HandshakeType::NTOR_V3;
1057            let extend2 = relaymsg::Extend2::new(linkspecs, handshake_type, vec![]).into();
1058            ctrl.send_fwd(None, extend2, Recognized::Yes, true).await;
1059            rt.advance_until_stalled().await;
1060            let _circid = ctrl.do_create2_handshake(&rt, handshake_type).await;
1061            assert!(logs_contain("Extended circuit to the next hop"));
1062            assert!(ctrl.outbound_chan_launched());
1063
1064            // Simulate the client sending us a DESTROY cell
1065            let destroy = Destroy::new(DestroyReason::PROTOCOL);
1066            ctrl.send_fwd_cmsg(destroy.into()).await;
1067            rt.advance_until_stalled().await;
1068
1069            assert!(logs_contain(
1070                "Received outbound DESTROY, circuit shutting down"
1071            ));
1072
1073            // Since this is a circuit of the form A -> B -> C,
1074            // and A sent us a DESTROY, we expect our relay (B) to forward
1075            // the DESTROY to C.
1076            assert_destroy_sent(&mut ctrl, DestroyReason::NONE, DestroyDirection::Forward);
1077        });
1078    }
1079
1080    #[traced_test]
1081    #[test]
1082    fn destroy_from_next_hop() {
1083        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
1084            let (mut ctrl, _incoming_streams) =
1085                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
1086            rt.advance_until_stalled().await;
1087
1088            // Extend the circuit by another hop
1089            let linkspecs = dummy_linkspecs();
1090            let handshake_type = HandshakeType::NTOR_V3;
1091            let extend2 = relaymsg::Extend2::new(linkspecs, handshake_type, vec![]).into();
1092            ctrl.send_fwd(None, extend2, Recognized::Yes, true).await;
1093            rt.advance_until_stalled().await;
1094            let circid = ctrl.do_create2_handshake(&rt, handshake_type).await;
1095            assert!(logs_contain("Extended circuit to the next hop"));
1096            assert!(ctrl.outbound_chan_launched());
1097
1098            // Simulate the next hop sending us a DESTROY cell
1099            let destroy = Destroy::new(DestroyReason::PROTOCOL);
1100            ctrl.write_outbound(circid, destroy.into());
1101            rt.advance_until_stalled().await;
1102
1103            // We have *not* received an outbound destroy
1104            assert!(!logs_contain(
1105                "Received outbound DESTROY, circuit shutting down"
1106            ));
1107
1108            // We received an inbound one (from the next hop)
1109            assert!(logs_contain(
1110                "Received inbound DESTROY, circuit shutting down"
1111            ));
1112
1113            // There is no next hop because we haven't extended the circuit,
1114            // so only expect the DESTROY to be sent toward the client (Backward).
1115            // This also ensures the destroy reason (PROTOCOL) is not propagated.
1116            assert_destroy_sent(&mut ctrl, DestroyReason::NONE, DestroyDirection::Backward);
1117        });
1118    }
1119
1120    #[traced_test]
1121    #[test]
1122    fn truncate() {
1123        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
1124            let (mut ctrl, _incoming_streams) =
1125                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
1126            rt.advance_until_stalled().await;
1127
1128            // Simulate the client sending us a TRUNCATE cell
1129            let truncate = relaymsg::Truncate::default().into();
1130            ctrl.send_fwd(None, truncate, Recognized::Yes, false).await;
1131            rt.advance_until_stalled().await;
1132
1133            assert!(logs_contain(
1134                "Circuit protocol violation: TRUNCATE not allowed"
1135            ));
1136
1137            // There is no next hop because we haven't extended the circuit,
1138            // so only expect the DESTROY to be sent toward the client (Backward).
1139            assert_destroy_sent(&mut ctrl, DestroyReason::NONE, DestroyDirection::Backward);
1140        });
1141    }
1142
1143    #[traced_test]
1144    #[test]
1145    fn data_stream() {
1146        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
1147            const TO_SEND: &[u8] = b"The bells were musical in the silvery sun";
1148
1149            let (mut ctrl, mut incoming_streams) =
1150                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
1151            rt.advance_until_stalled().await;
1152
1153            let begin = relaymsg::Begin::new("127.0.0.1", 1111, 0).unwrap().into();
1154            ctrl.send_fwd(StreamId::new(1), begin, Recognized::Yes, false)
1155                .await;
1156            rt.advance_until_stalled().await;
1157
1158            let data = relaymsg::Data::new(TO_SEND).unwrap().into();
1159            ctrl.send_fwd(StreamId::new(1), data, Recognized::Yes, false)
1160                .await;
1161
1162            // We should have a pending incoming stream
1163            let pending = incoming_streams.next().await.unwrap();
1164
1165            // Accept it, and let's see what we have!
1166            let mut stream = pending
1167                .accept_data(relaymsg::Connected::new_empty())
1168                .await
1169                .unwrap();
1170
1171            let mut recv_buf = [0_u8; TO_SEND.len()];
1172            stream.read_exact(&mut recv_buf).await.unwrap();
1173            assert_eq!(recv_buf, TO_SEND);
1174        });
1175    }
1176
1177    #[traced_test]
1178    #[test]
1179    fn reject_stream() {
1180        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
1181            let (mut ctrl, mut incoming_streams) =
1182                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::BEGIN]).await;
1183            rt.advance_until_stalled().await;
1184
1185            let begin = relaymsg::Begin::new("127.0.0.1", 1111, 0).unwrap().into();
1186            ctrl.send_fwd(StreamId::new(1), begin, Recognized::Yes, false)
1187                .await;
1188            rt.advance_until_stalled().await;
1189
1190            // We should have a pending incoming stream
1191            let pending = incoming_streams.next().await.unwrap();
1192
1193            // Reject the stream, and wait for the reactor to finish sending the END
1194            let end = relaymsg::End::new_misc();
1195            pending.reject(end.clone()).await.unwrap();
1196            rt.advance_until_stalled().await;
1197
1198            // The END cell written to the Tor channel should be the same as
1199            // the one we sent above, in reject().
1200            let cell = ctrl.read_inbound();
1201            let actual_end = expect_cell!(cell, Relay, End);
1202            assert_eq!(end.reason(), actual_end.reason());
1203
1204            // Sending another message on this stream results is flagged
1205            // as a proto violation
1206            let data = relaymsg::Data::new(b"no dice").unwrap().into();
1207            ctrl.send_fwd(StreamId::new(1), data, Recognized::Yes, false)
1208                .await;
1209            rt.advance_until_stalled().await;
1210
1211            assert!(logs_contain("Stream protocol violation"));
1212            assert!(logs_contain(
1213                "Unexpected RelayCmd(DATA) message on unknown stream 1"
1214            ));
1215        });
1216    }
1217
1218    #[traced_test]
1219    #[test]
1220    fn only_allow_begin_dir() {
1221        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
1222            let (mut ctrl, mut incoming_streams) = ReactorTestCtrl::spawn_reactor(
1223                &rt,
1224                // The stream reactor will only accept BEGIN_DIR streams
1225                &[RelayCmd::BEGIN_DIR],
1226            )
1227            .await;
1228            rt.advance_until_stalled().await;
1229
1230            // Directory streams should be allowed (because BEGIN_DIR is allowed)...
1231            let begin_dir = relaymsg::BeginDir::default().into();
1232            ctrl.send_fwd(StreamId::new(1), begin_dir, Recognized::Yes, false)
1233                .await;
1234            rt.advance_until_stalled().await;
1235
1236            let pending_dir_stream = incoming_streams.next().await.unwrap();
1237            assert!(matches!(
1238                pending_dir_stream.request(),
1239                IncomingStreamRequest::BeginDir(_)
1240            ));
1241
1242            let begin = relaymsg::Begin::new("127.0.0.1", 1111, 0).unwrap().into();
1243            ctrl.send_fwd(StreamId::new(2), begin, Recognized::Yes, false)
1244                .await;
1245            rt.advance_until_stalled().await;
1246
1247            // ... but the exit stream is not
1248            assert!(logs_contain("stream reactor shut down"));
1249            assert!(logs_contain(
1250                "Stream protocol violation: Unexpected BEGIN on incoming stream circ_uniq_id=Circ 8.17"
1251            ));
1252
1253            // The reactor won't create an IncomingStream,
1254            // because the stream request is rejected right away
1255            let mut noop_cx = Context::from_waker(Waker::noop());
1256            assert_eq!(
1257                incoming_streams.poll_next_unpin(&mut noop_cx).map(|_| ()),
1258                Poll::Pending
1259            );
1260        });
1261    }
1262
1263    #[traced_test]
1264    #[test]
1265    fn resolve_stream() {
1266        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
1267            let (mut ctrl, mut incoming_streams) =
1268                ReactorTestCtrl::spawn_reactor(&rt, &[RelayCmd::RESOLVE]).await;
1269            rt.advance_until_stalled().await;
1270
1271            let resolve = relaymsg::Resolve::new("example.com");
1272            let resolve_sid = StreamId::new(1337);
1273            ctrl.send_fwd(resolve_sid, resolve.into(), Recognized::Yes, false)
1274                .await;
1275            rt.advance_until_stalled().await;
1276
1277            // We should have a pending incoming stream
1278            let pending = incoming_streams.next().await.unwrap();
1279
1280            let mut resolved = relaymsg::Resolved::new_empty();
1281            let resolved_val = relaymsg::ResolvedVal::Ip(IpAddr::from([1, 2, 3, 4]));
1282            resolved.add_answer(resolved_val.clone(), 1337);
1283
1284            // We expect the client to receive this cell
1285            let expected_resolved = resolved.clone();
1286
1287            // Respond with RESOLVED
1288            pending.resolve(resolved).await.unwrap();
1289
1290            rt.advance_until_stalled().await;
1291            let (sid, resolved) = decode_relay_cell!(ctrl.read_inbound(), Resolved);
1292
1293            // Make sure the RESOLVED cell sent towards the client
1294            // matches what we sent via the IncomingStream::resolve() call above
1295            assert_eq!(resolved.into_answers(), expected_resolved.into_answers());
1296            assert_eq!(sid, resolve_sid);
1297            assert!(logs_contain("Ending stream"));
1298        });
1299    }
1300}