1
//! Implementation for parsing and encoding relay cells
2

            
3
use std::num::NonZeroU16;
4

            
5
use crate::chancell::{BoxedCellBody, CELL_DATA_LEN};
6
use derive_deftly::Deftly;
7
use smallvec::{SmallVec, smallvec};
8
use tor_bytes::{EncodeError, EncodeResult, Error, Result};
9
use tor_bytes::{Reader, Writer};
10
use tor_error::internal;
11
use tor_memquota::derive_deftly_template_HasMemoryCost;
12

            
13
use caret::caret_int;
14
use rand::{CryptoRng, Rng};
15

            
16
#[cfg(feature = "conflux")]
17
pub mod conflux;
18
pub mod extend;
19
mod extlist;
20
pub mod flow_ctrl;
21
#[cfg(feature = "hs")]
22
pub mod hs;
23
pub mod msg;
24
#[cfg(feature = "experimental-udp")]
25
pub mod udp;
26

            
27
pub use extlist::UnrecognizedExt;
28

            
29
caret_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.
115
enum 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

            
128
impl 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
19026
    fn expects_streamid(self, format: Option<RelayCellFormat>) -> StreamIdReq {
134
19026
        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
10017
            | 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
7119
            | RelayCmd::INTRODUCE_ACK => StreamIdReq::WantNone,
171
1827
            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
315
                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
1512
                None => StreamIdReq::Any,
181
            },
182
63
            _ => StreamIdReq::Unrecognized,
183
        }
184
19026
    }
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
17766
    pub fn accepts_streamid_val(self, id: Option<StreamId>) -> bool {
192
17766
        match self.expects_streamid(None) {
193
6804
            StreamIdReq::WantNone => id.is_none(),
194
9450
            StreamIdReq::WantSome => id.is_some(),
195
1512
            StreamIdReq::Any => true,
196
            StreamIdReq::Unrecognized => true,
197
        }
198
17766
    }
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)]
208
pub struct StreamId(NonZeroU16);
209

            
210
impl From<NonZeroU16> for StreamId {
211
52416
    fn from(id: NonZeroU16) -> Self {
212
52416
        Self(id)
213
52416
    }
214
}
215

            
216
impl From<StreamId> for NonZeroU16 {
217
19278
    fn from(id: StreamId) -> NonZeroU16 {
218
19278
        id.0
219
19278
    }
220
}
221

            
222
impl From<StreamId> for u16 {
223
126
    fn from(id: StreamId) -> u16 {
224
126
        id.0.get()
225
126
    }
226
}
227

            
228
impl std::fmt::Display for StreamId {
229
2709
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
230
2709
        self.0.fmt(f)
231
2709
    }
232
}
233

            
234
impl 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
230328
    pub fn new(stream_id: u16) -> Option<Self> {
240
230328
        NonZeroU16::new(stream_id).map(Self)
241
230328
    }
242

            
243
    /// Convenience function to convert to a `u16`; `None` is mapped to 0.
244
195804
    pub fn get_or_zero(stream_id: Option<Self>) -> u16 {
245
195804
        match stream_id {
246
178479
            Some(stream_id) => stream_id.0.get(),
247
17325
            None => 0,
248
        }
249
195804
    }
