tor_proto/circuit/reactor/
circhop.rs1use 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
19pub(crate) struct CircHop {
21 pub(crate) tx: Option<mpsc::Sender<CtrlMsg>>,
25 pub(crate) ccontrol: Arc<Mutex<CongestionControl>>,
32 pub(crate) inbound: CircHopInbound,
34 pub(crate) settings: HopSettings,
36}
37
38impl CircHop {
39 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
54pub(crate) enum CircHopList {
56 Relay(CircHop),
58 Client(Vec<CircHop>),
60}
61
62impl CircHopList {
63 pub(crate) fn new_relay(settings: HopSettings) -> Self {
65 Self::Relay(CircHop::new(settings))
66 }
67
68 pub(crate) fn new_client() -> Self {
70 Self::Client(Vec::with_capacity(HOPS))
71 }
72
73 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 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 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 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 fn num_hops(hops: &[CircHop]) -> u8 {
137 hops.len()
142 .try_into()
143 .expect("`hops.len()` has more than `u8::MAX` hops")
144 }
145}