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::{RelayCellFormat, RelayCmd};
7
use crate::chancell::msg::{
8
    DestroyReason, HandshakeType, TAP_C_HANDSHAKE_LEN, TAP_S_HANDSHAKE_LEN,
9
};
10
use crate::chancell::CELL_DATA_LEN;
11
use caret::caret_int;
12
use derive_deftly::Deftly;
13
use std::fmt::Write;
14
use std::net::{IpAddr, Ipv4Addr};
15
use std::num::NonZeroU8;
16
use tor_bytes::{EncodeError, EncodeResult, Error, Result};
17
use tor_bytes::{Readable, Reader, Writeable, Writer};
18
use tor_linkspec::EncodedLinkSpec;
19
use tor_llcrypto::pk::rsa::RsaIdentity;
20
use tor_llcrypto::util::ct::CtByteArray;
21
use tor_memquota::{derive_deftly_template_HasMemoryCost, memory_cost_structural_copy};
22

            
23
use bitflags::bitflags;
24

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

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

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

            
125
    _ =>
126
    /// An unrecognized command.
127
    Unrecognized,
128
    }
129
}
130

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

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

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

            
188
/// A Begin message creates a new data stream.
189
///
190
/// Upon receiving a Begin message, relays should try to open a new stream
191
/// for the client, if their exit policy permits, and associate it with a
192
/// new TCP connection to the target address.
193
///
194
/// If the exit decides to reject the Begin message, or if the TCP
195
/// connection fails, the exit should send an End message.
196
///
197
/// Clients should reject these messages.
198
#[derive(Debug, Clone, Deftly)]
199
#[derive_deftly(HasMemoryCost)]
200
pub struct Begin {
201
    /// Ascii string describing target address
202
    addr: Vec<u8>,
203
    /// Target port
204
    port: u16,
205
    /// Flags that describe how to resolve the address
206
    flags: BeginFlags,
207
}
208

            
209
impl Begin {
210
    /// Construct a new Begin cell
211
84
    pub fn new<F>(addr: &str, port: u16, flags: F) -> crate::Result<Self>
212
84
    where
213
84
        F: Into<BeginFlags>,
214
84
    {
215
84
        if !addr.is_ascii() {
216
2
            return Err(crate::Error::BadStreamAddress);
217
82
        }
218
82
        let mut addr = addr.to_string();
219
82
        addr.make_ascii_lowercase();
220
82
        Ok(Begin {
221
82
            addr: addr.into_bytes(),
222
82
            port,
223
82
            flags: flags.into(),
224
82
        })
225
84
    }
226

            
227
    /// Return the address requested in this message.
228
    pub fn addr(&self) -> &[u8] {
229
        &self.addr[..]
230
    }
231

            
232
    /// Return the port requested by this message.
233
    pub fn port(&self) -> u16 {
234
        self.port
235
    }
236

            
237
    /// Return the set of flags provided in this message.
238
    pub fn flags(&self) -> BeginFlags {
239
        self.flags
240
    }
241
}
242

            
243
impl Body for Begin {
244
2255
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
245
2200
        let addr = {
246
2255
            if r.peek(1)? == b"[" {
247
                // IPv6 address
248
110
                r.advance(1)?;
249
110
                let a = r.take_until(b']')?;
250
110
                let colon = r.take_u8()?;
251
110
                if colon != b':' {
252
55
                    return Err(Error::InvalidMessage("missing port in begin cell".into()));
253
55
                }
254
55
                a
255
            } else {
256
                // IPv4 address, or hostname.
257
2145
                r.take_until(b':')?
258
            }
259
        };
260
2200
        let port = r.take_until(0)?;
261
2200
        let flags = if r.remaining() >= 4 { r.take_u32()? } else { 0 };
262

            
263
2200
        if !addr.is_ascii() {
264
55
            return Err(Error::InvalidMessage(
265
55
                "target address in begin cell not ascii".into(),
266
55
            ));
267
2145
        }
268

            
269
2145
        let port = std::str::from_utf8(port)
270
2145
            .map_err(|_| Error::InvalidMessage("port in begin cell not utf8".into()))?;
271

            
272
2145
        let port = port
273
2145
            .parse()
274
2145
            .map_err(|_| Error::InvalidMessage("port in begin cell not a valid port".into()))?;
275

            
276
2145
        Ok(Begin {
277
2145
            addr: addr.into(),
278
2145
            port,
279
2145
            flags: flags.into(),
280
2145
        })
281
2255
    }
282
88
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
283
88
        if self.addr.contains(&b':') {
284
4
            w.write_u8(b'[');
285
4
            w.write_all(&self.addr[..]);
286
4
            w.write_u8(b']');
287
84
        } else {
288
84
            w.write_all(&self.addr[..]);
289
84
        }
290
88
        w.write_u8(b':');
291
88
        w.write_all(self.port.to_string().as_bytes());
292
88
        w.write_u8(0);
293
88
        if self.flags.bits() != 0 {
294
76
            w.write_u32(self.flags.bits());
295
80
        }
296
88
        Ok(())
297
88
    }