250
}
251

            
252
/// Specifies which encoding version of RelayCell to use.
253
#[non_exhaustive]
254
#[derive(Copy, Clone, Debug)]
255
pub 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)]
267
enum 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)]
278
pub struct RelayCellDecoder {
279
    /// Internal representation.
280
    internal: RelayCellDecoderInternal,
281
}
282

            
283
impl RelayCellDecoder {
284
    /// Returns a new `Decoder`, handling a stream of relay cells
285
    /// of the given `version`.
286
199206
    pub fn new(version: RelayCellFormat) -> Self {
287
199206
        match version {
288
198450
            RelayCellFormat::V0 => Self {
289
198450
                internal: RelayCellDecoderInternal::V0,
290
198450
            },
291
756
            RelayCellFormat::V1 => Self {
292
756
                internal: RelayCellDecoderInternal::V1,
293
756
            },
294
        }
295
199206
    }
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
182133
    pub fn decode(&self, cell: BoxedCellBody) -> Result<RelayCellDecoderResult> {
301
182133
        let msg_internal = match &self.internal {
302
181377
            RelayCellDecoderInternal::V0 => UnparsedRelayMsgInternal::V0(cell),
303
756
            RelayCellDecoderInternal::V1 => UnparsedRelayMsgInternal::V1(cell),
304
        };
305
        Ok(RelayCellDecoderResult {
306
182133
            msgs: smallvec![UnparsedRelayMsg {
307
                internal: msg_internal
308
            }],
309
182133
            incomplete: None,
310
        })
311
182133
    }
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)]
325
pub 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

            
334
impl 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
17514
    pub fn cmds(&self) -> impl Iterator<Item = RelayCmd> + '_ {
340
17514
        let complete_msg_cmds = self.msgs.iter().map(|m| m.cmd());
341
17514
        let partial_msg_cmd = self.incomplete.as_ref().map(|c| c.cmd());
342
17514
        complete_msg_cmds.chain(partial_msg_cmd)
343
17514
    }
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
182133
    pub fn into_parts(
348
182133
        self,
349
182133
    ) -> (
350
182133
        impl Iterator<Item = UnparsedRelayMsg>,
351
182133
        Option<IncompleteRelayMsgInfo>,
352
182133
    ) {
353
182133
        (self.msgs.into_iter(), self.incomplete)
354
182133
    }
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
17514
    pub fn is_padding(&self) -> bool {
372
        // If all the messages we have are padding...
373
17514
        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
17514
    }
380
}
381

            
382
/// Information about a relay message for which we don't yet have the complete body.
383
#[derive(Clone, Debug)]
384
pub 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

            
396
impl 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)]
422
enum 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)]
443
pub struct UnparsedRelayMsg {
444
    /// The internal representation.
445
    internal: UnparsedRelayMsgInternal,
446
}
447

            
448
/// Const helper to find the min between three u16 values.
449
const 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.
457
const 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.
465
const STREAM_ID_OFFSET_V0: usize = 3;
466

            
467
/// Position of the stream ID within the V1 cell body, if it is present.
468
const STREAM_ID_OFFSET_V1: usize = 16 + 1 + 2; // tag, command, length.
469

            
470
/// Position of the payload data length within the V0 cell body.
471
const 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.
474
const LENGTH_OFFSET_V1: usize = 16 + 1; // tag, command.
475

            
476
/// Position of the payload data within the V0 cell body.
477
const 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.
480
const 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.
483
const 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.
486
const 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.
489
const 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.
493
const 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.
497
const BODY_MAX_LEN_V0: u16 = 509;
498

            
499
/// The maximum length of a V1 cell message body.
500
const BODY_MAX_LEN_V1: u16 = 509;
501

            
502
/// The maximum amount of payload data that can fit within all cell body types.
503
pub 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.
510
pub 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

            
516
impl 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
164619
    pub fn from_singleton_body(version: RelayCellFormat, body: BoxedCellBody) -> Result<Self> {
527
164619
        let decoder = RelayCellDecoder::new(version);
528
164619
        let res = decoder.decode(body)?;
529
164619
        let (mut msgs, incomplete) = res.into_parts();
530
164619
        let Some(msg) = msgs.next() else {
531
            // There was no complete message in the cell.
532
            return Err(Error::MissingData);
533
        };
534
164619
        if incomplete.is_some() {
535
            // There was an incomplete message at the end of the cell.
536
            return Err(Error::ExtraneousBytes);
537
164619
        }
538
164619
        if msgs.next().is_some() {
539
            // There was more than one message in the cell.
540
            return Err(Error::ExtraneousBytes);
541
164619
        }
542
164619
        Ok(msg)
543
164619
    }
