1
//! Encoding and decoding for relay messages
2
//!
3
//! Relay messages are sent along circuits, inside RELAY or RELAY_EARLY
4
//! cells.
5

            
6
use super::flow_ctrl::{Xoff, Xon};
7
use super::{RelayCellFormat, RelayCmd};
8
use crate::chancell::CELL_DATA_LEN;
9
use crate::chancell::msg::{
10
    DestroyReason, HandshakeType, TAP_C_HANDSHAKE_LEN, TAP_S_HANDSHAKE_LEN,
11
};
12
use caret::caret_int;
13
use derive_deftly::Deftly;
14
use std::fmt::Write;
15
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
16
use std::num::{NonZero, NonZeroU8};
17
use tor_bytes::{EncodeError, EncodeResult, Error, Result};
18
use tor_bytes::{Readable, Reader, Writeable, Writer};
19
use tor_error::internal;
20
use tor_linkspec::EncodedLinkSpec;
21
use tor_llcrypto::pk::rsa::RsaIdentity;
22
use tor_llcrypto::util::ct::CtByteArray;
23
use tor_memquota::{derive_deftly_template_HasMemoryCost, memory_cost_structural_copy};
24

            
25
use bitflags::bitflags;
26

            
27
#[cfg(feature = "conflux")]
28
pub use super::conflux::{ConfluxLink, ConfluxLinked, ConfluxLinkedAck, ConfluxSwitch};
29

            
30
#[cfg(feature = "hs")]
31
pub use super::hs::{
32
    EstablishRendezvous, IntroEstablished, Introduce1, Introduce2, IntroduceAck, Rendezvous1,
33
    Rendezvous2, RendezvousEstablished, est_intro::EstablishIntro,
34
};
35
#[cfg(feature = "experimental-udp")]
36
pub use super::udp::{ConnectUdp, ConnectedUdp, Datagram};
37

            
38
crate::restrict::restricted_msg! {
39
/// A single parsed relay message, sent or received along a circuit
40
#[derive(Debug, Clone, Deftly)]
41
#[derive_deftly(HasMemoryCost)]
42
#[non_exhaustive]
43
@omit_from "avoid_conflict_with_a_blanket_implementation"
44
pub enum AnyRelayMsg : RelayMsg {
45
    /// Create a stream
46
    Begin,
47
    /// Send data on a stream
48
    Data,
49
    /// Close a stream
50
    End,
51
    /// Successful response to a Begin message
52
    Connected,
53
    /// For flow control
54
    Sendme,
55
    /// Extend a circuit to a new hop (deprecated)
56
    Extend,
57
    /// Successful response to an Extend message (deprecated)
58
    Extended,
59
    /// Extend a circuit to a new hop
60
    Extend2,
61
    /// Successful response to an Extend2 message
62
    Extended2,
63
    /// Partially close a circuit
64
    Truncate,
65
    /// Tell the client that a circuit has been partially closed
66
    Truncated,
67
    /// Used for padding
68
    Drop,
69
    /// Launch a DNS request
70
    Resolve,
71
    /// Response to a Resolve message
72
    Resolved,
73
    /// Start a directory stream
74
    BeginDir,
75
    /// Start a UDP stream.
76
    [feature = "experimental-udp"]
77
    ConnectUdp,
78
    /// Successful response to a ConnectUdp message
79
    [feature = "experimental-udp"]
80
    ConnectedUdp,
81
    /// UDP stream data
82
    [feature = "experimental-udp"]
83
    Datagram,
84
    /// Link circuits together at the receiving endpoint
85
    [feature = "conflux"]
86
    ConfluxLink,
87
    /// Confirm that the circuits were linked
88
    [feature = "conflux"]
89
    ConfluxLinked,
90
    /// Acknowledge the linkage of the circuits, for RTT measurement.
91
    [feature = "conflux"]
92
    ConfluxLinkedAck,
93
    /// Switch to another leg in an already linked circuit construction.
94
    [feature = "conflux"]
95
    ConfluxSwitch,
96
    /// Update a stream's transmit rate limit.
97
    Xon,
98
    /// Disable transmitting on a stream.
99
    Xoff,
100
    /// Establish Introduction
101
    [feature = "hs"]
102
    EstablishIntro,
103
    /// Establish Rendezvous
104
    [feature = "hs"]
105
    EstablishRendezvous,
106
    /// Introduce1 (client to introduction point)
107
    [feature = "hs"]
108
    Introduce1,
109
    /// Introduce2 (introduction point to service)
110
    [feature = "hs"]
111
    Introduce2,
112
    /// Rendezvous1 (service to rendezvous point)
113
    [feature = "hs"]
114
    Rendezvous1,
115
    /// Rendezvous2 (rendezvous point to client)
116
    [feature = "hs"]
117
    Rendezvous2,
118
    /// Acknowledgement for EstablishIntro.
119
    [feature = "hs"]
120
    IntroEstablished,
121
    /// Acknowledgment for EstablishRendezvous.
122
    [feature = "hs"]
123
    RendezvousEstablished,
124
    /// Acknowledgement for Introduce1.
125
    [feature = "hs"]
126
    IntroduceAck,
127

            
128
    _ =>
129
    /// An unrecognized command.
130
    Unrecognized,
131
    }
132
}
133

            
134
/// Internal: traits in common different cell bodies.
135
pub trait Body: Sized {
136
    /// Decode a relay cell body from a provided reader.
137
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self>;
138
    /// Encode the body of this cell into the end of a writer.
139
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()>;
140
}
141

            
142
bitflags! {
143
    /// A set of recognized flags that can be attached to a begin cell.
144
    ///
145
    /// For historical reasons, these flags are constructed so that 0
146
    /// is a reasonable default for all of them.
147
    #[derive(Clone, Copy, Debug, PartialEq)]
148
    pub struct BeginFlags : u32 {
149
        /// The client would accept a connection to an IPv6 address.
150
        const IPV6_OKAY = (1<<0);
151
        /// The client would not accept a connection to an IPv4 address.
152
        const IPV4_NOT_OKAY = (1<<1);
153
        /// The client would rather have a connection to an IPv6 address.
154
        const IPV6_PREFERRED = (1<<2);
155
    }
156
}
157
memory_cost_structural_copy!(BeginFlags);
158
impl From<u32> for BeginFlags {
159
6615
    fn from(v: u32) -> Self {
160
6615
        BeginFlags::from_bits_truncate(v)
161
6615
    }
162
}
163

            
164
/// A preference for IPv4 vs IPv6 addresses; usable as a nicer frontend for
165
/// BeginFlags.
166
#[derive(Clone, Default, Copy, Debug, Eq, PartialEq)]
167
#[non_exhaustive]
168
pub enum IpVersionPreference {
169
    /// Only IPv4 is allowed.
170
    Ipv4Only,
171
    /// IPv4 and IPv6 are both allowed, and IPv4 is preferred.
172
    #[default]
173
    Ipv4Preferred,
174
    /// IPv4 and IPv6 are both allowed, and IPv6 is preferred.
175
    Ipv6Preferred,
176
    /// Only IPv6 is allowed.
177
    Ipv6Only,
178
}
179
impl From<IpVersionPreference> for BeginFlags {
180
2646
    fn from(v: IpVersionPreference) -> Self {
181
        use IpVersionPreference::*;
182
2646
        match v {
183
            Ipv4Only => 0.into(),
184
2646
            Ipv4Preferred => BeginFlags::IPV6_OKAY,
185
            Ipv6Preferred => BeginFlags::IPV6_OKAY | BeginFlags::IPV6_PREFERRED,
186
            Ipv6Only => BeginFlags::IPV4_NOT_OKAY,
187
        }
188
2646
    }
189
}
190

            
191
/// A Begin message creates a new data stream.
192
///
193
/// Upon receiving a Begin message, relays should try to open a new stream
194
/// for the client, if their exit policy permits, and associate it with a
195
/// new TCP connection to the target address.
196
///
197
/// If the exit decides to reject the Begin message, or if the TCP
198
/// connection fails, the exit should send an End message.
199
///
200
/// Clients should reject these messages.
201
#[derive(Debug, Clone, PartialEq, Deftly)]
202
#[derive_deftly(HasMemoryCost)]
203
pub struct Begin {
204
    /// Target address.
205
    ///
206
    /// We don't attempt to immediately decode the address since
207
    /// (1) it requires parsing which may be a little slow, and
208
    /// (2) onion services are supposed to ignore the value.
209
    addr: EncodedBeginAddr,
210
    /// Target port
211
    port: NonZero<u16>,
212
    /// Flags that describe how to resolve the address
213
    flags: BeginFlags,
214
}
215

            
216
impl Begin {
217
    /// Construct a new Begin cell.
218
    ///
219
    /// ```
220
    /// # use std::num::NonZero;
221
    /// # use tor_cell::relaycell::msg::*;
222
    /// let hostname = BeginHostname::new("example.com").unwrap();
223
    /// let addr = BeginAddr::Hostname(hostname);
224
    /// let begin = Begin::new(addr.encode(), NonZero::new(80).unwrap(), 0);
225
    /// ```
226
79
    pub fn new<F>(addr: EncodedBeginAddr, port: NonZero<u16>, flags: F) -> Self
227
79
    where
228
79
        F: Into<BeginFlags>,
229
    {
230
79
        Begin {
231
79
            addr,
232
79
            port,
233
79
            flags: flags.into(),
234
79
        }
235
79
    }
236

            
237
    /// Return the address requested in this message.
238
    ///
239
    /// Onion services should not use this:
240
    ///
241
    /// > When \[an onion\] service receives a BEGIN message, it should check its port, *and ignore
242
    /// > all other fields in the begin message*, including its address and flags.
243
441
    pub fn addr(&self) -> &EncodedBeginAddr {
244
441
        &self.addr
245
441
    }
246

            
247
    /// Return the port requested by this message.
248
    pub fn port(&self) -> NonZero<u16> {
249
        self.port
250
    }
251

            
252
    /// Return the set of flags provided in this message.
253
    pub fn flags(&self) -> BeginFlags {
254
        self.flags
255
    }
256
}
257

            
258
impl Body for Begin {
259
4914
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
260
4914
        let BeginAddrPort(addr, port) = r.extract()?;
261
4725
        let flags = if r.remaining() >= 4 { r.take_u32()? } else { 0 };
262

            
263
4725
        Ok(Begin {
264
4725
            addr,
265
4725
            port,
266
4725
            flags: flags.into(),
267
4725
        })
268
4914
    }
