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
extern crate alloc;

use crate::io;
use alloc::string::String;
use core::{iter, option, slice};

pub use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};

/// A trait for objects which can be converted or resolved to one or more
/// [`SocketAddr`] values.
///
/// This trait is used for generic address resolution when constructing network
/// objects. By default it is implemented for the following types:
///
///  * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
///
///  * [`SocketAddrV4`], <code>([IpAddr], [u16])</code>,
///    <code>([Ipv4Addr], [u16])</code>:
///    [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
///
///  * <code>(&[str], [u16])</code>: <code>&[str]</code> should be either a string representation
///    of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
///    name. [`u16`] is the port number.
///
///  * <code>&[str]</code>: the string should be either a string representation of a
///    [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
///    `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
///
/// [`FromStr`]: core::str::FromStr
/// [`to_socket_addrs`]: ToSocketAddrs::to_socket_addrs
pub trait ToSocketAddrs {
    /// Returned iterator over socket addresses which this type may correspond to.
    type Iter: Iterator<Item = SocketAddr>;

    /// Converts this object to an iterator of resolved [`SocketAddr`]s.
    fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
}

impl ToSocketAddrs for SocketAddr {
    type Iter = option::IntoIter<SocketAddr>;
    fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
        Ok(Some(*self).into_iter())
    }
}

impl ToSocketAddrs for SocketAddrV4 {
    type Iter = option::IntoIter<SocketAddr>;
    fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
        SocketAddr::V4(*self).to_socket_addrs()
    }
}

impl ToSocketAddrs for (IpAddr, u16) {
    type Iter = option::IntoIter<SocketAddr>;
    fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
        let (ip, port) = *self;
        SocketAddr::new(ip, port).to_socket_addrs()
    }
}

impl ToSocketAddrs for (Ipv4Addr, u16) {
    type Iter = option::IntoIter<SocketAddr>;
    fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
        let (ip, port) = *self;
        SocketAddrV4::new(ip, port).to_socket_addrs()
    }
}

impl<'a> ToSocketAddrs for &'a [SocketAddr] {
    type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;

    fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
        Ok(self.iter().cloned())
    }
}

impl<T: ToSocketAddrs + ?Sized> ToSocketAddrs for &T {
    type Iter = T::Iter;
    fn to_socket_addrs(&self) -> io::Result<T::Iter> {
        (**self).to_socket_addrs()
    }
}

#[cfg(not(feature = "dns"))]
#[doc(cfg(feature = "net"))]
mod no_dns {
    use super::*;

    impl ToSocketAddrs for (&str, u16) {
        type Iter = option::IntoIter<SocketAddr>;
        fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
            let (host, port) = *self;
            Ok(host
                .parse::<Ipv4Addr>()
                .ok()
                .map(|addr| {
                    let addr = SocketAddrV4::new(addr, port);
                    SocketAddr::V4(addr)
                })
                .into_iter())
        }
    }

    impl ToSocketAddrs for str {
        type Iter = option::IntoIter<SocketAddr>;
        fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
            // parse as a regular SocketAddr first
            Ok(self.parse().ok().into_iter())
        }
    }

    impl ToSocketAddrs for (String, u16) {
        type Iter = option::IntoIter<SocketAddr>;
        fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
            (&*self.0, self.1).to_socket_addrs()
        }
    }

    impl ToSocketAddrs for String {
        type Iter = option::IntoIter<SocketAddr>;
        fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
            (**self).to_socket_addrs()
        }
    }
}

#[cfg(feature = "dns")]
#[doc(cfg(feature = "net"))]
mod dns {
    use super::*;
    use alloc::{vec, vec::Vec};

    impl ToSocketAddrs for (&str, u16) {
        type Iter = vec::IntoIter<SocketAddr>;
        fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
            let (host, port) = *self;

            // try to parse the host as a regular IP address first
            if let Ok(addr) = host.parse::<Ipv4Addr>() {
                let addr = SocketAddrV4::new(addr, port);
                return Ok(vec![SocketAddr::V4(addr)].into_iter());
            }

            Ok(arceos_api::net::ax_dns_query(host)?
                .into_iter()
                .map(|ip| SocketAddr::new(ip, port))
                .collect::<Vec<_>>()
                .into_iter())
        }
    }

    impl ToSocketAddrs for str {
        type Iter = vec::IntoIter<SocketAddr>;

        fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
            // try to parse as a regular SocketAddr first
            if let Ok(addr) = self.parse() {
                return Ok(vec![addr].into_iter());
            }

            // split the string by ':' and convert the second part to u16
            let (host, port_str) = self
                .rsplit_once(':')
                .ok_or_else(|| axerrno::ax_err_type!(InvalidInput, "invalid socket address"))?;
            let port: u16 = port_str
                .parse()
                .map_err(|_| axerrno::ax_err_type!(InvalidInput, "invalid port value"))?;

            Ok(arceos_api::net::ax_dns_query(host)?
                .into_iter()
                .map(|ip| SocketAddr::new(ip, port))
                .collect::<Vec<_>>()
                .into_iter())
        }
    }

    impl ToSocketAddrs for (String, u16) {
        type Iter = vec::IntoIter<SocketAddr>;
        fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
            (&*self.0, self.1).to_socket_addrs()
        }
    }

    impl ToSocketAddrs for String {
        type Iter = vec::IntoIter<SocketAddr>;
        fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
            (**self).to_socket_addrs()
        }
    }
}