544

            
545
    /// Return the command for this cell.
546
203301
    pub fn cmd(&self) -> RelayCmd {
547
203301
        match &self.internal {
548
            UnparsedRelayMsgInternal::V0(body) => {
549
                /// Position of the command within the v0 cell body.
550
                const CMD_OFFSET: usize = 0;
551
202293
                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
1008
                body[CMD_OFFSET].into()
557
            }
558
        }
559
203301
    }
560
    /// Return the stream ID for the stream that this msg corresponds to, if any.
561
17892
    pub fn stream_id(&self) -> Option<StreamId> {
562
17892
        match &self.internal {
563
17640
            UnparsedRelayMsgInternal::V0(body) => StreamId::new(u16::from_be_bytes(
564
17640
                body[STREAM_ID_OFFSET_V0..STREAM_ID_OFFSET_V0 + 2]
565
17640
                    .try_into()
566
17640
                    .expect("two-byte slice was not two bytes long!?"),
567
17640
            )),
568
            UnparsedRelayMsgInternal::V1(body) => {
569
252
                match self.cmd().expects_streamid(Some(RelayCellFormat::V1)) {
570
126
                    StreamIdReq::WantNone => None,
571
                    StreamIdReq::Unrecognized | StreamIdReq::Any => None,
572
126
                    StreamIdReq::WantSome => StreamId::new(u16::from_be_bytes(
573
126
                        body[STREAM_ID_OFFSET_V1..STREAM_ID_OFFSET_V1 + 2]
574
126
                            .try_into()
575
126
                            .expect("two-byte slice was not two bytes long!?"),
576
126
                    )),
577
                }
578
            }
579
        }
580
17892
    }
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
13860
    pub fn data_len(&self) -> Result<u16> {
587
13860
        if self.cmd() != RelayCmd::DATA {
588
7686
            return Ok(0);
589
6174
        }
590

            
591
6174
        let bytes: [u8; 2] = match &self.internal {
592
5985
            UnparsedRelayMsgInternal::V0(body) => &body[LENGTH_OFFSET_V0..LENGTH_OFFSET_V0 + 2],
593
189
            UnparsedRelayMsgInternal::V1(body) => &body[LENGTH_OFFSET_V1..LENGTH_OFFSET_V1 + 2],
594
        }
595
        .try_into()
596
6174
        .expect("two-byte slice was not two bytes long!?");
597

            
598
6174
        let len = u16::from_be_bytes(bytes);
599

            
600
6174
        let max = match &self.internal {
601
5985
            UnparsedRelayMsgInternal::V0(_body) => BODY_MAX_LEN_V0,
602
189
            UnparsedRelayMsgInternal::V1(_body) => BODY_MAX_LEN_V1,
603
        };
604

            
605
6174
        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
126
            return Err(Error::BadLengthValue);
610
6048
        }
611

            
612
6048
        Ok(len)
613
13860
    }
614
    /// Decode this unparsed cell into a given cell type.
615
2814
    pub fn decode<M: RelayMsg>(self) -> Result<RelayMsgOuter<M>> {
616
2814
        match self.internal {
617
            UnparsedRelayMsgInternal::V0(body) => {
618
2804
                let mut reader = Reader::from_slice(body.as_ref());
619
2804
                RelayMsgOuter::decode_v0_from_reader(&mut reader)
620
            }
621
            UnparsedRelayMsgInternal::V1(body) => {
622
10
                let mut reader = Reader::from_slice(body.as_ref());
623
10
                RelayMsgOuter::decode_v1_from_reader(&mut reader)
624
            }
625
        }
626
2814
    }
