1
//! Module exposing the circuit reactor subsystem.
2
//!
3
//! This module implements the new [multi-reactor circuit subsystem].
4
//!
5
// Note: this is currently only used for the relay side,
6
// but we plan to eventually rewrite client circuit implementation
7
// to use these new reactor types as well.
8
//!
9
//! The entry point of the reactor is [`Reactor::run`], which launches the
10
//! reactor background tasks, and begins listening for inbound cells on the provided
11
//! inbound Tor channel.
12
//!
13
//! ### Architecture
14
//!
15
//! Internally, the circuit reactor consists of multiple reactors,
16
//! each running in a separate task:
17
//!
18
//!   * [`StreamReactor`] (one per hop): handles all messages arriving to,
19
//!     and coming from the streams of a given hop. The ready stream messages
20
//!     are sent to the [`BackwardReactor`]
21
//!   * [`ForwardReactor`]: handles incoming cells arriving on the
22
//!     "inbound" Tor channel (towards the guard, if we are a client, or towards
23
//!     the client, if we are a relay). If we are a client, it moves stream messages
24
//!     towards the corresponding [`StreamReactor`]. If we are a relay,
25
//!     in addition to sending any stream messages to the `StreamReactor`,
26
//!     this reactor also moves cells in the forward direction
27
//!     (from the client towards the exit)
28
//!   * [`BackwardReactor`]: writes cells to the "inbound" Tor channel:
29
//!     towards the client if we are a relay, or the towards the exit
30
//!     if we are a client.
31
//!
32
// TODO: the forward/backward terminology no longer makes sense! Come up with better terms...
33
//!
34
//! If we are an exit relay, the cell flow looks roughly like this:
35
//!
36
//! ```text
37
//!                             <stream_tx
38
//!                              MPSC (0)>
39
//!   +--------------> FWD -------------------------+
40
//!   |                 |                           |
41
//!   |                 |                           |
42
//!   |                 |                           |
43
//!   |                 |                           v
44
//! relay      BackwardReactorCmd            StreamReactor
45
//!   ^             <MPSC (0)>                      |
46
//!   |                 |                           |
47
//!   |                 |                           |
48
//!   |                 |                           |
49
//!   |                 v                           |
50
//!   +--------------- BWD <------------------------+
51
//!     application stream data    <stream_rx
52
//!                                 MPSC (0)>
53
//!
54
//! For a middle relay (the `StreamReactor` is omitted for brevity,
55
//! but middle relays can have one too, if leaky pipe is in use):
56
//!
57
//! ```text                   unrecognized cell
58
//!   +--------------> FWD -------------------------+
59
//!   |                 |                           |
60
//!   |                 |                           |
61
//!   |                 |                           |
62
//!   |                 |                           v
63
//! client      BackwardReactorCmd                relay
64
//! or relay        <MPSC (0)>                      |
65
//!   ^                 |                           |
66
//!   |                 |                           |
67
//!   |                 |                           |
68
//!   |                 |                           |
69
//!   |                 v                           |
70
//!   +--------------- BWD <------------------------+
71
//! ```
72
//!
73
//! On the client-side the `ForwardReactor` reads cells from the Tor channel to the guard,
74
//! and the `BackwardReactor` writes to it.
75
//!
76
//! ```text
77
//!   +--------------- FWD <--------------------+
78
//!   |                 |                       |
79
//!   |                 |                       |
80
//!   |                 |                       |
81
//!   v                 |                       |
82
//! StreamReactor  BackwardReactorCmd         guard
83
//!   |               <MPSC (0)>                ^
84
//!   |                 |                       |
85
//!   |                 |                       |
86
//!   |                 |                       |
87
//!   |                 v                       |
88
//!   +--------------> BWD ---------------------+
89
//! ```
90
//!
91
//! Client with leaky pipe (`SR` = `StreamReactor`):
92
//!
93
//! ```text
94
//!   +------------------------------+
95
//!   |       +--------------------+ | (1 MPSC TX per SR)
96
//!   |       |                    | |
97
//!   |       |       +----------- FWD <------------------+
98
//!   |       |       |             |                     |
99
//!   |       |       |             |                     |
100
//!   |       |       |             |                     |
101
//!   v       v       v             |                     |
102
//!  SR      SR      SR           BackwardReactorCmd    guard
103
//! (hop 4) (hop 3)  (hop 2)      <MPSC (0)>              ^
104
//!   |       |       |             |                     |
105
//!   |       |       |             |                     |
106
//!   |       |       |             |                     |
107
//!   |       |       |             v                     |
108
//!   |       |       |            BWD -------------------+
109
//!   |       |       |             ^
110
//!   |       |       |             |
111
//!   |       |       |             | <stream_rx
112
//!   |       |       |             |  MPSC (0)>
113
//!   +-------+-------+-------------+
114
//! ```
115
//!
116
// TODO(tuning): The inter-reactor MPSC channels have no buffering,
117
// which is likely going to be bad for performance,
118
// so we will need to tune the sizes of these MPSC buffers.
119
//!
120
//! The read and write ends of the inbound and outbound Tor channels are "split",
121
//! such that each reactor holds an `inbound_chan_rx` stream (for reading)
122
//! and a `inbound_chan_tx` sink (for writing):
123
//!
124
//!  * `ForwardReactor` holds the reading end of the inbound
125
//!    (coming from the client, if we are a relay, or coming from the guard, if we are a client)
126
//!    Tor channel, and the writing end of the outbound (towards the exit, if we are a middle relay)
127
//!    Tor channel, if there is one
128
//!  * `BackwardReactor` holds the reading end of the outbound channel, if there is one,
129
//!    and the writing end of the inbound channel, if there is one
130
//!
131
//! #### `ForwardReactor`
132
//!
133
//! It handles forward cells, by delegating to the implementation-dependent
134
//! [`ForwardHandler::handle_forward_cell`], which decides
135
//! whether the cell needs to be handled in `ForwardReactor`,
136
//! or in the `ForwardHandler` itself.
137
//!
138
//! More concretely:
139
//!
140
//! ```text
141
//!
142
//! Legend: `F` = "forward reactor", `H` = "ForwardHandler"
143
//!
144
//! | Message           | Received in | Handled in | Description                            |
145
//! |-------------------|-------------|------------|----------------------------------------|
146
//! | DESTROY           | F           | H          | Handled internally by the FowardHandler|
147
//! |-------------------|-------------|------------|----------------------------------------|
148
//! | PADDING_NEGOTIATE | F           | H          | Handled internally by the FowardHandler|
149
//! |-------------------|-------------|------------|----------------------------------------|
150
//! | *unrecognized*    | F           | H          | Unrecognized relay cell handling is    |
151
//! | RELAY OR          |             |            | implementation-dependent so these are  |
152
//! | RELAY_EARLY       |             |            | handled in the ForwardHandler.         |
153
//! |                   |             |            |                                        |
154
//! |                   |             |            | The relay ForwardHandler will handle   |
155
//! |                   |             |            | these by forwarding them to the next   |
156
//! |                   |             |            | hop, if there is one.                  |
157
//! |                   |             |            |                                        |
158
//! |                   |             |            | Clients don't yet implement            |
159
//! |                   |             |            | ForwardHandler, but when they do,      |
160
//! |                   |             |            | its implementation will simply reject  |
161
//! |                   |             |            | any messages that can't be decrypted   |
162
//! |-------------------|-------------|------------|----------------------------------------|
163
//! | *recognized*      | F           | see table  | Handling depends on the cmd            |
164
//! | RELAY OR          |             | below      |                                        |
165
//! | RELAY_EARLY       |             |            |                                        |
166
//! ```
167
//!
168
//! Recognized relay cells are handled by splitting each cell into individual messages,
169
//! and handling each message individually as described in the table below
170
//! (Note: since prop340 is not yet implemented, in practice there is only 1 message per cell):
171
//!
172
//! ```text
173
//!
174
//! Legend: `F` = "forward reactor", `B` = "backward reactor", `S` = "stream reactor"
175
//!
176
//! | RELAY cmd         | Received in | Handled in | Description                            |
177
//! |-------------------|-------------|------------|----------------------------------------|
178
//! | SENDME            | F           | B          | Sent to BackwardReactor for handling   |
179
//! |                   |             |            | (BackwardReactorCmd::HandleSendme)     |
180
//! |                   |             |            | because the forward reactor doesn't    |
181
//! |                   |             |            | have access to the inbound_chan_tx part|
182
//! |                   |             |            | of the inbound (towards the client)    |
183
//! |                   |             |            | Tor channel, and so cannot obtain the  |
184
//! |                   |             |            | congestion signals needed for SENDME   |
185
//! |                   |             |            | handling                               |
186
//! |-------------------|-------------|------------|----------------------------------------|
187
//! | Other             | F           | F          | Passed to impl-dependent handler       |
188
//! | (StreamId = 0)    |             |            |  `ForwardHandler::handle_meta_msg()`   |
189
//! |-------------------|-------------|------------|----------------------------------------|
190
//! | Other             | F           | S          | All messages with a non-zero stream ID |
191
//! | (StreamId != 0)   |             |            | are forwarded to the stream reactor    |
192
//! |-------------------|-------------|------------|----------------------------------------|
193
//! ```
194
//!
195
//! #### `BackwardReactor`
196
//!
197
//! It handles
198
//!
199
//!  * the packaging and delivery of all cells that need to be written to the "inbound" Tor channel
200
//!    (it writes them to the towards-the-client Tor channel sink) (**partially implemented**)
201
//!  * incoming cells coming over the "outbound" Tor channel. This channel only exists
202
//!    if we are a middle relay. These cells are relayed to the "inbound" Tor channel (**not implemented**).
203
//!  * the sending of padding cells, according to the PaddingController's instructions
204
//!
205
//! This multi-reactor architecture should, in theory, have better performance than
206
//! a single reactor system, because it enables us to parallelize some of the work:
207
//! the forward and backward directions share little state,
208
//! because they read from, and write to, different sinks/streams,
209
//! so they can be run in parallel (as separate tasks).
210
//! With a single reactor architecture, the reactor would need to drive
211
//! both the forward and the backward direction, and on each iteration
212
//! would need to decide which to prioritize, which might prove tricky
213
//! (though prioritizing one of them at random would've probably been good enough).
214
//!
215
//! The monolithic single reactor alternative would also have been significantly
216
//! more convoluted, and so more difficult to maintain in the long run.
217
//!
218
//
219
// NOTE: The FWD and BWD currently share the hop list containing the per-hop state,
220
// (including the congestion control object, which is behind a mutex).
221
//
222
//! [multi-reactor circuit subsystem]: https://gitlab.torproject.org/tpo/core/arti/-/blob/main/doc/dev/notes/relay-conflux.md
223
//! [`StreamReactor`]: stream::StreamReactor
224

            
225
// TODO(DEDUP): this will replace CircHopList when we rewrite the client reactor
226
// to use the new reactor architecture
227
pub(crate) mod circhop;
228

            
229
pub(crate) mod backward;
230
pub(crate) mod forward;
231
pub(crate) mod hop_mgr;
232
pub(crate) mod macros;
233
pub(crate) mod stream;
234

            
235
use std::result::Result as StdResult;
236
use std::sync::Arc;
237

            
238
use derive_deftly::Deftly;
239
use futures::channel::mpsc;
240
use futures::{FutureExt as _, StreamExt as _, select_biased};
241
use oneshot_fused_workaround as oneshot;
242
use tracing::trace;
243

            
244
use tor_cell::chancell::CircId;
245
use tor_rtcompat::{DynTimeProvider, Runtime};
246

            
247
use crate::channel::Channel;
248
use crate::circuit::reactor::backward::BackwardHandler;
249
use crate::circuit::reactor::forward::ForwardHandler;
250
use crate::circuit::reactor::hop_mgr::HopMgr;
251
use crate::circuit::reactor::stream::ReadyStreamMsg;
252
use crate::circuit::{CircuitRxReceiver, UniqId};
253
use crate::memquota::CircuitAccount;
254
use crate::util::err::ReactorError;
255

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

            
259
use backward::BackwardReactor;
260
use forward::ForwardReactor;
261
use macros::derive_deftly_template_CircuitReactor;
262

            
263
/// The type of a oneshot channel used to inform reactor of the result of an operation.
264
pub(crate) type ReactorResultChannel<T> = oneshot::Sender<crate::Result<T>>;
265

            
266
/// A handle for interacting with a circuit reactor.
267
#[derive(derive_more::Debug)]
268
pub(crate) struct CircReactorHandle<F: ForwardHandler, B: BackwardHandler> {
269
    /// Sender for reactor control messages.
270
    #[debug(skip)]
271
    pub(crate) control: mpsc::UnboundedSender<CtrlMsg<F::CtrlMsg, B::CtrlMsg>>,
272
    /// Sender for reactor control commands.
273
    #[debug(skip)]
274
    pub(crate) command: mpsc::UnboundedSender<CtrlCmd<F::CtrlCmd, B::CtrlCmd>>,
275
    /// The time provider.
276
    #[allow(unused)] // TODO(relay)
277
    pub(crate) time_provider: DynTimeProvider,
278
    /// Memory quota account
279
    #[allow(unused)] // TODO(relay)
280
    pub(crate) memquota: CircuitAccount,
281
}
282

            
283
/// A control command.
284
///
285
/// The difference between this and [`CtrlMsg`] is that `CtrlCmd`s
286
/// never cause cells to be sent on the Tor channel,
287
/// while `CtrlMsg`s potentially do.
288
#[allow(unused)] // TODO(relay)
289
pub(crate) enum CtrlCmd<F, B> {
290
    /// A control command for the forward reactor.
291
    Forward(forward::CtrlCmd<F>),
292
    /// A control command for the backward reactor.
293
    Backward(backward::CtrlCmd<B>),
294
    /// Shut down the reactor.
295
    Shutdown,
296
}
297

            
298
/// A control message.
299
#[allow(unused)] // TODO(relay)
300
#[derive(derive_more::From)]
301
pub(crate) enum CtrlMsg<F, B> {
302
    /// A control message for the forward reactor.
303
    Forward(forward::CtrlMsg<F>),
304
    /// A control message for the backward reactor.
305
    Backward(backward::CtrlMsg<B>),
306
}
307

            
308
/// The entry point of the circuit reactor subsystem.
309
#[derive(Deftly)]
310
#[derive_deftly(CircuitReactor)]
311
#[deftly(reactor_name = "circuit reactor")]
312
#[deftly(only_run_once)]
313
#[deftly(run_inner_fn = "Self::run_inner")]
314
#[must_use = "If you don't call run() on a reactor, the circuit won't work."]
315
pub(crate) struct Reactor<R: Runtime, F: ForwardHandler, B: BackwardHandler> {
316
    /// The process-unique identifier of this circuit.
317
    ///
318
    /// Used for logging.
319
    unique_id: UniqId,
320
    /// The circuit identifier on the inbound Tor channel.
321
    circ_id: CircId,
322
    /// The reactor for handling
323
    ///
324
    ///   * cells moving in the forward direction (from the client towards exit), if we are a relay
325
    ///   * incoming cells (coming from the guard), if we are a client
326
    ///
327
    /// Optional so we can move it out of self in run().
328
    forward: Option<ForwardReactor<R, F>>,
329
    /// The reactor for handling
330
    ///
331
    ///   * cells moving in the backward direction (from the exit towards client), if we are a relay
332
    ///   * outgoing cells (moving towards the guard), if we are a client
333
    ///
334
    /// Optional so we can move it out of self in run().
335
    backward: Option<BackwardReactor<B>>,
336
    /// Receiver for control messages for this reactor, sent by reactor handle objects.
337
    control: mpsc::UnboundedReceiver<CtrlMsg<F::CtrlMsg, B::CtrlMsg>>,
338
    /// Receiver for command messages for this reactor, sent by reactor handle objects.
339
    ///
340
    /// This MPSC channel is polled in [`run`](Self::run).
341
    ///
342
    /// NOTE: this is a separate channel from `control`, because some messages
343
    /// have higher priority and need to be handled even if the `inbound_chan_tx` is not
344
    /// ready (whereas `control` messages are not read until the `inbound_chan_tx` sink
345
    /// is ready to accept cells).
346
    command: mpsc::UnboundedReceiver<CtrlCmd<F::CtrlCmd, B::CtrlCmd>>,
347
    /// Control channels for the [`ForwardReactor`].
348
    ///
349
    /// Handles [`CtrlCmd::Forward`] and [`CtrlMsg::Forward`] messages.
350
    fwd_ctrl: ReactorCtrl<forward::CtrlCmd<F::CtrlCmd>, forward::CtrlMsg<F::CtrlMsg>>,
351
    /// Control channels for the [`BackwardReactor`].
352
    ///
353
    /// Handles [`CtrlCmd::Backward`] and [`CtrlMsg::Backward`] messages.
354
    bwd_ctrl: ReactorCtrl<backward::CtrlCmd<B::CtrlCmd>, backward::CtrlMsg<B::CtrlMsg>>,
355
}
356

            
357
/// A handle for sending control/command messages to a FWD or BWD.
358
struct ReactorCtrl<C, M> {
359
    /// Sender for control commands.
360
    command_tx: mpsc::UnboundedSender<C>,
361
    /// Sender for control messages.
362
    control_tx: mpsc::UnboundedSender<M>,
363
}
364

            
365
impl<C, M> ReactorCtrl<C, M> {
366
    /// Create a new sender handle.
367
64
    fn new(command_tx: mpsc::UnboundedSender<C>, control_tx: mpsc::UnboundedSender<M>) -> Self {
368
64
        Self {
369
64
            command_tx,
370
64
            control_tx,
371
64
        }
372
64
    }
373

            
374
    /// Send a control command.
375
4
    fn send_cmd(&mut self, cmd: C) -> Result<(), ReactorError> {
376
4
        self.command_tx
377
4
            .unbounded_send(cmd)
378
4
            .map_err(|_| ReactorError::Shutdown)
379
4
    }
380

            
381
    /// Send a control message.
382
    fn send_msg(&mut self, msg: M) -> Result<(), ReactorError> {
383
        self.control_tx
384
            .unbounded_send(msg)
385
            .map_err(|_| ReactorError::Shutdown)
386
    }
387
}
388

            
389
/// Trait implemented by types that can handle control messages and commands.
390
pub(crate) trait ControlHandler {
391
    /// The type of control message expected by the forward reactor.
392
    type CtrlMsg;
393

            
394
    /// The type of control command expected by the forward reactor.
395
    type CtrlCmd;
396

            
397
    // TODO(DEDUP): do these APIs make sense?
398
    // What should we return here, maybe some instructions for the base reactor
399
    // to do something?
400

            
401
    /// Handle a control command.
402
    fn handle_cmd(&mut self, cmd: Self::CtrlCmd) -> StdResult<(), ReactorError>;
403

            
404
    /// Handle a control message.
405
    fn handle_msg(&mut self, msg: Self::CtrlMsg) -> StdResult<(), ReactorError>;
406
}
407

            
408
#[allow(unused)] // TODO(relay)
409
impl<R: Runtime, F: ForwardHandler + ControlHandler, B: BackwardHandler + ControlHandler>
410
    Reactor<R, F, B>
