Skip to main content

rtc_stun/
xoraddr.rs

1#[cfg(test)]
2mod xoraddr_test;
3
4use crate::addr::*;
5use crate::attributes::*;
6use crate::checks::*;
7use crate::message::*;
8use shared::error::*;
9
10use std::fmt;
11use std::mem;
12use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
13
14const WORD_SIZE: usize = mem::size_of::<usize>();
15
16//var supportsUnaligned = runtime.GOARCH == "386" || runtime.GOARCH == "amd64" // nolint:gochecknoglobals
17
18// fast_xor_bytes xors in bulk. It only works on architectures that
19// support unaligned read/writes.
20/*TODO: fn fast_xor_bytes(dst:&[u8], a:&[u8], b:&[u8]) ->usize {
21    let mut n = a.len();
22    if b.len() < n {
23        n = b.len();
24    }
25
26    let w = n / WORD_SIZE;
27    if w > 0 {
28        let dw = *(*[]uintptr)(unsafe.Pointer(&dst))
29        let aw = *(*[]uintptr)(unsafe.Pointer(&a))
30        let bw = *(*[]uintptr)(unsafe.Pointer(&b))
31        for i := 0; i < w; i++ {
32            dw[i] = aw[i] ^ bw[i]
33        }
34    }
35
36    for i := n - n%WORD_SIZE; i < n; i++ {
37        dst[i] = a[i] ^ b[i]
38    }
39
40    return n
41}*/
42
43fn safe_xor_bytes(dst: &mut [u8], a: &[u8], b: &[u8]) -> usize {
44    let mut n = a.len();
45    if b.len() < n {
46        n = b.len();
47    }
48    if dst.len() < n {
49        n = dst.len();
50    }
51    for i in 0..n {
52        dst[i] = a[i] ^ b[i];
53    }
54    n
55}
56
57/// xor_bytes xors the bytes in a and b. The destination is assumed to have enough
58/// space. Returns the number of bytes xor'd.
59pub fn xor_bytes(dst: &mut [u8], a: &[u8], b: &[u8]) -> usize {
60    //TODO: if supportsUnaligned {
61    //	return fastXORBytes(dst, a, b)
62    //}
63    safe_xor_bytes(dst, a, b)
64}
65
66/// XORMappedAddress implements XOR-MAPPED-ADDRESS attribute.
67///
68/// RFC 5389 Section 15.2
69pub struct XorMappedAddress {
70    /// The IP address.
71    pub ip: IpAddr,
72    /// The port.
73    pub port: u16,
74}
75
76impl Default for XorMappedAddress {
77    fn default() -> Self {
78        XorMappedAddress {
79            ip: IpAddr::V4(Ipv4Addr::from(0)),
80            port: 0,
81        }
82    }
83}
84
85impl fmt::Display for XorMappedAddress {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        match self.ip {
88            IpAddr::V4(_) => write!(f, "{}:{}", self.ip, self.port),
89            IpAddr::V6(_) => write!(f, "[{}]:{}", self.ip, self.port),
90        }
91    }
92}
93
94impl Setter for XorMappedAddress {
95    /// add_to adds XOR-MAPPED-ADDRESS to m. Can return ErrBadIPLength
96    /// if len(a.IP) is invalid.
97    fn add_to(&self, m: &mut Message) -> Result<()> {
98        self.add_to_as(m, ATTR_XORMAPPED_ADDRESS)
99    }
100}
101
102impl Getter for XorMappedAddress {
103    /// get_from decodes XOR-MAPPED-ADDRESS attribute in message and returns
104    /// error if any. While decoding, a.IP is reused if possible and can be
105    /// rendered to invalid state (e.g. if a.IP was set to IPv6 and then
106    /// IPv4 value were decoded into it), be careful.
107    fn get_from(&mut self, m: &Message) -> Result<()> {
108        self.get_from_as(m, ATTR_XORMAPPED_ADDRESS)
109    }
110}
111
112impl XorMappedAddress {
113    /// add_to_as adds XOR-MAPPED-ADDRESS value to m as t attribute.
114    pub fn add_to_as(&self, m: &mut Message, t: AttrType) -> Result<()> {
115        let (family, ip_len, ip) = match self.ip {
116            IpAddr::V4(ipv4) => (FAMILY_IPV4, IPV4LEN, ipv4.octets().to_vec()),
117            IpAddr::V6(ipv6) => (FAMILY_IPV6, IPV6LEN, ipv6.octets().to_vec()),
118        };
119
120        let mut value = [0; 32 + 128];
121        //value[0] = 0 // first 8 bits are zeroes
122        let mut xor_value = vec![0; IPV6LEN];
123        xor_value[4..].copy_from_slice(&m.transaction_id.0);
124        xor_value[0..4].copy_from_slice(&MAGIC_COOKIE.to_be_bytes());
125        value[0..2].copy_from_slice(&family.to_be_bytes());
126        value[2..4].copy_from_slice(&(self.port ^ (MAGIC_COOKIE >> 16) as u16).to_be_bytes());
127        xor_bytes(&mut value[4..4 + ip_len], &ip, &xor_value);
128        m.add(t, &value[..4 + ip_len]);
129        Ok(())
130    }
131
132    /// get_from_as decodes XOR-MAPPED-ADDRESS attribute value in message
133    /// getting it as for t type.
134    pub fn get_from_as(&mut self, m: &Message, t: AttrType) -> Result<()> {
135        let v = m.get(t)?;
136        if v.len() <= 4 {
137            return Err(Error::ErrUnexpectedEof);
138        }
139
140        let family = u16::from_be_bytes([v[0], v[1]]);
141        if family != FAMILY_IPV6 && family != FAMILY_IPV4 {
142            return Err(Error::Other(format!("bad value {family}")));
143        }
144
145        check_overflow(
146            t,
147            v[4..].len(),
148            if family == FAMILY_IPV4 {
149                IPV4LEN
150            } else {
151                IPV6LEN
152            },
153        )?;
154        self.port = u16::from_be_bytes([v[2], v[3]]) ^ (MAGIC_COOKIE >> 16) as u16;
155        let mut xor_value = vec![0; 4 + TRANSACTION_ID_SIZE];
156        xor_value[0..4].copy_from_slice(&MAGIC_COOKIE.to_be_bytes());
157        xor_value[4..].copy_from_slice(&m.transaction_id.0);
158
159        if family == FAMILY_IPV6 {
160            let mut ip = [0; IPV6LEN];
161            xor_bytes(&mut ip, &v[4..], &xor_value);
162            self.ip = IpAddr::V6(Ipv6Addr::from(ip));
163        } else {
164            let mut ip = [0; IPV4LEN];
165            xor_bytes(&mut ip, &v[4..], &xor_value);
166            self.ip = IpAddr::V4(Ipv4Addr::from(ip));
167        };
168
169        Ok(())
170    }
171}