298
}
299

            
300
/// A Data message represents data sent along a stream.
301
///
302
/// Upon receiving a Data message for a live stream, the client or
303
/// exit sends that data onto the associated TCP connection.
304
///
305
/// These messages hold between 1 and [Data::MAXLEN] bytes of data each;
306
/// they are the most numerous messages on the Tor network.
307
#[derive(Debug, Clone, Deftly)]
308
#[derive_deftly(HasMemoryCost)]
309
pub struct Data {
310
    /// Contents of the cell, to be sent on a specific stream
311
    ///
312
    /// INVARIANT: Holds between 1 and [`Data::MAXLEN`] bytes, inclusive.
313
    //
314
    // TODO: There's a good case to be made that this should be a BoxedCellBody
315
    // instead, to avoid allocations and copies.  But first probably we should
316
    // figure out how proposal 340 will work with this.  Possibly, we will wind
317
    // up using `bytes` or something.
318
    body: Vec<u8>,
319
}
320
impl Data {
321
    /// The longest allowable body length for a single V0 data cell.
322
    ///
323
    /// Relay command (1) + 'Recognized' (2) + StreamID (2) + Digest (4) + Length (2) = 11
324
    pub const MAXLEN_V0: usize = CELL_DATA_LEN - 11;
325

            
326
    /// The longest allowable body length for a single V1 data cell.
327
    ///
328
    /// Tag (16) + Relay command (1) + Length (2) + StreamID (2) = 21
329
    pub const MAXLEN_V1: usize = CELL_DATA_LEN - 21;
330

            
331
    /// The longest allowable body length for any data cell.
332
    ///
333
    /// Note that this value is too large to fit into a v1 relay cell;
334
    /// see [`MAXLEN_V1`](Data::MAXLEN_V1) if you are making a v1 data cell.
335
    ///
336
    pub const MAXLEN: usize = Data::MAXLEN_V0;
337

            
338
    /// Construct a new data cell.
339
    ///
340
    /// Returns an error if `inp` is longer than [`Data::MAXLEN`] bytes.
341
1045
    pub fn new(inp: &[u8]) -> crate::Result<Self> {
342
1045
        if inp.len() > Data::MAXLEN {
343
55
            return Err(crate::Error::CantEncode("Data message too long"));
344
990
        }
345
990
        if inp.is_empty() {
346
            return Err(crate::Error::CantEncode("Empty data message"));
347
990
        }
348
990
        Ok(Self::new_unchecked(inp.into()))
349
1045
    }
350

            
351
    /// Construct a new data cell, taking as many bytes from `inp`
352
    /// as possible.
353
    ///
354
    /// Return the data cell, and a slice holding any bytes that
355
    /// wouldn't fit (if any).
356
    ///
357
    /// Returns None if the input was empty.
358
79035
    pub fn try_split_from(version: RelayCellFormat, inp: &[u8]) -> Option<(Self, &[u8])> {
359
79035
        if inp.is_empty() {
360
            return None;
361
79035
        }
362
79035
        let upper_bound = Self::max_body_len(version);
363
79035
        let len = std::cmp::min(inp.len(), upper_bound);
364
79035
        let (data, remainder) = inp.split_at(len);
365
79035
        Some((Self::new_unchecked(data.into()), remainder))
366
79035
    }
367

            
368
    /// Construct a new data cell from a provided vector of bytes.
369
    ///
370
    /// The vector _must_ not have more than [`Data::MAXLEN`] bytes, and must
371
    /// not be empty.
372
80025
    fn new_unchecked(body: Vec<u8>) -> Self {
373
80025
        debug_assert!((1..=Data::MAXLEN).contains(&body.len()));
374
80025
        Data { body }
375
80025
    }
376

            
377
    /// Return the maximum allowable body length for a Data message
378
    /// using the provided `format`.
379
81015
    pub fn max_body_len(format: RelayCellFormat) -> usize {
380
81015
        match format {
381
81015
            RelayCellFormat::V0 => Self::MAXLEN_V0,
382
            RelayCellFormat::V1 => Self::MAXLEN_V1,
383
        }
384
81015
    }
385
}
386
impl From<Data> for Vec<u8> {
387
576
    fn from(data: Data) -> Vec<u8> {
388
576
        data.body
389
576
    }
390
}
391
impl AsRef<[u8]> for Data {
392
70895
    fn as_ref(&self) -> &[u8] {
393
70895
        &self.body[..]
394
70895
    }
395
}
396

            
397
impl Body for Data {
398
72985
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
399
72985
        if r.remaining() == 0 {
400
            return Err(Error::InvalidMessage("Empty DATA message".into()));
401
72985
        }
402
72985
        Ok(Data {
403
72985
            body: r.take(r.remaining())?.into(),
404
        })
405
72985
    }
406
2814
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
407
2814
        w.write_all(&self.body);
408
2814
        Ok(())
409
2814
    }
