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

            
227
pub(crate) mod circ_state;
228
pub(crate) mod decrypt;
229
pub(crate) mod encrypt;
230
pub(crate) mod macros;
231
pub(crate) mod stream;
232

            
233
use std::result::Result as StdResult;
234
use std::sync::Arc;
235

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

            
242
use tor_cell::chancell::CircId;
243
use tor_rtcompat::{DynTimeProvider, Runtime};
244

            
245
use crate::channel::Channel;
246
use crate::circuit::metrics::CircuitMetrics;
247
use crate::circuit::reactor::circ_state::CircuitState;
248
use crate::circuit::reactor::decrypt::DecryptingReactorInner;
249
use crate::circuit::reactor::encrypt::EncryptingReactorInner;
250
use crate::circuit::reactor::stream::ReadyStreamMsg;
251
use crate::circuit::{CircuitRxReceiver, UniqId};
252
use crate::memquota::CircuitAccount;
253
use crate::util::err::ReactorError;
254

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

            
258
use decrypt::DecryptingReactor;
259
use encrypt::EncryptingReactor;
260
use macros::derive_deftly_template_CircuitReactor;
261

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

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

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

            
297
/// A control message.
298
#[allow(unused)] // TODO(relay)
299
#[derive(derive_more::From)]
300
pub(crate) enum CtrlMsg<D, E> {
301
    /// A control message for the decrypting reactor.
302
    Decrypting(decrypt::CtrlMsg<D>),
303
    /// A control message for the encrypting reactor.
304
    Encrypting(encrypt::CtrlMsg<E>),
305
}
306

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

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

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

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

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

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

            
395
    /// The type of control command expected by the decrypting reactor.
396
    type CtrlCmd;
397

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

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

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

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

            
449
        // TODO: channels galore
450
32
        let (control_tx, control_rx) = mpsc::unbounded();
451
32
        let (command_tx, command_rx) = mpsc::unbounded();
452

            
453
32
        let (dec_control_tx, dec_control_rx) = mpsc::unbounded();
454
32
        let (dec_command_tx, dec_command_rx) = mpsc::unbounded();
455
32
        let (enc_control_tx, enc_control_rx) = mpsc::unbounded();
456
32
        let (enc_command_tx, enc_command_rx) = mpsc::unbounded();
457

            
458
32
        let dec_ctrl = ReactorCtrl::new(dec_command_tx, dec_control_tx);
459
32
        let enc_ctrl = ReactorCtrl::new(enc_command_tx, enc_control_tx);
460

            
461
32
        let handle = CircReactorHandle {
462
32
            control: control_tx,
463
32
            command: command_tx,
464
32
            time_provider: DynTimeProvider::new(runtime.clone()),
465
32
            memquota: memquota.clone(),
466
32
        };
467

            
468
        // Grab a handle to the shared part of the circuit state
469
        // (it's needed by the ENC)
470
32
        let shared = Arc::clone(circ_state.shared());
471
32
        let forward = DecryptingReactor::new(
472
32
            runtime.clone(),
473
32
            unique_id,
474
32
            circ_id,
475
32
            forward_impl,
476
32
            circ_state,
477
32
            inbound_chan_rx,
478
32
            dec_control_rx,
479
32
            dec_command_rx,
480
32
            encrypting_reactor_tx,
481
32
            dec_events,
482
32
            dec_events_tx,
483
32
            padding_ctrl.clone(),
484
32
            Arc::clone(&metrics),
485
32
        );
486

            
487
32
        let backward = EncryptingReactor::new(
488
32
            runtime,
489
32
            channel,
490
32
            circ_id,
491
32
            unique_id,
492
32
            backward_impl,
493
32
            shared,
494
32
            decrypting_reactor_rx,
495
32
            enc_control_rx,
496
32
            enc_command_rx,
497
32
            padding_ctrl,
498
32
            padding_event_stream,
499
32
            enc_rx,
500
32
            Arc::clone(&metrics),
501
32
        );
502

            
503
32
        let reactor = Reactor {
504
32
            unique_id,
505
32
            circ_id,
506
32
            forward: Some(forward),
507
32
            backward: Some(backward),
508
32
            control: control_rx,
509
32
            command: command_rx,
510
32
            dec_ctrl,
511
32
            enc_ctrl,
512
32
            metrics,
513
32
        };
514

            
515
32
        (reactor, handle)
516
32
    }
517

            
518
    /// Helper for [`run`](Self::run).
519
32
    pub(crate) async fn run_inner(&mut self) -> StdResult<(), ReactorError> {
520
        // This guard can be dropped if the task panics or if this future is cancelled,
521
        // in which case the close reason will be recorded as "Unknown".
522
32
        let guard = self.metrics.circuit_opened();
523

            
524
32
        let result = self.run_reactors().await;
525

            
526
32
        guard.circuit_closed(&result);
527

            
528
32
        result
529
32
    }
530

            
531
    /// Run the decrypting and encrypting reactors, and handle the control messages and commands.
