1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
//! Socket address related components.
//!
//! # Binary Format of Socket Address
//!
//! ```text
//!  0                   1                   2                   3
//!  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//! |0 0 0 0 0 0 0 0|    Family     |           Port                |
//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//! |                                                               |
//! |                 Address (32 bits or 128 bits)                 |
//! |                                                               |
//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//!
//! Family: IPv4=1, IPv6=2
//! ```
use bytecodec::bytes::{BytesDecoder, BytesEncoder};
use bytecodec::combinator::Peekable;
use bytecodec::fixnum::{U16beDecoder, U16beEncoder, U8Decoder, U8Encoder};
use bytecodec::{ByteCount, Decode, Encode, Eos, ErrorKind, Result, SizedEncode};
use std::net::{IpAddr, SocketAddr};

use constants::MAGIC_COOKIE;
use TransactionId;

const FAMILY_IPV4: u8 = 1;
const FAMILY_IPV6: u8 = 2;

/// Applies XOR operation on the given socket address.
pub fn socket_addr_xor(addr: SocketAddr, transaction_id: TransactionId) -> SocketAddr {
    let xor_port = addr.port() ^ (MAGIC_COOKIE >> 16) as u16;
    match addr.ip() {
        IpAddr::V4(ip) => {
            let mut octets = ip.octets();
            for (i, b) in octets.iter_mut().enumerate() {
                *b ^= (MAGIC_COOKIE >> (24 - i * 8)) as u8;
            }
            let xor_ip = From::from(octets);
            SocketAddr::new(IpAddr::V4(xor_ip), xor_port)
        }
        IpAddr::V6(ip) => {
            let mut octets = ip.octets();
            for (i, b) in octets.iter_mut().enumerate().take(4) {
                *b ^= (MAGIC_COOKIE >> (24 - i * 8)) as u8;
            }
            for (i, b) in octets.iter_mut().enumerate().take(16).skip(4) {
                *b ^= transaction_id.as_bytes()[i - 4];
            }
            let xor_ip = From::from(octets);
            SocketAddr::new(IpAddr::V6(xor_ip), xor_port)
        }
    }
}

/// Socket address decoder.
#[derive(Debug, Default)]
pub struct SocketAddrDecoder {
    unused: U8Decoder,
    family: Peekable<U8Decoder>,
    port: U16beDecoder,
    ip: BytesDecoder<IpBytes>,
}
impl SocketAddrDecoder {
    /// Makes a new `SocketAddrDecoder` instance.
    pub fn new() -> Self {
        Self::default()
    }
}
impl Decode for SocketAddrDecoder {
    type Item = SocketAddr;

    fn decode(&mut self, buf: &[u8], eos: Eos) -> Result<usize> {
        let mut offset = 0;
        if !self.family.is_idle() {
            bytecodec_try_decode!(self.unused, offset, buf, eos);
            bytecodec_try_decode!(self.family, offset, buf, eos);

            let family = self.family.peek().expect("never fails");
            match *family {
                FAMILY_IPV4 => self.ip.set_bytes(IpBytes::V4([0; 4])),
                FAMILY_IPV6 => self.ip.set_bytes(IpBytes::V6([0; 16])),
                _ => track_panic!(
                    ErrorKind::InvalidInput,
                    "Unknown address family: {}",
                    family
                ),
            }
        }
        bytecodec_try_decode!(self.port, offset, buf, eos);
        bytecodec_try_decode!(self.ip, offset, buf, eos);
        Ok(offset)
    }

    fn finish_decoding(&mut self) -> Result<Self::Item> {
        let _ = track!(self.unused.finish_decoding())?;
        let _ = track!(self.family.finish_decoding())?;
        let port = track!(self.port.finish_decoding())?;
        let ip = match track!(self.ip.finish_decoding())? {
            IpBytes::V4(b) => IpAddr::V4(b.into()),
            IpBytes::V6(b) => IpAddr::V6(b.into()),
        };
        Ok(SocketAddr::new(ip, port))
    }

    fn requiring_bytes(&self) -> ByteCount {
        self.unused
            .requiring_bytes()
            .add_for_decoding(self.family.requiring_bytes())
            .add_for_decoding(self.port.requiring_bytes())
            .add_for_decoding(self.ip.requiring_bytes())
    }

    fn is_idle(&self) -> bool {
        self.port.is_idle() && self.ip.is_idle()
    }
}

/// Socket address encoder.
#[derive(Debug, Default)]
pub struct SocketAddrEncoder {
    unused: U8Encoder,
    family: U8Encoder,
    port: U16beEncoder,
    ip: BytesEncoder<IpBytes>,
}
impl SocketAddrEncoder {
    /// Makes a new `SocketAddrEncoder` instance.
    pub fn new() -> Self {
        Self::default()
    }
}
impl Encode for SocketAddrEncoder {
    type Item = SocketAddr;

