1
//! Module exposing the relay circuit reactor subsystem.
2
//!
3
//! See [`reactor`](crate::circuit::reactor) for a description of the overall architecture.
4
//!
5
//! #### `ForwardReactor`
6
//!
7
//! It handles
8
//!
9
//!  * unrecognized RELAY cells, by moving them in the forward direction (towards the exit)
10
//!  * recognized RELAY cells, by splitting each cell into messages, and handling
11
//!    each message individually as described in the table below
12
//!    (Note: since prop340 is not yet implemented, in practice there is only 1 message per cell).
13
//!  * RELAY_EARLY cells (**not yet implemented**)
14
//!  * DESTROY cells (**not yet implemented**)
15
//!  * PADDING_NEGOTIATE cells (**not yet implemented**)
16
//!
17
//! ```text
18
//!
19
//! Legend: `F` = "forward reactor", `B` = "backward reactor", `S` = "stream reactor"
20
//!
21
//! | RELAY cmd         | Received in | Handled in | Description                            |
22
//! |-------------------|-------------|------------|----------------------------------------|
23
//! | DROP              | F           | F          | Passed to PaddingController for        |
24
//! |                   |             |            | validation                             |
25
//! |-------------------|-------------|------------|----------------------------------------|
26
//! | EXTEND2           | F           |            | Handled by instructing the channel     |
27
//! |                   |             |            | provider to launch a new channel, and  |
28
//! |                   |             |            | waiting for the new channel on its     |
29
//! |                   |             |            | outgoing_chan_rx receiver              |
30
//! |                   |             |            | (**not yet implemented**)              |
31
//! |-------------------|-------------|------------|----------------------------------------|
32
//! | TRUNCATE          | F           | F          | (**not yet implemented**)              |
33
//! |                   |             |            |                                        |
34
//! |-------------------|-------------|------------|----------------------------------------|
35
//! | TODO              |             |            |                                        |
36
//! |                   |             |            |                                        |
37
//! ```
38

            
39
pub(crate) mod backward;
40
pub(crate) mod forward;
41

            
42
use std::sync::Arc;
43
use std::time::Duration;
44

            
45
use futures::channel::mpsc;
46

            
47
use tor_cell::chancell::CircId;
48
use tor_linkspec::OwnedChanTarget;
49
use tor_rtcompat::Runtime;
50

            
51
use crate::channel::Channel;
52
use crate::circuit::circhop::{CircHopOutbound, HopSettings};
53
use crate::circuit::reactor::Reactor as BaseReactor;
54
use crate::circuit::reactor::hop_mgr::HopMgr;
55
use crate::circuit::reactor::stream;
56
use crate::circuit::{CircuitRxReceiver, UniqId};
57
use crate::crypto::cell::{InboundRelayLayer, OutboundRelayLayer};
58
use crate::memquota::CircuitAccount;
59
use crate::relay::RelayCirc;
60
use crate::relay::channel_provider::ChannelProvider;
61
use crate::relay::reactor::backward::Backward;
62
use crate::relay::reactor::forward::Forward;
63

            
64
// TODO(circpad): once padding is stabilized, the padding module will be moved out of client.
65
use crate::client::circuit::padding::{PaddingController, PaddingEventStream};
66

            
67
/// Type-alias for the relay base reactor type.
68
type RelayBaseReactor<R> = BaseReactor<R, Forward, Backward>;
69

            
70
/// The entry point of the circuit reactor subsystem.
71
#[allow(unused)] // TODO(relay)
72
#[must_use = "If you don't call run() on a reactor, the circuit won't work."]
73
pub(crate) struct Reactor<R: Runtime>(RelayBaseReactor<R>);
74

            
75
/// A handler customizing the relay stream reactor.
76
struct StreamHandler;
77

            
78
impl stream::StreamHandler for StreamHandler {
79
    fn halfstream_expiry(&self, hop: &CircHopOutbound) -> Duration {
80
        let ccontrol = hop.ccontrol();
81

            
82
        // Note: if we have no measurements for the RTT, this will be set to 0,
83
        // so the stream will be removed from the stream map immediately,
84
        // and any subsequent messages arriving on it will trigger
85
        // a proto violation causing the circuit to close.
86
        //
87
        // TODO(relay-tuning): we should make sure that this doesn't cause us to
88
        // wrongly close legitimate circuits that still have in-flight stream data
89
        ccontrol
90
            .lock()
91
            .expect("poisoned lock")
92
            .rtt()
93
            .max_rtt_usec()
94
            .map(|rtt| Duration::from_millis(u64::from(rtt)))
95
            // TODO(relay): we should fallback to a non-zero default here
96
            // if we don't have any RTT measurements yet
97
            .unwrap_or_default()
98
    }
99
}
100

            
101
#[allow(unused)] // TODO(relay)
102
impl<R: Runtime> Reactor<R> {
103
    /// Create a new circuit reactor.
104
    ///
105
    /// The reactor will send outbound messages on `channel`, receive incoming
106
    /// messages on `input`, and identify this circuit by the channel-local
107
    /// [`CircId`] provided.
108
    ///
109
    /// The internal unique identifier for this circuit will be `unique_id`.
110
    #[allow(clippy::too_many_arguments)] // TODO
111
16
    pub(crate) fn new(
112
16
        runtime: R,
113
16
        channel: &Arc<Channel>,
114
16
        circ_id: CircId,
115
16
        unique_id: UniqId,
116
16
        input: CircuitRxReceiver,
117
16
        crypto_in: Box<dyn InboundRelayLayer + Send>,
118
16
        crypto_out: Box<dyn OutboundRelayLayer + Send>,
119
16
        settings: &HopSettings,
120
16
        chan_provider: Arc<dyn ChannelProvider<BuildSpec = OwnedChanTarget> + Send + Sync>,
121
16
        padding_ctrl: PaddingController,
122
16
        padding_event_stream: PaddingEventStream,
123
16
        memquota: &CircuitAccount,
124
16
    ) -> crate::Result<(Self, Arc<RelayCirc>)> {
125
        // NOTE: not registering this channel with the memquota subsystem is okay,
126
        // because it has no buffering (if ever decide to make the size of this buffer
127
        // non-zero for whatever reason, we must remember to register it with memquota
128
        // so that it counts towards the total memory usage for the circuit.
129
        #[allow(clippy::disallowed_methods)]
130
16
        let (stream_tx, stream_rx) = mpsc::channel(0);
131

            
132
16
        let mut hop_mgr = HopMgr::new(
133
16
            runtime.clone(),
134
16
            unique_id,
135
16
            StreamHandler,
136
16
            stream_tx,
137
16
            memquota.clone(),
138
        );
139

            
140
        // On the relay side, we always have one "hop" (ourselves).
141
        //
142
        // Clients will need to call this function in response to CtrlMsg::Create
143
        // (TODO: for clients, we probably will need to store a bunch more state here)
144
16
        hop_mgr.add_hop(settings.clone())?;
145

            
146
        // TODO(relay): currently we don't need buffering on this channel,
147
        // but we might need it if we start using it for more than just EXTENDED2 events
148
        #[allow(clippy::disallowed_methods)]
149
16
        let (fwd_ev_tx, fwd_ev_rx) = mpsc::channel(0);
150
16
        let forward_foo = Forward::new(
151
16
            unique_id,
152
16
            crypto_out,
153
16
            chan_provider,
154
16
            fwd_ev_tx,
155
16
            memquota.clone(),
156
        );
157
16
        let backward_foo = Backward::new(crypto_in);
158

            
159
16
        let (inner, handle) = BaseReactor::new(
160
16
            runtime,
161
16
            channel,
162
16
            circ_id,
163
16
            unique_id,
164
16
            input,
165
16
            forward_foo,
166
16
            backward_foo,
167
16
            hop_mgr,
168
16
            padding_ctrl,
169
16
            padding_event_stream,
170
16
            stream_rx,
171
16
            fwd_ev_rx,
172
16
            memquota,
173
16
        );
174

            
175
16
        let reactor = Self(inner);
176
16
        let handle = Arc::new(RelayCirc(handle));
177

            
178
16
        Ok((reactor, handle))
179
16
    }
180

            
181
    /// Launch the reactor, and run until the circuit closes or we
182
    /// encounter an error.
183
    ///
184
    /// Once this method returns, the circuit is dead and cannot be
185
    /// used again.
186
16
    pub(crate) async fn run(mut self) -> crate::Result<()> {
187
16
        self.0.run().await
188
16
    }
189
}
190

            
191
#[cfg(test)]
192
pub(crate) mod test {
193
    // @@ begin test lint list maintained by maint/add_warning @@
194
    #![allow(clippy::bool_assert_comparison)]
195
    #![allow(clippy::clone_on_copy)]
196
    #![allow(clippy::dbg_macro)]
197
    #![allow(clippy::mixed_attributes_style)]
198
    #![allow(clippy::print_stderr)]
199
    #![allow(clippy::print_stdout)]
200
    #![allow(clippy::single_char_pattern)]
201
    #![allow(clippy::unwrap_used)]
202
    #![allow(clippy::unchecked_time_subtraction)]
203
    #![allow(clippy::useless_vec)]
204
    #![allow(clippy::needless_pass_by_value)]
205
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
206

            
207
    use super::*;
208
    use crate::circuit::reactor::test::{AllowAllStreamsFilter, rmsg_to_ccmsg};
209
    use crate::circuit::{CircParameters, CircuitRxSender};
210
    use crate::client::circuit::padding::new_padding;
211
    use crate::congestion::test_utils::params::build_cc_vegas_params;
212
    use crate::crypto::cell::RelayCellBody;
213
    use crate::crypto::cell::{InboundRelayLayer, OutboundRelayLayer};
214
    use crate::fake_mpsc;
215
    use crate::memquota::SpecificAccount as _;
216
    use crate::relay::channel::test::{DummyChan, DummyChanProvider, working_dummy_channel};
217
    use crate::stream::flow_ctrl::params::FlowCtrlParameters;
218
    use crate::stream::incoming::{IncomingStream, IncomingStreamRequestFilter};
219

            
220
    use futures::{AsyncReadExt as _, SinkExt as _, StreamExt as _};
221
    use tracing_test::traced_test;
222

            
223
    use tor_cell::chancell::{ChanCell, ChanCmd, msg as chanmsg};
224
    use tor_cell::relaycell::{
225
        AnyRelayMsgOuter, RelayCellFormat, RelayCmd, StreamId, msg as relaymsg,
226
    };
227
    use tor_linkspec::{EncodedLinkSpec, LinkSpec};
228
    use tor_protover::{Protocols, named};
229
    use tor_rtcompat::SpawnExt;
230
    use tor_rtcompat::{DynTimeProvider, Runtime};
231
    use tor_rtmock::MockRuntime;
232

            
233
    use chanmsg::{AnyChanMsg, DestroyReason, HandshakeType};
234
    use relaymsg::SendmeTag;
235

            
236
    use std::net::IpAddr;
237
    use std::sync::{Arc, Mutex, mpsc};
238

            
239
    // An inbound encryption layer that doesn't do any crypto.
240
    struct DummyInboundCrypto {}
241

            
242
    // An outbound encryption layer that doesn't do any crypto.
243
    struct DummyOutboundCrypto {
244
        /// Channel for controlling whether the current cell is meant for us or not.
245
        ///
246
        /// Useful for tests that check if recognized/unrecognized
247
        /// cells are handled/forwarded correctly.
248
        recognized_rx: mpsc::Receiver<Recognized>,
249
    }
250

            
251
    const DUMMY_TAG: [u8; 20] = [1; 20];
252

            
253
    impl InboundRelayLayer for DummyInboundCrypto {
254
        fn originate(&mut self, _cmd: ChanCmd, _cell: &mut RelayCellBody) -> SendmeTag {
255
            DUMMY_TAG.into()
256
        }
257

            
258
        fn encrypt_inbound(&mut self, _cmd: ChanCmd, _cell: &mut RelayCellBody) {}
259
    }
260

            
261
    impl OutboundRelayLayer for DummyOutboundCrypto {
262
        fn decrypt_outbound(
263
            &mut self,
264
            _cmd: ChanCmd,
265
            _cell: &mut RelayCellBody,
266
        ) -> Option<SendmeTag> {
267
            // Note: this should never block.
268
            let recognized = self.recognized_rx.recv().unwrap();
269

            
270
            match recognized {
271
                Recognized::Yes => Some(DUMMY_TAG.into()),
272
                Recognized::No => None,
273
            }
274
        }
275
    }
276

            
277
    struct ReactorTestCtrl {
278
        /// The relay circuit handle.
279
        relay_circ: Arc<RelayCirc>,
280
        /// Mock channel -> circuit reactor MPSC channel.
281
        circmsg_send: CircuitRxSender,
282
        /// The inbound channel ("towards the client").
283
        inbound_chan: DummyChan,
284
        /// The outbound channel ("away from the client"), if any.
285
        ///
286
        /// Shared with the DummyChanProvider, which initializes this
287
        /// when the relay reactor launches a channel to the next hop
288
        /// via `get_or_launch()`.
289
        outbound_chan: Arc<Mutex<Option<DummyChan>>>,
290
        /// MPSC channel for telling the DummyOutboundCrypto that the next
291
        /// cell we're about to send to the reactor should be "recognized".
292
        recognized_tx: mpsc::Sender<Recognized>,
293
    }
294

            
295
    /// Whether a forward cell to send should be "recognized"
296
    /// or "unrecognized" by the relay under test.
297
    enum Recognized {
298
        /// Recognized
299
        Yes,
300
        /// Unrecognized
301
        No,
302
    }
303

            
304
    impl ReactorTestCtrl {
305
        /// Spawn a relay circuit reactor, returning a `ReactorTestCtrl` for
306
        /// controlling it.
307
        fn spawn_reactor<R: Runtime>(rt: &R) -> Self {
308
            let inbound_chan = working_dummy_channel(rt);
309
            let circid = CircId::new(1337).unwrap();
310
            let unique_id = UniqId::new(8, 17);
311
            let (padding_ctrl, padding_stream) = new_padding(DynTimeProvider::new(rt.clone()));
312
            let (circmsg_send, circmsg_recv) = fake_mpsc(64);
313
            let params = CircParameters::new(
314
                true,
315
                build_cc_vegas_params(),
316
                FlowCtrlParameters::defaults_for_tests(),
317
            );
318
            let settings = HopSettings::from_params_and_caps(
319
                crate::circuit::circhop::HopNegotiationType::Full,
320
                &params,
321
                &[named::FLOWCTRL_CC].into_iter().collect::<Protocols>(),
322
            )
323
            .unwrap();
324

            
325
            let outbound_chan = Arc::new(Mutex::new(None));
326
            let (recognized_tx, recognized_rx) = mpsc::channel();
327
            let chan_provider = Arc::new(DummyChanProvider::new(
328
                rt.clone(),
329
                Arc::clone(&outbound_chan),
330
            ));
331

            
332
            let (reactor, relay_circ) = Reactor::new(
333
                rt.clone(),
334
                &Arc::clone(&inbound_chan.channel),
335
                circid,
336
                unique_id,
337
                circmsg_recv,
338
                Box::new(DummyInboundCrypto {}),
339
                Box::new(DummyOutboundCrypto { recognized_rx }),
340
                &settings,
341
                chan_provider,
342
                padding_ctrl,
343
                padding_stream,
344
                &CircuitAccount::new_noop(),
345
            )
346
            .unwrap();
347

            
348
            rt.spawn(async {
349
                let _ = reactor.run().await;
350
            })
351
            .unwrap();
352

            
353
            Self {
354
                relay_circ,
355
                circmsg_send,
356
                recognized_tx,
357
                inbound_chan,
358
                outbound_chan,
359
            }
360
        }
361

            
362
        /// Simulate the sending of a forward relay message through our relay.
363
        async fn send_fwd(
364
            &mut self,
365
            id: Option<StreamId>,
366
            msg: relaymsg::AnyRelayMsg,
367
            recognized: Recognized,
368
            early: bool,
369
        ) {
370
            // This a bit janky, but for each forward cell we send to the reactor
371
            // we need to send a bit of metadata to the DummyOutboundLayer
372
            // specifying whether the cell should be treated as recognized
373
            // or unrecognized
374
            self.recognized_tx.send(recognized).unwrap();
375
            self.circmsg_send
376
                .send(rmsg_to_ccmsg(id, msg, early))
377
                .await
378
                .unwrap();
379
        }
380

            
381
        /// Whether the reactor opened an outbound channel
382
        /// (i.e. a channel to the next relay in the circuit).
383
        fn outbound_chan_launched(&self) -> bool {
384
            self.outbound_chan.lock().unwrap().is_some()
385
        }
386

            
387
        /// Allow inbound stream requests.
388
        ///
389
        /// Used for testing leaky pipe and exit functionality.
390
        async fn allow_stream_requests<'a, FILT>(
391
            &self,
392
            allow_commands: &'a [RelayCmd],
393
            filter: FILT,
394
        ) -> impl futures::Stream<Item = IncomingStream> + use<'a, FILT>
395
        where
396
            FILT: IncomingStreamRequestFilter,
397
        {
398
            Arc::clone(&self.relay_circ)
399
                .allow_stream_requests(allow_commands, filter)
400
                .await
401
                .unwrap()
402
        }
403

            
404
        /// Perform the CREATE2 handshake.
405
        async fn do_create2_handshake(
406
            &mut self,
407
            rt: &MockRuntime,
408
            expected_hs_type: HandshakeType,
409
        ) {
410
            // First, check that the reactor actually sent a CREATE2 to the next hop...
411
            let (circid, msg) = self.read_outbound().into_circid_and_msg();
412
            let _create2 = match msg {
413
                chanmsg::AnyChanMsg::Create2(c) => {
414
                    assert_eq!(c.handshake_type(), expected_hs_type);
415
                    c
416
                }
417
                _ => panic!("unexpected forwarded {msg:?}"),
418
            };
419

            
420
            let handshake = vec![];
421
            let created2 = chanmsg::Created2::new(handshake);
422
            // ...and then finalize the handshake by pretending to be
423
            // the responding relay
424
            self.write_outbound(circid, chanmsg::AnyChanMsg::Created2(created2));
425
            rt.advance_until_stalled().await;
426
        }
427

            
428
        /// Whether the circuit is closing (e.g. due to a proto violation).
429
        fn is_closing(&self) -> bool {
430
            self.relay_circ.is_closing()
431
        }
432

            
433
        /// Read a cell from the inbound channel
434
        /// (moving towards the client).
435
        ///
436
        /// Panics if there are no ready cells on the inbound MPSC channel.
437
        fn read_inbound(&mut self) -> ChanCell<AnyChanMsg> {
438
            #[allow(deprecated)] // TODO(#2386)
439
            self.inbound_chan.rx.try_next().unwrap().unwrap()
440
        }
441

            
442
        /// Read a cell from the outbound channel
443
        /// (moving towards the next hop).
444
        ///
445
        /// Panics if there are no ready cells on the outbound MPSC channel.
446
        fn read_outbound(&mut self) -> ChanCell<AnyChanMsg> {
447
            let mut lock = self.outbound_chan.lock().unwrap();
448
            let chan = lock.as_mut().unwrap();
449
            #[allow(deprecated)] // TODO(#2386)
450
            chan.rx.try_next().unwrap().unwrap()
451
        }
452

            
453
        /// Write to the sending end of the outbound Tor channel.
454
        ///
455
        /// Simulates the receipt of a cell from the next hop.
456
        ///
457
        /// Panics if the outbound chan sender is full.
458
        fn write_outbound(&mut self, circid: Option<CircId>, msg: chanmsg::AnyChanMsg) {
459
            let mut lock = self.outbound_chan.lock().unwrap();
460
            let chan = lock.as_mut().unwrap();
461
            let cell = ChanCell::new(circid, msg);
462

            
463
            chan.tx.try_send(Ok(cell)).unwrap();
464
        }
465
    }