410
}
411

            
412
/// An End message tells the other end of the circuit to close a stream.
413
///
414
/// Note that End messages do not implement a true half-closed state,
415
/// so after sending an End message each party needs to wait a while
416
/// to be sure that the stream is completely dead.
417
#[derive(Debug, Clone, Deftly)]
418
#[derive_deftly(HasMemoryCost)]
419
pub struct End {
420
    /// Reason for closing the stream
421
    reason: EndReason,
422
    /// If the reason is EXITPOLICY, this holds the resolved address an
423
    /// associated TTL.  The TTL is set to MAX if none was given.
424
    addr: Option<(IpAddr, u32)>,
425
}
426

            
427
caret_int! {
428
    /// A declared reason for closing a stream
429
    #[derive(Deftly)]
430
    #[derive_deftly(HasMemoryCost)]
431
    pub struct EndReason(u8) {
432
        /// Closing a stream because of an unspecified reason.
433
        ///
434
        /// This is the only END reason that clients send.
435
        MISC = 1,
436
        /// Couldn't look up hostname.
437
        RESOLVEFAILED = 2,
438
        /// Remote host refused connection.
439
        CONNECTREFUSED = 3,
440
        /// Closing a stream because of an exit-policy violation.
441
        EXITPOLICY = 4,
442
        /// Circuit destroyed
443
        DESTROY = 5,
444
        /// Anonymized TCP connection was closed
445
        DONE = 6,
446
        /// Connection timed out, or OR timed out while connecting
447
        TIMEOUT = 7,
448
        /// No route to target destination.
449
        NOROUTE = 8,
450
        /// OR is entering hibernation and not handling requests
451
        HIBERNATING = 9,
452
        /// Internal error at the OR
453
        INTERNAL = 10,
454
        /// Ran out of resources to fulfill requests
455
        RESOURCELIMIT = 11,
456
        /// Connection unexpectedly reset
457
        CONNRESET = 12,
458
        /// Tor protocol violation
459
        TORPROTOCOL = 13,
460
        /// BEGIN_DIR cell at a non-directory-cache.
461
        NOTDIRECTORY = 14,
462
    }
463
}
464

            
465
impl tor_error::HasKind for EndReason {
466
    fn kind(&self) -> tor_error::ErrorKind {
467
        use tor_error::ErrorKind as EK;
468
        use EndReason as E;
469
        match *self {
470
            E::MISC => EK::RemoteStreamError,
471
            E::RESOLVEFAILED => EK::RemoteHostResolutionFailed,
472
            E::CONNECTREFUSED => EK::RemoteConnectionRefused,
473
            E::EXITPOLICY => EK::ExitPolicyRejected,
474
            E::DESTROY => EK::CircuitCollapse,
475
            E::DONE => EK::RemoteStreamClosed,
476
            E::TIMEOUT => EK::ExitTimeout,
477
            E::NOROUTE => EK::RemoteNetworkFailed,
478
            E::RESOURCELIMIT | E::HIBERNATING => EK::RelayTooBusy,
479
            E::INTERNAL | E::TORPROTOCOL | E::NOTDIRECTORY => EK::TorProtocolViolation,
480
            E::CONNRESET => EK::RemoteStreamReset,
481
            _ => EK::RemoteStreamError,
482
        }
483
    }
484
}
485

            
486
impl End {
487
    /// Make a new END_REASON_MISC message.
488
    ///
489
    /// Clients send this every time they decide to close a stream.
490
935
    pub fn new_misc() -> Self {
491
935
        End {
492
935
            reason: EndReason::MISC,
493
935
            addr: None,
494
935
        }
495
935
    }
496
    /// Make a new END message with the provided end reason.
497
495
    pub fn new_with_reason(reason: EndReason) -> Self {
498
495
        End { reason, addr: None }
499
495
    }
500
    /// Make a new END message with END_REASON_EXITPOLICY, and the
501
    /// provided address and ttl.
502
165
    pub fn new_exitpolicy(addr: IpAddr, ttl: u32) -> Self {
503
165
        End {
504
165
            reason: EndReason::EXITPOLICY,
505
165
            addr: Some((addr, ttl)),
506
165
        }
507
165
    }
508
    /// Return the provided EndReason for this End cell.
509
220
    pub fn reason(&self) -> EndReason {
510
220
        self.reason
511
220
    }
512
}
513
impl Body for End {
514
990
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
515
990
        if r.remaining() == 0 {
516
55
            return Ok(End {
517
55
                reason: EndReason::MISC,
518
55
                addr: None,
519
55
            });
520
935
        }
521
935
        let reason = r.take_u8()?.into();
522
935
        if reason == EndReason::EXITPOLICY {
523
165
            let addr = match r.remaining() {
524
110
                4 | 8 => IpAddr::V4(r.extract()?),
525
55
                16 | 20 => IpAddr::V6(r.extract()?),
526
                _ => {
527
                    // Ignores other message lengths.
528
                    return Ok(End { reason, addr: None });
529
                }
530
            };
531
165
            let ttl = if r.remaining() == 4 {
532
110
                r.take_u32()?
533
            } else {
534
55
                u32::MAX
535
            };
536
165
            Ok(End {
537
165
                reason,
538
165
                addr: Some((addr, ttl)),
539
165
            })
540
        } else {
541
770
            Ok(End { reason, addr: None })
542
        }
543
990
    }
544
70
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
545
70
        w.write_u8(self.reason.into());
546
70
        if let (EndReason::EXITPOLICY, Some((addr, ttl))) = (self.reason, self.addr) {
547
12
            match addr {
548
8
                IpAddr::V4(v4) => w.write(&v4)?,
549
4
                IpAddr::V6(v6) => w.write(&v6)?,
550
            }
551
12
            w.write_u32(ttl);
552
58
        }
