Skip to main content

tor_proto/circuit/reactor/
circhop.rs

1//! Module exposing structures relating to the reactor's view of a circuit's hops.
2//!
3//! TODO(DEDUP): this will eventually replace [crate::client::reactor::circuit::circhop].
4
5use crate::circuit::HOPS;
6use crate::circuit::circhop::{CircHopInbound, HopSettings};
7use crate::circuit::reactor::stream::CtrlMsg;
8use crate::congestion::CongestionControl;
9use crate::{HopNum, Result};
10use std::sync::{Arc, Mutex};
11
12use futures::channel::mpsc;
13
14use tor_cell::relaycell::RelayCellDecoder;
15use tor_error::{Bug, internal};
16
17use std::result::Result as StdResult;
18
19/// Per-hop state.
20pub(crate) struct CircHop {
21    /// A sender for sending relay messages to this hop's stream reactor.
22    ///
23    /// Set to `None` if we haven't yet spawned a stream reactor for this hop.
24    pub(crate) tx: Option<mpsc::Sender<CtrlMsg>>,
25    /// The congestion control state.
26    ///
27    /// This is shared with `CircHopOutbound`.
28    ///
29    // TODO(DEDUP): the Arc is not actually needed in the new generic circuit reactor
30    // (it only exists because CircHopOutbound/CircHop needs it).
31    pub(crate) ccontrol: Arc<Mutex<CongestionControl>>,
32    /// The inbound hop state of this hop.
33    pub(crate) inbound: CircHopInbound,
34    /// Settings negotiated with this hop.
35    pub(crate) settings: HopSettings,
36}
37
38impl CircHop {
39    /// Create a new [`CircHop`] from the specified settings.
40    fn new(settings: HopSettings) -> Self {
41        let relay_format = settings.relay_crypt_protocol().relay_cell_format();
42        let inbound = CircHopInbound::new(RelayCellDecoder::new(relay_format), &settings);
43        let ccontrol = Arc::new(Mutex::new(CongestionControl::new(&settings.ccontrol)));
44
45        Self {
46            inbound,
47            ccontrol,
48            settings,
49            tx: None,
50        }
51    }
52}
53
54/// Represents the reactor's view of a circuit's hops.
55pub(crate) enum CircHopList {
56    /// A relay's view of the circuit hop it represents.
57    Relay(CircHop),
58    /// A client's view of the circuit hops.
59    Client(Vec<CircHop>),
60}
61
62impl CircHopList {
63    /// Create a new [`CircHopList`] for a relay circuit.
64    pub(crate) fn new_relay(settings: HopSettings) -> Self {
65        Self::Relay(CircHop::new(settings))
66    }
67
68    /// Create a new [`CircHopList`] for a client circuit.
69    pub(crate) fn new_client() -> Self {
70        Self::Client(Vec::with_capacity(HOPS))
71    }
72
73    /// Return a reference to the hop corresponding to `hopnum`, if there is one.
74    ///
75    /// Relays pass `None` for the `hopnum`.
76    pub(crate) fn get(&self, hop: Option<HopNum>) -> StdResult<&CircHop, Bug> {
77        use CircHopList::*;
78
79        let res = match (self, hop) {
80            (Relay(circhop), None) => Some(circhop),
81            (Client(hops), Some(hop)) => hops.get(usize::from(hop)),
82            (Relay(_), Some(_)) => None,
83            (Client(_), None) => None,
84        };
85
86        res.ok_or_else(|| internal!("tried to use non-existent hop {hop:?}?!"))
87    }
88
89    /// Return a mutable reference to the hop corresponding to `hopnum`, if there is one.
90    ///
91    /// Relays pass `None` for the `hopnum`.
92    pub(crate) fn get_mut(&mut self, hop: Option<HopNum>) -> StdResult<&mut CircHop, Bug> {
93        use CircHopList::*;
94
95        let res = match (self, hop) {
96            (Relay(circhop), None) => Some(circhop),
97            (Client(hops), Some(hop)) => hops.get_mut(usize::from(hop)),
98            (Relay(_), Some(_)) => None,
99            (Client(_), None) => None,
100        };
101
102        res.ok_or_else(|| internal!("tried to use non-existent hop {hop:?}?!"))
103    }
104
105    /// Push a new hop to our hop list.
106    ///
107    /// Prepares a cc object for the hop, but does not spawn a stream reactor.
108    ///
109    /// Will return an error if the circuit already has [`u8::MAX`] hops.
110    pub(crate) fn add_hop(&mut self, settings: HopSettings) -> Result<()> {
111        match self {
112            CircHopList::Relay(_) => {
113                Err(internal!("tried to add another hop to a relay CircHopList?!").into())
114            }
115            CircHopList::Client(hops) => {
116                let hop_num = hops.len();
117                debug_assert_eq!(hop_num, usize::from(Self::num_hops(hops)));
118
119                // There are several places in the code that assume that a `usize` hop number
120                // can be cast or converted to a `u8` hop number,
121                // so this check is important to prevent panics or incorrect behaviour.
122                if hop_num == usize::from(u8::MAX) {
123                    return Err(
124                        internal!("cannot add more hops to a circuit with `u8::MAX` hops").into(),
125                    );
126                }
127
128                hops.push(CircHop::new(settings));
129
130                Ok(())
131            }
132        }
133    }
134
135    /// The number of hops in this circuit.
136    fn num_hops(hops: &[CircHop]) -> u8 {
137        // `Self::add_hop` checks to make sure that we never have more than `u8::MAX` hops,
138        // so `self.hops.len()` should be safe to cast to a `u8`.
139        // If that assumption is violated,
140        // we choose to panic rather than silently use the wrong hop due to an `as` cast.
141        hops.len()
142            .try_into()
143            .expect("`hops.len()` has more than `u8::MAX` hops")
144    }
145}