466

            
467
    fn dummy_linkspecs() -> Vec<EncodedLinkSpec> {
468
        vec![
469
            LinkSpec::Ed25519Id([43; 32].into()).encode().unwrap(),
470
            LinkSpec::RsaId([45; 20].into()).encode().unwrap(),
471
            LinkSpec::OrPort("127.0.0.1".parse::<IpAddr>().unwrap(), 999)
472
                .encode()
473
                .unwrap(),
474
        ]
475
    }
476

            
477
    /// Assert that the relay circuit is shutting down.
478
    ///
479
    /// Also asserts that the next cell on the inbound channel
480
    /// is a DESTROY with the specified `reason`.
481
    /// The test is expected to drain the inbound Tor "channel"
482
    /// of any non-ending cells it might be expecting before calling this function.
483
    fn assert_circuit_destroyed(ctrl: &mut ReactorTestCtrl, reason: DestroyReason) {
484
        assert!(ctrl.is_closing());
485

            
486
        let cell = ctrl.read_inbound();
487

            
488
        match cell.msg() {
489
            chanmsg::AnyChanMsg::Destroy(d) => {
490
                assert_eq!(d.reason(), reason);
491
            }
492
            _ => panic!("unexpected ending {cell:?}"),
493
        }
494
    }
495

            
496
    #[traced_test]
