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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

use crate::inet::{
    ipv4::{IpV4Address, SocketAddressV4},
    ipv6::{IpV6Address, SocketAddressV6},
    unspecified::Unspecified,
};
use core::fmt;

#[cfg(any(test, feature = "generator"))]
use bolero_generator::*;

/// An IP address, either IPv4 or IPv6.
///
/// Instead of using `std::net::IPAddr`, this implementation
/// is geared towards `no_std` environments and zerocopy decoding.
///
/// The size is also consistent across target operating systems.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(any(test, feature = "generator"), derive(TypeGenerator))]
pub enum IpAddress {
    Ipv4(IpV4Address),
    Ipv6(IpV6Address),
}

impl IpAddress {
    /// Converts the IP address into IPv4 if it is mapped, otherwise the address is unchanged
    #[inline]
    #[must_use]
    pub fn unmap(self) -> Self {
        match self {
            Self::Ipv4(_) => self,
            Self::Ipv6(addr) => addr.unmap(),
        }
    }

    /// Converts the IP address into IPv6 if it is IPv4, otherwise the address is unchanged
    #[inline]
    #[must_use]
    pub fn to_ipv6_mapped(self) -> IpV6Address {
        match self {
            Self::Ipv4(addr) => addr.to_ipv6_mapped(),
            Self::Ipv6(addr) => addr,
        }
    }

    #[inline]
    #[must_use]
    pub fn with_port(self, port: u16) -> SocketAddress {
        match self {
            Self::Ipv4(addr) => addr.with_port(port).into(),
            Self::Ipv6(addr) => addr.with_port(port).into(),
        }
    }
}

impl From<IpV4Address> for IpAddress {
    fn from(ip: IpV4Address) -> Self {
        Self::Ipv4(ip)
    }
}

impl From<IpV6Address> for IpAddress {
    fn from(ip: IpV6Address) -> Self {
        Self::Ipv6(ip)
    }
}

impl Unspecified for IpAddress {
    fn is_unspecified(&self) -> bool {
        match self {
            Self::Ipv4(addr) => addr.is_unspecified(),
            Self::Ipv6(addr) => addr.is_unspecified(),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum IpAddressRef<'a> {
    IPv4(&'a IpV4Address),
    IPv6(&'a IpV6Address),
}

impl<'a> IpAddressRef<'a> {
    pub fn to_owned(self) -> IpAddress {
        match self {
            Self::IPv4(addr) => IpAddress::Ipv4(*addr),
            Self::IPv6(addr) => IpAddress::Ipv6(*addr),
        }
    }
}

impl<'a> From<&'a IpV4Address> for IpAddressRef<'a> {
    fn from(ip: &'a IpV4Address) -> Self {
        Self::IPv4(ip)
    }
}

impl<'a> From<&'a IpV6Address> for IpAddressRef<'a> {
    fn from(ip: &'a IpV6Address) -> Self {
        Self::IPv6(ip)
    }
}

/// An IP socket address, either IPv4 or IPv6, with a specific port.
///
/// Instead of using `std::net::SocketAddr`, this implementation
/// is geared towards `no_std` environments and zerocopy decoding.
///
/// The size is also consistent across target operating systems.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(any(test, feature = "generator"), derive(TypeGenerator))]
#[cfg_attr(kani, derive(kani::Arbitrary))]
pub enum SocketAddress {
    IpV4(SocketAddressV4),
    IpV6(SocketAddressV6),
}

impl SocketAddress {
    #[inline]
    pub fn ip(&self) -> IpAddress {
        match self {
            SocketAddress::IpV4(addr) => IpAddress::Ipv4(*addr.ip()),
            SocketAddress::IpV6(addr) => IpAddress::Ipv6(*addr.ip()),
        }
    }

    #[inline]
    pub fn port(&self) -> u16 {
        match self {
            SocketAddress::IpV4(addr) => addr.port(),
            SocketAddress::IpV6(addr) => addr.port(),
        }
    }

    #[inline]
    pub fn set_port(&mut self, port: u16) {
        match self {
            SocketAddress::IpV4(addr) => addr.set_port(port),
            SocketAddress::IpV6(addr) => addr.set_port(port),
        }
    }

    #[inline]
    pub const fn unicast_scope(&self) -> Option<UnicastScope> {
        match self {
            Self::IpV4(addr) => addr.unicast_scope(),
            Self::IpV6(addr) => addr.unicast_scope(),
        }
    }

    /// Converts the IP address into a IPv6 mapped address
    pub fn to_ipv6_mapped(self) -> SocketAddressV6 {
        match self {
            Self::IpV4(addr) => addr.to_ipv6_mapped(),
            Self::IpV6(addr) => addr,
        }
    }

    /// Converts the IP address into IPv4 if it is mapped, otherwise the address is unchanged
    #[inline]
    #[must_use]
    pub fn unmap(self) -> Self {
        match self {
            Self::IpV4(_) => self,
            Self::IpV6(addr) => addr.unmap(),
        }
    }
}

impl Default for SocketAddress {
    fn default() -> Self {
        SocketAddress::IpV4(Default::default())
    }
}

impl fmt::Display for SocketAddress {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            SocketAddress::IpV4(addr) => write!(fmt, "{addr}"),
            SocketAddress::IpV6(addr) => write!(fmt, "{addr}"),
        }
    }
}