    fn encode(&mut self, buf: &mut [u8], eos: Eos) -> Result<usize> {
        let mut offset = 0;
        bytecodec_try_encode!(self.unused, offset, buf, eos);
        bytecodec_try_encode!(self.family, offset, buf, eos);
        bytecodec_try_encode!(self.port, offset, buf, eos);
        bytecodec_try_encode!(self.ip, offset, buf, eos);
        Ok(offset)
    }

    fn start_encoding(&mut self, item: Self::Item) -> Result<()> {
        track!(self.unused.start_encoding(0))?;
        if item.ip().is_ipv4() {
            track!(self.family.start_encoding(FAMILY_IPV4))?;
        } else {
            track!(self.family.start_encoding(FAMILY_IPV6))?;
        }
        track!(self.port.start_encoding(item.port()))?;
        track!(self.ip.start_encoding(IpBytes::new(item.ip())))?;
        Ok(())
    }

    fn requiring_bytes(&self) -> ByteCount {
        ByteCount::Finite(self.exact_requiring_bytes())
    }

    fn is_idle(&self) -> bool {
        self.ip.is_idle()
    }
}
impl SizedEncode for SocketAddrEncoder {
    fn exact_requiring_bytes(&self) -> u64 {
        self.unused.exact_requiring_bytes()
            + self.family.exact_requiring_bytes()
            + self.port.exact_requiring_bytes()
            + self.ip.exact_requiring_bytes()
    }
}

#[derive(Debug)]
enum IpBytes {
    V4([u8; 4]),
    V6([u8; 16]),
}
impl IpBytes {
    fn new(ip: IpAddr) -> Self {
        match ip {
            IpAddr::V4(ip) => IpBytes::V4(ip.octets()),
            IpAddr::V6(ip) => IpBytes::V6(ip.octets()),
        }
    }
}
impl AsRef<[u8]> for IpBytes {
    fn as_ref(&self) -> &[u8] {
        match self {
            IpBytes::V4(bytes) => bytes,
            IpBytes::V6(bytes) => bytes,
        }
    }
}
impl AsMut<[u8]> for IpBytes {
    fn as_mut(&mut self) -> &mut [u8] {
        match self {
            IpBytes::V4(bytes) => bytes,
            IpBytes::V6(bytes) => bytes,
        }
    }
}

#[cfg(test)]
mod tests {
    use bytecodec::{DecodeExt, EncodeExt};

    use super::*;

    #[test]
    fn socket_addr_xor_works() {
        let transaction_id = TransactionId::new([
            0xb7, 0xe7, 0xa7, 0x01, 0xbc, 0x34, 0xd6, 0x86, 0xfa, 0x87, 0xdf, 0xae,
        ]);

        // IPv4
        let addr: SocketAddr = "192.0.2.1:32853".parse().unwrap();
        assert_eq!(
            socket_addr_xor(addr, transaction_id),
            "225.18.166.67:41287".parse().unwrap()
        );

        // IPv6
        let addr: SocketAddr = "[2001:db8:1234:5678:11:2233:4455:6677]:32853"
            .parse()
            .unwrap();
        assert_eq!(
            socket_addr_xor(addr, transaction_id),
            "[113:a9fa:a5d3:f179:bc25:f4b5:bed2:b9d9]:41287"
                .parse()
                .unwrap()
        );
    }

    #[test]
    fn socket_addr_encoder_works() {
        let mut encoder = SocketAddrEncoder::new();

        let v4addr = "127.0.0.1:80".parse().unwrap();
        let bytes = encoder.encode_into_bytes(v4addr).unwrap();
        assert_eq!(bytes, [0, 1, 0, 80, 127, 0, 0, 1]);

        let v6addr = "[::]:90".parse().unwrap();
        let bytes = encoder.encode_into_bytes(v6addr).unwrap();
        assert_eq!(
            bytes,
            [0, 2, 0, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        );
    }

    #[test]
    fn socket_addr_decoder_works() {
        let mut decoder = SocketAddrDecoder::new();

        let v4addr = decoder
            .decode_from_bytes(&[0, 1, 0, 80, 127, 0, 0, 1])
            .unwrap();
        assert_eq!(v4addr.to_string(), "127.0.0.1:80");

        let v6addr = decoder
            .decode_from_bytes(&[0, 2, 0, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
            .unwrap();
        assert_eq!(v6addr.to_string(), "[::]:90");
    }
}