497
    #[test]
498
    fn reject_extend2_relay() {
499
        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
500
            let mut ctrl = ReactorTestCtrl::spawn_reactor(&rt);
501
            rt.advance_until_stalled().await;
502

            
503
            let linkspecs = dummy_linkspecs();
504
            let extend2 = relaymsg::Extend2::new(linkspecs, HandshakeType::NTOR_V3, vec![]).into();
505
            ctrl.send_fwd(None, extend2, Recognized::Yes, false).await;
506
            rt.advance_until_stalled().await;
507

            
508
            assert!(logs_contain("got EXTEND2 in a RELAY cell?!"));
509
            assert!(!ctrl.outbound_chan_launched());
510
            assert_circuit_destroyed(&mut ctrl, DestroyReason::NONE);
511
        });
512
    }
513

            
514
    #[traced_test]
515
    #[test]
516
    fn extend_and_forward() {
517
        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
518
            let mut ctrl = ReactorTestCtrl::spawn_reactor(&rt);
519
            rt.advance_until_stalled().await;
520

            
521
            // No outbound circuits yet
522
            assert!(!ctrl.outbound_chan_launched());
523

            
524
            let linkspecs = dummy_linkspecs();
525
            let handshake_type = HandshakeType::NTOR_V3;
526
            let extend2 = relaymsg::Extend2::new(linkspecs, handshake_type, vec![]).into();
527
            ctrl.send_fwd(None, extend2, Recognized::Yes, true).await;
528
            rt.advance_until_stalled().await;
529

            
530
            // The reactor handled the EXTEND2 and launched an outbound channel
531
            assert!(logs_contain(
532
                "Launched channel to the next hop circ_id=Circ 8.17"
533
            ));
534
            assert!(ctrl.outbound_chan_launched());
535
            assert!(!ctrl.is_closing());
536

            
537
            ctrl.do_create2_handshake(&rt, handshake_type).await;
538
            assert!(logs_contain("Got CREATED2 response from next hop"));
539
            assert!(logs_contain("Extended circuit to the next hop"));
540

            
541
            // Time to forward a message to the next hop!
542
            let early = false;
543
            let begin = relaymsg::Begin::new("127.0.0.1", 1111, 0).unwrap();
544
            ctrl.send_fwd(None, begin.clone().into(), Recognized::No, early)
545
                .await;
546
            rt.advance_until_stalled().await;
547

            
548
            macro_rules! expect_cell {
549
                ($chanmsg:tt, $relaymsg:tt) => {{
550
                    let cell = ctrl.read_outbound();
551
                    let msg = match cell.msg() {
552
                        chanmsg::AnyChanMsg::$chanmsg(m) => {
553
                            let body = m.clone().into_relay_body();
554
                            AnyRelayMsgOuter::decode_singleton(RelayCellFormat::V0, body).unwrap()
555
                        }
556
                        _ => panic!("unexpected forwarded {cell:?}"),
557
                    };
558

            
559
                    match msg.msg() {
560
                        relaymsg::AnyRelayMsg::$relaymsg(m) => m.clone(),
561
                        _ => panic!("unexpected cell {msg:?}"),
562
                    }
563
                }};
564
            }
565

            
566
            // Ensure the other end received the BEGIN cell
567
            let recvd_begin = expect_cell!(Relay, Begin);
568
            assert_eq!(begin, recvd_begin);
569

            
570
            // Now send the same message again, but this time in a RELAY_EARLY
571
            let early = true;
572
            let begin = relaymsg::Begin::new("127.0.0.1", 1111, 0).unwrap();
573
            ctrl.send_fwd(None, begin.clone().into(), Recognized::No, early)
574
                .await;
575
            rt.advance_until_stalled().await;
576
            let recvd_begin = expect_cell!(RelayEarly, Begin);
577
            assert_eq!(begin, recvd_begin);
578
        });