impl Unspecified for SocketAddress {
    fn is_unspecified(&self) -> bool {
        match self {
            SocketAddress::IpV4(addr) => addr.is_unspecified(),
            SocketAddress::IpV6(addr) => addr.is_unspecified(),
        }
    }
}

impl From<SocketAddressV4> for SocketAddress {
    fn from(addr: SocketAddressV4) -> Self {
        SocketAddress::IpV4(addr)
    }
}

impl From<SocketAddressV6> for SocketAddress {
    fn from(addr: SocketAddressV6) -> Self {
        SocketAddress::IpV6(addr)
    }
}

/// An IP socket address, either IPv4 or IPv6, with a specific port.
///
/// This is the borrowed version of `SocketAddress`, aimed at zerocopy
/// use cases.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SocketAddressRef<'a> {
    IpV4(&'a SocketAddressV4),
    IpV6(&'a SocketAddressV6),
}

impl<'a> SocketAddressRef<'a> {
    pub fn to_owned(self) -> SocketAddress {
        match self {
            Self::IpV4(addr) => SocketAddress::IpV4(*addr),
            Self::IpV6(addr) => SocketAddress::IpV6(*addr),
        }
    }
}

//= https://www.rfc-editor.org/rfc/rfc9000#section-21.5.6
//# Similarly, endpoints could regard a change in address to a link-local
//# address [RFC4291] or an address in a private-use range [RFC1918] from
//# a global, unique-local [RFC4193], or non-private address as a
//# potential attempt at request forgery.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UnicastScope {
    Loopback,
    LinkLocal,
    Private,
    Global,
}

#[cfg(any(test, feature = "std"))]
mod std_conversion {
    use super::*;
    use std::net;

    impl net::ToSocketAddrs for SocketAddress {
        type Iter = std::iter::Once<net::SocketAddr>;

        fn to_socket_addrs(&self) -> std::io::Result<Self::Iter> {
            match self {
                Self::IpV4(addr) => addr.to_socket_addrs(),
                Self::IpV6(addr) => addr.to_socket_addrs(),
            }
        }
    }

    impl<'a> net::ToSocketAddrs for SocketAddressRef<'a> {
        type Iter = std::iter::Once<net::SocketAddr>;

        fn to_socket_addrs(&self) -> std::io::Result<Self::Iter> {
            match self {
                Self::IpV4(addr) => addr.to_socket_addrs(),
                Self::IpV6(addr) => addr.to_socket_addrs(),
            }
        }
    }

    impl From<SocketAddress> for net::SocketAddr {
        fn from(address: SocketAddress) -> Self {
            match address {
                SocketAddress::IpV4(addr) => addr.into(),
                SocketAddress::IpV6(addr) => addr.into(),
            }
        }
    }

    impl From<(net::IpAddr, u16)> for SocketAddress {
        fn from((ip, port): (net::IpAddr, u16)) -> Self {
            match ip {
                net::IpAddr::V4(ip) => Self::IpV4((ip, port).into()),
                net::IpAddr::V6(ip) => Self::IpV6((ip, port).into()),
            }
        }
    }

    impl<'a> From<SocketAddressRef<'a>> for net::SocketAddr {
        fn from(address: SocketAddressRef<'a>) -> Self {
            match address {
                SocketAddressRef::IpV4(addr) => addr.into(),
                SocketAddressRef::IpV6(addr) => addr.into(),
            }
        }
    }

    impl From<net::SocketAddr> for SocketAddress {
        fn from(addr: net::SocketAddr) -> Self {
            match addr {
                net::SocketAddr::V4(addr) => Self::IpV4(addr.into()),
                net::SocketAddr::V6(addr) => Self::IpV6(addr.into()),
            }
        }
    }
}