269
83
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
270
83
        w.write_all(&self.addr.0);
271
83
        w.write_u8(b':');
272
83
        w.write_all(self.port.to_string().as_bytes());
273
83
        w.write_u8(0);
274
83
        if self.flags.bits() != 0 {
275
62
            w.write_u32(self.flags.bits());
276
21
        }
277
83
        Ok(())
278
83
    }
279
}
280

            
281
/// Helper type for reading the NUL-terminated [`BeginAddr`] and port string from a [`Begin`]
282
/// message.
283
struct BeginAddrPort(EncodedBeginAddr, NonZero<u16>);
284

            
285
impl Readable for BeginAddrPort {
286
4914
    fn take_from(r: &mut Reader<'_>) -> Result<Self> {
287
        // TODO(nightly: slice_split_once): In the future we will hopefully be able to use
288
        // `.rsplit_once(':')` here instead, which would make this a lot cleaner.
289
        // (Alternatively, the bstr crate also has this functionality.)
290
16569
        let mut addr_port_iter = r.take_until(0)?.rsplitn(2, |c| *c == b':');
291

            
292
        // The `rsplitn(2, ...)` seems to always return at least one item,
293
        // so this error should never happen.
294
        // But we return an error instead of panicking just in case that changes since
295
        // the behaviour for edge cases like an empty string isn't documented.
296
4851
        let port = addr_port_iter
297
4851
            .next()
298
            .ok_or_else(|| internal!("expected at least one item from rsplitn()"))?;
299
4851
        let addr = addr_port_iter
300
4851
            .next()
301
            .ok_or_else(|| Error::InvalidMessage("target address in begin cell missing".into()))?;
302

            
303
        // The later `u16::parse()` allows a leading `+` which we don't want to allow.
304
4851
        if let Some(first_byte) = port.first()
305
4851
            && !first_byte.is_ascii_digit()
306
        {
307
63
            return Err(Error::InvalidMessage(
308
63
                "port in begin cell has non-digit character".into(),
309
63
            ));
310
4788
        }
311

            
312
4788
        let port = std::str::from_utf8(port)
313
            .map_err(|_| Error::InvalidMessage("port in begin cell not utf8".into()))?;
314

            
315
        // TODO(nightly: int_from_ascii): In the future we will hopefully be able to skip the utf-8
316
        // conversion and use `u16::from_ascii()` instead of `parse()`.
317
4788
        let port = port
318
4788
            .parse()
319
            .map_err(|_| Error::InvalidMessage("port in begin cell not a valid port".into()))?;
320

            
321
        // torspec:
322
        //
323
        // > PORT is a decimal integer between 1 and 65535, inclusive
324
4788
        let port = NonZero::new(port)
325
63
            .ok_or_else(|| Error::InvalidMessage("port in begin cell is zero".into()))?;
326

            
327
4725
        Ok(Self(EncodedBeginAddr(addr.to_owned()), port))
328
4914
    }
329
}
330

            
331
/// Target address of a [`Begin`] message exactly as it was read,
332
/// or should be written, over the wire.
333
///
334
/// This can only be constructed through [`BeginAddr::encode()`]
335
/// or [`Begin::decode_from_reader()`].
336
#[derive(Debug, Clone, PartialEq, Eq, Deftly)]
337
#[derive_deftly(HasMemoryCost)]
338
pub struct EncodedBeginAddr(Vec<u8>);
339

            
340
impl EncodedBeginAddr {
341
    /// Decode the address of a [`Begin`] message, if valid.
342
    ///
343
    /// If an IP address was provided in the message,
344
    /// you probably want to [`to_canonical()`](IpAddr::to_canonical)ize the address
345
    /// to convert a possible IPv4-mapped IPv6 address to an IPv4 address
346
    /// before considering the exit policy.
347
441
    pub fn decode(&self) -> Result<BeginAddr> {
348
441
        let addr = std::str::from_utf8(&self.0)
349
            .map_err(|_| Error::InvalidMessage("target addr in begin cell is not utf8".into()))?;
350

            
351
        // torspec:
352
        //
353
        // > an IPv4 address in dotted-quad format
354
        //
355
        // rust docs:
356
        //
357
        // > Textual representation
358
        // >
359
        // > `Ipv4Addr` provides a `FromStr` implementation. The four octets are in decimal
360
        // > notation, divided by `.` (this is called "dot-decimal notation"). Notably, octal
361
        // > numbers (which are indicated with a leading `0`) and hexadecimal numbers (which are
362
        // > indicated with a leading `0x`) are not allowed per IETF RFC 6943.
363
        //
364
        // TODO(nightly: addr_parse_ascii): In the future we will hopefully be able to skip the
365
        // utf-8 conversion here and use `Ipv4Addr::parse_ascii()` instead of `parse()`.
366
441
        if let Ok(addr) = addr.parse() {
367
63
            return Ok(BeginAddr::Ip(IpAddr::V4(addr)));
368
378
        }
369

            
370
        // torspec:
371
        //
372
        // > an IPv6 address surrounded by square brackets
373
        //
374
        // rust docs:
375
        //
376
        // > Textual representation
377
        // >
378
        // > `Ipv6Addr` provides a `FromStr` implementation. There are many ways to represent an
379
        // > IPv6 address in text, but in general, each segments is written in hexadecimal notation,
380
        // > and segments are separated by `:`. For more information, see IETF RFC 5952.
381
        //
382
        // TODO(nightly: addr_parse_ascii): In the future we will hopefully be able to skip the
383
        // utf-8 conversion here and use `Ipv6Addr::parse_ascii()` instead of `parse()`.
384
378
        if let Some(addr) = addr.strip_prefix('[')
385
126
            && let Some(addr) = addr.strip_suffix(']')
386
126
            && let Ok(addr) = addr.parse()
387
        {
388
63
            return Ok(BeginAddr::Ip(IpAddr::V6(addr)));
389
315
        }
390

            
391
        // Anything that we don't parse as an IP address, we consider a hostname.
392
315
        let addr = BeginHostname::new_with_useful_error_msg(addr.to_owned().into_bytes())?;
393
126
        Ok(BeginAddr::Hostname(addr))
394
441
    }
395
}
396

            
397
/// An address in a [`Begin`] message.
398
#[derive(Debug, Clone, PartialEq, Eq, Deftly)]
399
#[derive_deftly(HasMemoryCost)]
400
// This is a low-level crate and we want users to handle every variant.
401
// And I don't see us adding more variants in the future without introducing a new cell type.
402
#[allow(clippy::exhaustive_enums)]
403
pub enum BeginAddr {
404
    /// An IP address.
405
    Ip(IpAddr),
406
    /// A non-ipv4/ipv6 address.
407
    Hostname(BeginHostname),
408
}
409

            
410
impl BeginAddr {
411
    /// A [`BeginAddr`] with an empty hostname.
412
    pub fn empty() -> Self {
413
        Self::Hostname(BeginHostname::default())
414
    }
415

            
416
    /// Encode the [`BeginAddr`] as it should be written in a [`Begin`] message.
417
    ///
418
    /// NOTE: A `begin_addr.encode().decode()` will not necessarily round-trip to the same value.
419
    /// For example, we convert to lower-case when encoding.
420
    /// Or a `BeginAddr::Hostname(BeginHostname::new("127.0.0.1").unwrap()).encode().decode()`
421
    /// would result in a `BeginAddr::Ip(_)`.
422
4914
    pub fn encode(&self) -> EncodedBeginAddr {
423
4914
        let mut encoded = self.encode_raw();
424

            
425
        // torspec:
426
        //
427
        // > The ADDRPORT string SHOULD be sent in lower case, to avoid fingerprinting.
428
4914
        encoded.0.make_ascii_lowercase();
429

            
430
4914
        encoded
431
4914
    }
432

            
433
    /// Encode the [`BeginAddr`] without making any changes.
434
    ///
435
    /// WARNING: This is probably not what you want.
436
    /// You should use [`BeginAddr::encode()`] instead.
437
4977
    pub fn encode_raw(&self) -> EncodedBeginAddr {
438
4977
        let mut w = Vec::new();
439

            
440
4977
        match self {
441
            Self::Ip(IpAddr::V4(addr)) => {
442
                // TODO: It might be nicer to encode to a stack buffer instead of allocating new
443
                // memory just to discard it. But it would be good to do that without adding new
444
                // dependencies. (And for ipv6 addresses below.)
445
819
                w.write_all(addr.to_string().as_bytes());
446
            }
447
            Self::Ip(IpAddr::V6(addr)) => {
448
63
                w.write_u8(b'[');
449
63
                w.write_all(addr.to_string().as_bytes());
450
63
                w.write_u8(b']');
451
            }
452
4095
            Self::Hostname(addr) => w.write_all(addr.as_ref()),
453
        }
454

            
455
4977
        EncodedBeginAddr(w)
456
4977
    }
457
}
458

            
459
impl From<IpAddr> for BeginAddr {
460
    fn from(x: IpAddr) -> Self {
461
        Self::Ip(x)
462
    }
463
}
464

            
465
impl From<Ipv4Addr> for BeginAddr {
466
756
    fn from(x: Ipv4Addr) -> Self {
467
756
        Self::Ip(IpAddr::V4(x))
468
756
    }
469
}
470

            
471
impl From<Ipv6Addr> for BeginAddr {
472
    fn from(x: Ipv6Addr) -> Self {
473
        Self::Ip(IpAddr::V6(x))
474
    }
475
}
476

            
477
impl From<BeginHostname> for BeginAddr {
478
    fn from(x: BeginHostname) -> Self {
479
        Self::Hostname(x)
480
    }
481
}
482

            
483
/// A hostname in a [`Begin`] message.
484
///
485
/// This is meant for hostnames specifically,
486
/// not IP address strings like "127.0.0.1".
487
/// But since `Begin` messages don't encode the type of address that they contain,
488
/// using a `BeginHostname` of "127.0.0.1" will be interpreted by the decoder
489
/// as an IP address and not a hostname.
490
#[derive(Debug, Clone, Default, PartialEq, Eq, Deftly)]
491
#[derive_deftly(HasMemoryCost)]
492
pub struct BeginHostname(Vec<u8>);
493

            
494
impl BeginHostname {
495
    /// A new hostname for a [`Begin`] message.
496
    ///
497
    /// The hostname must have only alphanumeric (upper and lower case),
498
    /// ".", "-", and "_" ascii characters.
499
    /// The length must be at most 255 bytes.
500
70
    pub fn new(hostname: impl Into<Vec<u8>>) -> crate::Result<Self> {
501
70
        Self::new_with_useful_error_msg(hostname.into()).map_err(|_| crate::Error::BadStreamAddress)
502
70
    }
503

            
504
    /// See [`BeginHostname::new()`].
505
4725
    fn new_with_useful_error_msg(hostname: Vec<u8>) -> Result<Self> {
506
        // torspec:
507
        //
508
        // > When used as a DNS hostname ADDRESS MUST only have alphanumeric
509
        // > (upper and lower case), ".", "-", and "_" characters,
510
        // > and be at most 255 characters long.
511
        //
512
        // We only do the validation that's specified in torspec.
513
        // Other possible addresses are invalid (for example a hostname of just '-'),
514
        // but these addresses are allowed by torspec and we expect that Arti's DNS code will handle
515
        // these reasonably.
516
        //
517
        // Another edge case is an empty hostname string,
518
        // but (1) this is allowed by torspec,
519
        // and (2) this is needed by onion services which do use an empty hostname.
520

            
521
4725
        if hostname.len() > 255 {
522
            return Err(Error::InvalidMessage("hostname was too long".into()));
523
4725
        }
524

            
525
60291
        let is_allowed = |c: &u8| c.is_ascii_alphanumeric() || b".-_".contains(c);
526

            
527
4725
        if !hostname.iter().all(is_allowed) {
528
378
            return Err(Error::InvalidMessage(
529
378
                "hostname had invalid characters".into(),
530
378
            ));
531
4347
        }
532

            
533
4347
        Ok(Self(hostname))
534
4725
    }
535
}
536

            
537
impl AsRef<[u8]> for BeginHostname {
538
4095
    fn as_ref(&self) -> &[u8] {
539
4095
        &self.0
540
4095
    }
541
}
542

            
543
/// A Data message represents data sent along a stream.
544
///
545
/// Upon receiving a Data message for a live stream, the client or
546
/// exit sends that data onto the associated TCP connection.
547
///
548
/// These messages hold between 1 and [Data::MAXLEN] bytes of data each;
549
/// they are the most numerous messages on the Tor network.
550
#[derive(Debug, Clone, Deftly)]
551
#[derive_deftly(HasMemoryCost)]
552
pub struct Data {
553
    /// Contents of the cell, to be sent on a specific stream
554
    ///
555
    /// INVARIANT: Holds between 1 and [`Data::MAXLEN`] bytes, inclusive.
556
    //
557
    // TODO: There's a good case to be made that this should be a BoxedCellBody
558
    // instead, to avoid allocations and copies.  But first probably we should
559
    // figure out how proposal 340 will work with this.  Possibly, we will wind
560
    // up using `bytes` or something.
561
    body: Vec<u8>,
562
}
563
impl Data {
564
    /// The longest allowable body length for a single V0 data cell.
565
    ///
566
    /// Relay command (1) + 'Recognized' (2) + StreamID (2) + Digest (4) + Length (2) = 11
567
    pub const MAXLEN_V0: usize = CELL_DATA_LEN - 11;
568

            
569
    /// The longest allowable body length for a single V1 data cell.
570
    ///
571
    /// Tag (16) + Relay command (1) + Length (2) + StreamID (2) = 21
572
    pub const MAXLEN_V1: usize = CELL_DATA_LEN - 21;
573

            
574
    /// The longest allowable body length for any data cell.
575
    ///
576
    /// Note that this value is too large to fit into a v1 relay cell;
577
    /// see [`MAXLEN_V1`](Data::MAXLEN_V1) if you are making a v1 data cell.
578
    ///
579
    pub const MAXLEN: usize = Data::MAXLEN_V0;
580

            
581
    /// Construct a new data cell.
582
    ///
583
    /// Returns an error if `inp` is longer than [`Data::MAXLEN`] bytes.
584
3717
    pub fn new(inp: &[u8]) -> crate::Result<Self> {
585
3717
        if inp.len() > Data::MAXLEN {
586
63
            return Err(crate::Error::CantEncode("Data message too long"));
587
3654
        }
588
3654
        if inp.is_empty() {
589
            return Err(crate::Error::CantEncode("Empty data message"));
590
3654
        }
591
3654
        Ok(Self::new_unchecked(inp.into()))
592
3717
    }
593

            
594
    /// Construct a new data cell, taking as many bytes from `inp`
595
    /// as possible.
596
    ///
597
    /// Return the data cell, and a slice holding any bytes that
598
    /// wouldn't fit (if any).
599
    ///
600
    /// Returns None if the input was empty.
601
135639
    pub fn try_split_from(version: RelayCellFormat, inp: &[u8]) -> Option<(Self, &[u8])> {
602
135639
        if inp.is_empty() {
603
            return None;
604
135639
        }
605
135639
        let upper_bound = Self::max_body_len(version);
606
135639
        let len = std::cmp::min(inp.len(), upper_bound);
607
135639
        let (data, remainder) = inp.split_at(len);
608
135639
        Some((Self::new_unchecked(data.into()), remainder))
609
135639
    }
610

            
611
    /// Construct a new data cell from a provided vector of bytes.
612
    ///
613
    /// The vector _must_ not have more than [`Data::MAXLEN`] bytes, and must
614
    /// not be empty.
615
139293
    fn new_unchecked(body: Vec<u8>) -> Self {
616
139293
        debug_assert!((1..=Data::MAXLEN).contains(&body.len()));
617
139293
        Data { body }
618
139293
    }
619

            
620
    /// Return the maximum allowable body length for a Data message
621
    /// using the provided `format`.
622
139545
    pub fn max_body_len(format: RelayCellFormat) -> usize {
623
139545
        match format {
624
139545
            RelayCellFormat::V0 => Self::MAXLEN_V0,
625
            RelayCellFormat::V1 => Self::MAXLEN_V1,
626
        }
627
139545
    }
628
}
629
impl From<Data> for Vec<u8> {
630
2898
    fn from(data: Data) -> Vec<u8> {
631
2898
        data.body
632
2898
    }
633
}
634
impl AsRef<[u8]> for Data {
635
159453
    fn as_ref(&self) -> &[u8] {
636
159453
        &self.body[..]
637
159453
    }
638
}
639

            
640
impl Body for Data {
641
156555
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
642
156555
        if r.remaining() == 0 {
643
            return Err(Error::InvalidMessage("Empty DATA message".into()));
644
156555
        }
645
156555
        Ok(Data {
646
156555
            body: r.take_rest().into(),
647
156555
        })
648
156555
    }