532
32
    async fn run_reactors(&mut self) -> StdResult<(), ReactorError> {
533
32
        let (forward, backward) = (|| Some((self.forward.take()?, self.backward.take()?)))()
534
32
            .expect("relay reactor spawned twice?!");
535

            
536
32
        let mut forward = Box::pin(forward.run()).fuse();
537
32
        let mut backward = Box::pin(backward.run()).fuse();
538
        loop {
539
            // If either of these completes, this function returns,
540
            // dropping dec_ctrl/enc_ctrl channels, which will, in turn,
541
            // cause the remaining reactor, if there is one, to shut down too
542
36
            select_biased! {
543
36
                res = self.command.next() => {
544
19
                    let Some(cmd) = res else {
545
15
                        trace!(
546
                            circ_uniq_id = %self.unique_id,
547
                            backward_circ_id = %self.circ_id,
548
                            reason = "command channel drop",
549
                            "reactor shutdown",
550
                        );
551

            
552
15
                        return Err(ReactorError::Shutdown);
553
                    };
554

            
555
4
                    self.handle_command(cmd)?;
556
                },
557
36
                res = self.control.next() => {
558
                    let Some(msg) = res else {
559
                        trace!(
560
                            circ_uniq_id = %self.unique_id,
561
                            backward_circ_id = %self.circ_id,
562
                            reason = "control channel drop",
563
                            "reactor shutdown",
564
                        );
565

            
566
                        return Err(ReactorError::Shutdown);
567
                    };
568

            
569
                    self.handle_control(msg)?;
570
                },
571
                // No need to log the error here, because it was already logged
572
                // by the reactor that shut down
573
36
                res = forward => return Ok(res?),
574
36
                res = backward => return Ok(res?),
575
            }
576
        }
577
32
    }
578

            
579
    /// Handle a shutdown request.
580
    fn handle_shutdown(&self) -> StdResult<(), ReactorError> {
581
        trace!(
582
            tunnel_id = %self.unique_id,
583
            "reactor shutdown due to explicit request",
584
        );
585

            
586
        Err(ReactorError::Shutdown)
587
    }
588

            
589
    /// Handle a [`CtrlCmd`].
590
4
    fn handle_command(
591
4
        &mut self,
592
4
        cmd: CtrlCmd<D::CtrlCmd, E::CtrlCmd>,
593
4
    ) -> StdResult<(), ReactorError> {
594
4
        match cmd {
595
4
            CtrlCmd::Decrypting(c) => self.dec_ctrl.send_cmd(c),
596
            CtrlCmd::Encrypting(c) => self.enc_ctrl.send_cmd(c),
597
            CtrlCmd::Shutdown => self.handle_shutdown(),
598
        }
599
4
    }
600

            
601
    /// Handle a [`CtrlMsg`].
602
    fn handle_control(
603
        &mut self,
604
        cmd: CtrlMsg<D::CtrlMsg, E::CtrlMsg>,
605
    ) -> StdResult<(), ReactorError> {
606
        match cmd {
607
            CtrlMsg::Decrypting(c) => self.dec_ctrl.send_msg(c),
608
            CtrlMsg::Encrypting(c) => self.enc_ctrl.send_msg(c),
609
        }
610
    }
611
}
612

            
613
#[cfg(test)]
614
pub(crate) mod test {
615
    // @@ begin test lint list maintained by maint/add_warning @@
616
    #![allow(clippy::bool_assert_comparison)]
617
    #![allow(clippy::clone_on_copy)]
618
    #![allow(clippy::dbg_macro)]
619
    #![allow(clippy::mixed_attributes_style)]
620
    #![allow(clippy::print_stderr)]
621
    #![allow(clippy::print_stdout)]
622
    #![allow(clippy::single_char_pattern)]
623
    #![allow(clippy::unwrap_used)]
624
    #![allow(clippy::unchecked_time_subtraction)]
625
    #![allow(clippy::useless_vec)]
626
    #![allow(clippy::needless_pass_by_value)]
627
    #![allow(clippy::string_slice)] // See arti#2571
628
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
629

            
630
    use tor_basic_utils::test_rng::testing_rng;
631
    use tor_cell::chancell::{BoxedCellBody, msg as chanmsg};
632
    use tor_cell::relaycell::{AnyRelayMsgOuter, RelayCellFormat, StreamId, msg as relaymsg};
633

            
634
    use chanmsg::AnyChanMsg;
635

            
636
    #[cfg(any(feature = "hs-service", feature = "relay"))]
637
    use crate::stream::IncomingStreamRequestFilter;
638

            
639
    pub(crate) fn rmsg_to_ccmsg(
640
        id: Option<StreamId>,
641
        msg: relaymsg::AnyRelayMsg,
642
        early: bool,
643
    ) -> AnyChanMsg {
644
        // TODO #1947: test other formats.
645
        let rfmt = RelayCellFormat::V0;
646
        let body: BoxedCellBody = AnyRelayMsgOuter::new(id, msg)
647
            .encode(rfmt, &mut testing_rng())
648
            .unwrap();
649
        let chanmsg = chanmsg::Relay::from(body);
650

            
651
        if early {
652
            let chanmsg = chanmsg::RelayEarly::from(chanmsg);
653
            AnyChanMsg::RelayEarly(chanmsg)
654
        } else {
655
            AnyChanMsg::Relay(chanmsg)
656
        }
657
    }
658

            
659
    #[cfg(any(feature = "hs-service", feature = "relay"))]
660
    pub(crate) struct AllowAllStreamsFilter;
661
    #[cfg(any(feature = "hs-service", feature = "relay"))]
662
    impl IncomingStreamRequestFilter for AllowAllStreamsFilter {
663
        fn disposition(
664
            &mut self,
665
            _ctx: &crate::stream::IncomingStreamRequestContext<'_>,
666
            _circ: &crate::circuit::CircHopSyncView<'_>,
667
        ) -> crate::Result<crate::stream::IncomingStreamRequestDisposition> {
668
            Ok(crate::stream::IncomingStreamRequestDisposition::Accept)
669
        }
670
    }
671
}