553
70
        Ok(())
554
70
    }
555
}
556

            
557
impl From<EndReason> for std::io::ErrorKind {
558
    fn from(e: EndReason) -> Self {
559
        use std::io::ErrorKind::*;
560
        match e {
561
            EndReason::RESOLVEFAILED => NotFound,
562
            EndReason::CONNECTREFUSED => ConnectionRefused,
563
            EndReason::EXITPOLICY => ConnectionRefused,
564
            EndReason::DESTROY => ConnectionAborted,
565
            EndReason::DONE => UnexpectedEof,
566
            EndReason::TIMEOUT => TimedOut,
567
            EndReason::HIBERNATING => ConnectionRefused,
568
            EndReason::RESOURCELIMIT => ConnectionRefused,
569
            EndReason::CONNRESET => ConnectionReset,
570
            EndReason::TORPROTOCOL => InvalidData,
571
            EndReason::NOTDIRECTORY => ConnectionRefused,
572
            EndReason::INTERNAL | EndReason::NOROUTE | EndReason::MISC => Other,
573
            _ => Other,
574
        }
575
    }
576
}
577

            
578
/// A Connected message is a successful response to a Begin message
579
///
580
/// When an outgoing connection succeeds, the exit sends a Connected
581
/// back to the client.
582
///
583
/// Clients never send Connected messages.
584
#[derive(Debug, Clone, Deftly)]
585
#[derive_deftly(HasMemoryCost)]
586
pub struct Connected {
587
    /// Resolved address and TTL (time to live) in seconds
588
    addr: Option<(IpAddr, u32)>,
589
}
590
impl Connected {
591
    /// Construct a new empty connected cell.
592
1100
    pub fn new_empty() -> Self {
593
1100
        Connected { addr: None }
594
1100
    }
595
    /// Construct a connected cell with an address and a time-to-live value.
596
1210
    pub fn new_with_addr(addr: IpAddr, ttl: u32) -> Self {
597
1210
        Connected {
598
1210
            addr: Some((addr, ttl)),
599
1210
        }
600
1210
    }
601
}
602
impl Body for Connected {
603
1870
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
604
1870
        if r.remaining() == 0 {
605
605
            return Ok(Connected { addr: None });
606
1265
        }
607
1265
        let ipv4 = r.take_u32()?;
608
1265
        let addr = if ipv4 == 0 {
609
110
            if r.take_u8()? != 6 {
610
55
                return Err(Error::InvalidMessage(
611
55
                    "Invalid address type in CONNECTED cell".into(),
612
55
                ));
613
55
            }
614
55
            IpAddr::V6(r.extract()?)
615
        } else {
616
1155
            IpAddr::V4(ipv4.into())
617
        };
618
1210
        let ttl = r.take_u32()?;
619

            
620
1210
        Ok(Connected {
621
1210
            addr: Some((addr, ttl)),
622
1210
        })
623
1870
    }
624
94
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
625
94
        if let Some((addr, ttl)) = self.addr {
626
48
            match addr {
627
44
                IpAddr::V4(v4) => w.write(&v4)?,
628
4
                IpAddr::V6(v6) => {
629
4
                    w.write_u32(0);
630
4
                    w.write_u8(6);
631
4
                    w.write(&v6)?;
632
                }
633
            }
634
48
            w.write_u32(ttl);
635
46
        }
636
94
        Ok(())
637
94
    }