649
2642
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
650
2642
        w.write_all(&self.body);
651
2642
        Ok(())
652
2642
    }
653
}
654

            
655
/// An End message tells the other end of the circuit to close a stream.
656
///
657
/// Note that End messages do not implement a true half-closed state,
658
/// so after sending an End message each party needs to wait a while
659
/// to be sure that the stream is completely dead.
660
#[derive(Debug, Clone, Deftly)]
661
#[derive_deftly(HasMemoryCost)]
662
pub struct End {
663
    /// Reason for closing the stream
664
    reason: EndReason,
665
    /// If the reason is EXITPOLICY, this holds the resolved address an
666
    /// associated TTL.  The TTL is set to MAX if none was given.
667
    addr: Option<(IpAddr, u32)>,
668
}
669

            
670
caret_int! {
671
    /// A declared reason for closing a stream
672
    #[derive(Deftly)]
673
    #[derive_deftly(HasMemoryCost)]
674
    pub struct EndReason(u8) {
675
        /// Closing a stream because of an unspecified reason.
676
        ///
677
        /// This is the only END reason that clients send.
678
        MISC = 1,
679
        /// Couldn't look up hostname.
680
        RESOLVEFAILED = 2,
681
        /// Remote host refused connection.
682
        CONNECTREFUSED = 3,
683
        /// Closing a stream because of an exit-policy violation.
684
        EXITPOLICY = 4,
685
        /// Circuit destroyed
686
        DESTROY = 5,
687
        /// Anonymized TCP connection was closed
688
        DONE = 6,
689
        /// Connection timed out, or OR timed out while connecting
690
        TIMEOUT = 7,
691
        /// No route to target destination.
692
        NOROUTE = 8,
693
        /// OR is entering hibernation and not handling requests
694
        HIBERNATING = 9,
695
        /// Internal error at the OR
696
        INTERNAL = 10,
697
        /// Ran out of resources to fulfill requests
698
        RESOURCELIMIT = 11,
699
        /// Connection unexpectedly reset
700
        CONNRESET = 12,
701
        /// Tor protocol violation
702
        TORPROTOCOL = 13,
703
        /// BEGIN_DIR cell at a non-directory-cache.
704
        NOTDIRECTORY = 14,
705
    }
706
}
707

            
708
impl tor_error::HasKind for EndReason {
709
    fn kind(&self) -> tor_error::ErrorKind {
710
        use EndReason as E;
711
        use tor_error::ErrorKind as EK;
712
        match *self {
713
            E::MISC => EK::RemoteStreamError,
714
            E::RESOLVEFAILED => EK::RemoteHostResolutionFailed,
715
            E::CONNECTREFUSED => EK::RemoteConnectionRefused,
716
            E::EXITPOLICY => EK::ExitPolicyRejected,
717
            E::DESTROY => EK::CircuitCollapse,
718
            E::DONE => EK::RemoteStreamClosed,
719
            E::TIMEOUT => EK::ExitTimeout,
720
            E::NOROUTE => EK::RemoteNetworkFailed,
721
            E::RESOURCELIMIT | E::HIBERNATING => EK::RelayTooBusy,
722
            E::INTERNAL | E::TORPROTOCOL | E::NOTDIRECTORY => EK::TorProtocolViolation,
723
            E::CONNRESET => EK::RemoteStreamReset,
724
            _ => EK::RemoteStreamError,
725
        }
726
    }
727
}
728

            
729
impl End {
730
    /// Make a new END_REASON_MISC message.
731
    ///
732
    /// Clients send this every time they decide to close a stream.
733
2268
    pub fn new_misc() -> Self {
734
2268
        End {
735
2268
            reason: EndReason::MISC,
736
2268
            addr: None,
737
2268
        }
738
2268
    }
739
    /// Make a new END message with the provided end reason.
740
1197
    pub fn new_with_reason(reason: EndReason) -> Self {
741
1197
        End { reason, addr: None }
742
1197
    }
743
    /// Make a new END message with END_REASON_EXITPOLICY, and the
744
    /// provided address and ttl.
745
189
    pub fn new_exitpolicy(addr: IpAddr, ttl: u32) -> Self {
746
189
        End {
747
189
            reason: EndReason::EXITPOLICY,
748
189
            addr: Some((addr, ttl)),
749
189
        }
750
189
    }
751
    /// Return the provided EndReason for this End cell.
752
1008
    pub fn reason(&self) -> EndReason {
753
1008
        self.reason
754
1008
    }
755
}
756
impl Body for End {
757
2016
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
758
2016
        if r.remaining() == 0 {
759
63
            return Ok(End {
760
63
                reason: EndReason::MISC,
761
63
                addr: None,
762
63
            });
763
1953
        }
764
1953
        let reason = r.take_u8()?.into();
765
1953
        if reason == EndReason::EXITPOLICY {
766
189
            let addr = match r.remaining() {
767
126
                4 | 8 => IpAddr::V4(r.extract()?),
768
63
                16 | 20 => IpAddr::V6(r.extract()?),
769
                _ => {
770
                    // Ignores other message lengths.
771
                    return Ok(End { reason, addr: None });
772
                }
773
            };
774
189
            let ttl = if r.remaining() == 4 {
775
126
                r.take_u32()?
776
            } else {
777
63
                u32::MAX
778
            };
779
189
            Ok(End {
780
189
                reason,
781
189
                addr: Some((addr, ttl)),
782
189
            })
783
        } else {
784
1764
            Ok(End { reason, addr: None })
785
        }
786
2016
    }