579
    }
580

            
581
    #[traced_test]
582
    #[test]
583
    fn forward_before_extend() {
584
        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
585
            let mut ctrl = ReactorTestCtrl::spawn_reactor(&rt);
586
            rt.advance_until_stalled().await;
587

            
588
            // Send an arbitrary unrecognized cell. The reactor should flag this as
589
            // a protocol violation, because we don't have an outbound channel to forward it on.
590
            let extend2 = relaymsg::End::new_misc().into();
591
            ctrl.send_fwd(None, extend2, Recognized::No, true).await;
592
            rt.advance_until_stalled().await;
593

            
594
            // The reactor handled the EXTEND2 and launched an outbound channel
595
            assert!(logs_contain(
596
                "Asked to forward cell before the circuit was extended?!"
597
            ));
598
            assert_circuit_destroyed(&mut ctrl, DestroyReason::NONE);
599
        });
600
    }
601

            
602
    #[traced_test]
603
    #[test]
604
    fn reject_invalid_begin() {
605
        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
606
            let mut ctrl = ReactorTestCtrl::spawn_reactor(&rt);
607
            rt.advance_until_stalled().await;
608

            
609
            let _streams = ctrl
610
                .allow_stream_requests(&[RelayCmd::BEGIN], AllowAllStreamsFilter)
611
                .await;
612

            
613
            let begin = relaymsg::Begin::new("127.0.0.1", 1111, 0).unwrap().into();
614

            
615
            // BEGIN cells *must* have a stream ID, so expect the reactor to reject this
616
            // and close the circuit
617
            ctrl.send_fwd(None, begin, Recognized::Yes, false).await;
618
            rt.advance_until_stalled().await;
619

            
620
            assert!(logs_contain(
621
                "Invalid stream ID [scrubbed] for relay command BEGIN"
622
            ));
623
            assert_circuit_destroyed(&mut ctrl, DestroyReason::NONE);
624
        });