638
}
639

            
640
/// An authentication tag to use for circuit-level SENDME messages.
641
///
642
/// It is either a 20-byte tag (used with Tor1 encryption),
643
/// or a 16-byte tag (used with CGO encryption).
644
#[derive(Debug, Clone, Copy, Eq, PartialEq, Deftly)]
645
#[derive_deftly(HasMemoryCost)]
646
pub struct SendmeTag {
647
    /// The number of bytes present in the tag.
648
    /// Always equal to 16 or 20.
649
    ///
650
    /// We use a NonZeroU8 here so Rust can use its niche optimization.
651
    len: NonZeroU8,
652
    /// The actual contents of the tag.
653
    ///
654
    /// Tags above 20 bytes long are always an error.
655
    ///
656
    /// Unused bytes are always set to zero, so we can derive PartialEq.
657
    tag: CtByteArray<20>,
658
}
659
impl From<[u8; 20]> for SendmeTag {
660
    // In experimentation, these "inlines" were necessary for good generated asm.
661
    #[inline]
662
95064
    fn from(value: [u8; 20]) -> Self {
663
95064
        Self {
664
95064
            len: NonZeroU8::new(20).expect("20 was not nonzero?"),
665
95064
            tag: CtByteArray::from(value),
666
95064
        }
667
95064
    }
668
}
669
impl From<[u8; 16]> for SendmeTag {
670
    // In experimentation, these "inlines" were necessary for good generated asm.
671
    #[inline]
672
792
    fn from(value: [u8; 16]) -> Self {
673
792
        let mut tag = CtByteArray::from([0; 20]);
674
792
        tag.as_mut()[0..16].copy_from_slice(&value[..]);
675
792
        Self {
676
792
            len: NonZeroU8::new(16).expect("16 was not nonzero?"),
677
792
            tag,
678
792
        }
679
792
    }
680
}
681
impl AsRef<[u8]> for SendmeTag {
682
499
    fn as_ref(&self) -> &[u8] {
683
499
        &self.tag.as_ref()[0..usize::from(u8::from(self.len))]
684
499
    }
685
}
686
/// An error from attempting to decode a SENDME tag.
687
#[derive(Clone, Debug, thiserror::Error)]
688
#[non_exhaustive]
689
#[error("Invalid size {} on SENDME tag", len)]
690
pub struct InvalidSendmeTag {
691
    /// The length of the invalid tag.
692
    len: usize,
693
}
694
impl From<InvalidSendmeTag> for tor_bytes::Error {
695
    fn from(_: InvalidSendmeTag) -> Self {
696
        tor_bytes::Error::BadLengthValue
697
    }
698
}
699

            
700
impl<'a> TryFrom<&'a [u8]> for SendmeTag {
701
    type Error = InvalidSendmeTag;
702

            
703
    // In experimentation, this "inline" was especially necessary for good generated asm.
704
    #[inline]
705
3955
    fn try_from(value: &'a [u8]) -> std::result::Result<Self, Self::Error> {
706
3955
        match value.len() {
707
            16 => {
708
480
                let a: [u8; 16] = value.try_into().expect("16 was not 16?");
709
480
                Ok(Self::from(a))
710
            }
711
            20 => {
712
3473
                let a: [u8; 20] = value.try_into().expect("20 was not 20?");
713
3473
                Ok(Self::from(a))
714
            }
715
2
            _ => Err(InvalidSendmeTag { len: value.len() }),
716
        }
717
3955
    }
718
}
719

            
720
/// A Sendme message is used to increase flow-control windows.
721
///
722
/// To avoid congestion, each Tor circuit and stream keeps track of a
723
/// number of data cells that it is willing to send.  It decrements
724
/// these numbers every time it sends a cell.  If these numbers reach
725
/// zero, then no more cells can be sent on the stream or circuit.
726
///
727
/// The only way to re-increment these numbers is by receiving a
728
/// Sendme cell from the other end of the circuit or stream.
729
///
730
/// For security, current circuit-level Sendme cells include an
731
/// authentication tag that proves knowledge of the cells that they are
732
/// acking.
733
///
734
/// See [tor-spec.txt](https://spec.torproject.org/tor-spec) for more
735
/// information; also see the source for `tor_proto::circuit::sendme`.
736
#[derive(Debug, Clone, Deftly)]
737
#[derive_deftly(HasMemoryCost)]
738
pub struct Sendme {
739
    /// A tag value authenticating the previously received data.
740
    tag: Option<SendmeTag>,
741
}
742
impl Sendme {
743
    /// Return a new empty sendme cell
744
    ///
745
    /// This format is used on streams, and on circuits without sendme
746
    /// authentication.
747
220
    pub fn new_empty() -> Self {
748
220
        Sendme { tag: None }
749
220
    }
750
    /// This format is used on circuits with sendme authentication.
751
330
    pub fn new_tag(x: [u8; 20]) -> Self {
752
330
        Sendme {
753
330
            tag: Some(x.into()),
754
330
        }
755
330
    }
756
    /// Consume this cell and return its authentication tag, if any
757
220
    pub fn into_sendme_tag(self) -> Option<SendmeTag> {
758
220
        self.tag
759
220
    }
760
}
761
impl From<SendmeTag> for Sendme {
762
    fn from(value: SendmeTag) -> Self {
763
        Self { tag: Some(value) }
764
    }
765
}
766
impl Body for Sendme {
767
660
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
768
660
        let tag = if r.remaining() == 0 {
769
275
            None
770
        } else {
771
385
            let ver = r.take_u8()?;
772
385
            match ver {
773
                0 => None,
774
                1 => {
775
385
                    let dlen = r.take_u16()?;
776
385
                    Some(r.take(dlen as usize)?.try_into()?)
777
                }
778
                _ => {
779
                    return Err(Error::InvalidMessage("Unrecognized SENDME version.".into()));
780
                }
781
            }
782
        };
783
660
        Ok(Sendme { tag })
784
660
    }
785
30
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
786
30
        match self.tag {
787
12
            None => (),
788
18
            Some(x) => {
789
18
                w.write_u8(1);
790
18
                let x = x.as_ref();
791
18
                let bodylen: u16 = x
792
18
                    .len()
793
18
                    .try_into()
794
18
                    .map_err(|_| EncodeError::BadLengthValue)?;
795
18
                w.write_u16(bodylen);
796
18
                w.write_all(x);
797
            }
798
        }
799
30
        Ok(())
800
30
    }