787
60
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
788
60
        w.write_u8(self.reason.into());
789
60
        if let (EndReason::EXITPOLICY, Some((addr, ttl))) = (self.reason, self.addr) {
790
6
            match addr {
791
4
                IpAddr::V4(v4) => w.write(&v4)?,
792
2
                IpAddr::V6(v6) => w.write(&v6)?,
793
            }
794
6
            w.write_u32(ttl);
795
54
        }
796
60
        Ok(())
797
60
    }
798
}
799

            
800
impl From<EndReason> for std::io::ErrorKind {
801
    fn from(e: EndReason) -> Self {
802
        use std::io::ErrorKind::*;
803
        match e {
804
            EndReason::RESOLVEFAILED => NotFound,
805
            EndReason::CONNECTREFUSED => ConnectionRefused,
806
            EndReason::EXITPOLICY => ConnectionRefused,
807
            EndReason::DESTROY => ConnectionAborted,
808
            EndReason::DONE => UnexpectedEof,
809
            EndReason::TIMEOUT => TimedOut,
810
            EndReason::HIBERNATING => ConnectionRefused,
811
            EndReason::RESOURCELIMIT => ConnectionRefused,
812
            EndReason::CONNRESET => ConnectionReset,
813
            EndReason::TORPROTOCOL => InvalidData,
814
            EndReason::NOTDIRECTORY => ConnectionRefused,
815
            EndReason::INTERNAL | EndReason::NOROUTE | EndReason::MISC => Other,
816
            _ => Other,
817
        }
818
    }
819
}
820

            
821
/// A Connected message is a successful response to a Begin message
822
///
823
/// When an outgoing connection succeeds, the exit sends a Connected
824
/// back to the client.
825
///
826
/// Clients never send Connected messages.
827
#[derive(Debug, Clone, Deftly)]
828
#[derive_deftly(HasMemoryCost)]
829
pub struct Connected {
830
    /// Resolved address and TTL (time to live) in seconds
831
    addr: Option<(IpAddr, u32)>,
832
}
833
impl Connected {
834
    /// Construct a new empty connected cell.
835
2142
    pub fn new_empty() -> Self {
836
2142
        Connected { addr: None }
837
2142
    }
838
    /// Construct a connected cell with an address and a time-to-live value.
839
2142
    pub fn new_with_addr(addr: IpAddr, ttl: u32) -> Self {
840
2142
        Connected {
841
2142
            addr: Some((addr, ttl)),
842
2142
        }
843
2142
    }
844
}
845
impl Body for Connected {
846
3402
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
847
3402
        if r.remaining() == 0 {
848
1197
            return Ok(Connected { addr: None });
849
2205
        }
850
2205
        let ipv4 = r.take_u32()?;
851
2205
        let addr = if ipv4 == 0 {
852
126
            if r.take_u8()? != 6 {
853
63
                return Err(Error::InvalidMessage(
854
63
                    "Invalid address type in CONNECTED cell".into(),
855
63
                ));
856
63
            }
857
63
            IpAddr::V6(r.extract()?)
858
        } else {
859
2079
            IpAddr::V4(ipv4.into())
860
        };
861
2142
        let ttl = r.take_u32()?;
862

            
863
2142
        Ok(Connected {
864
2142
            addr: Some((addr, ttl)),
865
2142
        })
866
3402
    }
