1mod extend_handler;
4
5use extend_handler::ExtendRequestHandler;
6
7use crate::channel::{Channel, ChannelSender};
8use crate::circuit::CircuitRxReceiver;
9use crate::circuit::UniqId;
10use crate::circuit::celltypes::RelayMaybeEarlyChanMsg;
11use crate::circuit::reactor::ControlHandler;
12use crate::circuit::reactor::backward::BackwardReactorCmd;
13use crate::circuit::reactor::forward::{ForwardCellDisposition, ForwardHandler};
14use crate::circuit::reactor::hop_mgr::HopMgr;
15use crate::crypto::cell::OutboundRelayLayer;
16use crate::crypto::cell::RelayCellBody;
17use crate::relay::RelayCircChanMsg;
18use crate::util::err::ReactorError;
19use crate::{Error, HopNum, Result};
20
21use crate::client::circuit::padding::QueuedCellPaddingInfo;
23
24use crate::relay::channel_provider::ChannelProvider;
25use crate::relay::reactor::CircuitAccount;
26use tor_cell::chancell::msg::{AnyChanMsg, Destroy, PaddingNegotiate, Relay};
27use tor_cell::chancell::{AnyChanCell, BoxedCellBody, ChanMsg, CircId};
28use tor_cell::relaycell::msg::{Extended2, SendmeTag};
29use tor_cell::relaycell::{RelayCellDecoderResult, RelayCellFormat, RelayCmd, UnparsedRelayMsg};
30use tor_error::internal;
31use tor_linkspec::OwnedChanTarget;
32use tor_rtcompat::Runtime;
33
34use futures::channel::mpsc;
35use futures::{SinkExt as _, future};
36use tracing::{debug, trace};
37
38use std::result::Result as StdResult;
39use std::sync::Arc;
40use std::task::Poll;
41
42type CtrlMsg = ();
44
45type CtrlCmd = ();
47
48const MAX_RELAY_EARLY_CELLS_PER_CIRCUIT: usize = 8;
52
53pub(crate) struct Forward {
55 unique_id: UniqId,
57 circ_id: CircId,
59 outbound: Option<Outbound>,
65 crypto_out: Box<dyn OutboundRelayLayer + Send>,
67 relay_early_count: usize,
71 extend_handler: ExtendRequestHandler,
75}
76
77pub(crate) enum CircEvent {
79 ExtendResult(StdResult<ExtendResult, ReactorError>),
81}
82
83pub(crate) struct ExtendResult {
85 extended2: Extended2,
87 outbound: Outbound,
89 outbound_chan_rx: CircuitRxReceiver,
93}
94
95struct Outbound {
97 circ_id: CircId,
99 channel: Arc<Channel>,
101 outbound_chan_tx: ChannelSender,
103}
104
105enum CellDecodeResult {
107 Recognized(SendmeTag, RelayCellDecoderResult),
109 Unrecognizd(RelayCellBody),
111}
112
113impl Forward {
114 pub(crate) fn new(
116 inbound_chan: &Arc<Channel>,
117 circ_id: CircId,
118 unique_id: UniqId,
119 crypto_out: Box<dyn OutboundRelayLayer + Send>,
120 chan_provider: Arc<dyn ChannelProvider<BuildSpec = OwnedChanTarget> + Send + Sync>,
121 event_tx: mpsc::Sender<CircEvent>,
122 memquota: CircuitAccount,
123 ) -> Self {
124 let inbound_peer = Arc::clone(inbound_chan.peer_info());
125 let extend_handler = ExtendRequestHandler::new(
126 unique_id,
127 circ_id,
128 chan_provider,
129 inbound_peer,
130 event_tx,
131 memquota,
132 );
133
134 Self {
135 unique_id,
136 circ_id,
137 outbound: None,
139 crypto_out,
140 relay_early_count: 0,
141 extend_handler,
142 }
143 }
144
145 fn decode_relay_cell<R: Runtime>(
147 &mut self,
148 hop_mgr: &HopMgr<R>,
149 cell: RelayMaybeEarlyChanMsg,
150 ) -> Result<(Option<HopNum>, CellDecodeResult)> {
151 let hopnum = None;
153 let cmd = cell.cmd();
154 let mut body = cell.into_relay_body().into();
155 let Some(tag) = self.crypto_out.decrypt_outbound(cmd, &mut body) else {
156 return Ok((hopnum, CellDecodeResult::Unrecognizd(body)));
157 };
158
159 let hops = hop_mgr.hops().read().expect("poisoned lock");
161 let decode_res = hops.get(hopnum)?.inbound.decode(body.into())?;
162
163 Ok((hopnum, CellDecodeResult::Recognized(tag, decode_res)))
164 }
165
166 #[allow(clippy::unnecessary_wraps)] fn handle_drop(&mut self) -> StdResult<(), ReactorError> {
169 cfg_if::cfg_if! {
170 if #[cfg(feature = "circ-padding")] {
171 Err(internal!("relay circuit padding not yet supported").into())
172 } else {
173 Ok(())
174 }
175 }
176 }
177
178 fn handle_extend_result(
180 &mut self,
181 res: StdResult<ExtendResult, ReactorError>,
182 ) -> StdResult<Option<BackwardReactorCmd>, ReactorError> {
183 let ExtendResult {
184 extended2,
185 outbound,
186 outbound_chan_rx,
187 } = res?;
188
189 self.outbound = Some(outbound);
190
191 Ok(Some(BackwardReactorCmd::HandleCircuitExtended {
192 hop: None,
193 extended2,
194 outbound_chan_rx,
195 }))
196 }
197
198 fn handle_relay_cell<R: Runtime>(
200 &mut self,
201 hop_mgr: &HopMgr<R>,
202 cell: RelayMaybeEarlyChanMsg,
203 ) -> StdResult<Option<ForwardCellDisposition>, ReactorError> {
204 let early = matches!(cell, RelayMaybeEarlyChanMsg::RelayEarly(_));
205
206 if early {
207 self.relay_early_count += 1;
208
209 if self.relay_early_count > MAX_RELAY_EARLY_CELLS_PER_CIRCUIT {
210 return Err(
211 Error::CircProto("Circuit received too many RELAY_EARLY cells".into()).into(),
212 );
213 }
214 }
215
216 let (hopnum, res) = self.decode_relay_cell(hop_mgr, cell)?;
217 let (tag, decode_res) = match res {
218 CellDecodeResult::Unrecognizd(body) => {
219 self.handle_unrecognized_cell(body, None, early)?;
220 return Ok(None);
221 }
222 CellDecodeResult::Recognized(tag, res) => (tag, res),
223 };
224
225 Ok(Some(ForwardCellDisposition::HandleRecognizedRelay {
226 cell: decode_res,
227 early,
228 hopnum,
229 tag,
230 }))
231 }
232
233 fn handle_unrecognized_cell(
235 &mut self,
236 body: RelayCellBody,
237 info: Option<QueuedCellPaddingInfo>,
238 early: bool,
239 ) -> StdResult<(), ReactorError> {
240 let Some(chan) = self.outbound.as_mut() else {
241 return Err(Error::CircProto(
244 "Asked to forward cell before the circuit was extended?!".into(),
245 )
246 .into());
247 };
248
249 trace!(
253 circ_uniq_id = %self.unique_id,
254 forward_circ_id = %chan.circ_id,
255 "Forwarding unrecognized cell"
256 );
257
258 let msg = Relay::from(BoxedCellBody::from(body));
259 let relay = if early {
260 AnyChanMsg::RelayEarly(msg.into())
261 } else {
262 AnyChanMsg::Relay(msg)
263 };
264 let cell = AnyChanCell::new(Some(chan.circ_id), relay);
265
266 chan.outbound_chan_tx.start_send_unpin((cell, info))?;
269
270 Ok(())
271 }
272
273 fn handle_truncate(&mut self) -> StdResult<(), ReactorError> {
275 Err(Error::CircProto("TRUNCATE not allowed".into()).into())
281 }
282
283 fn handle_destroy_cell(&mut self, cell: &Destroy) -> StdResult<(), ReactorError> {
285 debug!(
286 circ_uniq_id = %self.unique_id,
287 backward_circ_id = %self.circ_id,
288 reason = %cell.reason(),
289 "Received outbound DESTROY, circuit shutting down",
290 );
291
292 Err(ReactorError::Shutdown)
295 }
296
297 #[allow(clippy::needless_pass_by_value)] fn handle_padding_negotiate(&mut self, _cell: PaddingNegotiate) -> StdResult<(), ReactorError> {
300 Err(internal!("PADDING_NEGOTIATE is not implemented").into())
301 }
302}
303
304impl ForwardHandler for Forward {
305 type BuildSpec = OwnedChanTarget;
306 type CircChanMsg = RelayCircChanMsg;
307 type CircEvent = CircEvent;
308
309 async fn handle_meta_msg<R: Runtime>(
310 &mut self,
311 runtime: &R,
312 early: bool,
313 _hopnum: Option<HopNum>,
314 msg: UnparsedRelayMsg,
315 _relay_cell_format: RelayCellFormat,
316 ) -> StdResult<(), ReactorError> {
317 match msg.cmd() {
318 RelayCmd::DROP => self.handle_drop(),
319 RelayCmd::EXTEND2 => self.extend_handler.handle_extend2(runtime, early, msg),
320 RelayCmd::TRUNCATE => self.handle_truncate(),
321 cmd => Err(internal!("relay cmd {cmd} not supported").into()),
322 }
323 }
324
325 async fn handle_forward_cell<R: Runtime>(
326 &mut self,
327 hop_mgr: &HopMgr<R>,
328 cell: RelayCircChanMsg,
329 ) -> StdResult<Option<ForwardCellDisposition>, ReactorError> {
330 use RelayCircChanMsg::*;
331
332 match cell {
333 Relay(r) => self.handle_relay_cell(hop_mgr, r.into()),
334 RelayEarly(r) => self.handle_relay_cell(hop_mgr, r.into()),
335 Destroy(d) => {
336 self.handle_destroy_cell(&d)?;
337 Ok(None)
338 }
339 PaddingNegotiate(p) => {
340 self.handle_padding_negotiate(p)?;
341 Ok(None)
342 }
343 }
344 }
345
346 fn handle_event(
347 &mut self,
348 event: Self::CircEvent,
349 ) -> StdResult<Option<BackwardReactorCmd>, ReactorError> {
350 match event {
351 CircEvent::ExtendResult(res) => self.handle_extend_result(res),
352 }
353 }
354
355 async fn outbound_chan_ready(&mut self) -> Result<()> {
356 future::poll_fn(|cx| match &mut self.outbound {
357 Some(chan) => {
358 let _ = chan.outbound_chan_tx.poll_flush_unpin(cx);
359
360 chan.outbound_chan_tx.poll_ready_unpin(cx)
361 }
362 None => {
363 Poll::Ready(Ok(()))
373 }
374 })
375 .await
376 }
377}
378
379impl ControlHandler for Forward {
380 type CtrlMsg = CtrlMsg;
381 type CtrlCmd = CtrlCmd;
382
383 fn handle_cmd(&mut self, cmd: Self::CtrlCmd) -> StdResult<(), ReactorError> {
384 let () = cmd;
385 Ok(())
386 }
387
388 fn handle_msg(&mut self, msg: Self::CtrlMsg) -> StdResult<(), ReactorError> {
389 let () = msg;
390 Ok(())
391 }
392}
393
394impl Drop for Forward {
395 fn drop(&mut self) {
396 if let Some(outbound) = self.outbound.as_mut() {
397 let _ = outbound.channel.close_circuit(outbound.circ_id);
399 }
400 }
401}