define_inet_type!(
    pub struct Protocol {
        id: u8,
    }
);

impl fmt::Debug for Protocol {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("ip::Protocol")
            .field(&format_args!("{self}"))
            .finish()
    }
}

impl fmt::Display for Protocol {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Self::HOPOPT => "IPv6 Hop-by-Hop Option",
            Self::ICMP => "Internet Control Message",
            Self::IPV4 => "IPv4 Encapsulation",
            Self::TCP => "Transmission Control",
            Self::UDP => "User Datagram",
            Self::IPV6 => "IPv6 Encapsulation",
            Self::IPV6_ROUTE => "Routing Header for IPv6",
            Self::IPV6_FRAG => "Fragment Header for IPv6",
            Self::IPV6_ICMP => "ICMP for IPv6",
            Self::IPV6_NO_NXT => "No Next Header for IPv6",
            Self::IPV6_OPTS => "Destination Options for IPv6",
            Self::UDPLITE => "Lightweight User Datagram",
            Self { id } => return write!(f, "[unknown 0x{id:02x}]"),
        }
        .fmt(f)
    }
}

macro_rules! impl_p {
    ($fun:ident, $cap:ident, $val:literal) => {
        pub const $cap: Self = Self { id: $val };

        #[inline]
        pub const fn $fun(self) -> bool {
            self.id == $val
        }
    };
}

impl Protocol {
    // https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
    // NOTE: these variants were added as the ones we think we'll need. feel free to add more as
    //       needed.
    impl_p!(is_hop_by_hop, HOPOPT, 0);
    impl_p!(is_icmp, ICMP, 1);
    impl_p!(is_ipv4, IPV4, 4);
    impl_p!(is_tcp, TCP, 6);
    impl_p!(is_udp, UDP, 17);
    impl_p!(is_ipv6, IPV6, 41);
    impl_p!(is_ipv6_route, IPV6_ROUTE, 43);
    impl_p!(is_ipv6_fragment, IPV6_FRAG, 44);
    impl_p!(is_ipv6_icmp, IPV6_ICMP, 58);
    impl_p!(is_ipv6_no_next, IPV6_NO_NXT, 59);
    impl_p!(is_ipv6_options, IPV6_OPTS, 60);
    impl_p!(is_udplite, UDPLITE, 136);
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::{SocketAddr, ToSocketAddrs};

    const TESTS: &[&str] = &[
        "127.0.0.1:80",
        "192.168.1.1:40",
        "255.255.255.255:12345",
        "[::]:443",
        "[::1]:123",
        "[2001:0db8:85a3:0001:0002:8a2e:0370:7334]:9000",
    ];

    #[test]
    //= https://www.rfc-editor.org/rfc/rfc5156#section-2.2
    //= type=test
    //# ::FFFF:0:0/96 are the IPv4-mapped addresses [RFC4291].
    fn to_ipv6_mapped_test() {
        for test in TESTS.iter() {
            // assert that this implementation matches the standard library
            let addr: SocketAddr = test.parse().unwrap();
            let address: SocketAddress = addr.into();
            let addr = match addr {
                SocketAddr::V4(addr) => {
                    let ip = addr.ip().to_ipv6_mapped();
                    (ip, addr.port()).into()
                }
                _ => addr,
            };
            let address = address.to_ipv6_mapped().into();
            assert_eq!(addr, address);
        }
    }

    #[test]
    fn unmap_test() {
        for test in TESTS.iter() {
            // assert that unmap correctly converts IPv4 mapped addresses
            let addr: SocketAddr = test.parse().unwrap();
            let address: SocketAddress = addr.into();
            let actual: SocketAddress = address.to_ipv6_mapped().into();
            let actual = actual.unmap();
            assert_eq!(address, actual);
        }
    }

    #[test]
    fn display_test() {
        for test in TESTS.iter() {
            // assert that this implementation matches the standard library
            let addr: SocketAddr = test.parse().unwrap();
            let address: SocketAddress = addr.into();
            assert_eq!(addr.to_string(), address.to_string());
        }
    }

    #[test]
    fn to_socket_addrs_test() {
        for test in TESTS.iter() {
            let addr: SocketAddr = test.parse().unwrap();
            let address: SocketAddress = addr.into();
            for address in address.to_socket_addrs().unwrap() {
                assert_eq!(addr, address);
            }
        }
    }
}