867
73
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
868
73
        if let Some((addr, ttl)) = self.addr {
869
36
            match addr {
870
34
                IpAddr::V4(v4) => w.write(&v4)?,
871
                IpAddr::V6(v6) => {
872
2
                    w.write_u32(0);
873
2
                    w.write_u8(6);
874
2
                    w.write(&v6)?;
875
                }
876
            }
877
36
            w.write_u32(ttl);
878
37
        }
879
73
        Ok(())
880
73
    }
881
}
882

            
883
/// An authentication tag to use for circuit-level SENDME messages.
884
///
885
/// It is either a 20-byte tag (used with Tor1 encryption),
886
/// or a 16-byte tag (used with CGO encryption).
887
#[derive(Debug, Clone, Copy, Eq, PartialEq, Deftly)]
888
#[derive_deftly(HasMemoryCost)]
889
pub struct SendmeTag {
890
    /// The number of bytes present in the tag.
891
    /// Always equal to 16 or 20.
892
    ///
893
    /// We use a NonZeroU8 here so Rust can use its niche optimization.
894
    len: NonZeroU8,
895
    /// The actual contents of the tag.
896
    ///
897
    /// Tags above 20 bytes long are always an error.
898
    ///
899
    /// Unused bytes are always set to zero, so we can derive PartialEq.
900
    tag: CtByteArray<20>,
901
}
902
impl From<[u8; 20]> for SendmeTag {
903
    // In experimentation, these "inlines" were necessary for good generated asm.
904
    #[inline]
905
177952
    fn from(value: [u8; 20]) -> Self {
906
177952
        Self {
907
177952
            len: NonZeroU8::new(20).expect("20 was not nonzero?"),
908
177952
            tag: CtByteArray::from(value),
909
177952
        }
910
177952
    }
911
}
912
impl From<[u8; 16]> for SendmeTag {
913
    // In experimentation, these "inlines" were necessary for good generated asm.
914
    #[inline]
915
408
    fn from(value: [u8; 16]) -> Self {
916
408
        let mut tag = CtByteArray::from([0; 20]);
917
408
        tag.as_mut()[0..16].copy_from_slice(&value[..]);
918
408
        Self {
919
408
            len: NonZeroU8::new(16).expect("16 was not nonzero?"),
920
408
            tag,
921
408
        }
922
408
    }
923
}
924
impl AsRef<[u8]> for SendmeTag {
925
1703
    fn as_ref(&self) -> &[u8] {
926
1703
        &self.tag.as_ref()[0..usize::from(u8::from(self.len))]
927
1703
    }
928
}
929
/// An error from attempting to decode a SENDME tag.
930
#[derive(Clone, Debug, thiserror::Error)]
931
#[non_exhaustive]
932
#[error("Invalid size {} on SENDME tag", len)]
933
pub struct InvalidSendmeTag {
934
    /// The length of the invalid tag.
935
    len: usize,
936
}
937
impl From<InvalidSendmeTag> for tor_bytes::Error {
938
    fn from(_: InvalidSendmeTag) -> Self {
939
        tor_bytes::Error::BadLengthValue
940
    }
941
}
942

            
943
impl<'a> TryFrom<&'a [u8]> for SendmeTag {
944
    type Error = InvalidSendmeTag;
945

            
946
    // In experimentation, this "inline" was especially necessary for good generated asm.
947
    #[inline]
948
3372
    fn try_from(value: &'a [u8]) -> std::result::Result<Self, Self::Error> {
949
3372
        match value.len() {
950
            16 => {
951
252
                let a: [u8; 16] = value.try_into().expect("16 was not 16?");
952
252
                Ok(Self::from(a))
953
            }
954
            20 => {
955
3119
                let a: [u8; 20] = value.try_into().expect("20 was not 20?");
956
3119
                Ok(Self::from(a))
957
            }
958
1
            _ => Err(InvalidSendmeTag { len: value.len() }),
959
        }
960
3372
    }
961
}
962

            
963
/// A Sendme message is used to increase flow-control windows.
964
///
965
/// To avoid congestion, each Tor circuit and stream keeps track of a
966
/// number of data cells that it is willing to send.  It decrements
967
/// these numbers every time it sends a cell.  If these numbers reach
968
/// zero, then no more cells can be sent on the stream or circuit.
969
///
970
/// The only way to re-increment these numbers is by receiving a
971
/// Sendme cell from the other end of the circuit or stream.
972
///
973
/// For security, current circuit-level Sendme cells include an
974
/// authentication tag that proves knowledge of the cells that they are
975
/// acking.
976
///
977
/// See [tor-spec.txt](https://spec.torproject.org/tor-spec) for more
978
/// information; also see the source for `tor_proto::circuit::sendme`.
979
#[derive(Debug, Clone, Deftly)]
980
#[derive_deftly(HasMemoryCost)]
981
pub struct Sendme {
982
    /// A tag value authenticating the previously received data.
983
    tag: Option<SendmeTag>,
984
}
985
impl Sendme {
986
    /// Return a new empty sendme cell
987
    ///
988
    /// This format is used on streams, and on circuits without sendme
989
    /// authentication.
990
252
    pub fn new_empty() -> Self {
991
252
        Sendme { tag: None }
992
252
    }
993
    /// This format is used on circuits with sendme authentication.
994
378
    pub fn new_tag(x: [u8; 20]) -> Self {
995
378
        Sendme {
996
378
            tag: Some(x.into()),
997
378
        }
998
378
    }
999
    /// Consume this cell and return its authentication tag, if any
1386
    pub fn into_sendme_tag(self) -> Option<SendmeTag> {
1386
        self.tag
1386
    }
}
impl From<SendmeTag> for Sendme {
1134
    fn from(value: SendmeTag) -> Self {
1134
        Self { tag: Some(value) }
1134
    }
}
impl Body for Sendme {
1890
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
1890
        let tag = if r.remaining() == 0 {
315
            None
        } else {
1575
            let ver = r.take_u8()?;
1575
            match ver {
                0 => None,
                1 => {
1575
                    let dlen = r.take_u16()?;
1575
                    Some(r.take(dlen as usize)?.try_into()?)
                }
                _ => {
                    return Err(Error::InvalidMessage("Unrecognized SENDME version.".into()));
                }
            }
        };
1890
        Ok(Sendme { tag })
1890
    }
