1
//! A circuit's view of the forward state of the circuit.
2

            
3
use crate::circuit::UniqId;
4
use crate::circuit::metrics::CircuitMetrics;
5
use crate::circuit::reactor::circ_state::CircuitState;
6
use crate::circuit::reactor::encrypt::EncryptingReactorCmd;
7
use crate::circuit::reactor::macros::derive_deftly_template_CircuitReactor;
8
use crate::circuit::reactor::stream;
9
use crate::circuit::reactor::{ControlHandler, ReactorResultChannel};
10
use crate::congestion::sendme;
11
use crate::stream::cmdcheck::AnyCmdChecker;
12
use crate::stream::msg_streamid;
13
use crate::util::err::ReactorError;
14
use crate::{Error, HopNum, Result};
15

            
16
#[cfg(any(feature = "hs-service", feature = "relay"))]
17
use {
18
    crate::stream::CloseStreamBehavior,
19
    crate::stream::incoming::{
20
        IncomingStreamRequestFilter, IncomingStreamRequestHandler, StreamReqSender,
21
    },
22
};
23

            
24
// TODO(circpad): once padding is stabilized, the padding module will be moved out of client.
25
use crate::client::circuit::padding::PaddingController;
26

            
27
use tor_cell::chancell::{CircId, msg::AnyChanMsg};
28
use tor_cell::relaycell::flow_ctrl::XonKBpsEwma;
29
use tor_cell::relaycell::msg::{Sendme, SendmeTag};
30
use tor_cell::relaycell::{RelayCellDecoderResult, RelayCmd, StreamId, UnparsedRelayMsg};
31
use tor_linkspec::HasRelayIds;
32
use tor_rtcompat::Runtime;
33

            
34
use derive_deftly::Deftly;
35
use futures::SinkExt;
36
use futures::channel::mpsc;
37
use futures::{FutureExt as _, StreamExt, select_biased};
38
use std::result::Result as StdResult;
39
use std::sync::Arc;
40
use tracing::debug;
41

            
42
use crate::circuit::CircuitRxReceiver;
43

            
44
/// The decrypting circuit reactor.
45
///
46
/// See the [`reactor`](crate::circuit::reactor) module-level docs.
47
///
48
/// Shuts downs down if an error occurs, or if either the [`Reactor`](super::Reactor)
49
/// or the [`EncryptingReactor`](super::EncryptingReactor) shuts down:
50
///
51
///   * if the `Reactor` shuts down, we are alerted via the ctrl/command mpsc channels
52
///     (their sending ends will close, which causes run_once() to return ReactorError::Shutdown)
53
///   * if `EncryptingReactor` shuts down, the `Reactor` will notice and will itself shut down,
54
///     which, in turn, causes the `DecryptingReactor` to shut down as described above
55
#[derive(Deftly)]
56
#[derive_deftly(CircuitReactor)]
57
#[deftly(reactor_name = "decrypting reactor")]
58
#[deftly(run_inner_fn = "Self::run_once")]
59
#[must_use = "If you don't call run() on a reactor, the circuit won't work."]
60
pub(super) struct DecryptingReactor<R: Runtime, D: DecryptingReactorInner> {
61
    /// A handle to the runtime.
62
    runtime: R,
63
    /// An identifier for logging about this reactor's circuit.
64
    unique_id: UniqId,
65
    /// The circuit identifier on the inbound Tor channel.
66
    circ_id: CircId,
67
    /// Implementation-dependent part of the reactor.
68
    ///
69
    /// This enables us to customize the behavior of the reactor,
70
    /// depending on whether we are a client or a relay.
71
    inner: D,
72
    /// Channel for receiving control commands.
73
    command_rx: mpsc::UnboundedReceiver<CtrlCmd<D::CtrlCmd>>,
74
    /// Channel for receiving control messages.
75
    control_rx: mpsc::UnboundedReceiver<CtrlMsg<D::CtrlMsg>>,
76
    /// The reading end of the inbound Tor channel.
77
    ///
78
    /// Yields cells moving from the client towards the exit, if we are a relay,
79
    /// or cells moving towards *us*, if we are a client.
80
    inbound_chan_rx: CircuitRxReceiver,
81
    /// Sender for sending commands to the EncryptingReactor.
82
    ///
83
    /// Used for sending:
84
    ///
85
    ///    * circuit-level SENDMEs received from the other endpoint
86
    ///      (`[EncryptingReactorCmd::HandleSendme]`)
87
    ///    * circuit-level SENDMEs that need to be delivered to the other endpoint
88
    ///      (using `[EncryptingReactorCmd::SendRelayMsg]`)
89
    ///
90
    /// The receiver is in [`EncryptingReactor`](super::EncryptingReactor), which is responsible for
91
    /// sending cell over the inbound channel.
92
    encrypting_reactor_tx: mpsc::Sender<EncryptingReactorCmd>,
93
    /// The per-hop state of the circuit.
94
    ///
95
    /// Contains the `CircHopList` and handles to the corresponding stream reactors.
96
    circ_state: CircuitState<R>,
97
    /// An implementation-specific event stream.
98
    ///
99
    /// Polled from the main loop of the reactor.
100
    /// Each event is passed to [`DecryptingReactorInner::handle_event`].
101
    circ_events: mpsc::Receiver<D::CircEvent>,
102
    /// Sender for for the circ_events MPSC.
103
    ///
104
    /// This is unused, but we need it here in order to keep the circ_events MPSC open,
105
    /// even if this circuit has already used (and dropped) its ExtendRequestHandler
106
    /// (the ExtendRequestHandler holds a sending end to this MPSC channel).
107
    //
108
    //
109
    // TODO(relay): this whole circ_events indirection is hard to follow and brittle.
110
    // It would be nice if we could replace it with a simpler approach
111
    #[allow(unused)]
112
    circ_events_tx: mpsc::Sender<D::CircEvent>,
113
    /// A padding controller to which padding-related events should be reported.
114
    padding_ctrl: PaddingController,
115
    /// The circuit metrics.
116
    metrics: Arc<CircuitMetrics>,
117
}
118

            
119
/// A control command aimed at the generic decrypting reactor.
120
pub(crate) enum CtrlCmd<C> {
121
    /// Begin accepting streams on this circuit.
122
    //
123
    // TODO(DEDUP): this is very similar to its client-side counterpart,
124
    // except the hop is a Option<HopNum> instead of a TargetHop.
125
    #[cfg(feature = "hs-service")]
126
    #[allow(unused)] // TODO(dedup): this will be used by hs services
127
    AwaitStreamRequests {
128
        /// A channel for sending information about an incoming stream request.
129
        incoming_sender: StreamReqSender,
130
        /// A `CmdChecker` to keep track of which message types are acceptable.
131
        cmd_checker: AnyCmdChecker,
132
        /// Oneshot channel to notify on completion.
133
        done: ReactorResultChannel<()>,
134
        /// The hop that is allowed to create streams.
135
        ///
136
        /// Set to None if we are a relay wanting to accept stream requests.
137
        hop: Option<HopNum>,
138
        /// A filter used to check requests before passing them on.
139
        filter: Box<dyn IncomingStreamRequestFilter>,
140
    },
141

            
142
    /// Close the specified pending incoming stream, sending the provided END message.
143
    ///
144
    /// A stream is said to be pending if the message for initiating the stream was received but
145
    /// not has not been responded to yet.
146
    ///
147
    /// This should be used by responders for closing pending incoming streams initiated by the
148
    /// other party on the circuit.
149
    ///
150
    /// TODO(dedup): this is almost identical to the ClosePendingStream control message
151
    /// from the client-side. We can get rid of the duplication by rewriting
152
    /// the client circuit reactor to use the new multi-reactor architecture
153
    #[cfg(any(feature = "hs-service", feature = "relay"))]
154
    ClosePendingStream {
155
        /// The hop number the stream is on.
156
        ///
157
        /// Set to None if we are a relay.
158
        hop: Option<HopNum>,
159
        /// The stream ID to send the END for.
160
        stream_id: StreamId,
161
        /// The END message to send, if any.
162
        message: CloseStreamBehavior,
163
        /// Oneshot channel to notify on completion.
164
        done: ReactorResultChannel<()>,
165
    },
166
    /// Inform the stream reactor that the drain rate of a stream has changed so that it
167
    /// can send an XON if needed.
168
    ///
169
    /// This is routed to the stream reactor because the it owns the stream map and the
170
    /// XON/XOFF state. It is also the reactor that decides to send an XOFF or not. It is
171
    /// in charge of sending the XON to the encrypting reactor if need be.
172
    StreamDrainRateUpdate {
173
        /// The hop number the stream is on.
174
        ///
175
        /// Set to None if we are a relay.
176
        hop: Option<HopNum>,
177
        /// The stream ID to send the XON on.
178
        stream_id: StreamId,
179
        /// The drain rate to advertise in the XON.
180
        rate: XonKBpsEwma,
181
    },
182
    /// An implementation-dependent control command.
183
    #[allow(unused)] // TODO(relay)
184
    Custom(C),
185
}
186

            
187
/// A control message aimed at the generic decrypting reactor.
188
pub(crate) enum CtrlMsg<M> {
189
    /// An implementation-dependent control message.
190
    #[allow(unused)] // TODO(relay)
191
    Custom(M),
192
}
193

            
194
/// Trait for customizing the behavior of the decrypting reactor.
195
///
196
/// Used for plugging in the implementation-dependent (client vs relay)
197
/// parts of the implementation into the generic one.
198
pub(crate) trait DecryptingReactorInner: ControlHandler {
199
    /// Type that explains how to build an outgoing channel.
200
    type BuildSpec: HasRelayIds;
201

            
202
    /// The subclass of ChanMsg that can arrive on this type of circuit.
203
    type CircChanMsg: TryFrom<AnyChanMsg, Error = crate::Error>;
204

            
205
    /// An opaque event type.
206
    ///
207
    /// The [`DecryptingReactor`] polls an MPSC stream yielding `CircEvent`s from the main loop.
208
    /// Each event is passed to [`Self::handle_event`] for handling.
209
    type CircEvent;
210

            
211
    /// Handle a non-SENDME RELAY message on this circuit with stream ID 0.
212
    async fn handle_meta_msg<R: Runtime>(
213
        &mut self,
214
        runtime: &R,
215
        early: bool,
216
        hopnum: Option<HopNum>,
217
        msg: UnparsedRelayMsg,
218
    ) -> StdResult<(), ReactorError>;
219

            
220
    /// Try to handle a ChanMsg that arrived on this circuit.
221
    ///
222
    /// The cell is
223
    ///   - moving from the client towards the exit, if we're a relay
224
    ///   - moving from the guard towards us, if we're a client
225
    ///
226
    /// Returns an error if the cell should cause the reactor to shut down,
227
    /// or a [`DecodedRelayCell`], if the cell was successfully decoded.
228
    ///
229
    /// Returns `None` if the cell was handled internally by this handler.
230
    /// Returns `Some` if the cell needs to be handled by the base reactor.
231
    async fn maybe_handle_cell<R: Runtime>(
232
        &mut self,
233
        circ_state: &CircuitState<R>,
234
        cell: Self::CircChanMsg,
235
    ) -> StdResult<Option<DecodedRelayCell>, ReactorError>;
236

            
237
    /// Handle an implementation-specific circuit event.
238
    ///
239
    /// Returns a command for the encrypting reactor.
240
    fn handle_event(
241
        &mut self,
242
        event: Self::CircEvent,
243
    ) -> StdResult<Option<EncryptingReactorCmd>, ReactorError>;
244

            
245
    /// Wait until the outbound channel, if there is one, is ready to accept more cells.
246
    ///
247
    /// Resolves immediately if there is no outbound channel.
248
    /// Blocks if there is a pending outbound channel.
249
    async fn outbound_chan_ready(&mut self) -> Result<()>;
250
}
251

            
252
/// A decoded RELAY or RELAY_EARLY cell.
253
pub(crate) struct DecodedRelayCell {
254
    /// The decoded cell.
255
    pub(crate) cell: RelayCellDecoderResult,
256
    /// Whether this was a RELAY_EARLY.
257
    pub(crate) early: bool,
258
    /// The hop this cell was for.
259
    pub(crate) hopnum: Option<HopNum>,
260
    /// The SENDME tag.
261
    pub(crate) tag: SendmeTag,
262
}
263

            
264
impl<R: Runtime, D: DecryptingReactorInner> DecryptingReactor<R, D> {
265
    /// Create a new [`DecryptingReactor`].
266
    #[allow(clippy::too_many_arguments)] // TODO
267
32
    pub(super) fn new(
268
32
        runtime: R,
269
32
        unique_id: UniqId,
270
32
        circ_id: CircId,
271
32
        inner: D,
272
32
        circ_state: CircuitState<R>,
273
32
        inbound_chan_rx: CircuitRxReceiver,
274
32
        control_rx: mpsc::UnboundedReceiver<CtrlMsg<D::CtrlMsg>>,
275
32
        command_rx: mpsc::UnboundedReceiver<CtrlCmd<D::CtrlCmd>>,
276
32
        encrypting_reactor_tx: mpsc::Sender<EncryptingReactorCmd>,
277
32
        circ_events: mpsc::Receiver<D::CircEvent>,
278
32
        circ_events_tx: mpsc::Sender<D::CircEvent>,
279
32
        padding_ctrl: PaddingController,
280
32
        metrics: Arc<CircuitMetrics>,
281
32
    ) -> Self {
282
32
        Self {
283
32
            runtime,
284
32
            unique_id,
285
32
            circ_id,
286
32
            inbound_chan_rx,
287
32
            control_rx,
288
32
            command_rx,
289
32
            inner,
290
32
            encrypting_reactor_tx,
291
32
            circ_state,
292
32
            circ_events,
293
32
            circ_events_tx,
294
32
            padding_ctrl,
295
32
            metrics,
296
32
        }
297
32
    }
298

            
299
    /// Helper for [`run`](Self::run).
300
65
    async fn run_once(&mut self) -> StdResult<(), ReactorError> {
301
65
        let outbound_chan_ready = self.inner.outbound_chan_ready();
302

            
303
65
        let inbound_chan_rx_fut = async {
304
            // Avoid reading from the inbound_chan_rx Tor Channel if the outgoing sink is blocked
305
65
            outbound_chan_ready.await?;
306
65
            Ok(self.inbound_chan_rx.next().await)
307
39
        };
308

            
309
65
        select_biased! {
310
65
            res = self.command_rx.next().fuse() => {
311
4
                let cmd = res.ok_or_else(|| ReactorError::Shutdown)?;
312
4
                self.handle_cmd(cmd).await
313
            }
314
65
            res = self.control_rx.next().fuse() => {
315
                let msg = res.ok_or_else(|| ReactorError::Shutdown)?;
316
                self.handle_msg(msg)
317
            }
318
65
            res = self.circ_events.next().fuse() => {
319
6
                let ev = res.ok_or_else(|| ReactorError::Shutdown)?;
320
6
                if let Some(cmd) = self.inner.handle_event(ev)? {
321
6
                    self.send_reactor_cmd(cmd).await?;
322
                }
323

            
324
6
                Ok(())
325
            }
326
65
            res = inbound_chan_rx_fut.fuse() => {
327
39
                let cell = res.map_err(ReactorError::Err)?;
328
39
                let Some(cell) = cell else {
329
                    debug!(
330
                        circ_uniq_id = %self.unique_id,
331
                        backward_circ_id = %self.circ_id,
332
                        "Backward channel has closed, shutting down decrypting reactor",
333
                    );
334

            
335
                    return Err(ReactorError::Shutdown);
336
                };
337
                // TODO(relay): This assumes cells travel in the forward direction.
338
39
                self.metrics.forward_cell_read();
339

            
340
39
                let cell: D::CircChanMsg = cell.try_into()?;
341
39
                let Some(decoded_cell) = self.inner.maybe_handle_cell(&self.circ_state, cell).await? else {
342
4
                    return Ok(());
343
                };
344

            
345
28
                let DecodedRelayCell { cell, early, hopnum, tag } = decoded_cell;
346
28
                self.handle_relay_cell(cell, early, hopnum, tag).await
347
            },
348
        }
349
48
    }
350

            
351
    /// Handle a control command.
352
    #[allow(clippy::unused_async)] // used if feature = "hs-service"
353
4
    async fn handle_cmd(&mut self, cmd: CtrlCmd<D::CtrlCmd>) -> StdResult<(), ReactorError> {
354
4
        match cmd {
355
            #[cfg(feature = "hs-service")]
356
            CtrlCmd::AwaitStreamRequests {
357
                incoming_sender,
358
                cmd_checker,
359
                done,
360
                hop,
361
                filter,
362
            } => {
363
                let handler = IncomingStreamRequestHandler {
364
                    incoming_sender,
365
                    cmd_checker,
366
                    hop_num: hop,
367
                    filter,
368
                };
369

            
370
                let ret = self.circ_state.set_incoming_handler(handler);
371
                let _ = done.send(ret); // don't care if the corresponding receiver goes away.
372
                Ok(())
373
            }
374
            #[cfg(any(feature = "hs-service", feature = "relay"))]
375
            CtrlCmd::ClosePendingStream {
376
                hop,
377
                stream_id,
378
                message,
379
                done,
380
            } => {
381
4
                let ret = self.circ_state.close_pending(hop, stream_id, message).await;
382
4
                let _ = done.send(ret); // don't care if the corresponding receiver goes away.
383

            
384
4
                Ok(())
385
            }
386
            CtrlCmd::StreamDrainRateUpdate {
387
                hop,
388
                stream_id,
389
                rate,
390
            } => {
391
                let msg = stream::CtrlMsg::DrainRateUpdate { stream_id, rate };
392
                self.circ_state.send(hop, msg).await
393
            }
394
            CtrlCmd::Custom(c) => self.inner.handle_cmd(c),
395
        }
396
4
    }
397

            
398
    /// Handle a control message.
399
    fn handle_msg(&mut self, msg: CtrlMsg<D::CtrlMsg>) -> StdResult<(), ReactorError> {
400
        match msg {
401
            CtrlMsg::Custom(c) => self.inner.handle_msg(c),
402
        }
403
    }
404

            
405
    /// Handle a RELAY cell.
406
    ///
407
    // TODO(DEDUP): very similar to Client::handle_relay_cell()
408
28
    async fn handle_relay_cell(
409
28
        &mut self,
410
28
        decode_res: RelayCellDecoderResult,
411
28
        early: bool,
412
28
        hopnum: Option<HopNum>,
413
28
        tag: SendmeTag,
414
28
    ) -> StdResult<(), ReactorError> {
415
        // For padding purposes, if we are a relay, we set the hopnum to 0
416
        // TODO(relay): is this right?
417
28
        let hopnum_padding = hopnum.unwrap_or_else(|| HopNum::from(0));
418
28
        if decode_res.is_padding() {
419
            self.padding_ctrl.decrypted_padding(hopnum_padding)?;
420
        } else {
421
28
            self.padding_ctrl.decrypted_data(hopnum_padding);
422
        }
423

            
424
28
        let c_t_w = decode_res.cmds().any(sendme::cmd_counts_towards_windows);
425
28
        let sendme = self
426
28
            .circ_state
427
28
            .shared()
428
28
            .note_relay_cell_received(hopnum, c_t_w, tag)?;
429

            
430
        // If we do need to send a circuit-level SENDME cell, do so.
431
28
        if let Some(msg) = sendme {
432
            let forward = EncryptingReactorCmd::SendRelayMsg { hop: hopnum, msg };
433

            
434
            // NOTE: sending the SENDME to the encrypting reactor for handling
435
            // might seem counterintuitive, given that we have access to
436
            // the congestion control object right here (via circ_state).
437
            //
438
            // However, the decrypting reactor does not have access to the
439
            // outbound_chan_tx part of the inbound (towards the client) Tor channel,
440
            // and so it cannot handle the SENDME on its own
441
            // (because it cannot obtain the congestion signals),
442
            // so the SENDME needs to be handled in the encrypting reactor.
443
            //
444
            // NOTE: this will block if the encrypting reactor is not ready
445
            // to send any more cells.
446
            self.send_reactor_cmd(forward).await?;
447
28
        }
448

            
449
28
        let (mut msgs, incomplete) = decode_res.into_parts();
450
47
        while let Some(msg) = msgs.next() {
451
28
            match self.handle_relay_msg(early, hopnum, msg, c_t_w).await {
452
19
                Ok(()) => continue,
453
                Err(e) => {
454
8
                    for m in msgs {
455
                        debug!(
456
                            circ_uniq_id = %self.unique_id,
457
                            backward_circ_id = %self.circ_id,
458
                            "Ignoring relay msg received after triggering shutdown: {m:?}",
459
                        );
460
                    }
461
8
                    if let Some(incomplete) = incomplete {
462
                        debug!(
463
                            circ_uniq_id = %self.unique_id,
464
                            backward_circ_id = %self.circ_id,
465
                            "Ignoring partial relay msg received after triggering shutdown: {:?}",
466
                            incomplete,
467
                        );
468
8
                    }
469

            
470
8
                    return Err(e);
471
                }
472
            }
473
        }
474

            
475
19
        Ok(())
476
27
    }
477

            
478
    /// Handle a single incoming RELAY message.
479
28
    async fn handle_relay_msg(
480
28
        &mut self,
481
28
        early: bool,
482
28
        hop: Option<HopNum>,
483
28
        msg: UnparsedRelayMsg,
484
28
        cell_counts_toward_windows: bool,
485
28
    ) -> StdResult<(), ReactorError> {
486
        // If this msg wants/refuses to have a Stream ID, does it
487
        // have/not have one?
488
28
        let streamid = msg_streamid(&msg)?;
489

            
490
        // If this doesn't have a StreamId, it's a meta cell,
491
        // not meant for a particular stream.
492
26
        if let Some(sid) = streamid {
493
14
            self.handle_stream_msg(early, hop, msg, sid, cell_counts_toward_windows)
494
14
                .await
495
        } else {
496
12
            self.handle_meta_msg(early, hop, msg).await
497
        }
498
27
    }
499

            
500
    /// Handle a stream message arriving on this circuit.
501
14
    async fn handle_stream_msg(
502
14
        &mut self,
503
14
        _early: bool,
504
14
        hop: Option<HopNum>,
505
14
        msg: UnparsedRelayMsg,
506
14
        sid: StreamId,
507
14
        cell_counts_toward_windows: bool,
508
14
    ) -> StdResult<(), ReactorError> {
509
        // TODO(relay): return an error if this arrived in an RELAY_EARLY?
510

            
511
14
        let msg = stream::CtrlMsg::DeliverStreamMsg {
512
14
            sid,
513
14
            msg,
514
14
            cell_counts_toward_windows,
515
14
        };
516

            
517
        // All messages on streams are handled in the stream reactor
518
        // (because that's where the stream map is)
519
        //
520
        // Internally, this will spawn a StreamReactor for the target hop,
521
        // if not already spawned.
522
14
        self.circ_state.send(hop, msg).await
523
13
    }
524

            
525
    /// Handle a RELAY or RELAY_EARLY message on this circuit with stream ID 0.
526
12
    async fn handle_meta_msg(
527
12
        &mut self,
528
12
        early: bool,
529
12
        hopnum: Option<HopNum>,
530
12
        msg: UnparsedRelayMsg,
531
12
    ) -> StdResult<(), ReactorError> {
532
12
        match msg.cmd() {
533
            RelayCmd::SENDME => self.handle_sendme(hopnum, msg).await,
534
            _ => {
535
12
                self.inner
536
12
                    .handle_meta_msg(&self.runtime, early, hopnum, msg)
537
12
                    .await
538
            }
539
        }
540
12
    }
541

            
542
    /// Handle a circuit SENDME coming from the specified `hopnum`.
543
    async fn handle_sendme(
544
        &mut self,
545
        hopnum: Option<HopNum>,
546
        msg: UnparsedRelayMsg,
547
    ) -> StdResult<(), ReactorError> {
548
        let sendme = msg
549
            .decode::<Sendme>()
550
            .map_err(|e| Error::from_bytes_err(e, "sendme message"))?
551
            .into_msg();
552

            
553
        let cmd = EncryptingReactorCmd::HandleSendme {
554
            hop: hopnum,
555
            sendme,
556
        };
557

            
558
        self.send_reactor_cmd(cmd).await
559
    }
560

            
561
    /// Send a command to the encrypting reactor.
562
    ///
563
    /// Blocks if the `encrypting_reactor_tx` channel is full, i.e. if the encrypting reactor
564
    /// is not ready to send any more cells.
565
    ///
566
    /// Returns an error if the encrypting reactor has shut down.
567
6
    async fn send_reactor_cmd(
568
6
        &mut self,
569
6
        forward: EncryptingReactorCmd,
570
6
    ) -> StdResult<(), ReactorError> {
571
6
        self.encrypting_reactor_tx.send(forward).await.map_err(|_| {
572
            // The other reactor has shut down
573
            ReactorError::Shutdown
574
        })
575
6
    }
576
}