801
}
802

            
803
/// Extend was an obsolete circuit extension message format.
804
///
805
/// This format only handled IPv4 addresses, RSA identities, and the
806
/// TAP handshake.  Modern Tor clients use Extend2 instead.
807
#[derive(Debug, Clone, Deftly)]
808
#[derive_deftly(HasMemoryCost)]
809
pub struct Extend {
810
    /// Where to extend to (address)
811
    addr: Ipv4Addr,
812
    /// Where to extend to (port)
813
    port: u16,
814
    /// A TAP handshake to send
815
    handshake: Vec<u8>,
816
    /// The RSA identity of the target relay
817
    rsaid: RsaIdentity,
818
}
819
impl Extend {
820
    /// Construct a new (deprecated) extend cell
821
55
    pub fn new(addr: Ipv4Addr, port: u16, handshake: Vec<u8>, rsaid: RsaIdentity) -> Self {
822
55
        Extend {
823
55
            addr,
824
55
            port,
825
55
            handshake,
826
55
            rsaid,
827
55
        }
828
55
    }
829
}
830
impl Body for Extend {
831
55
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
832
55
        let addr = r.extract()?;
833
55
        let port = r.take_u16()?;
834
55
        let handshake = r.take(TAP_C_HANDSHAKE_LEN)?.into();
835
55
        let rsaid = r.extract()?;
836
55
        Ok(Extend {
837
55
            addr,
838
55
            port,
839
55
            handshake,
840
55
            rsaid,
841
55
        })
842
55
    }
843
4
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
844
4
        w.write(&self.addr)?;
845
4
        w.write_u16(self.port);
846
4
        w.write_all(&self.handshake[..]);
847
4
        w.write(&self.rsaid)?;
848
4
        Ok(())
849
4
    }
850
}
851

            
852
/// Extended was an obsolete circuit extension message, sent in reply to
853
/// an Extend message.
854
///
855
/// Like Extend, the Extended message was only designed for the TAP
856
/// handshake.
857
#[derive(Debug, Clone, Deftly)]
858
#[derive_deftly(HasMemoryCost)]
859
pub struct Extended {
860
    /// Contents of the handshake sent in response to the EXTEND
861
    handshake: Vec<u8>,
862
}
863
impl Extended {
864
    /// Construct a new Extended message with the provided handshake
865
275
    pub fn new(handshake: Vec<u8>) -> Self {
866
275
        Extended { handshake }
867
275
    }
868
}
869
impl Body for Extended {
870
55
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
871
55
        let handshake = r.take(TAP_S_HANDSHAKE_LEN)?.into();
872
55
        Ok(Extended { handshake })
873
55
    }
874
12
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
875
12
        w.write_all(&self.handshake);
876
12
        Ok(())
877
12
    }
878
}
879

            
880
/// An Extend2 message tells the last relay in a circuit to extend to a new
881
/// hop.
882
///
883
/// When a relay (call it R) receives an Extend2 message, it tries to
884
/// find (or make) a channel to the other relay (R') described in the
885
/// list of link specifiers. (A link specifier can be an IP addresses
886
/// or a cryptographic identity).  Once R has such a channel, the
887
/// it packages the client's handshake data as a new Create2 message
888
/// R'.  If R' replies with a Created2 (success) message, R packages
889
/// that message's contents in an Extended message.
890
//
891
/// Unlike Extend messages, Extend2 messages can encode any handshake
892
/// type, and can describe relays in ways other than IPv4 addresses
893
/// and RSA identities.
894
#[derive(Debug, Clone, Deftly)]
895
#[derive_deftly(HasMemoryCost)]
896
pub struct Extend2 {
897
    /// A vector of "link specifiers"
898
    ///
899
    /// These link specifiers describe where to find the target relay
900
    /// that the recipient should extend to.  They include things like
901
    /// IP addresses and identity keys.
902
    linkspec: Vec<EncodedLinkSpec>,
903
    /// Type of handshake to be sent in a CREATE2 cell
904
    handshake_type: HandshakeType,
905
    /// Body of the handshake to be sent in a CREATE2 cell
906
    handshake: Vec<u8>,
907
}
908
impl Extend2 {
909
    /// Create a new Extend2 cell.
910
1375
    pub fn new(
911
1375
        linkspec: Vec<EncodedLinkSpec>,
912
1375
        handshake_type: HandshakeType,
913
1375
        handshake: Vec<u8>,
914
1375
    ) -> Self {
915
1375
        Extend2 {
916
1375
            linkspec,
917
1375
            handshake_type,
918
1375
            handshake,
919
1375
        }
920
1375
    }
921

            
922
    /// Return the type of this handshake.
923
55
    pub fn handshake_type(&self) -> HandshakeType {
924
55
        self.handshake_type
925
55
    }
926

            
927
    /// Return the inner handshake for this Extend2 cell.
928
495
    pub fn handshake(&self) -> &[u8] {
929
495
        &self.handshake[..]
930
495
    }
931
}
932

            
933
impl Body for Extend2 {
934
550
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
935
550
        let n = r.take_u8()?;
936
550
        let linkspec = r.extract_n(n as usize)?;
937
550
        let handshake_type = r.take_u16()?.into();
938
550
        let hlen = r.take_u16()?;
939
550
        let handshake = r.take(hlen as usize)?.into();
940
550
        Ok(Extend2 {
941
550
            linkspec,
942
550
            handshake_type,
943
550
            handshake,
944
550
        })
945
550
    }
946
52
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
947
52
        let n_linkspecs: u8 = self
948
52
            .linkspec
949
52
            .len()
950
52
            .try_into()
951
52
            .map_err(|_| EncodeError::BadLengthValue)?;
952
52
        w.write_u8(n_linkspecs);
953
156
        for ls in &self.linkspec {
954
104
            w.write(ls)?;
955
        }
956
52
        w.write_u16(self.handshake_type.into());