33
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
33
        match self.tag {
6
            None => (),
            Some(x) => {
27
                w.write_u8(1);
27
                let x = x.as_ref();
27
                let bodylen: u16 = x
27
                    .len()
27
                    .try_into()
                    .map_err(|_| EncodeError::BadLengthValue)?;
27
                w.write_u16(bodylen);
27
                w.write_all(x);
            }
        }
33
        Ok(())
33
    }
}
/// Extend was an obsolete circuit extension message format.
///
/// This format only handled IPv4 addresses, RSA identities, and the
/// TAP handshake.  Modern Tor clients use Extend2 instead.
#[derive(Debug, Clone, Deftly)]
#[derive_deftly(HasMemoryCost)]
pub struct Extend {
    /// Where to extend to (address)
    addr: Ipv4Addr,
    /// Where to extend to (port)
    port: u16,
    /// A TAP handshake to send
    handshake: Vec<u8>,
    /// The RSA identity of the target relay
    rsaid: RsaIdentity,
}
impl Extend {
    /// Construct a new (deprecated) extend cell
63
    pub fn new(addr: Ipv4Addr, port: u16, handshake: Vec<u8>, rsaid: RsaIdentity) -> Self {
63
        Extend {
63
            addr,
63
            port,
63
            handshake,
63
            rsaid,
63
        }
63
    }
}
impl Body for Extend {
63
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
63
        let addr = r.extract()?;
63
        let port = r.take_u16()?;
63
        let handshake = r.take(TAP_C_HANDSHAKE_LEN)?.into();
63
        let rsaid = r.extract()?;
63
        Ok(Extend {
63
            addr,
63
            port,
63
            handshake,
63
            rsaid,
63
        })
63
    }
2
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
2
        w.write(&self.addr)?;
2
        w.write_u16(self.port);
2
        w.write_all(&self.handshake[..]);
2
        w.write(&self.rsaid)?;
2
        Ok(())
2
    }
}
/// Extended was an obsolete circuit extension message, sent in reply to
/// an Extend message.
///
/// Like Extend, the Extended message was only designed for the TAP
/// handshake.
#[derive(Debug, Clone, Deftly)]
#[derive_deftly(HasMemoryCost)]
pub struct Extended {
    /// Contents of the handshake sent in response to the EXTEND
    handshake: Vec<u8>,
}
impl Extended {
    /// Construct a new Extended message with the provided handshake
441
    pub fn new(handshake: Vec<u8>) -> Self {
441
        Extended { handshake }
441
    }
}
impl Body for Extended {
63
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
63
        let handshake = r.take(TAP_S_HANDSHAKE_LEN)?.into();
63
        Ok(Extended { handshake })
63
    }
8
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
8
        w.write_all(&self.handshake);
8
        Ok(())
8
    }
}
/// An Extend2 message tells the last relay in a circuit to extend to a new
/// hop.
///
/// When a relay (call it R) receives an Extend2 message, it tries to
/// find (or make) a channel to the other relay (R') described in the
/// list of link specifiers. (A link specifier can be an IP addresses
/// or a cryptographic identity).  Once R has such a channel, the
/// it packages the client's handshake data as a new Create2 message
/// R'.  If R' replies with a Created2 (success) message, R packages
/// that message's contents in an Extended message.
//
/// Unlike Extend messages, Extend2 messages can encode any handshake
/// type, and can describe relays in ways other than IPv4 addresses
/// and RSA identities.
#[derive(Debug, Clone, Deftly)]
#[derive_deftly(HasMemoryCost)]
pub struct Extend2 {
    /// A vector of "link specifiers"
    ///
    /// These link specifiers describe where to find the target relay
    /// that the recipient should extend to.  They include things like
    /// IP addresses and identity keys.
    linkspec: Vec<EncodedLinkSpec>,
    /// Type of handshake to be sent in a CREATE2 cell
    handshake_type: HandshakeType,
    /// Body of the handshake to be sent in a CREATE2 cell
    handshake: Vec<u8>,
}
impl Extend2 {
    /// Create a new Extend2 cell.
2961
    pub fn new(
2961
        linkspec: Vec<EncodedLinkSpec>,
2961
        handshake_type: HandshakeType,
2961
        handshake: Vec<u8>,
2961
    ) -> Self {
2961
        Extend2 {
2961
            linkspec,
2961
            handshake_type,
2961
            handshake,
2961
        }
2961
    }
    /// Return the type of this handshake.
441
    pub fn handshake_type(&self) -> HandshakeType {
441
        self.handshake_type
441
    }
    /// Return the inner handshake for this Extend2 cell.
1197
    pub fn handshake(&self) -> &[u8] {
1197
        &self.handshake[..]
1197
    }
    /// Return a reference to the link specifiers in this cell.
504
    pub fn linkspecs(&self) -> &[EncodedLinkSpec] {
504
        &self.linkspec
504
    }
}
impl Body for Extend2 {
1386
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
1386
        let n = r.take_u8()?;
1386
        let linkspec = r.extract_n(n as usize)?;
1386
        let handshake_type = r.take_u16()?.into();
1386
        let hlen = r.take_u16()?;
1386
        let handshake = r.take(hlen as usize)?.into();
1386
        Ok(Extend2 {
1386
            linkspec,
1386
            handshake_type,
1386
            handshake,
1386
        })
1386
    }
48
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
48
        let n_linkspecs: u8 = self
48
            .linkspec
48
            .len()
48
            .try_into()
            .map_err(|_| EncodeError::BadLengthValue)?;
48
        w.write_u8(n_linkspecs);
48
        for ls in &self.linkspec {
106
            w.write(ls)?;
        }
48
        w.write_u16(self.handshake_type.into());
48
        let handshake_len: u16 = self
48
            .handshake
48
            .len()
48
            .try_into()
            .map_err(|_| EncodeError::BadLengthValue)?;
48
        w.write_u16(handshake_len);
48
        w.write_all(&self.handshake[..]);
48
        Ok(())
48
    }
}
/// Extended2 is a successful reply to an Extend2 message.
///
/// Extended2 messages are generated by the former last hop of a
/// circuit, to tell the client that they have successfully completed
/// a handshake on the client's behalf.
#[derive(Debug, Clone, Deftly)]
#[derive_deftly(HasMemoryCost)]
pub struct Extended2 {
    /// Contents of the CREATED2 cell that the new final hop sent in
    /// response
    handshake: Vec<u8>,
}
impl Extended2 {
    /// Construct a new Extended2 message with the provided handshake
2079
    pub fn new(handshake: Vec<u8>) -> Self {
2079
        Extended2 { handshake }
2079
    }
    /// Consume this extended2 cell and return its body.
1512
    pub fn into_body(self) -> Vec<u8> {
1512
        self.handshake
1512
    }
}
impl Body for Extended2 {
1701
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
1701
        let hlen = r.take_u16()?;
1701
        let handshake = r.take(hlen as usize)?;
1701
        Ok(Extended2 {
1701
            handshake: handshake.into(),
1701
        })
1701
    }
