tor_cell/relaycell.rs
1//! Implementation for parsing and encoding relay cells
2
3use std::num::NonZeroU16;
4
5use crate::chancell::{BoxedCellBody, CELL_DATA_LEN};
6use derive_deftly::Deftly;
7use smallvec::{SmallVec, smallvec};
8use tor_bytes::{EncodeError, EncodeResult, Error, Result};
9use tor_bytes::{Reader, Writer};
10use tor_error::internal;
11use tor_memquota::derive_deftly_template_HasMemoryCost;
12
13use caret::caret_int;
14use rand::{CryptoRng, Rng};
15
16#[cfg(feature = "conflux")]
17pub mod conflux;
18pub mod extend;
19mod extlist;
20pub mod flow_ctrl;
21#[cfg(feature = "hs")]
22pub mod hs;
23pub mod msg;
24#[cfg(feature = "experimental-udp")]
25pub mod udp;
26
27pub use extlist::UnrecognizedExt;
28
29caret_int! {
30 /// A command that identifies the type of a relay cell
31 #[derive(Deftly)]
32 #[derive_deftly(HasMemoryCost)]
33 pub struct RelayCmd(u8) {
34 /// Start a new stream
35 BEGIN = 1,
36 /// Data on a stream
37 DATA = 2,
38 /// Close a stream
39 END = 3,
40 /// Acknowledge a BEGIN; stream is open
41 CONNECTED = 4,
42 /// Used for flow control
43 SENDME = 5,
44 /// Extend a circuit to a new hop; deprecated
45 EXTEND = 6,
46 /// Reply to EXTEND handshake; deprecated
47 EXTENDED = 7,
48 /// Partially close a circuit
49 TRUNCATE = 8,
50 /// Circuit has been partially closed
51 TRUNCATED = 9,
52 /// Padding cell
53 DROP = 10,
54 /// Start a DNS lookup
55 RESOLVE = 11,
56 /// Reply to a DNS lookup
57 RESOLVED = 12,
58 /// Start a directory stream
59 BEGIN_DIR = 13,
60 /// Extend a circuit to a new hop
61 EXTEND2 = 14,
62 /// Reply to an EXTEND2 cell.
63 EXTENDED2 = 15,
64
65 /// NOTE: UDP command are reserved but only used with experimental-udp feature
66
67 /// UDP: Start of a stream
68 CONNECT_UDP = 16,
69 /// UDP: Acknowledge a CONNECT_UDP. Stream is open.
70 CONNECTED_UDP = 17,
71 /// UDP: Data on a UDP stream.
72 DATAGRAM = 18,
73
74 /// CONFLUX: Link circuits together at the receiving endpoint.
75 CONFLUX_LINK = 19,
76 /// CONFLUX: Confirm that the circuits were linked.
77 CONFLUX_LINKED = 20,
78 /// CONFLUX: Acknowledge the linkage of the circuits, for RTT measurement.
79 CONFLUX_LINKED_ACK = 21,
80 /// CONFLUX: Switch to another leg in an already linked circuit construction.
81 CONFLUX_SWITCH = 22,
82
83 /// HS: establish an introduction point.
84 ESTABLISH_INTRO = 32,
85 /// HS: establish a rendezvous point.
86 ESTABLISH_RENDEZVOUS = 33,
87 /// HS: send introduction (client to introduction point)
88 INTRODUCE1 = 34,
89 /// HS: send introduction (introduction point to service)
90 INTRODUCE2 = 35,
91 /// HS: connect rendezvous point (service to rendezvous point)
92 RENDEZVOUS1 = 36,
93 /// HS: connect rendezvous point (rendezvous point to client)
94 RENDEZVOUS2 = 37,
95 /// HS: Response to ESTABLISH_INTRO
96 INTRO_ESTABLISHED = 38,
97 /// HS: Response to ESTABLISH_RENDEZVOUS
98 RENDEZVOUS_ESTABLISHED = 39,
99 /// HS: Response to INTRODUCE1 from introduction point to client
100 INTRODUCE_ACK = 40,
101
102 /// Padding: declare what kind of padding we want
103 PADDING_NEGOTIATE = 41,
104 /// Padding: reply to a PADDING_NEGOTIATE
105 PADDING_NEGOTIATED = 42,
106
107 /// Flow control: rate update (transmit off)
108 XOFF = 43,
109 /// Flow control: rate update (transmit on with rate limit)
110 XON = 44,
111 }
112}
113
114/// Possible requirements on stream IDs for a relay command.
115enum StreamIdReq {
116 /// Can only be used with a stream ID of 0
117 WantNone,
118 /// Can only be used with a stream ID that isn't 0
119 WantSome,
120 /// Can be used with any stream ID.
121 ///
122 /// This result is impossible with `RelayCellFormat::V1`.
123 Any,
124 /// Unrecognized; might be used with a stream ID or without.
125 Unrecognized,
126}
127
128impl RelayCmd {
129 /// Check whether this command requires a certain kind of
130 /// StreamId in the provided `format`, and return a corresponding StreamIdReq.
131 ///
132 /// If `format` is None, return a result that is correct for _any_ version.
133 fn expects_streamid(self, format: Option<RelayCellFormat>) -> StreamIdReq {
134 match self {
135 RelayCmd::BEGIN
136 | RelayCmd::DATA
137 | RelayCmd::END
138 | RelayCmd::CONNECTED
139 | RelayCmd::RESOLVE
140 | RelayCmd::RESOLVED
141 | RelayCmd::BEGIN_DIR
142 | RelayCmd::XOFF
143 | RelayCmd::XON => StreamIdReq::WantSome,
144 // NOTE: Even when a RelayCmd is not implemented (like these UDP-based commands),
145 // we need to implement expects_streamid() unconditionally.
146 // Otherwise we leak more information than necessary
147 // when parsing RelayCellFormat::V1 cells.
148 RelayCmd::CONNECT_UDP | RelayCmd::CONNECTED_UDP | RelayCmd::DATAGRAM => {
149 StreamIdReq::WantSome
150 }
151 RelayCmd::EXTEND
152 | RelayCmd::EXTENDED
153 | RelayCmd::TRUNCATE
154 | RelayCmd::TRUNCATED
155 | RelayCmd::DROP
156 | RelayCmd::EXTEND2
157 | RelayCmd::EXTENDED2
158 | RelayCmd::CONFLUX_LINK
159 | RelayCmd::CONFLUX_LINKED
160 | RelayCmd::CONFLUX_LINKED_ACK
161 | RelayCmd::CONFLUX_SWITCH
162 | RelayCmd::ESTABLISH_INTRO
163 | RelayCmd::ESTABLISH_RENDEZVOUS
164 | RelayCmd::INTRODUCE1
165 | RelayCmd::INTRODUCE2
166 | RelayCmd::RENDEZVOUS1
167 | RelayCmd::RENDEZVOUS2
168 | RelayCmd::INTRO_ESTABLISHED
169 | RelayCmd::RENDEZVOUS_ESTABLISHED
170 | RelayCmd::INTRODUCE_ACK => StreamIdReq::WantNone,
171 RelayCmd::SENDME => match format {
172 // There are no stream-level SENDMES in V1, since CC is mandatory.
173 // Further, the 'Any' result is not possible with V1, since
174 // we need be able to decide whether a stream ID is present
175 // from the value of the command.
176 Some(RelayCellFormat::V1) => StreamIdReq::WantNone,
177 // In V0, CC is not mandatory, so stream-level SENDMES are possible.
178 Some(RelayCellFormat::V0) => StreamIdReq::Any,
179 // When we're checking for general compatibility, we need to allow V0 or V1.
180 None => StreamIdReq::Any,
181 },
182 _ => StreamIdReq::Unrecognized,
183 }
184 }
185 /// Return true if this command is one that accepts the particular
186 /// stream ID `id`.
187 ///
188 /// Note that this method does not consider the [`RelayCellFormat`] in use:
189 /// it will return "true" for _any_ stream ID if the command is `SENDME`,
190 /// and if the command is unrecognized.
191 pub fn accepts_streamid_val(self, id: Option<StreamId>) -> bool {
192 match self.expects_streamid(None) {
193 StreamIdReq::WantNone => id.is_none(),
194 StreamIdReq::WantSome => id.is_some(),
195 StreamIdReq::Any => true,
196 StreamIdReq::Unrecognized => true,
197 }
198 }
199}
200
201/// Identify a single stream on a circuit.
202///
203/// These identifiers are local to each hop on a circuit.
204/// This can't be zero; if you need something that can be zero in the protocol,
205/// use `Option<StreamId>`.
206#[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Debug, Hash, Deftly)]
207#[derive_deftly(HasMemoryCost)]
208pub struct StreamId(NonZeroU16);
209
210impl From<NonZeroU16> for StreamId {
211 fn from(id: NonZeroU16) -> Self {
212 Self(id)
213 }
214}
215
216impl From<StreamId> for NonZeroU16 {
217 fn from(id: StreamId) -> NonZeroU16 {
218 id.0
219 }
220}
221
222impl From<StreamId> for u16 {
223 fn from(id: StreamId) -> u16 {
224 id.0.get()
225 }
226}
227
228impl std::fmt::Display for StreamId {
229 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
230 self.0.fmt(f)
231 }
232}
233
234impl StreamId {
235 /// Creates a `StreamId` for non-zero `stream_id`.
236 ///
237 /// Returns `None` when `stream_id` is zero. Messages with a zero/None stream ID
238 /// apply to the circuit as a whole instead of a particular stream.
239 pub fn new(stream_id: u16) -> Option<Self> {
240 NonZeroU16::new(stream_id).map(Self)
241 }
242
243 /// Convenience function to convert to a `u16`; `None` is mapped to 0.
244 pub fn get_or_zero(stream_id: Option<Self>) -> u16 {
245 match stream_id {
246 Some(stream_id) => stream_id.0.get(),
247 None => 0,
248 }
249 }
250}
251
252/// Specifies which encoding version of RelayCell to use.
253#[non_exhaustive]
254#[derive(Copy, Clone, Debug)]
255pub enum RelayCellFormat {
256 /// This is the "legacy" pre-prop340 format. No packing or fragmentation.
257 V0,
258 /// A "transitional" format for use with Counter Galois Onion encryption.
259 ///
260 /// It provides a 16-byte tag field, and a simplified layout for the rest of
261 /// the cell.
262 V1,
263}
264
265/// Internal decoder state.
266#[derive(Clone, Debug)]
267enum RelayCellDecoderInternal {
268 /// Internal state for `RelayCellFormat::V0`
269 V0,
270 /// Internal state for `RelayCellFormat::V1`
271 V1,
272}
273
274// TODO prop340: We should also fuzz RelayCellDecoder, but not in this fuzzer.
275
276/// Decodes a stream of relay cell bodies into `UnparsedRelayMsg`s.
277#[derive(Clone, Debug)]
278pub struct RelayCellDecoder {
279 /// Internal representation.
280 internal: RelayCellDecoderInternal,
281}
282
283impl RelayCellDecoder {
284 /// Returns a new `Decoder`, handling a stream of relay cells
285 /// of the given `version`.
286 pub fn new(version: RelayCellFormat) -> Self {
287 match version {
288 RelayCellFormat::V0 => Self {
289 internal: RelayCellDecoderInternal::V0,
290 },
291 RelayCellFormat::V1 => Self {
292 internal: RelayCellDecoderInternal::V1,
293 },
294 }
295 }
296 /// Parse a RELAY or RELAY_EARLY cell body.
297 ///
298 /// Requires that the cryptographic checks on the message have already been
299 /// performed
300 pub fn decode(&self, cell: BoxedCellBody) -> Result<RelayCellDecoderResult> {
301 let msg_internal = match &self.internal {
302 RelayCellDecoderInternal::V0 => UnparsedRelayMsgInternal::V0(cell),
303 RelayCellDecoderInternal::V1 => UnparsedRelayMsgInternal::V1(cell),
304 };
305 Ok(RelayCellDecoderResult {
306 msgs: smallvec![UnparsedRelayMsg {
307 internal: msg_internal
308 }],
309 incomplete: None,
310 })
311 }
312 /// Returns the `IncompleteRelayMsgInfo` describing the partial
313 /// (fragmented) relay message at the end of the so-far-processed relay cell
314 /// stream.
315 pub fn incomplete_info(&self) -> Option<IncompleteRelayMsgInfo> {
316 match &self.internal {
317 // V0 and V1 don't support fragmentation, so there is never a pending fragment.
318 RelayCellDecoderInternal::V0 | RelayCellDecoderInternal::V1 => None,
319 }
320 }
321}
322
323/// Result of calling `RelayCellDecoder::decode`.
324#[derive(Debug)]
325pub struct RelayCellDecoderResult {
326 /// Complete messages obtained by decoding the cell. i.e. messages
327 /// that were completely contained within the cell, or for which the cell
328 /// contained the final fragment.
329 msgs: SmallVec<[UnparsedRelayMsg; 1]>,
330 /// Description of the partial message at the end of the cell, if any.
331 incomplete: Option<IncompleteRelayMsgInfo>,
332}
333
334impl RelayCellDecoderResult {
335 /// Returns a non-empty iterator over commands in relay messages that the
336 /// cell producing this result contained *any* part of. i.e. this includes
337 /// the command of "head", "middle", and/or "tail" message fragments that
338 /// were in the cell.
339 pub fn cmds(&self) -> impl Iterator<Item = RelayCmd> + '_ {
340 let complete_msg_cmds = self.msgs.iter().map(|m| m.cmd());
341 let partial_msg_cmd = self.incomplete.as_ref().map(|c| c.cmd());
342 complete_msg_cmds.chain(partial_msg_cmd)
343 }
344 /// Converts `self` to an iterator over the complete messages, and metadata
345 /// about the trailing incomplete message (as for `Self::incomplete_info`),
346 /// if any.
347 pub fn into_parts(
348 self,
349 ) -> (
350 impl Iterator<Item = UnparsedRelayMsg>,
351 Option<IncompleteRelayMsgInfo>,
352 ) {
353 (self.msgs.into_iter(), self.incomplete)
354 }
355 /// Returns the `IncompleteRelayMsgInfo` describing the incomplete
356 /// relay message that this cell contained a fragment of, if any.
357 ///
358 /// Note that:
359 /// * This does not describe a fragment that includes the end of the relay
360 /// message, since the message is then complete.
361 /// * This *does* include a fragment that continues, but does not complete,
362 /// a message started in an earlier relay cell.
363 /// * There is at most one such incomplete relay message, since no current
364 /// relay cell format supports starting a new message before completing the
365 /// previous one.
366 pub fn incomplete_info(&self) -> Option<IncompleteRelayMsgInfo> {
367 self.incomplete.clone()
368 }
369
370 /// Return true if this consists of nothing but padding.
371 pub fn is_padding(&self) -> bool {
372 // If all the messages we have are padding...
373 self.msgs.iter().all(|m| m.cmd() == RelayCmd::DROP) &&
374 // ... and any pending incomplete message is either absent or is padding...
375 self.incomplete
376 .as_ref()
377 .is_none_or(|incomplete| incomplete.cmd() == RelayCmd::DROP)
378 // ... then this is padding.
379 }
380}
381
382/// Information about a relay message for which we don't yet have the complete body.
383#[derive(Clone, Debug)]
384pub struct IncompleteRelayMsgInfo {
385 /// The message's command.
386 cmd: RelayCmd,
387 /// The message's stream ID, if any.
388 stream_id: Option<StreamId>,
389 /// The total number of bytes in the body of the message.
390 total_msg_len: usize,
391 /// The number of bytes of the body of the message that we've decoded so
392 /// far.
393 num_bytes_present: usize,
394}
395
396impl IncompleteRelayMsgInfo {
397 /// Returns the message's command.
398 pub fn cmd(&self) -> RelayCmd {
399 self.cmd
400 }
401 /// Returns the message's `StreamId`, if any.
402 pub fn stream_id(&self) -> Option<StreamId> {
403 self.stream_id
404 }
405 /// Returns the total size of the complete message body.
406 pub fn total_msg_len(&self) -> usize {
407 self.total_msg_len
408 }
409 /// Returns the number of bytes of the message body that we have so far.
410 pub fn num_bytes_present(&self) -> usize {
411 self.num_bytes_present
412 }
413 /// Returns the number of bytes of the message body that we still need.
414 pub fn num_bytes_missing(&self) -> usize {
415 self.total_msg_len - self.num_bytes_present
416 }
417}
418
419/// Internal representation of an `UnparsedRelayMsg`.
420#[derive(Clone, Debug, Deftly)]
421#[derive_deftly(HasMemoryCost)]
422enum UnparsedRelayMsgInternal {
423 /// For `RelayCellFormat::V0` we can avoid copying data around by just
424 /// storing the original cell body here.
425 // NOTE: we could also have a separate command and stream ID field here, but
426 // we expect to be working with a TON of these, so we will be mildly
427 // over-optimized and just peek into the body.
428 //
429 // It *is* a bit ugly to have to encode so much knowledge about the format in
430 // different functions here, but that information shouldn't leak out of this module.
431 V0(BoxedCellBody),
432
433 /// For `V1` we can also avoid copies, since there is still exactly one
434 /// relay message per cell.
435 V1(BoxedCellBody),
436}
437
438/// An enveloped relay message that has not yet been fully parsed, but where we
439/// have access to the command, stream ID, and payload data length for dispatching
440/// and congestion control purposes.
441#[derive(Clone, Debug, Deftly)]
442#[derive_deftly(HasMemoryCost)]
443pub struct UnparsedRelayMsg {
444 /// The internal representation.
445 internal: UnparsedRelayMsgInternal,
446}
447
448/// Const helper to find the min between three u16 values.
449const fn min(a: u16, b: u16, c: u16) -> u16 {
450 const fn min_2(a: u16, b: u16) -> u16 {
451 if a < b { a } else { b }
452 }
453 min_2(a, min_2(b, c))
454}
455
456/// Const helper to find the max between three u16 values.
457const fn max(a: u16, b: u16, c: u16) -> u16 {
458 const fn max_2(a: u16, b: u16) -> u16 {
459 if a > b { a } else { b }
460 }
461 max_2(a, max_2(b, c))
462}
463
464/// Position of the stream ID within the V0 cell body.
465const STREAM_ID_OFFSET_V0: usize = 3;
466
467/// Position of the stream ID within the V1 cell body, if it is present.
468const STREAM_ID_OFFSET_V1: usize = 16 + 1 + 2; // tag, command, length.
469
470/// Position of the payload data length within the V0 cell body.
471const LENGTH_OFFSET_V0: usize = 1 + 2 + 2 + 4; // command, recognized, stream_id, digest.
472
473/// Position of the payload data length within the V1 cell body.
474const LENGTH_OFFSET_V1: usize = 16 + 1; // tag, command.
475
476/// Position of the payload data within the V0 cell body.
477const PAYLOAD_OFFSET_V0: usize = LENGTH_OFFSET_V0 + 2; // (everything before length), length.
478
479/// Position of the payload data within the V1 cell body, when not including a stream ID.
480const PAYLOAD_OFFSET_V1_WITHOUT_STREAM_ID: usize = LENGTH_OFFSET_V1 + 2; // (everything before length), length.
481
482/// Position of the payload data within the V1 cell body, when including a stream ID.
483const PAYLOAD_OFFSET_V1_WITH_STREAM_ID: usize = LENGTH_OFFSET_V1 + 2 + 2; // (everything before length), length, stream_id.
484
485/// Max amount of payload data that can be stored in a V0 cell body.
486const PAYLOAD_MAX_SIZE_V0: u16 = BODY_MAX_LEN_V0 - (PAYLOAD_OFFSET_V0 as u16);
487
488/// Max amount of payload data that can be stored in a V1 cell body, when not including a stream ID.
489const PAYLOAD_MAX_SIZE_V1_WITHOUT_STREAM_ID: u16 =
490 BODY_MAX_LEN_V1 - (PAYLOAD_OFFSET_V1_WITHOUT_STREAM_ID as u16);
491
492/// Max amount of payload data that can be stored in a V1 cell body, when including a stream ID.
493const PAYLOAD_MAX_SIZE_V1_WITH_STREAM_ID: u16 =
494 BODY_MAX_LEN_V1 - (PAYLOAD_OFFSET_V1_WITH_STREAM_ID as u16);
495
496/// The maximum length of a V0 cell message body.
497const BODY_MAX_LEN_V0: u16 = 509;
498
499/// The maximum length of a V1 cell message body.
500const BODY_MAX_LEN_V1: u16 = 509;
501
502/// The maximum amount of payload data that can fit within all cell body types.
503pub const PAYLOAD_MAX_SIZE_ALL: u16 = min(
504 PAYLOAD_MAX_SIZE_V0,
505 PAYLOAD_MAX_SIZE_V1_WITH_STREAM_ID,
506 PAYLOAD_MAX_SIZE_V1_WITHOUT_STREAM_ID,
507);
508
509/// The maximum amount of payload data that can fit within any cell body type.
510pub const PAYLOAD_MAX_SIZE_ANY: u16 = max(
511 PAYLOAD_MAX_SIZE_V0,
512 PAYLOAD_MAX_SIZE_V1_WITH_STREAM_ID,
513 PAYLOAD_MAX_SIZE_V1_WITHOUT_STREAM_ID,
514);
515
516impl UnparsedRelayMsg {
517 /// Wrap a BoxedCellBody as an UnparsedRelayMsg.
518 ///
519 /// Fails if the body doesn't correspond to exactly one relay message, but
520 /// doesn't parse the message itself.
521 ///
522 /// Non-test code should generally use `RelayCellDecoder` instead.
523 // Ideally we'd make this `#[cfg(test)]`, but then we wouldn't be able
524 // to use it in integration tests.
525 // https://github.com/rust-lang/rust/issues/84629
526 pub fn from_singleton_body(version: RelayCellFormat, body: BoxedCellBody) -> Result<Self> {
527 let decoder = RelayCellDecoder::new(version);
528 let res = decoder.decode(body)?;
529 let (mut msgs, incomplete) = res.into_parts();
530 let Some(msg) = msgs.next() else {
531 // There was no complete message in the cell.
532 return Err(Error::MissingData);
533 };
534 if incomplete.is_some() {
535 // There was an incomplete message at the end of the cell.
536 return Err(Error::ExtraneousBytes);
537 }
538 if msgs.next().is_some() {
539 // There was more than one message in the cell.
540 return Err(Error::ExtraneousBytes);
541 }
542 Ok(msg)
543 }
544
545 /// Return the command for this cell.
546 pub fn cmd(&self) -> RelayCmd {
547 match &self.internal {
548 UnparsedRelayMsgInternal::V0(body) => {
549 /// Position of the command within the v0 cell body.
550 const CMD_OFFSET: usize = 0;
551 body[CMD_OFFSET].into()
552 }
553 UnparsedRelayMsgInternal::V1(body) => {
554 /// Position of the command within the v1 body.
555 const CMD_OFFSET: usize = 16;
556 body[CMD_OFFSET].into()
557 }
558 }
559 }
560 /// Return the stream ID for the stream that this msg corresponds to, if any.
561 pub fn stream_id(&self) -> Option<StreamId> {
562 match &self.internal {
563 UnparsedRelayMsgInternal::V0(body) => StreamId::new(u16::from_be_bytes(
564 body[STREAM_ID_OFFSET_V0..STREAM_ID_OFFSET_V0 + 2]
565 .try_into()
566 .expect("two-byte slice was not two bytes long!?"),
567 )),
568 UnparsedRelayMsgInternal::V1(body) => {
569 match self.cmd().expects_streamid(Some(RelayCellFormat::V1)) {
570 StreamIdReq::WantNone => None,
571 StreamIdReq::Unrecognized | StreamIdReq::Any => None,
572 StreamIdReq::WantSome => StreamId::new(u16::from_be_bytes(
573 body[STREAM_ID_OFFSET_V1..STREAM_ID_OFFSET_V1 + 2]
574 .try_into()
575 .expect("two-byte slice was not two bytes long!?"),
576 )),
577 }
578 }
579 }
580 }
581 /// Return the "length" field of a data cell, or 0 if not a data cell.
582 ///
583 /// This is the size of the cell data (the "data" field), not the size of the cell.
584 ///
585 /// If the field value is invalid (for example >509 for V0 cells), an error will be returned.
586 pub fn data_len(&self) -> Result<u16> {
587 if self.cmd() != RelayCmd::DATA {
588 return Ok(0);
589 }
590
591 let bytes: [u8; 2] = match &self.internal {
592 UnparsedRelayMsgInternal::V0(body) => &body[LENGTH_OFFSET_V0..LENGTH_OFFSET_V0 + 2],
593 UnparsedRelayMsgInternal::V1(body) => &body[LENGTH_OFFSET_V1..LENGTH_OFFSET_V1 + 2],
594 }
595 .try_into()
596 .expect("two-byte slice was not two bytes long!?");
597
598 let len = u16::from_be_bytes(bytes);
599
600 let max = match &self.internal {
601 UnparsedRelayMsgInternal::V0(_body) => BODY_MAX_LEN_V0,
602 UnparsedRelayMsgInternal::V1(_body) => BODY_MAX_LEN_V1,
603 };
604
605 if len > max {
606 // TODO: This error value isn't quite right as it has the error message "object length
607 // too large to represent as usize", which isn't what we're checking here.
608 // But it wouldn't make sense to add a different but similar variant to `Error`.
609 return Err(Error::BadLengthValue);
610 }
611
612 Ok(len)
613 }
614 /// Decode this unparsed cell into a given cell type.
615 pub fn decode<M: RelayMsg>(self) -> Result<RelayMsgOuter<M>> {
616 match self.internal {
617 UnparsedRelayMsgInternal::V0(body) => {
618 let mut reader = Reader::from_slice(body.as_ref());
619 RelayMsgOuter::decode_v0_from_reader(&mut reader)
620 }
621 UnparsedRelayMsgInternal::V1(body) => {
622 let mut reader = Reader::from_slice(body.as_ref());
623 RelayMsgOuter::decode_v1_from_reader(&mut reader)
624 }
625 }
626 }
627}
628
629/// A decoded and parsed relay message of unrestricted type,
630/// with an accompanying optional Stream ID.
631pub type AnyRelayMsgOuter = RelayMsgOuter<msg::AnyRelayMsg>;
632
633/// A deprecated name for AnyRelayMsgOuter.
634#[deprecated(note = "Use AnyRelayMsgOuter instead.")]
635pub type AnyRelayCell = AnyRelayMsgOuter;
636
637/// Trait implemented by anything that can serve as a relay message.
638///
639/// Typically, this will be [`RelayMsg`] (to represent an unrestricted relay
640/// message), or a restricted subset of `RelayMsg`.
641pub trait RelayMsg {
642 /// Return the stream command associated with this message.
643 fn cmd(&self) -> RelayCmd;
644 /// Encode the body of this message, not including command or length
645 fn encode_onto<W: tor_bytes::Writer + ?Sized>(self, w: &mut W) -> tor_bytes::EncodeResult<()>;
646 /// Extract the body of a message with command `cmd` from reader `r`.
647 fn decode_from_reader(cmd: RelayCmd, r: &mut Reader<'_>) -> Result<Self>
648 where
649 Self: Sized;
650}
651
652/// A decoded and parsed relay message, along with an optional Stream ID.
653///
654/// This type represents a message that can be sent along a
655/// circuit, along with the ID for an associated stream that the
656/// message is meant for.
657///
658/// NOTE: This name is a placeholder; we intend to replace it once we have
659/// standardized our vocabulary in this area.
660#[derive(Debug)]
661pub struct RelayMsgOuter<M> {
662 /// The stream ID for the stream that this cell corresponds to.
663 streamid: Option<StreamId>,
664 /// The relay message for this cell.
665 msg: M,
666}
667
668/// A deprecated name for RelayMsgOuter.
669#[deprecated(note = "Use RelayMsgOuter instead.")]
670pub type RelayCell<M> = RelayMsgOuter<M>;
671
672impl<M: RelayMsg> RelayMsgOuter<M> {
673 /// Construct a new relay cell.
674 pub fn new(streamid: Option<StreamId>, msg: M) -> Self {
675 RelayMsgOuter { streamid, msg }
676 }
677 /// Consume this cell and return its components.
678 pub fn into_streamid_and_msg(self) -> (Option<StreamId>, M) {
679 (self.streamid, self.msg)
680 }
681 /// Return the command for this cell.
682 pub fn cmd(&self) -> RelayCmd {
683 self.msg.cmd()
684 }
685 /// Return the stream ID for the stream that this cell corresponds to.
686 pub fn stream_id(&self) -> Option<StreamId> {
687 self.streamid
688 }
689 /// Return the underlying message for this cell.
690 pub fn msg(&self) -> &M {
691 &self.msg
692 }
693 /// Consume this cell and return the underlying message.
694 pub fn into_msg(self) -> M {
695 self.msg
696 }
697 /// Consume this relay message and encode it as a 509-byte padded cell
698 /// body.
699 //
700 // TODO prop340: This API won't work for packed or fragmented messages.
701 pub fn encode<R: Rng + CryptoRng>(
702 self,
703 format: RelayCellFormat,
704 rng: &mut R,
705 ) -> crate::Result<BoxedCellBody> {
706 /// We skip this much space before adding any random padding to the
707 /// end of the cell
708 const MIN_SPACE_BEFORE_PADDING: usize = 4;
709
710 let (mut body, enc_len) = match format {
711 RelayCellFormat::V0 => self.encode_to_cell_v0()?,
712 RelayCellFormat::V1 => self.encode_to_cell_v1()?,
713 };
714 debug_assert!(enc_len <= CELL_DATA_LEN);
715 if enc_len < CELL_DATA_LEN - MIN_SPACE_BEFORE_PADDING {
716 rng.fill_bytes(&mut body[enc_len + MIN_SPACE_BEFORE_PADDING..]);
717 }
718
719 Ok(body)
720 }
721
722 /// Consume a relay cell and return its contents, encoded for use
723 /// in a RELAY or RELAY_EARLY cell.
724 fn encode_to_cell_v0(self) -> EncodeResult<(BoxedCellBody, usize)> {
725 // NOTE: This implementation is a bit optimized, since it happens to
726 // literally every relay cell that we produce.
727
728 // TODO -NM: Add a specialized implementation for making a DATA cell from
729 // a body?
730
731 /// The position of the length field within a relay cell.
732 const LEN_POS: usize = 9;
733 /// The position of the body a relay cell.
734 const BODY_POS: usize = 11;
735
736 let body = BodyWrapper(Box::new([0_u8; BODY_MAX_LEN_V0 as usize]));
737
738 let mut w = crate::slicewriter::SliceWriter::new(body);
739 w.write_u8(self.msg.cmd().into());
740 w.write_u16(0); // "Recognized"
741 w.assert_offset_is(STREAM_ID_OFFSET_V0);
742 w.write_u16(StreamId::get_or_zero(self.streamid));
743 w.write_u32(0); // Digest
744 // (It would be simpler to use NestedWriter at this point, but it uses an internal Vec that we are trying to avoid.)
745 w.assert_offset_is(LEN_POS);
746 w.write_u16(0); // Length.
747 w.assert_offset_is(BODY_POS);
748 self.msg.encode_onto(&mut w)?; // body
749 let (mut body, written) = w.try_unwrap().map_err(|_| {
750 EncodeError::Bug(internal!(
751 "Encoding of relay message was too long to fit into a cell!"
752 ))
753 })?;
754 let payload_len = written - BODY_POS;
755 debug_assert!(payload_len < u16::MAX as usize);
756 *(<&mut [u8; 2]>::try_from(&mut body.0[LEN_POS..LEN_POS + 2])
757 .expect("Two-byte slice was not two bytes long!?")) =
758 (payload_len as u16).to_be_bytes();
759 Ok((body.0, written))
760 }
761
762 /// Consume a relay cell and return its contents, encoded for use
763 /// in a RELAY or RELAY_EARLY cell.
764 fn encode_to_cell_v1(self) -> EncodeResult<(BoxedCellBody, usize)> {
765 // NOTE: This implementation is a bit optimized, since it happens to
766 // literally every relay cell that we produce.
767 // TODO -NM: Add a specialized implementation for making a DATA cell from
768 // a body?
769
770 /// Position of the length field within the cell.
771 const LEN_POS_V1: usize = 16 + 1; // Skipping tag, command.
772
773 let cmd = self.msg.cmd();
774 let body = BodyWrapper(Box::new([0_u8; BODY_MAX_LEN_V1 as usize]));
775 let mut w = crate::slicewriter::SliceWriter::new(body);
776 w.advance(16); // Tag: 16 bytes
777 w.write_u8(cmd.get()); // Command: 1 byte.
778 w.assert_offset_is(LEN_POS_V1);
779 w.advance(2); // Length: 2 bytes.
780 let mut body_pos = 16 + 1 + 2;
781 match (
782 cmd.expects_streamid(Some(RelayCellFormat::V1)),
783 self.streamid,
784 ) {
785 (StreamIdReq::WantNone, None) => {}
786 (StreamIdReq::WantSome, Some(id)) => {
787 w.write_u16(id.into());
788 body_pos += 2;
789 }
790 (_, id) => {
791 return Err(EncodeError::Bug(internal!(
792 "Tried to encode invalid stream ID {id:?} for {cmd}"
793 )));
794 }
795 }
796 w.assert_offset_is(body_pos);
797
798 self.msg.encode_onto(&mut w)?; // body
799 let (mut body, written) = w.try_unwrap().map_err(|_| {
800 EncodeError::Bug(internal!(
801 "Encoding of relay message was too long to fit into a cell!"
802 ))
803 })?;
804 let payload_len = written - body_pos;
805 debug_assert!(payload_len < u16::MAX as usize);
806 *(<&mut [u8; 2]>::try_from(&mut body.0[LEN_POS_V1..LEN_POS_V1 + 2])
807 .expect("Two-byte slice was not two bytes long!?")) =
808 (payload_len as u16).to_be_bytes();
809 Ok((body.0, written))
810 }
811
812 /// Parse a RELAY or RELAY_EARLY cell body into a RelayMsgOuter.
813 /// Requires that the cryptographic checks on the message have already been
814 /// performed
815 ///
816 /// Fails if the cell doesn't contain exactly one message.
817 ///
818 /// Non-test code should generally use `RelayCellDecoder` instead.
819 // Ideally we'd make this `#[cfg(test)]`, but then we wouldn't be able
820 // to use it in integration tests.
821 // https://github.com/rust-lang/rust/issues/84629
822 #[allow(clippy::needless_pass_by_value)] // TODO this will go away soon.
823 pub fn decode_singleton(version: RelayCellFormat, body: BoxedCellBody) -> Result<Self> {
824 let unparsed_msg = UnparsedRelayMsg::from_singleton_body(version, body)?;
825 unparsed_msg.decode()
826 }
827 /// Parse a `RelayCellFormat::V0` RELAY or RELAY_EARLY cell body into a
828 /// RelayMsgOuter from a reader.
829 ///
830 /// Requires that the cryptographic checks on the message have already been
831 /// performed
832 fn decode_v0_from_reader(r: &mut Reader<'_>) -> Result<Self> {
833 let cmd = r.take_u8()?.into();
834 r.advance(2)?; // "recognized"
835 let streamid = StreamId::new(r.take_u16()?);
836 r.advance(4)?; // digest
837 let len = r.take_u16()? as usize;
838 if r.remaining() < len {
839 return Err(Error::InvalidMessage(
840 "Insufficient data in relay cell".into(),
841 ));
842 }
843 r.truncate(len);
844 let msg = M::decode_from_reader(cmd, r)?;
845 Ok(Self { streamid, msg })
846 }
847
848 /// Parse a `RelayCellFormat::V1` RELAY or RELAY_EARLY cell body into a
849 /// RelayMsgOuter from a reader.
850 ///
851 /// Requires that the cryptographic checks on the message have already been
852 /// performed.
853 fn decode_v1_from_reader(r: &mut Reader<'_>) -> Result<Self> {
854 r.advance(16)?; // Tag
855 let cmd: RelayCmd = r.take_u8()?.into();
856 let len = r.take_u16()?.into();
857 let streamid = match cmd.expects_streamid(Some(RelayCellFormat::V1)) {
858 // If no stream ID is expected, then the body begins immediately.
859 StreamIdReq::WantNone => None,
860 // In this case, a stream ID _is_ expected.
861 //
862 // (If it happens to be zero, we will reject the message,
863 // since zero is never a stream ID.)
864 StreamIdReq::WantSome => Some(StreamId::new(r.take_u16()?).ok_or_else(|| {
865 Error::InvalidMessage(
866 format!("Zero-valued stream ID with relay command {cmd}").into(),
867 )
868 })?),
869 // We treat an unrecognized command as having no stream ID.
870 //
871 // (Note: This command is truly unrecognized, and not one that we could parse
872 // differently under other circumstances.)
873 //
874 // Note that this enables a destructive fingerprinting opportunity,
875 // where an attacker can learn whether we have a version of Arti that recognizes this
876 // command, at the expense of our killing this circuit immediately if they are wrong.
877 // This is not a very bad attack.
878 //
879 // Note that StreamIdReq::Any should be impossible here, since we're using the V1
880 // format.
881 StreamIdReq::Unrecognized | StreamIdReq::Any => {
882 return Err(Error::InvalidMessage(
883 format!("Unrecognized relay command {cmd}").into(),
884 ));
885 }
886 };
887 if r.remaining() < len {
888 //
889 return Err(Error::InvalidMessage(
890 "Insufficient data in relay cell".into(),
891 ));
892 }
893 r.truncate(len);
894 let msg = M::decode_from_reader(cmd, r)?;
895 Ok(Self { streamid, msg })
896 }
897}
898
899/// Wrap a BoxedCellBody and implement AsMut<[u8]>, so we can use it with `SliceWriter`.
900struct BodyWrapper(BoxedCellBody);
901impl AsMut<[u8]> for BodyWrapper {
902 fn as_mut(&mut self) -> &mut [u8] {
903 self.0.as_mut()
904 }
905}