625
    }
626

            
627
    #[traced_test]
628
    #[test]
629
    #[ignore] // TODO(relay): Sad trombone, this is not yet supported
630
    fn data_stream() {
631
        tor_rtmock::MockRuntime::test_with_various(|rt| async move {
632
            const TO_SEND: &[u8] = b"The bells were musical in the silvery sun";
633

            
634
            let mut ctrl = ReactorTestCtrl::spawn_reactor(&rt);
635
            rt.advance_until_stalled().await;
636

            
637
            let mut incoming_streams = ctrl
638
                .allow_stream_requests(&[RelayCmd::BEGIN], AllowAllStreamsFilter)
639
                .await;
640

            
641
            let begin = relaymsg::Begin::new("127.0.0.1", 1111, 0).unwrap().into();
642
            ctrl.send_fwd(StreamId::new(1), begin, Recognized::Yes, false)
643
                .await;
644
            rt.advance_until_stalled().await;
645

            
646
            let data = relaymsg::Data::new(TO_SEND).unwrap().into();
647
            ctrl.send_fwd(StreamId::new(1), data, Recognized::Yes, false)
648
                .await;
649

            
650
            // We should have a pending incoming stream
651
            let pending = incoming_streams.next().await.unwrap();
652

            
653
            // Accept it, and let's see what we have!
654
            let mut stream = pending
655
                .accept_data(relaymsg::Connected::new_empty())
656
                .await
657
                .unwrap();
658

            
659
            let mut recv_buf = [0_u8; TO_SEND.len()];
660
            stream.read_exact(&mut recv_buf).await.unwrap();
661
            assert_eq!(recv_buf, TO_SEND);
662
        });
663
    }
664
}