36
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
36
        let handshake_len: u16 = self
36
            .handshake
36
            .len()
36
            .try_into()
            .map_err(|_| EncodeError::BadLengthValue)?;
36
        w.write_u16(handshake_len);
36
        w.write_all(&self.handshake[..]);
36
        Ok(())
36
    }
}
/// A Truncated message is sent to the client when the remaining hops
/// of a circuit have gone away.
///
/// NOTE: Current Tor implementations often treat Truncated messages and
/// Destroy messages interchangeably.  Truncated was intended to be a
/// "soft" Destroy, that would leave the unaffected parts of a circuit
/// still usable.
#[derive(Debug, Clone, Deftly)]
#[derive_deftly(HasMemoryCost)]
pub struct Truncated {
    /// Reason for which this circuit was truncated.
    reason: DestroyReason,
}
impl Truncated {
    /// Construct a new truncated message.
63
    pub fn new(reason: DestroyReason) -> Self {
63
        Truncated { reason }
63
    }
    /// Get the provided reason to truncate the circuit.
    pub fn reason(self) -> DestroyReason {
        self.reason
    }
}
impl Body for Truncated {
63
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
        Ok(Truncated {
63
            reason: r.take_u8()?.into(),
        })
63
    }
2
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
2
        w.write_u8(self.reason.into());
2
        Ok(())
2
    }
}
/// A Resolve message launches a DNS lookup stream.
///
/// A client sends a Resolve message when it wants to perform a DNS
/// lookup _without_ connecting to the resulting address.  On success
/// the exit responds with a Resolved message; on failure it responds
/// with an End message.
#[derive(Debug, Clone, Deftly)]
#[derive_deftly(HasMemoryCost)]
pub struct Resolve {
    /// Ascii-encoded address to resolve
    query: Vec<u8>,
}
impl Resolve {
    /// Construct a new resolve message to look up a hostname.
252
    pub fn new(s: &str) -> Self {
252
        Resolve {
252
            query: s.as_bytes().into(),
252
        }
252
    }
    /// Construct a new resolve message to do a reverse lookup on an address
126
    pub fn new_reverse(addr: &IpAddr) -> Self {
126
        let query = match addr {
            IpAddr::V4(v4) => {
63
                let [a, b, c, d] = v4.octets();
63
                format!("{}.{}.{}.{}.in-addr.arpa", d, c, b, a)
            }
            IpAddr::V6(v6) => {
63
                let mut s = String::with_capacity(72);
63
                for o in v6.octets().iter().rev() {
1008
                    let high_nybble = o >> 4;
1008
                    let low_nybble = o & 15;
1008
                    write!(s, "{:x}.{:x}.", low_nybble, high_nybble)
1008
                        .expect("write to string failed");
                }
63
                write!(s, "ip6.arpa").expect("write to string failed");
63
                s
            }
        };
126
        Resolve {
126
            query: query.into_bytes(),
126
        }
126
    }
    /// Return a reference to the ASCII-encoded address from this message.
    pub fn query(&self) -> &[u8] {
        &self.query
    }
}
impl Body for Resolve {
315
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
315
        let query = r.take_until(0)?;
315
        Ok(Resolve {
315
            query: query.into(),
315
        })
315
    }
9
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
9
        w.write_all(&self.query[..]);
9
        w.write_u8(0);
9
        Ok(())
9
    }
}
/// Possible response to a DNS lookup
#[derive(Debug, Clone, Eq, PartialEq, Deftly)]
#[derive_deftly(HasMemoryCost)]
#[non_exhaustive]
pub enum ResolvedVal {
    /// We found an IP address
    Ip(IpAddr),
    /// We found a hostname
    Hostname(Vec<u8>),
    /// Error; try again
    TransientError,
    /// Error; don't try again
    NontransientError,
    /// A DNS lookup response that we didn't recognize
    Unrecognized(u8, Vec<u8>),
}
/// Indicates a hostname response
const RES_HOSTNAME: u8 = 0;
/// Indicates an IPv4 response
const RES_IPV4: u8 = 4;
/// Indicates an IPv6 response
const RES_IPV6: u8 = 6;
/// Transient error (okay to try again)
const RES_ERR_TRANSIENT: u8 = 0xF0;
/// Non-transient error (don't try again)
const RES_ERR_NONTRANSIENT: u8 = 0xF1;
impl Readable for ResolvedVal {
693
    fn take_from(r: &mut Reader<'_>) -> Result<Self> {
        /// Helper: return the expected length of a resolved answer with
        /// a given type, if there is a particular expected length.
693
        fn res_len(tp: u8) -> Option<usize> {
693
            match tp {
315
                RES_IPV4 => Some(4),
126
                RES_IPV6 => Some(16),
252
                _ => None,
            }
693
        }
693
        let tp = r.take_u8()?;
693
        let len = r.take_u8()? as usize;
693
        if let Some(expected_len) = res_len(tp) {
441
            if len != expected_len {
63
                return Err(Error::InvalidMessage(
63
                    "Wrong length for RESOLVED answer".into(),
63
                ));
378
            }
252
        }
630
        Ok(match tp {
63
            RES_HOSTNAME => Self::Hostname(r.take(len)?.into()),
252
            RES_IPV4 => Self::Ip(IpAddr::V4(r.extract()?)),
126
            RES_IPV6 => Self::Ip(IpAddr::V6(r.extract()?)),
            RES_ERR_TRANSIENT => {
63
                r.advance(len)?;
63
                Self::TransientError
            }
            RES_ERR_NONTRANSIENT => {
63
                r.advance(len)?;
63
                Self::NontransientError
            }
63
            _ => Self::Unrecognized(tp, r.take(len)?.into()),
        })
693
    }
}
impl Writeable for ResolvedVal {
16
    fn write_onto<B: Writer + ?Sized>(&self, w: &mut B) -> EncodeResult<()> {
16
        match self {
            Self::Hostname(h) => {
2
                w.write_u8(RES_HOSTNAME);
2
                let h_len: u8 = h
2
                    .len()
2
                    .try_into()
                    .map_err(|_| EncodeError::BadLengthValue)?;
2
                w.write_u8(h_len);
2
                w.write_all(&h[..]);
            }
            Self::Ip(IpAddr::V4(a)) => {
6
                w.write_u8(RES_IPV4);
6
                w.write_u8(4); // length
6
                w.write(a)?;
            }
            Self::Ip(IpAddr::V6(a)) => {
2
                w.write_u8(RES_IPV6);
2
                w.write_u8(16); // length
2
                w.write(a)?;
            }
            Self::TransientError => {
2
                w.write_u8(RES_ERR_TRANSIENT);
2
                w.write_u8(0); // length
            }
            Self::NontransientError => {
2
                w.write_u8(RES_ERR_NONTRANSIENT);
2
                w.write_u8(0); // length
            }
            Self::Unrecognized(tp, v) => {
2
                w.write_u8(*tp);
2
                let v_len: u8 = v
2
                    .len()
2
                    .try_into()
                    .map_err(|_| EncodeError::BadLengthValue)?;
2
                w.write_u8(v_len);
2
                w.write_all(&v[..]);
            }
        }
16
        Ok(())
16
    }
}
/// A Resolved message is a successful reply to a Resolve message.
///
/// The Resolved message contains a list of zero or more addresses,
/// and their associated times-to-live in seconds.
#[derive(Debug, Clone, Deftly)]
#[derive_deftly(HasMemoryCost)]
pub struct Resolved {
    /// List of addresses and their associated time-to-live values.
    answers: Vec<(ResolvedVal, u32)>,
}
impl Resolved {
    /// Return a new empty Resolved object with no answers.
567
    pub fn new_empty() -> Self {
567
        Resolved {
567
            answers: Vec::new(),
567
        }
567
    }
    /// Return a new Resolved object reporting a name lookup error.
    ///
    /// TODO: Is getting no answer an error; or it is represented by
    /// a list of no answers?
126
    pub fn new_err(transient: bool, ttl: u32) -> Self {
126
        let mut res = Self::new_empty();
126
        let err = if transient {
63
            ResolvedVal::TransientError
        } else {
63
            ResolvedVal::NontransientError
        };
126
        res.add_answer(err, ttl);
126
        res
126
    }
    /// Add a single answer to this Resolved message
567
    pub fn add_answer(&mut self, answer: ResolvedVal, ttl: u32) {
567
        self.answers.push((answer, ttl));
567
    }
    /// Consume this Resolved message, returning a vector of the
    /// answers and TTL values that it contains.
    ///
    /// Note that actually relying on these TTL values can be
    /// dangerous in practice, since the relay that sent the cell
    /// could be lying in order to cause more lookups, or to get a
    /// false answer cached for longer.
315
    pub fn into_answers(self) -> Vec<(ResolvedVal, u32)> {
315
        self.answers
315
    }
}
impl Body for Resolved {
693
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
693
        let mut answers = Vec::new();
1323
        while r.remaining() > 0 {
693
            let rv = r.extract()?;
630
            let ttl = r.take_u32()?;
630
            answers.push((rv, ttl));
        }
630
        Ok(Resolved { answers })
693
    }
