Debian Codegraph @

debian/rust-vendor/dns-lookup/src/addrinfo.rs

raw
1 use socket2::SockAddr;
2 use std::ffi::{CStr, CString};
3 use std::io;
4 use std::iter::FusedIterator;
5 use std::mem;
6 use std::net::SocketAddr;
7 use std::os::raw::c_char;
8 use std::ptr;
9
10 #[cfg(unix)]
11 use libc::{
12 addrinfo as c_addrinfo, c_char as libc_c_char, freeaddrinfo as c_freeaddrinfo,
13 getaddrinfo as c_getaddrinfo,
14 };
15
16 #[cfg(windows)]
17 #[allow(non_camel_case_types)]
18 type libc_c_char = u8;
19 #[cfg(windows)]
20 use windows_sys::Win32::Networking::WinSock::{
21 freeaddrinfo as c_freeaddrinfo, getaddrinfo as c_getaddrinfo, ADDRINFOA as c_addrinfo,
22 };
23
24 use crate::err::LookupError;
25
26 /// A struct used as the hints argument to getaddrinfo.
27 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
28 pub struct AddrInfoHints {
29 /// Optional bitmask arguments. Bitwise OR bitflags to change the
30 /// behaviour of getaddrinfo. 0 for none. `ai_flags` in libc.
31 ///
32 /// Values are defined by the libc on your system.
33 pub flags: i32,
34 /// Address family for this socket. 0 for none. `ai_family` in libc.
35 ///
36 /// Values are defined by the libc on your system.
37 pub address: i32,
38 /// Type of this socket. 0 for none. `ai_socktype` in libc.
39 ///
40 /// Values are defined by the libc on your system.
41 pub socktype: i32,
42 /// Protcol for this socket. 0 for none. `ai_protocol` in libc.
43 ///
44 /// Values are defined by the libc on your system.
45 pub protocol: i32,
46 }
47
48 impl AddrInfoHints {
49 /// Create a new AddrInfoHints using built-in types.
50 ///
51 /// Included Enums only provide common values, for anything else
52 /// create this struct directly using appropriate values from the
53 /// libc crate.
54 #[allow(dead_code)]
55 fn new(
56 flags: Option<i32>,
57 address: Option<crate::AddrFamily>,
58 socktype: Option<crate::SockType>,
59 protocol: Option<crate::Protocol>,
60 ) -> AddrInfoHints {
61 AddrInfoHints {
62 flags: flags.unwrap_or(0),
63 address: address.map_or(0, |a| a.into()),
64 socktype: socktype.map_or(0, |a| a.into()),
65 protocol: protocol.map_or(0, |a| a.into()),
66 }
67 }
68
69 // Create libc addrinfo from AddrInfoHints struct.
70 unsafe fn as_addrinfo(&self) -> c_addrinfo {
71 unsafe {
72 let mut addrinfo: c_addrinfo = mem::zeroed();
73 addrinfo.ai_flags = self.flags;
74 addrinfo.ai_family = self.address;
75 addrinfo.ai_socktype = self.socktype;
76 addrinfo.ai_protocol = self.protocol;
77 addrinfo
78 }
79 }
80 }
81
82 impl Default for AddrInfoHints {
83 /// Generate a blank AddrInfoHints struct, so new values can easily
84 /// be specified.
85 fn default() -> Self {
86 AddrInfoHints {
87 flags: 0,
88 address: 0,
89 socktype: 0,
90 protocol: 0,
91 }
92 }
93 }
94
95 /// Struct that stores socket information, as returned by getaddrinfo.
96 #[derive(Clone, Debug, PartialEq, Eq)]
97 pub struct AddrInfo {
98 /// Optional bitmask arguments, usually set to zero. `ai_flags` in libc.
99 pub flags: i32,
100 /// Address family for this socket (usually matches protocol family). `ai_family` in libc.
101 ///
102 /// Values are defined by the libc on your system.
103 pub address: i32,
104 /// Type of this socket. `ai_socktype` in libc.
105 ///
106 /// Values are defined by the libc on your system.
107 pub socktype: i32,
108 /// Protcol family for this socket. `ai_protocol` in libc.
109 ///
110 /// Values are defined by the libc on your system.
111 pub protocol: i32,
112 /// Socket address for this socket, usually containing an actual
113 /// IP Address and port. Combination of `ai_addrlen` and `ai_addr` in libc.
114 pub sockaddr: SocketAddr,
115 /// If requested, this is the canonical name for this socket/host. `ai_canonname` in libc.
116 pub canonname: Option<String>,
117 }
118
119 impl AddrInfo {
120 /// Copy the informataion from the given addrinfo pointer, and
121 /// create a new AddrInfo struct with that information.
122 ///
123 /// Used for interfacing with getaddrinfo.
124 unsafe fn from_ptr(a: *mut c_addrinfo) -> io::Result<Self> {
125 unsafe {
126 if a.is_null() {
127 return Err(io::Error::new(
128 io::ErrorKind::Other,
129 "Supplied pointer is null.",
130 ))?;
131 }
132
133 let addrinfo = *a;
134 let ((), sockaddr) = SockAddr::try_init(|storage, len| {
135 *len = addrinfo.ai_addrlen as _;
136 #[cfg_attr(windows, allow(clippy::unnecessary_cast))]
137 std::ptr::copy_nonoverlapping(
138 addrinfo.ai_addr as *const u8,
139 storage as *mut u8,
140 addrinfo.ai_addrlen as usize,
141 );
142 Ok(())
143 })?;
144 let sock = sockaddr.as_socket().ok_or_else(|| {
145 io::Error::new(
146 io::ErrorKind::Other,
147 format!("Found unknown address family: {}", sockaddr.family()),
148 )
149 })?;
150 Ok(AddrInfo {
151 flags: 0,
152 address: addrinfo.ai_family,
153 socktype: addrinfo.ai_socktype,
154 protocol: addrinfo.ai_protocol,
155 sockaddr: sock,
156 canonname: addrinfo.ai_canonname.as_ref().map(|s| {
157 CStr::from_ptr(s as *const libc_c_char as *const c_char)
158 .to_str()
159 .unwrap()
160 .to_owned()
161 }),
162 })
163 }
164 }
165 }
166
167 /// An iterator of `AddrInfo` structs, wrapping a linked-list
168 /// returned by getaddrinfo.
169 ///
170 /// It's recommended to use `.collect<io::Result<..>>()` on this
171 /// to collapse possible errors.
172 pub struct AddrInfoIter {
173 orig: *mut c_addrinfo,
174 cur: *mut c_addrinfo,
175 }
176
177 impl Iterator for AddrInfoIter {
178 type Item = io::Result<AddrInfo>;
179
180 fn next(&mut self) -> Option<Self::Item> {
181 unsafe {
182 if self.cur.is_null() {
183 return None;
184 }
185 let ret = AddrInfo::from_ptr(self.cur);
186 #[allow(clippy::unnecessary_cast)]
187 {
188 self.cur = (*self.cur).ai_next as *mut c_addrinfo;
189 }
190 Some(ret)
191 }
192 }
193 }
194
195 impl FusedIterator for AddrInfoIter {}
196 unsafe impl Sync for AddrInfoIter {}
197 unsafe impl Send for AddrInfoIter {}
198
199 impl Drop for AddrInfoIter {
200 fn drop(&mut self) {
201 unsafe { c_freeaddrinfo(self.orig) }
202 }
203 }
204
205 /// Retrieve socket information for a host, service, or both. Acts as a thin
206 /// wrapper around the libc getaddrinfo.
207 ///
208 /// The only portable way to support International Domain Names (UTF8 DNS
209 /// names) is to manually convert to puny code before calling this function -
210 /// which can be done using the `idna` crate. However some libc backends may
211 /// support this natively, or by using bitflags in the hints argument.
212 ///
213 /// Resolving names from non-UTF8 locales is currently not supported (as the
214 /// interface uses &str). Raise an issue if this is a concern for you.
215 pub fn getaddrinfo(
216 host: Option<&str>,
217 service: Option<&str>,
218 hints: Option<AddrInfoHints>,
219 ) -> Result<AddrInfoIter, LookupError> {
220 // We must have at least host or service.
221 if host.is_none() && service.is_none() {
222 Err(io::Error::new(
223 io::ErrorKind::Other,
224 "Either host or service must be supplied",
225 ))?;
226 }
227
228 // Allocate CStrings, and keep around to free.
229 let host = match host {
230 Some(host_str) => Some(CString::new(host_str)?),
231 None => None,
232 };
233 let c_host = host.as_ref().map_or(ptr::null(), |s| s.as_ptr()) as *const libc_c_char;
234 let service = match service {
235 Some(service_str) => Some(CString::new(service_str)?),
236 None => None,
237 };
238 let c_service = service.as_ref().map_or(ptr::null(), |s| s.as_ptr()) as *const libc_c_char;
239
240 let c_hints = unsafe {
241 match hints {
242 Some(hints) => hints.as_addrinfo(),
243 None => mem::zeroed(),
244 }
245 };
246
247 let mut res = ptr::null_mut();
248
249 // Prime windows.
250 #[cfg(windows)]
251 crate::win::init_winsock();
252
253 unsafe {
254 LookupError::match_gai_error(c_getaddrinfo(c_host, c_service, &c_hints, &mut res))?;
255 }
256
257 Ok(AddrInfoIter {
258 orig: res,
259 cur: res,
260 })
261 }
262
263 #[test]
264 fn test_addrinfohints() {
265 use crate::{AddrFamily, SockType};
266
267 assert_eq!(
268 AddrInfoHints {
269 flags: 1,
270 address: AddrFamily::Inet.into(),
271 socktype: SockType::Stream.into(),
272 ..AddrInfoHints::default()
273 },
274 AddrInfoHints::new(
275 Some(1),
276 Some(AddrFamily::Inet),
277 Some(SockType::Stream),
278 None
279 )
280 );
281
282 assert_eq!(
283 AddrInfoHints {
284 address: AddrFamily::Inet.into(),
285 socktype: SockType::Stream.into(),
286 ..AddrInfoHints::default()
287 },
288 AddrInfoHints::new(None, Some(AddrFamily::Inet), Some(SockType::Stream), None)
289 );
290 }