957
52
        let handshake_len: u16 = self
958
52
            .handshake
959
52
            .len()
960
52
            .try_into()
961
52
            .map_err(|_| EncodeError::BadLengthValue)?;
962
52
        w.write_u16(handshake_len);
963
52
        w.write_all(&self.handshake[..]);
964
52
        Ok(())
965
52
    }
966
}
967

            
968
/// Extended2 is a successful reply to an Extend2 message.
969
///
970
/// Extended2 messages are generated by the former last hop of a
971
/// circuit, to tell the client that they have successfully completed
972
/// a handshake on the client's behalf.
973
#[derive(Debug, Clone, Deftly)]
974
#[derive_deftly(HasMemoryCost)]
975
pub struct Extended2 {
976
    /// Contents of the CREATED2 cell that the new final hop sent in
977
    /// response
978
    handshake: Vec<u8>,
979
}
980
impl Extended2 {
981
    /// Construct a new Extended2 message with the provided handshake
982
1045
    pub fn new(handshake: Vec<u8>) -> Self {
983
1045
        Extended2 { handshake }
984
1045
    }
985
    /// Consume this extended2 cell and return its body.
986
660
    pub fn into_body(self) -> Vec<u8> {
987
660
        self.handshake
988
660
    }
989
}
990
impl Body for Extended2 {
991
825
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
992
825
        let hlen = r.take_u16()?;
993
825
        let handshake = r.take(hlen as usize)?;
994
825
        Ok(Extended2 {
995
825
            handshake: handshake.into(),
996
825
        })
997
825
    }
998
44
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
999
44
        let handshake_len: u16 = self
44
            .handshake
44
            .len()
44
            .try_into()
44
            .map_err(|_| EncodeError::BadLengthValue)?;
44
        w.write_u16(handshake_len);
44
        w.write_all(&self.handshake[..]);
44
        Ok(())
44
    }
}
/// 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.
55
    pub fn new(reason: DestroyReason) -> Self {
55
        Truncated { reason }
55
    }
    /// Get the provided reason to truncate the circuit.
    pub fn reason(self) -> DestroyReason {
        self.reason
    }
}
impl Body for Truncated {
55
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
55
        Ok(Truncated {
55
            reason: r.take_u8()?.into(),
        })
55
    }
4
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
4
        w.write_u8(self.reason.into());
4
        Ok(())
4
    }
}
/// 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.
110
    pub fn new(s: &str) -> Self {
110
        Resolve {
110
            query: s.as_bytes().into(),
110
        }
110
    }
    /// Construct a new resolve message to do a reverse lookup on an address
110
    pub fn new_reverse(addr: &IpAddr) -> Self {
110
        let query = match addr {
55
            IpAddr::V4(v4) => {
55
                let [a, b, c, d] = v4.octets();
55
                format!("{}.{}.{}.{}.in-addr.arpa", d, c, b, a)
            }
55
            IpAddr::V6(v6) => {
55
                let mut s = String::with_capacity(72);
880
                for o in v6.octets().iter().rev() {
880
                    let high_nybble = o >> 4;
880
                    let low_nybble = o & 15;
880
                    write!(s, "{:x}.{:x}.", low_nybble, high_nybble).unwrap();
880
                }
55
                write!(s, "ip6.arpa").unwrap();
55
                s
            }
        };
110
        Resolve {
110
            query: query.into_bytes(),
110
        }
110
    }
}
impl Body for Resolve {
165
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
165
        let query = r.take_until(0)?;
165
        Ok(Resolve {
165
            query: query.into(),
165
        })
165
    }
14
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
14
        w.write_all(&self.query[..]);
14
        w.write_u8(0);
14
        Ok(())
14
    }
}
/// 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 {
495
    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.
495
        fn res_len(tp: u8) -> Option<usize> {
495
            match tp {
165
                RES_IPV4 => Some(4),
110
                RES_IPV6 => Some(16),
220
                _ => None,
            }
495
        }
495
        let tp = r.take_u8()?;
495
        let len = r.take_u8()? as usize;
495
        if let Some(expected_len) = res_len(tp) {
275
            if len != expected_len {
55
                return Err(Error::InvalidMessage(
55
                    "Wrong length for RESOLVED answer".into(),
55
                ));
220
            }
220
        }
440
        Ok(match tp {
55
            RES_HOSTNAME => Self::Hostname(r.take(len)?.into()),
110
            RES_IPV4 => Self::Ip(IpAddr::V4(r.extract()?)),
110
            RES_IPV6 => Self::Ip(IpAddr::V6(r.extract()?)),
            RES_ERR_TRANSIENT => {
55
                r.advance(len)?;
55
                Self::TransientError
            }
            RES_ERR_NONTRANSIENT => {
55
                r.advance(len)?;
55
                Self::NontransientError
            }
55
            _ => Self::Unrecognized(tp, r.take(len)?.into()),
        })