16
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
16
        for (rv, ttl) in &self.answers {
16
            w.write(rv)?;
16
            w.write_u32(*ttl);
        }
16
        Ok(())
16
    }
}
/// A relay message that we didn't recognize
///
/// NOTE: Clients should generally reject these.
#[derive(Debug, Clone, Deftly)]
#[derive_deftly(HasMemoryCost)]
pub struct Unrecognized {
    /// Command that we didn't recognize
    cmd: RelayCmd,
    /// Body associated with that command
    body: Vec<u8>,
}
impl Unrecognized {
    /// Create a new 'unrecognized' cell.
1
    pub fn new<B>(cmd: RelayCmd, body: B) -> Self
1
    where
1
        B: Into<Vec<u8>>,
    {
1
        let body = body.into();
1
        Unrecognized { cmd, body }
1
    }
    /// Return the command associated with this message
63
    pub fn cmd(&self) -> RelayCmd {
63
        self.cmd
63
    }
    /// Decode this message, using a provided command.
63
    pub fn decode_with_cmd(cmd: RelayCmd, r: &mut Reader<'_>) -> Result<Self> {
63
        let mut r = Unrecognized::decode_from_reader(r)?;
63
        r.cmd = cmd;
63
        Ok(r)
63
    }
}
impl Body for Unrecognized {
63
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
63
        Ok(Unrecognized {
63
            cmd: 0.into(),
63
            body: r.take_rest().into(),
63
        })
63
    }
2
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
2
        w.write_all(&self.body[..]);
2
        Ok(())
2
    }
}
/// Declare a message type for a message with an empty body.
macro_rules! empty_body {
   {
       $(#[$meta:meta])*
       pub struct $name:ident {}
   } => {
       $(#[$meta])*
       #[derive(Clone,Debug,Default,derive_deftly::Deftly)]
       #[derive_deftly(tor_memquota::HasMemoryCost)]
       #[non_exhaustive]
       pub struct $name {}
       impl $crate::relaycell::msg::Body for $name {
1449
           fn decode_from_reader(_r: &mut Reader<'_>) -> Result<Self> {
1449
               Ok(Self::default())
1449
           }
49
           fn encode_onto<W: Writer + ?Sized>(self, _w: &mut W) -> EncodeResult<()> {
49
               Ok(())
49
           }
       }
   }
}
#[allow(unused_imports)] // TODO #1060
pub(crate) use empty_body;
empty_body! {
    /// A padding message, which is always ignored.
    pub struct Drop {}
}
empty_body! {
    /// Tells a circuit to close all downstream hops on the circuit.
    pub struct Truncate {}
}
empty_body! {
    /// Opens a new stream on a directory cache.
    pub struct BeginDir {}
}
/// Helper: declare a RelayMsg implementation for a message type that has a
/// fixed command.
//
// TODO: It might be better to merge Body with RelayMsg, but that is complex,
// since their needs are _slightly_ different.
//
// TODO: If we *do* make the change above, then perhaps we should also implement
// our restricted enums in terms of this, so that there is only one instance of
// [<$body:snake:upper>]
macro_rules! msg_impl_relaymsg {
    ($($body:ident),* $(,)?) =>
    {paste::paste!{
       $(impl crate::relaycell::RelayMsg for $body {
            fn cmd(&self) -> crate::relaycell::RelayCmd { crate::relaycell::RelayCmd::[< $body:snake:upper >] }
85
            fn encode_onto<W: tor_bytes::Writer + ?Sized>(self, w: &mut W) -> tor_bytes::EncodeResult<()> {
85
                crate::relaycell::msg::Body::encode_onto(self, w)
85
            }
8568
            fn decode_from_reader(cmd: RelayCmd, r: &mut tor_bytes::Reader<'_>) -> tor_bytes::Result<Self> {
8568
                if cmd != crate::relaycell::RelayCmd::[< $body:snake:upper >] {
378
                    return Err(tor_bytes::Error::InvalidMessage(
378
                        format!("Expected {} command; got {cmd}", stringify!([< $body:snake:upper >])).into()
378
                    ));
8190
                }
8190
                crate::relaycell::msg::Body::decode_from_reader(r)
8568
            }
        }
        impl TryFrom<AnyRelayMsg> for $body {
            type Error = crate::Error;
23814
            fn try_from(msg: AnyRelayMsg) -> crate::Result<$body> {
                use crate::relaycell::RelayMsg;
23814
                match msg {
23814
                    AnyRelayMsg::$body(b) => Ok(b),
                    _ => Err(crate::Error::CircProto(format!("Expected {}; got {}" ,
                                                     stringify!([<$body:snake:upper>]),
                                                     msg.cmd())) ),
                }
23814
            }
        }
        )*
    }}
}
msg_impl_relaymsg!(
    Begin, Data, End, Connected, Sendme, Extend, Extended, Extend2, Extended2, Truncate, Truncated,
    Drop, Resolve, Resolved, BeginDir,
);
#[cfg(feature = "experimental-udp")]
msg_impl_relaymsg!(ConnectUdp, ConnectedUdp, Datagram);
#[cfg(feature = "hs")]
msg_impl_relaymsg!(
    EstablishIntro,
    EstablishRendezvous,
    Introduce1,
    Introduce2,
    Rendezvous1,
    Rendezvous2,
    IntroEstablished,
    RendezvousEstablished,
    IntroduceAck,
);
#[cfg(feature = "conflux")]
msg_impl_relaymsg!(ConfluxSwitch, ConfluxLink, ConfluxLinked, ConfluxLinkedAck);
msg_impl_relaymsg!(Xon, Xoff);
#[cfg(test)]
mod test {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_time_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    #![allow(clippy::string_slice)] // See arti#2571
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
    use super::*;
    #[test]
    fn sendme_tags() {
        // strings of 20 or 16 bytes.
        let ts: Vec<SendmeTag> = vec![
            (*b"Yea, on the word of ").into(),
            (*b"a Bloom, ye shal").into(),
            (*b"l ere long enter int").into(),
            (*b"o the golden cit").into(),
        ];
        for (i1, i2) in (0..4).zip(0..4) {
            if i1 == i2 {
                assert_eq!(ts[i1], ts[i2]);
            } else {
                assert_ne!(ts[i1], ts[i2]);
            }
        }
        assert_eq!(ts[0].as_ref(), &b"Yea, on the word of "[..]);
        assert_eq!(ts[3].as_ref(), &b"o the golden cit"[..]);
        assert_eq!(ts[1], b"a Bloom, ye shal"[..].try_into().unwrap());
        assert_eq!(ts[2], b"l ere long enter int"[..].try_into().unwrap());
        // 15 bytes long.
        assert!(matches!(
            SendmeTag::try_from(&b"o the golden ci"[..]),
            Err(InvalidSendmeTag { .. }),
        ));
    }
}