411
{
412
    /// Create a new circuit reactor.
413
    ///
414
    /// The reactor will send outbound messages on `channel`, receive incoming
415
    /// messages on `inbound_chan_rx`, and identify this circuit by the channel-local
416
    /// [`CircId`] provided.
417
    ///
418
    /// The internal unique identifier for this circuit will be `unique_id`.
419
    #[allow(clippy::too_many_arguments)] // TODO
420
32
    pub(crate) fn new(
421
32
        runtime: R,
422
32
        channel: &Arc<Channel>,
423
32
        circ_id: CircId,
424
32
        unique_id: UniqId,
425
32
        inbound_chan_rx: CircuitRxReceiver,
426
32
        forward_impl: F,
427
32
        backward_impl: B,
428
32
        hop_mgr: HopMgr<R>,
429
32
        padding_ctrl: PaddingController,
430
32
        padding_event_stream: PaddingEventStream,
431
32
        // The sending end of this channel should be in HopMgr
432
32
        bwd_rx: mpsc::Receiver<ReadyStreamMsg>,
433
32
        fwd_events: mpsc::Receiver<F::CircEvent>,
434
32
        memquota: &CircuitAccount,
435
32
    ) -> (Self, CircReactorHandle<F, B>) {
436
        // NOTE: not registering this channel with the memquota subsystem is okay,
437
        // because it has no buffering (if ever decide to make the size of this buffer
438
        // non-zero for whatever reason, we must remember to register it with memquota
439
        // so that it counts towards the total memory usage for the circuit.
440
        #[allow(clippy::disallowed_methods)]
441
32
        let (backward_reactor_tx, forward_reactor_rx) = mpsc::channel(0);
442

            
443
        // TODO: channels galore
444
32
        let (control_tx, control_rx) = mpsc::unbounded();
445
32
        let (command_tx, command_rx) = mpsc::unbounded();
446

            
447
32
        let (fwd_control_tx, fwd_control_rx) = mpsc::unbounded();
448
32
        let (fwd_command_tx, fwd_command_rx) = mpsc::unbounded();
449
32
        let (bwd_control_tx, bwd_control_rx) = mpsc::unbounded();
450
32
        let (bwd_command_tx, bwd_command_rx) = mpsc::unbounded();
451

            
452
32
        let fwd_ctrl = ReactorCtrl::new(fwd_command_tx, fwd_control_tx);
453
32
        let bwd_ctrl = ReactorCtrl::new(bwd_command_tx, bwd_control_tx);
454

            
455
32
        let handle = CircReactorHandle {
456
32
            control: control_tx,
457
32
            command: command_tx,
458
32
            time_provider: DynTimeProvider::new(runtime.clone()),
459
32
            memquota: memquota.clone(),
460
32
        };
461

            
462
        /// Grab a handle to the hop list (it's needed by the BWD)
463
32
        let hops = Arc::clone(hop_mgr.hops());
464
32
        let forward = ForwardReactor::new(
465
32
            runtime.clone(),
466
32
            unique_id,
467
32
            circ_id,
468
32
            forward_impl,
469
32
            hop_mgr,
470
32
            inbound_chan_rx,
471
32
            fwd_control_rx,
472
32
            fwd_command_rx,
473
32
            backward_reactor_tx,
474
32
            fwd_events,
475
32
            padding_ctrl.clone(),
476
        );
477

            
478
32
        let backward = BackwardReactor::new(
479
32
            runtime,
480
32
            channel,
481
32
            circ_id,
482
32
            unique_id,
483
32
            backward_impl,
484
32
            hops,
485
32
            forward_reactor_rx,
486
32
            bwd_control_rx,
487
32
            bwd_command_rx,
488
32
            padding_ctrl,
489
32
            padding_event_stream,
490
32
            bwd_rx,
491
        );
492

            
493
32
        let reactor = Reactor {
494
32
            unique_id,
495
32
            circ_id,
496
32
            forward: Some(forward),
497
32
            backward: Some(backward),
498
32
            control: control_rx,
499
32
            command: command_rx,
500
32
            fwd_ctrl,
501
32
            bwd_ctrl,
502
32
        };
503

            
504
32
        (reactor, handle)
505
32
    }
506

            
507
    /// Helper for [`run`](Self::run).
508
32
    pub(crate) async fn run_inner(&mut self) -> StdResult<(), ReactorError> {
509
32
        let (forward, backward) = (|| Some((self.forward.take()?, self.backward.take()?)))()
510
32
            .expect("relay reactor spawned twice?!");
511

            
512
32
        let mut forward = Box::pin(forward.run()).fuse();
513
32
        let mut backward = Box::pin(backward.run()).fuse();
514
        loop {
515
            // If either of these completes, this function returns,
516
            // dropping fwd_ctrl/bwd_ctrl channels, which will, in turn,
517
            // cause the remaining reactor, if there is one, to shut down too
518
36
            select_biased! {
519
36
                res = self.command.next() => {
520
18
                    let Some(cmd) = res else {
521
14
                        trace!(
522
                            circ_uniq_id = %self.unique_id,
523
                            backward_circ_id = %self.circ_id,
524
                            reason = "command channel drop",
525
                            "reactor shutdown",
526
                        );
527

            
528
14
                        return Err(ReactorError::Shutdown);
529
                    };
530

            
531
4
                    self.handle_command(cmd)?;
532
                },
533
36
                res = self.control.next() => {
534
                    let Some(msg) = res else {
535
                        trace!(
536
                            circ_uniq_id = %self.unique_id,
537
                            backward_circ_id = %self.circ_id,
538
                            reason = "control channel drop",
539
                            "reactor shutdown",
540
                        );
541

            
542
                        return Err(ReactorError::Shutdown);
543
                    };
544

            
545
                    self.handle_control(msg)?;
546
                },
547
                // No need to log the error here, because it was already logged
548
                // by the reactor that shut down
549
16
                res = forward => return Ok(res?),
550
2
                res = backward => return Ok(res?),
551
            }
552
        }
553
32
    }
554

            
555
    /// Handle a shutdown request.
556
    fn handle_shutdown(&self) -> StdResult<(), ReactorError> {
557
        trace!(
558
            tunnel_id = %self.unique_id,
559
            "reactor shutdown due to explicit request",
560
        );
561

            
562
        Err(ReactorError::Shutdown)
563
    }
564

            
565
    /// Handle a [`CtrlCmd`].
566
4
    fn handle_command(
567
4
        &mut self,
568
4
        cmd: CtrlCmd<F::CtrlCmd, B::CtrlCmd>,
569
4
    ) -> StdResult<(), ReactorError> {
570
4
        match cmd {
571
4
            CtrlCmd::Forward(c) => self.fwd_ctrl.send_cmd(c),
572
            CtrlCmd::Backward(c) => self.bwd_ctrl.send_cmd(c),
573
            CtrlCmd::Shutdown => self.handle_shutdown(),
574
        }
575
4
    }
576

            
577
    /// Handle a [`CtrlMsg`].
578
    fn handle_control(
579
        &mut self,
580
        cmd: CtrlMsg<F::CtrlMsg, B::CtrlMsg>,
581
    ) -> StdResult<(), ReactorError> {
582
        match cmd {
583
            CtrlMsg::Forward(c) => self.fwd_ctrl.send_msg(c),
584
            CtrlMsg::Backward(c) => self.bwd_ctrl.send_msg(c),
585
        }
586
    }
587
}
588

            
589
#[cfg(test)]
590
pub(crate) mod test {
591
    // @@ begin test lint list maintained by maint/add_warning @@
592
    #![allow(clippy::bool_assert_comparison)]
593
    #![allow(clippy::clone_on_copy)]
594
    #![allow(clippy::dbg_macro)]
595
    #![allow(clippy::mixed_attributes_style)]
596
    #![allow(clippy::print_stderr)]
597
    #![allow(clippy::print_stdout)]
598
    #![allow(clippy::single_char_pattern)]
599
    #![allow(clippy::unwrap_used)]
600
    #![allow(clippy::unchecked_time_subtraction)]
601
    #![allow(clippy::useless_vec)]
602
    #![allow(clippy::needless_pass_by_value)]
603
    #![allow(clippy::string_slice)] // See arti#2571
604
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
605

            
606
    use tor_basic_utils::test_rng::testing_rng;
607
    use tor_cell::chancell::{BoxedCellBody, msg as chanmsg};
608
    use tor_cell::relaycell::{AnyRelayMsgOuter, RelayCellFormat, StreamId, msg as relaymsg};
609

            
610
    use chanmsg::AnyChanMsg;
611

            
612
    #[cfg(any(feature = "hs-service", feature = "relay"))]
613
    use crate::stream::IncomingStreamRequestFilter;
614

            
615
    pub(crate) fn rmsg_to_ccmsg(
616
        id: Option<StreamId>,
617
        msg: relaymsg::AnyRelayMsg,
618
        early: bool,
619
    ) -> AnyChanMsg {
620
        // TODO #1947: test other formats.
621
        let rfmt = RelayCellFormat::V0;
622
        let body: BoxedCellBody = AnyRelayMsgOuter::new(id, msg)
623
            .encode(rfmt, &mut testing_rng())
624
            .unwrap();
625
        let chanmsg = chanmsg::Relay::from(body);
626

            
627
        if early {
628
            let chanmsg = chanmsg::RelayEarly::from(chanmsg);
629
            AnyChanMsg::RelayEarly(chanmsg)
630
        } else {
631
            AnyChanMsg::Relay(chanmsg)
632
        }
633
    }
634

            
635
    #[cfg(any(feature = "hs-service", feature = "relay"))]
636
    pub(crate) struct AllowAllStreamsFilter;
637
    #[cfg(any(feature = "hs-service", feature = "relay"))]
638
    impl IncomingStreamRequestFilter for AllowAllStreamsFilter {
639
        fn disposition(
640
            &mut self,
641
            _ctx: &crate::stream::IncomingStreamRequestContext<'_>,
642
            _circ: &crate::circuit::CircHopSyncView<'_>,
643
        ) -> crate::Result<crate::stream::IncomingStreamRequestDisposition> {
644
            Ok(crate::stream::IncomingStreamRequestDisposition::Accept)
645
        }
646
    }
647
}