Skip to main content

stem/client/
datatypes.rs

1use std::net::{Ipv4Addr, Ipv6Addr};
2
3use sha1::{Digest, Sha1};
4
5use crate::error::{Error, Result};
6
7pub const HASH_LENGTH: usize = 20;
8pub const KEY_LENGTH: usize = 16;
9
10macro_rules! integer_enum {
11    ($name:ident($int:ty) { $($variant:ident = $value:literal),+ $(,)? }) => {
12        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
13        pub enum $name {
14            $($variant,)+
15            Unknown($int),
16        }
17
18        impl $name {
19            pub fn value(self) -> $int {
20                match self {
21                    $(Self::$variant => $value,)+
22                    Self::Unknown(value) => value,
23                }
24            }
25
26            pub fn from_value(value: $int) -> Self {
27                match value {
28                    $($value => Self::$variant,)+
29                    other => Self::Unknown(other),
30                }
31            }
32
33            pub fn is_unknown(self) -> bool {
34                matches!(self, Self::Unknown(_))
35            }
36        }
37    };
38}
39
40integer_enum!(AddrType(u8) {
41    Hostname = 0,
42    Ipv4 = 4,
43    Ipv6 = 6,
44    ErrorTransient = 16,
45    ErrorPermanent = 17,
46});
47
48integer_enum!(RelayCommand(u8) {
49    Begin = 1,
50    Data = 2,
51    End = 3,
52    Connected = 4,
53    Sendme = 5,
54    Extend = 6,
55    Extended = 7,
56    Truncate = 8,
57    Truncated = 9,
58    Drop = 10,
59    Resolve = 11,
60    Resolved = 12,
61    BeginDir = 13,
62    Extend2 = 14,
63    Extended2 = 15,
64});
65
66integer_enum!(CertType(u8) {
67    Link = 1,
68    Identity = 2,
69    Authenticate = 3,
70    Ed25519Signing = 4,
71    LinkCert = 5,
72    Ed25519Authenticate = 6,
73    Ed25519Identity = 7,
74    HsV3DescSigning = 8,
75    HsV3IntroAuth = 9,
76    NtorOnionKey = 10,
77    HsV3NtorEnc = 11,
78});
79
80integer_enum!(CloseReason(u8) {
81    None = 0,
82    Protocol = 1,
83    Internal = 2,
84    Requested = 3,
85    Hibernating = 4,
86    ResourceLimit = 5,
87    ConnectFailed = 6,
88    OrIdentity = 7,
89    OrConnClosed = 8,
90    Finished = 9,
91    Timeout = 10,
92    Destroyed = 11,
93    NoSuchService = 12,
94});
95
96impl RelayCommand {
97    pub fn name(self) -> String {
98        match self {
99            Self::Unknown(value) => format!("UNKNOWN({value})"),
100            known => {
101                let mut name = String::from("RELAY");
102                for character in format!("{known:?}").chars() {
103                    if character.is_uppercase() {
104                        name.push('_');
105                    }
106                    name.push(character.to_ascii_uppercase());
107                }
108                name
109            }
110        }
111    }
112}
113
114pub struct Reader<'a> {
115    data: &'a [u8],
116}
117
118impl<'a> Reader<'a> {
119    pub fn new(data: &'a [u8]) -> Self {
120        Self { data }
121    }
122
123    pub fn remaining(&self) -> usize {
124        self.data.len()
125    }
126
127    pub fn rest(self) -> &'a [u8] {
128        self.data
129    }
130
131    pub fn take(&mut self, count: usize) -> Result<&'a [u8]> {
132        if self.data.len() < count {
133            return Err(Error::parse(format!(
134                "Expected {count} more bytes, but only {} remained",
135                self.data.len()
136            )));
137        }
138        let (taken, rest) = self.data.split_at(count);
139        self.data = rest;
140        Ok(taken)
141    }
142
143    pub fn u8(&mut self) -> Result<u8> {
144        Ok(self.take(1)?[0])
145    }
146
147    pub fn u16(&mut self) -> Result<u16> {
148        Ok(u16::from_be_bytes(
149            self.take(2)?.try_into().expect("two bytes"),
150        ))
151    }
152
153    pub fn u32(&mut self) -> Result<u32> {
154        Ok(u32::from_be_bytes(
155            self.take(4)?.try_into().expect("four bytes"),
156        ))
157    }
158
159    pub fn u64(&mut self) -> Result<u64> {
160        Ok(u64::from_be_bytes(
161            self.take(8)?.try_into().expect("eight bytes"),
162        ))
163    }
164}
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
167pub struct LinkProtocol {
168    pub version: u32,
169}
170
171impl LinkProtocol {
172    pub fn new(version: u32) -> Self {
173        Self { version }
174    }
175
176    pub fn circuit_id_size(&self) -> usize {
177        match self.version > 3 {
178            true => 4,
179            false => 2,
180        }
181    }
182
183    pub fn first_circuit_id(&self) -> u32 {
184        match self.version > 3 {
185            true => 0x8000_0000,
186            false => 1,
187        }
188    }
189
190    pub fn fixed_cell_length(&self) -> usize {
191        self.circuit_id_size() + 1 + crate::client::cells::FIXED_PAYLOAD_LENGTH
192    }
193
194    pub fn pack_circuit_id(&self, circuit_id: u32) -> Result<Vec<u8>> {
195        match self.circuit_id_size() {
196            4 => Ok(circuit_id.to_be_bytes().to_vec()),
197            _ => u16::try_from(circuit_id)
198                .map(|id| id.to_be_bytes().to_vec())
199                .map_err(|_| {
200                    Error::invalid_input("Circuit id is too large for this link protocol")
201                }),
202        }
203    }
204
205    pub fn pop_circuit_id(&self, reader: &mut Reader<'_>) -> Result<u32> {
206        match self.circuit_id_size() {
207            4 => reader.u32(),
208            _ => reader.u16().map(u32::from),
209        }
210    }
211}
212
213impl From<u32> for LinkProtocol {
214    fn from(version: u32) -> Self {
215        Self::new(version)
216    }
217}
218
219#[derive(Debug, Clone, PartialEq, Eq, Hash)]
220pub struct Address {
221    pub addr_type: AddrType,
222    value_bin: Vec<u8>,
223}
224
225impl Address {
226    pub fn parse(value: &str) -> Result<Self> {
227        if let Ok(address) = value.parse::<Ipv4Addr>() {
228            return Self::from_bytes(AddrType::Ipv4, address.octets().to_vec());
229        }
230        if let Ok(address) = value.parse::<Ipv6Addr>() {
231            return Self::from_bytes(AddrType::Ipv6, address.octets().to_vec());
232        }
233        Err(Error::invalid_input(format!(
234            "'{value}' isn't an IPv4 or IPv6 address"
235        )))
236    }
237
238    pub fn from_bytes(addr_type: AddrType, value_bin: Vec<u8>) -> Result<Self> {
239        match (addr_type, value_bin.len()) {
240            (AddrType::Ipv4, 4) | (AddrType::Ipv6, 16) => {}
241            (AddrType::Ipv4, _) => {
242                return Err(Error::invalid_input(format!(
243                    "Packed IPv4 addresses should be four bytes, but was: {value_bin:?}"
244                )));
245            }
246            (AddrType::Ipv6, _) => {
247                return Err(Error::invalid_input(format!(
248                    "Packed IPv6 addresses should be sixteen bytes, but was: \
249                    {value_bin:?}"
250                )));
251            }
252            _ => {}
253        }
254        Ok(Self {
255            addr_type,
256            value_bin,
257        })
258    }
259
260    pub fn value(&self) -> Option<String> {
261        match self.addr_type {
262            AddrType::Ipv4 => {
263                let octets: [u8; 4] = self.value_bin.as_slice().try_into().ok()?;
264                Some(Ipv4Addr::from(octets).to_string())
265            }
266            AddrType::Ipv6 => {
267                let octets: [u8; 16] = self.value_bin.as_slice().try_into().ok()?;
268                let groups: Vec<String> = Ipv6Addr::from(octets)
269                    .segments()
270                    .iter()
271                    .map(|group| format!("{group:04x}"))
272                    .collect();
273                Some(groups.join(":"))
274            }
275            _ => None,
276        }
277    }
278
279    pub fn value_bin(&self) -> &[u8] {
280        &self.value_bin
281    }
282
283    pub fn pack(&self) -> Vec<u8> {
284        let mut packed = vec![self.addr_type.value(), self.value_bin.len() as u8];
285        packed.extend_from_slice(&self.value_bin);
286        packed
287    }
288
289    pub fn pop(reader: &mut Reader<'_>) -> Result<Self> {
290        let addr_type = AddrType::from_value(reader.u8()?);
291        let length = usize::from(reader.u8()?);
292        if reader.remaining() < length {
293            return Err(Error::parse(format!(
294                "Address specified a payload of {length} bytes, but only had {}",
295                reader.remaining()
296            )));
297        }
298        Self::from_bytes(addr_type, reader.take(length)?.to_vec())
299    }
300}
301
302#[derive(Debug, Clone, PartialEq, Eq, Hash)]
303pub struct Certificate {
304    pub cert_type: CertType,
305    pub value: Vec<u8>,
306}
307
308impl Certificate {
309    pub fn new(cert_type: CertType, value: Vec<u8>) -> Self {
310        Self { cert_type, value }
311    }
312
313    pub fn pack(&self) -> Result<Vec<u8>> {
314        let length = u16::try_from(self.value.len())
315            .map_err(|_| Error::invalid_input("Certificates can't exceed 65535 bytes"))?;
316        let mut packed = vec![self.cert_type.value()];
317        packed.extend_from_slice(&length.to_be_bytes());
318        packed.extend_from_slice(&self.value);
319        Ok(packed)
320    }
321
322    pub fn pop(reader: &mut Reader<'_>) -> Result<Self> {
323        let cert_type = CertType::from_value(reader.u8()?);
324        let size = usize::from(reader.u16()?);
325        if size > reader.remaining() {
326            return Err(Error::parse(format!(
327                "CERTS cell should have a certificate with {size} bytes, but only had \
328                {} remaining",
329                reader.remaining()
330            )));
331        }
332        Ok(Self::new(cert_type, reader.take(size)?.to_vec()))
333    }
334}
335
336#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)]
337pub enum LinkSpecifier {
338    Ipv4 { address: Ipv4Addr, port: u16 },
339    Ipv6 { address: Ipv6Addr, port: u16 },
340    Fingerprint([u8; 20]),
341    Ed25519([u8; 32]),
342    Other { link_type: u8, value: Vec<u8> },
343}
344
345impl LinkSpecifier {
346    pub fn link_type(&self) -> u8 {
347        match self {
348            Self::Ipv4 { .. } => 0,
349            Self::Ipv6 { .. } => 1,
350            Self::Fingerprint(_) => 2,
351            Self::Ed25519(_) => 3,
352            Self::Other { link_type, .. } => *link_type,
353        }
354    }
355
356    fn value(&self) -> Vec<u8> {
357        match self {
358            Self::Ipv4 { address, port } => {
359                [address.octets().as_slice(), &port.to_be_bytes()].concat()
360            }
361            Self::Ipv6 { address, port } => {
362                [address.octets().as_slice(), &port.to_be_bytes()].concat()
363            }
364            Self::Fingerprint(value) => value.to_vec(),
365            Self::Ed25519(value) => value.to_vec(),
366            Self::Other { value, .. } => value.clone(),
367        }
368    }
369
370    pub fn pack(&self) -> Vec<u8> {
371        let value = self.value();
372        let mut packed = vec![self.link_type(), value.len() as u8];
373        packed.extend_from_slice(&value);
374        packed
375    }
376
377    pub fn pop(reader: &mut Reader<'_>) -> Result<Self> {
378        let link_type = reader.u8()?;
379        let size = usize::from(reader.u8()?);
380        if size > reader.remaining() {
381            return Err(Error::parse(format!(
382                "Link specifier should have {size} bytes, but only had {} remaining",
383                reader.remaining()
384            )));
385        }
386        let value = reader.take(size)?;
387        Self::from_parts(link_type, value)
388    }
389
390    fn from_parts(link_type: u8, value: &[u8]) -> Result<Self> {
391        let size_error = |name: &str, expected: usize| {
392            Error::parse(format!(
393                "{name} link specifiers should be {expected} bytes, but was {} instead: \
394                {}",
395                value.len(),
396                hex::encode(value)
397            ))
398        };
399        Ok(match link_type {
400            0 => {
401                let bytes: [u8; 6] =
402                    value.try_into().map_err(|_| size_error("IPv4", 6))?;
403                Self::Ipv4 {
404                    address: Ipv4Addr::new(bytes[0], bytes[1], bytes[2], bytes[3]),
405                    port: u16::from_be_bytes([bytes[4], bytes[5]]),
406                }
407            }
408            1 => {
409                let bytes: [u8; 18] =
410                    value.try_into().map_err(|_| size_error("IPv6", 18))?;
411                let octets: [u8; 16] = bytes[..16].try_into().expect("sixteen bytes");
412                Self::Ipv6 {
413                    address: Ipv6Addr::from(octets),
414                    port: u16::from_be_bytes([bytes[16], bytes[17]]),
415                }
416            }
417            2 => Self::Fingerprint(
418                value
419                    .try_into()
420                    .map_err(|_| size_error("Fingerprint", 20))?,
421            ),
422            3 => Self::Ed25519(value.try_into().map_err(|_| size_error("Ed25519", 32))?),
423            other => Self::Other {
424                link_type: other,
425                value: value.to_vec(),
426            },
427        })
428    }
429}
430
431#[derive(Debug, Clone, PartialEq, Eq)]
432pub struct Kdf {
433    pub key_hash: Vec<u8>,
434    pub forward_digest: Vec<u8>,
435    pub backward_digest: Vec<u8>,
436    pub forward_key: Vec<u8>,
437    pub backward_key: Vec<u8>,
438}
439
440impl Kdf {
441    pub fn from_value(key_material: &[u8]) -> Self {
442        let wanted = KEY_LENGTH * 2 + HASH_LENGTH * 3;
443        let mut derived = Vec::with_capacity(wanted + HASH_LENGTH);
444        let mut counter: u8 = 0;
445        while derived.len() < wanted {
446            let mut hasher = Sha1::new();
447            hasher.update(key_material);
448            hasher.update([counter]);
449            derived.extend_from_slice(&hasher.finalize());
450            counter += 1;
451        }
452        let mut reader = Reader::new(&derived);
453        let mut next = |count| reader.take(count).expect("enough derived bytes").to_vec();
454        Self {
455            key_hash: next(HASH_LENGTH),
456            forward_digest: next(HASH_LENGTH),
457            backward_digest: next(HASH_LENGTH),
458            forward_key: next(KEY_LENGTH),
459            backward_key: next(KEY_LENGTH),
460        }
461    }
462}