495
    }
}
impl Writeable for ResolvedVal {
28
    fn write_onto<B: Writer + ?Sized>(&self, w: &mut B) -> EncodeResult<()> {
12
        match self {
4
            Self::Hostname(h) => {
4
                w.write_u8(RES_HOSTNAME);
4
                let h_len: u8 = h
4
                    .len()
4
                    .try_into()
4
                    .map_err(|_| EncodeError::BadLengthValue)?;
4
                w.write_u8(h_len);
4
                w.write_all(&h[..]);
            }
8
            Self::Ip(IpAddr::V4(a)) => {
8
                w.write_u8(RES_IPV4);
8
                w.write_u8(4); // length
8
                w.write(a)?;
            }
4
            Self::Ip(IpAddr::V6(a)) => {
4
                w.write_u8(RES_IPV6);
4
                w.write_u8(16); // length
4
                w.write(a)?;
            }
4
            Self::TransientError => {
4
                w.write_u8(RES_ERR_TRANSIENT);
4
                w.write_u8(0); // length
4
            }
4
            Self::NontransientError => {
4
                w.write_u8(RES_ERR_NONTRANSIENT);
4
                w.write_u8(0); // length
4
            }
4
            Self::Unrecognized(tp, v) => {
4
                w.write_u8(*tp);
4
                let v_len: u8 = v
4
                    .len()
4
                    .try_into()
4
                    .map_err(|_| EncodeError::BadLengthValue)?;
4
                w.write_u8(v_len);
4
                w.write_all(&v[..]);
            }
        }
28
        Ok(())
28
    }
}
/// 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.
385
    pub fn new_empty() -> Self {
385
        Resolved {
385
            answers: Vec::new(),
385
        }
385
    }
    /// 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?
110
    pub fn new_err(transient: bool, ttl: u32) -> Self {
110
        let mut res = Self::new_empty();
110
        let err = if transient {
55
            ResolvedVal::TransientError
        } else {
55
            ResolvedVal::NontransientError
        };
110
        res.add_answer(err, ttl);
110
        res
110
    }
    /// Add a single answer to this Resolved message
385
    pub fn add_answer(&mut self, answer: ResolvedVal, ttl: u32) {
385
        self.answers.push((answer, ttl));
385
    }
    /// 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.
55
    pub fn into_answers(self) -> Vec<(ResolvedVal, u32)> {
55
        self.answers
55
    }
}
impl Body for Resolved {
495
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
495
        let mut answers = Vec::new();
935
        while r.remaining() > 0 {
495
            let rv = r.extract()?;
440
            let ttl = r.take_u32()?;
440
            answers.push((rv, ttl));
        }
440
        Ok(Resolved { answers })
495
    }
28
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
56
        for (rv, ttl) in &self.answers {
28
            w.write(rv)?;
28
            w.write_u32(*ttl);
        }
28
        Ok(())
28
    }
}
/// 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.
2
    pub fn new<B>(cmd: RelayCmd, body: B) -> Self
2
    where
2
        B: Into<Vec<u8>>,
2
    {
2
        let body = body.into();
2
        Unrecognized { cmd, body }
2
    }
    /// Return the command associated with this message
55
    pub fn cmd(&self) -> RelayCmd {
55
        self.cmd
55
    }
    /// Decode this message, using a provided command.
55
    pub fn decode_with_cmd(cmd: RelayCmd, r: &mut Reader<'_>) -> Result<Self> {
55
        let mut r = Unrecognized::decode_from_reader(r)?;
55
        r.cmd = cmd;
55
        Ok(r)
55
    }
}
impl Body for Unrecognized {
55
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
55
        Ok(Unrecognized {
55
            cmd: 0.into(),
55
            body: r.take(r.remaining())?.into(),
        })
55
    }
4
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
4
        w.write_all(&self.body[..]);
4
        Ok(())
4
    }
}
/// 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 {
385
           fn decode_from_reader(_r: &mut Reader<'_>) -> Result<Self> {
385
               Ok(Self::default())
385
           }
22
           fn encode_onto<W: Writer + ?Sized>(self, _w: &mut W) -> EncodeResult<()> {
22
               Ok(())
22
           }
       }
   }
}
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 >] }
            fn encode_onto<W: tor_bytes::Writer + ?Sized>(self, w: &mut W) -> tor_bytes::EncodeResult<()> {
                crate::relaycell::msg::Body::encode_onto(self, w)
            }
2090
            fn decode_from_reader(cmd: RelayCmd, r: &mut tor_bytes::Reader<'_>) -> tor_bytes::Result<Self> {
2090
                if cmd != crate::relaycell::RelayCmd::[< $body:snake:upper >] {
220
                    return Err(tor_bytes::Error::InvalidMessage(
220
                        format!("Expected {} command; got {cmd}", stringify!([< $body:snake:upper >])).into()
220
                    ));
1870
                }
1870
                crate::relaycell::msg::Body::decode_from_reader(r)
2090
            }
        }
        impl TryFrom<AnyRelayMsg> for $body {
            type Error = crate::Error;
4400
            fn try_from(msg: AnyRelayMsg) -> crate::Result<$body> {
                use crate::relaycell::RelayMsg;
4400
                match msg {
4400
                    AnyRelayMsg::$body(b) => Ok(b),
                    _ => Err(crate::Error::CircProto(format!("Expected {}; got {}" ,
                                                     stringify!([<$body:snake:upper>]),
                                                     msg.cmd())) ),
                }
4400
            }
        }
        )*
    }}
}
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);
#[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_duration_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    //! <!-- @@ 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 { .. }),
        ));
    }
}