Debian Codegraph @

src/addrinfo.rs

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 use socket2::SockAddr;
2 use std::ffi::{CStr, CString};
3 use std::io;
4 use std::mem;
5 use std::net::SocketAddr;
6 use std::ptr;
7
8 #[cfg(unix)]
9 use libc::{getaddrinfo as c_getaddrinfo, freeaddrinfo as c_freeaddrinfo, addrinfo as c_addrinfo};
10
11 #[cfg(windows)]
12 use winapi::shared::ws2def::{ADDRINFOA as c_addrinfo};
13 #[cfg(windows)]
14 use winapi::um::ws2tcpip::{getaddrinfo as c_getaddrinfo, freeaddrinfo as c_freeaddrinfo};
15
16 use err::LookupError;
17
18 /// A struct used as the hints argument to getaddrinfo.
19 #[derive(Copy, Clone, Debug, PartialEq)]
20 pub struct AddrInfoHints {
21 /// Type of this socket. 0 for none.
22 ///
23 /// Values are defined by the libc on your system.
24 pub socktype: i32,
25 /// Protcol for this socket. 0 for none.
26 ///
27 /// Values are defined by the libc on your system.
28 pub protocol: i32,
29 /// Address family for this socket. 0 for none.
30 ///
31 /// Values are defined by the libc on your system.
32 pub address: i32,
33 /// Optional bitmask arguments. Bitwise OR bitflags to change the
34 /// behaviour of getaddrinfo. 0 for none.
35 ///
36 /// Values are defined by the libc on your system.
37 pub flags: i32,
38 }
39
40 impl AddrInfoHints {
41 unsafe fn as_addrinfo(&self) -> c_addrinfo {
42 let mut addrinfo: c_addrinfo = mem::zeroed();
43 addrinfo.ai_socktype = self.socktype;
44 addrinfo.ai_protocol = self.protocol;
45 addrinfo.ai_family = self.address;
46 addrinfo.ai_flags = self.flags;
47 addrinfo
48 }
49 }
50
51 impl Default for AddrInfoHints {
52 /// Generate a blank AddrInfoHints struct, so new values can easily
53 /// be specified.
54 fn default() -> Self {
55 AddrInfoHints {
56 socktype: 0,
57 protocol: 0,
58 address: 0,
59 flags: 0,
60 }
61 }
62 }
63
64 /// Struct that stores socket information, as returned by getaddrinfo.
65 ///
66 /// This maps to the same definition provided by libc backends.
67 #[derive(Clone, Debug, PartialEq)]
68 pub struct AddrInfo {
69 /// Type of this socket.
70 ///
71 /// Values are defined by the libc on your system.
72 pub socktype: i32,
73 /// Protcol family for this socket.
74 ///
75 /// Values are defined by the libc on your system.
76 pub protocol: i32,
77 /// Address family for this socket (usually matches protocol family).
78 ///
79 /// Values are defined by the libc on your system.
80 pub address: i32,
81 /// Socket address for this socket, usually containing an actual
82 /// IP Address and port.
83 pub sockaddr: SocketAddr,
84 /// If requested, this is the canonical name for this socket/host.
85 pub canonname: Option<String>,
86 /// Optional bitmask arguments, usually set to zero.
87 pub flags: i32,
88 }
89
90 impl AddrInfo {
91 /// Copy the informataion from the given addrinfo pointer, and
92 /// create a new AddrInfo struct with that information.
93 ///
94 /// Used for interfacing with getaddrinfo.
95 unsafe fn from_ptr(a: *mut c_addrinfo) -> io::Result<Self> {
96 if a.is_null() {
97 return Err(
98 io::Error::new(io::ErrorKind::Other,
99 "Supplied pointer is null."
100 ))?;
101 }
102
103 let addrinfo = *a;
104 let ((), sockaddr) = SockAddr::init(|storage, len| {
105 *len = addrinfo.ai_addrlen as _;
106 std::ptr::copy_nonoverlapping(
107 addrinfo.ai_addr as *const u8,
108 storage as *mut u8,
109 addrinfo.ai_addrlen as usize
110 );
111 Ok(())
112 })?;
113 let sock = sockaddr.as_socket().ok_or_else(|| io::Error::new(
114 io::ErrorKind::Other,
115 format!("Found unknown address family: {}", sockaddr.family())
116 ))?;
117 Ok(AddrInfo {
118 socktype: addrinfo.ai_socktype,
119 protocol: addrinfo.ai_protocol,
120 address: addrinfo.ai_family,
121 sockaddr: sock,
122 canonname: addrinfo.ai_canonname.as_ref().map(|s|
123 CStr::from_ptr(s).to_str().unwrap().to_owned()
124 ),
125 flags: 0,
126 })
127 }
128 }
129
130 /// An iterator of `AddrInfo` structs, wrapping a linked-list
131 /// returned by getaddrinfo.
132 ///
133 /// It's recommended to use `.collect<io::Result<..>>()` on this
134 /// to collapse possible errors.
135 pub struct AddrInfoIter {
136 orig: *mut c_addrinfo,
137 cur: *mut c_addrinfo,
138 }
139
140 impl Iterator for AddrInfoIter {
141 type Item = io::Result<AddrInfo>;
142
143 fn next(&mut self) -> Option<Self::Item> {
144 unsafe {
145 if self.cur.is_null() { return None; }
146 let ret = AddrInfo::from_ptr(self.cur);
147 self.cur = (*self.cur).ai_next as *mut c_addrinfo;
148 Some(ret)
149 }
150 }
151 }
152
153 unsafe impl Sync for AddrInfoIter {}
154 unsafe impl Send for AddrInfoIter {}
155
156 impl Drop for AddrInfoIter {
157 fn drop(&mut self) {
158 unsafe { c_freeaddrinfo(self.orig) }
159 }
160 }
161
162 /// Retrieve socket information for a host, service, or both. Acts as a thin
163 /// wrapper around the libc getaddrinfo.
164 ///
165 /// The only portable way to support International Domain Names (UTF8 DNS
166 /// names) is to manually convert to puny code before calling this function -
167 /// which can be done using the `idna` crate. However some libc backends may
168 /// support this natively, or by using bitflags in the hints argument.
169 ///
170 /// Resolving names from non-UTF8 locales is currently not supported (as the
171 /// interface uses &str). Raise an issue if this is a concern for you.
172 pub fn getaddrinfo(host: Option<&str>, service: Option<&str>, hints: Option<AddrInfoHints>)
173 -> Result<AddrInfoIter, LookupError> {
174 // We must have at least host or service.
175 if host.is_none() && service.is_none() {
176 return Err(io::Error::new(
177 io::ErrorKind::Other,
178 "Either host or service must be supplied"
179 ))?;
180 }
181
182 // Allocate CStrings, and keep around to free.
183 let host = match host {
184 Some(host_str) => Some(CString::new(host_str)?),
185 None => None
186 };
187 let c_host = host.as_ref().map_or(ptr::null(), |s| s.as_ptr());
188 let service = match service {
189 Some(service_str) => Some(CString::new(service_str)?),
190 None => None
191 };
192 let c_service = service.as_ref().map_or(ptr::null(), |s| s.as_ptr());
193
194 let c_hints = unsafe {
195 match hints {
196 Some(hints) => hints.as_addrinfo(),
197 None => mem::zeroed(),
198 }
199 };
200
201 let mut res = ptr::null_mut();
202
203 // Prime windows.
204 #[cfg(windows)]
205 ::win::init_winsock();
206
207 unsafe {
208 LookupError::match_gai_error(
209 c_getaddrinfo(c_host, c_service, &c_hints, &mut res)
210 )?;
211 }
212
213 Ok(AddrInfoIter { orig: res, cur: res })
214 }