627
}
628

            
629
/// A decoded and parsed relay message of unrestricted type,
630
/// with an accompanying optional Stream ID.
631
pub type AnyRelayMsgOuter = RelayMsgOuter<msg::AnyRelayMsg>;
632

            
633
/// A deprecated name for AnyRelayMsgOuter.
634
#[deprecated(note = "Use AnyRelayMsgOuter instead.")]
635
pub 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`.
641
pub 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)]
661
pub 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.")]
670
pub type RelayCell<M> = RelayMsgOuter<M>;
671

            
672
impl<M: RelayMsg> RelayMsgOuter<M> {
673
    /// Construct a new relay cell.
674
3111
    pub fn new(streamid: Option<StreamId>, msg: M) -> Self {
675
3111
        RelayMsgOuter { streamid, msg }
676
3111
    }
677
    /// Consume this cell and return its components.
678
2031
    pub fn into_streamid_and_msg(self) -> (Option<StreamId>, M) {
679
2031
        (self.streamid, self.msg)
680
2031
    }
681
    /// Return the command for this cell.
682
7563
    pub fn cmd(&self) -> RelayCmd {
683
7563
        self.msg.cmd()
684
7563
    }
685
    /// Return the stream ID for the stream that this cell corresponds to.
686
2315
    pub fn stream_id(&self) -> Option<StreamId> {
687
2315
        self.streamid
688
2315
    }
689
    /// Return the underlying message for this cell.
690
2106
    pub fn msg(&self) -> &M {
691
2106
        &self.msg
692
2106
    }
693
    /// Consume this cell and return the underlying message.
694
234
    pub fn into_msg(self) -> M {
695
234
        self.msg
696
234
    }
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
3110
    pub fn encode<R: Rng + CryptoRng>(
702
3110
        self,
703
3110
        format: RelayCellFormat,
704
3110
        rng: &mut R,
705
3110
    ) -> 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
3110
        let (mut body, enc_len) = match format {
711
3104
            RelayCellFormat::V0 => self.encode_to_cell_v0()?,
712
6
            RelayCellFormat::V1 => self.encode_to_cell_v1()?,
713
        };
714
3110
        debug_assert!(enc_len <= CELL_DATA_LEN);
715
3110
        if enc_len < CELL_DATA_LEN - MIN_SPACE_BEFORE_PADDING {
716
1041
            rng.fill_bytes(&mut body[enc_len + MIN_SPACE_BEFORE_PADDING..]);
717
2069
        }
718

            
719
3110
        Ok(body)
720
3110
    }
721

            
722
    /// Consume a relay cell and return its contents, encoded for use
723
    /// in a RELAY or RELAY_EARLY cell.
724
3104
    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
3104
        let body = BodyWrapper(Box::new([0_u8; BODY_MAX_LEN_V0 as usize]));
737

            
738
3104
        let mut w = crate::slicewriter::SliceWriter::new(body);
739
3104
        w.write_u8(self.msg.cmd().into());
740
3104
        w.write_u16(0); // "Recognized"
741
3104
        w.assert_offset_is(STREAM_ID_OFFSET_V0);
742
3104
        w.write_u16(StreamId::get_or_zero(self.streamid));
743
3104
        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
3104
        w.assert_offset_is(LEN_POS);
746
3104
        w.write_u16(0); // Length.
747
3104
        w.assert_offset_is(BODY_POS);
748
3104
        self.msg.encode_onto(&mut w)?; // body
749
3104
        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
3104
        let payload_len = written - BODY_POS;
755
3104
        debug_assert!(payload_len < u16::MAX as usize);
756
3104
        *(<&mut [u8; 2]>::try_from(&mut body.0[LEN_POS..LEN_POS + 2])
757
3104
            .expect("Two-byte slice was not two bytes long!?")) =
758
3104
            (payload_len as u16).to_be_bytes();
759
3104
        Ok((body.0, written))
760
3104
    }
761

            
762
    /// Consume a relay cell and return its contents, encoded for use
763
    /// in a RELAY or RELAY_EARLY cell.
764
6
    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
6
        let cmd = self.msg.cmd();
774
6
        let body = BodyWrapper(Box::new([0_u8; BODY_MAX_LEN_V1 as usize]));
775
6
        let mut w = crate::slicewriter::SliceWriter::new(body);
776
6
        w.advance(16); // Tag: 16 bytes
777
6
        w.write_u8(cmd.get()); // Command: 1 byte.
778
6
        w.assert_offset_is(LEN_POS_V1);
779
6
        w.advance(2); //  Length: 2 bytes.
780
6
        let mut body_pos = 16 + 1 + 2;
781
6
        match (
782
6
            cmd.expects_streamid(Some(RelayCellFormat::V1)),
783
6
            self.streamid,
784
6
        ) {
785
4
            (StreamIdReq::WantNone, None) => {}
786
            (StreamIdReq::WantSome, Some(id)) => {
787
2
                w.write_u16(id.into());
788
2
                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
6
        w.assert_offset_is(body_pos);
797

            
798
6
        self.msg.encode_onto(&mut w)?; // body
799
6
        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
6
        let payload_len = written - body_pos;
805
6
        debug_assert!(payload_len < u16::MAX as usize);
806
6
        *(<&mut [u8; 2]>::try_from(&mut body.0[LEN_POS_V1..LEN_POS_V1 + 2])
807
6
            .expect("Two-byte slice was not two bytes long!?")) =
808
6
            (payload_len as u16).to_be_bytes();
809
6
        Ok((body.0, written))
810
6
    }
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
2066
    pub fn decode_singleton(version: RelayCellFormat, body: BoxedCellBody) -> Result<Self> {
824
2066
        let unparsed_msg = UnparsedRelayMsg::from_singleton_body(version, body)?;
825
2066
        unparsed_msg.decode()
826
2066
    }
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
2804
    fn decode_v0_from_reader(r: &mut Reader<'_>) -> Result<Self> {
833
2804
        let cmd = r.take_u8()?.into();
834
2804
        r.advance(2)?; // "recognized"
835
2804
        let streamid = StreamId::new(r.take_u16()?);
836
2804
        r.advance(4)?; // digest
837
2804
        let len = r.take_u16()? as usize;
838
2804
        if r.remaining() < len {
839
1
            return Err(Error::InvalidMessage(
840
1
                "Insufficient data in relay cell".into(),
841
1
            ));
842
2803
        }
843
2803
        r.truncate(len);
844
2803
        let msg = M::decode_from_reader(cmd, r)?;
845
2797
        Ok(Self { streamid, msg })
846
2804
    }
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
10
    fn decode_v1_from_reader(r: &mut Reader<'_>) -> Result<Self> {
854
10
        r.advance(16)?; // Tag
855
10
        let cmd: RelayCmd = r.take_u8()?.into();
856
10
        let len = r.take_u16()?.into();
857
10
        let streamid = match cmd.expects_streamid(Some(RelayCellFormat::V1)) {
858
            // If no stream ID is expected, then the body begins immediately.
859
4
            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
5
            StreamIdReq::WantSome => Some(StreamId::new(r.take_u16()?).ok_or_else(|| {
865
1
                Error::InvalidMessage(
866
1
                    format!("Zero-valued stream ID with relay command {cmd}").into(),
867
1
                )
868
1
            })?),
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
1
                return Err(Error::InvalidMessage(
883
1
                    format!("Unrecognized relay command {cmd}").into(),
884
1
                ));
885
            }
886
        };
887
8
        if r.remaining() < len {
888
            //
889
1
            return Err(Error::InvalidMessage(
890
1
                "Insufficient data in relay cell".into(),
891
1
            ));
892
7
        }
893
7
        r.truncate(len);
894
7
        let msg = M::decode_from_reader(cmd, r)?;
895
7
        Ok(Self { streamid, msg })
896
10
    }
897
}
898

            
899
/// Wrap a BoxedCellBody and implement AsMut<[u8]>, so we can use it with `SliceWriter`.
900
struct BodyWrapper(BoxedCellBody);
901
impl AsMut<[u8]> for BodyWrapper {
902
2495052
    fn as_mut(&mut self) -> &mut [u8] {
903
2495052
        self.0.as_mut()
904
2495052
    }
905
}