Skip to main content

tor_proto/relay/reactor/
forward.rs

1//! A relay's view of the forward (away from the client, towards the exit) state of a circuit.
2
3mod 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
21// TODO(circpad): once padding is stabilized, the padding module will be moved out of client.
22use 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
42/// Placeholder for our custom control message type.
43type CtrlMsg = ();
44
45/// Placeholder for our custom control command type.
46type CtrlCmd = ();
47
48/// The maximum number of RELAY_EARLY cells allowed on a circuit.
49///
50// TODO(relay): should we come up with a consensus parameter for this? (arti#2349)
51const MAX_RELAY_EARLY_CELLS_PER_CIRCUIT: usize = 8;
52
53/// Relay-specific state for the forward reactor.
54pub(crate) struct Forward {
55    /// An identifier for logging about this reactor's circuit.
56    unique_id: UniqId,
57    /// The circuit identifier on the inbound Tor channel.
58    circ_id: CircId,
59    /// The outbound view of this circuit, if we are not the last hop.
60    ///
61    /// Delivers cells towards the exit.
62    ///
63    /// Only set for middle relays.
64    outbound: Option<Outbound>,
65    /// The cryptographic state for this circuit for inbound cells.
66    crypto_out: Box<dyn OutboundRelayLayer + Send>,
67    /// The number of RELAY_EARLY cells we have seen so far on this circuit.
68    ///
69    /// If we see more than [`MAX_RELAY_EARLY_CELLS_PER_CIRCUIT`] RELAY_EARLY cells, we tear down the circuit.
70    relay_early_count: usize,
71    /// Helper for handling circuit extension requests.
72    ///
73    /// Used for validating EXTEND2 cells.
74    extend_handler: ExtendRequestHandler,
75}
76
77/// A type of event issued by the relay forward reactor.
78pub(crate) enum CircEvent {
79    /// The outcome of an EXTEND2 request.
80    ExtendResult(StdResult<ExtendResult, ReactorError>),
81}
82
83/// A successful circuit extension result.
84pub(crate) struct ExtendResult {
85    /// The EXTENDED2 cell to send back to the client.
86    extended2: Extended2,
87    /// The outbound channel.
88    outbound: Outbound,
89    /// The reading end of the outbound Tor channel, if we are not the last hop.
90    ///
91    /// Yields cells moving from the exit towards the client, if we are a middle relay.
92    outbound_chan_rx: CircuitRxReceiver,
93}
94
95/// The outbound view of a relay circuit.
96struct Outbound {
97    /// The circuit identifier on the outbound Tor channel.
98    circ_id: CircId,
99    /// The outbound Tor channel.
100    channel: Arc<Channel>,
101    /// The sending end of the outbound Tor channel.
102    outbound_chan_tx: ChannelSender,
103}
104
105/// The outcome of `decode_relay_cell`.
106enum CellDecodeResult {
107    /// A decrypted cell.
108    Recognized(SendmeTag, RelayCellDecoderResult),
109    /// A cell we could not decrypt.
110    Unrecognizd(RelayCellBody),
111}
112
113impl Forward {
114    /// Create a new [`Forward`].
115    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            // Initially, we are the last hop in the circuit.
138            outbound: None,
139            crypto_out,
140            relay_early_count: 0,
141            extend_handler,
142        }
143    }
144
145    /// Decode `cell`, returning its corresponding hop number, tag and decoded body.
146    fn decode_relay_cell<R: Runtime>(
147        &mut self,
148        hop_mgr: &HopMgr<R>,
149        cell: RelayMaybeEarlyChanMsg,
150    ) -> Result<(Option<HopNum>, CellDecodeResult)> {
151        // Note: the client reactor will return the actual source hopnum
152        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        // The message is addressed to us! Now it's time to handle it...
160        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    /// Handle a DROP message.
167    #[allow(clippy::unnecessary_wraps)] // Returns Err if circ-padding is enabled
168    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    /// Handle the outcome of handling an EXTEND2.
179    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    /// Handle a RELAY or RELAY_EARLY cell.
199    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    /// Handle a forward cell that we could not decrypt.
234    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            // The client shouldn't try to send us any cells before it gets
242            // an EXTENDED2 cell from us
243            return Err(Error::CircProto(
244                "Asked to forward cell before the circuit was extended?!".into(),
245            )
246            .into());
247        };
248
249        // TODO(relay): remove this log once we add some tests
250        // and confirm relaying cells works as expected
251        // (in practice it will be too noisy to be useful, even at trace level).
252        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        // Note: this future is always `Ready`, because we checked the sink for readiness
267        // before polling the input channel, so await won't block.
268        chan.outbound_chan_tx.start_send_unpin((cell, info))?;
269
270        Ok(())
271    }
272
273    /// Handle a TRUNCATE cell.
274    fn handle_truncate(&mut self) -> StdResult<(), ReactorError> {
275        // This is not strictly spec compliant,
276        // but since none of our implementations use TRUNCATE,
277        // we deem it a proto violation and shut down the circuit.
278        //
279        // TODO(spec): codify this in the spec
280        Err(Error::CircProto("TRUNCATE not allowed".into()).into())
281    }
282
283    /// Handle a DESTROY cell originating from the client.
284    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        // We don't need to send a DESTROY cell down the channel,
293        // because that's handled implicitly by our Drop implementation
294        Err(ReactorError::Shutdown)
295    }
296
297    /// Handle a PADDING_NEGOTIATE cell originating from the client.
298    #[allow(clippy::needless_pass_by_value)] // TODO(relay)
299    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                // Pedantically, if the channel doesn't exist, it can't be ready,
364                // but we have no choice here than to return Ready
365                // (returning Pending would cause the reactor to lock up).
366                //
367                // Returning ready here means the base reactor is allowed to read
368                // from its inbound channel. This is OK, because if we *do*
369                // read a cell from that channel and find ourselves needing to
370                // forward it to the next hop, we simply return a proto violation error,
371                // shutting down the reactor.
372                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            // This will send a DESTROY down the outbound channel
398            let _ = outbound.channel.close_circuit(outbound.circ_id);
399        }
400    }
401}