Debian Codegraph @

src/unix.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 use super::{htons, ntohs};
2 use std::io;
3
4 pub mod public {
5
6 use libc;
7 use super::{htons, ntohs};
8 use std::io;
9 use std::mem;
10 use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
11 use std::time::Duration;
12
13 pub type CSocket = libc::c_int;
14 pub type Buf = *const libc::c_void;
15 pub type MutBuf = *mut libc::c_void;
16 pub type BufLen = libc::size_t;
17 pub type CouldFail = libc::ssize_t;
18 pub type SockLen = libc::socklen_t;
19 pub type MutSockLen = *mut libc::socklen_t;
20 pub type SockAddr = libc::sockaddr;
21 pub type SockAddrIn = libc::sockaddr_in;
22 pub type SockAddrIn6 = libc::sockaddr_in6;
23 pub type SockAddrStorage = libc::sockaddr_storage;
24 pub type SockAddrFamily = libc::sa_family_t;
25 pub type SockAddrFamily6 = libc::sa_family_t;
26 pub type InAddr = libc::in_addr;
27 pub type In6Addr = libc::in6_addr;
28
29 #[cfg(not(any(
30 target_os = "macos",
31 target_os = "ios",
32 target_os = "tvos",
33 target_os = "netbsd"
34 )))]
35 pub type TvUsecType = libc::c_long;
36 #[cfg(any(
37 target_os = "macos",
38 target_os = "ios",
39 target_os = "tvos",
40 target_os = "netbsd"
41 ))]
42 pub type TvUsecType = libc::c_int;
43 #[cfg(not(any(target_os = "illumos", target_os = "solaris")))]
44 pub type InAddrType = libc::c_uint;
45 #[cfg(any(target_os = "illumos", target_os = "solaris"))]
46 pub type InAddrType = libc::c_ulonglong;
47
48 pub const AF_INET: libc::c_int = libc::AF_INET;
49 pub const AF_INET6: libc::c_int = libc::AF_INET6;
50 pub const SOCK_RAW: libc::c_int = libc::SOCK_RAW;
51
52 pub const SOL_SOCKET: libc::c_int = libc::SOL_SOCKET;
53 pub const SO_RCVTIMEO: libc::c_int = libc::SO_RCVTIMEO;
54 pub const SO_SNDTIMEO: libc::c_int = libc::SO_SNDTIMEO;
55
56 pub const IPPROTO_IP: libc::c_int = libc::IPPROTO_IP;
57 pub const IP_HDRINCL: libc::c_int = libc::IP_HDRINCL;
58 pub const IP_TTL: libc::c_int = libc::IP_TTL;
59 pub const IP_TOS: libc::c_int = 1;
60
61 pub const IPPROTO_IPV6: libc::c_int = libc::IPPROTO_IPV6;
62 pub const IPV6_UNICAST_HOPS: libc::c_int = libc::IPV6_UNICAST_HOPS;
63 pub const IPV6_TCLASS: libc::c_int = libc::IPV6_TCLASS;
64
65 pub use libc::{IFF_BROADCAST, IFF_LOOPBACK, IFF_RUNNING, IFF_MULTICAST, IFF_POINTOPOINT, IFF_UP};
66
67 #[cfg(any(target_os = "linux", target_os = "android"))]
68 pub use libc::{IFF_LOWER_UP, IFF_DORMANT};
69
70 pub const INVALID_SOCKET: CSocket = -1;
71
72 pub unsafe fn close(sock: CSocket) {
73 let _ = libc::close(sock);
74 }
75
76 pub unsafe fn socket(af: libc::c_int, sock: libc::c_int, proto: libc::c_int) -> CSocket {
77 libc::socket(af, sock, proto)
78 }
79
80 pub unsafe fn getsockopt(
81 socket: CSocket,
82 level: libc::c_int,
83 name: libc::c_int,
84 value: MutBuf,
85 option_len: MutSockLen,
86 ) -> libc::c_int {
87 libc::getsockopt(socket, level, name, value, option_len)
88 }
89
90 pub unsafe fn setsockopt(
91 socket: CSocket,
92 level: libc::c_int,
93 name: libc::c_int,
94 value: Buf,
95 option_len: SockLen,
96 ) -> libc::c_int {
97 libc::setsockopt(socket, level, name, value, option_len)
98 }
99
100 /// Convert a platform specific `timeval` into a Duration.
101 pub fn timeval_to_duration(tv: libc::timeval) -> Duration {
102 Duration::new(tv.tv_sec as u64, (tv.tv_usec as u32) * 1000)
103 }
104
105 /// Convert a Duration into a platform specific `timeval`.
106 pub fn duration_to_timeval(dur: Duration) -> libc::timeval {
107 libc::timeval {
108 tv_sec: dur.as_secs() as libc::time_t,
•109 tv_usec: dur.subsec_micros() as libc::time_t,
110 }
111 }
112
113 /// Convert a platform specific `timespec` into a Duration.
114 pub fn timespec_to_duration(ts: libc::timespec) -> Duration {
115 Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32)
116 }
117
118 /// Convert a Duration into a platform specific `timespec`.
119 pub fn duration_to_timespec(dur: Duration) -> libc::timespec {
•120 let mut timespec: libc::timespec = unsafe { std::mem::zeroed() };
121 timespec.tv_sec = dur.as_secs() as libc::time_t;
122 timespec.tv_nsec = (dur.subsec_nanos() as TvUsecType).into();
123
124 return timespec
125 }
126
127 fn make_in6_addr(segments: [u16; 8]) -> In6Addr {
128 // Safety: We're transmuting an array of ints to an array of ints.
129 // There is no padding involved, and they must be the same size.
130 let s6_addr = unsafe {
131 mem::transmute::<[u16; 8], [u8; 16]>([
132 htons(segments[0]),
133 htons(segments[1]),
134 htons(segments[2]),
135 htons(segments[3]),
136 htons(segments[4]),
137 htons(segments[5]),
138 htons(segments[6]),
139 htons(segments[7]),
140 ])
141 };
142
143 In6Addr { s6_addr }
144 }
145
146 pub fn addr_to_sockaddr(addr: SocketAddr, storage: &mut SockAddrStorage) -> SockLen {
147 unsafe {
148 let len = match addr {
149 SocketAddr::V4(sa) => {
150 let ip_addr = sa.ip();
151 let octets = ip_addr.octets();
152 let inaddr = super::mk_inaddr(u32::from_be(
153 ((octets[0] as u32) << 24)
154 | ((octets[1] as u32) << 16)
155 | ((octets[2] as u32) << 8)
156 | (octets[3] as u32),
157 ));
158 let storage = storage as *mut _ as *mut SockAddrIn;
159 (*storage).sin_family = AF_INET as SockAddrFamily;
160 (*storage).sin_port = htons(addr.port());
161 (*storage).sin_addr = inaddr;
162 mem::size_of::<SockAddrIn>()
163 }
164 SocketAddr::V6(sa) => {
165 let ip_addr = sa.ip();
166 let segments = ip_addr.segments();
167 let inaddr = make_in6_addr(segments);
168 let storage = storage as *mut _ as *mut SockAddrIn6;
169 (*storage).sin6_family = AF_INET6 as SockAddrFamily6;
170 (*storage).sin6_port = htons(addr.port());
171 (*storage).sin6_addr = inaddr;
172 (*storage).sin6_scope_id = sa.scope_id();
173 mem::size_of::<SockAddrIn6>()
174 }
175 };
176
177 len as SockLen
178 }
179 }
180
181 pub fn sockaddr_to_addr(storage: &SockAddrStorage, len: usize) -> io::Result<SocketAddr> {
182 match storage.ss_family as libc::c_int {
183 AF_INET => {
184 assert!(len as usize >= mem::size_of::<SockAddrIn>());
185 let storage: &SockAddrIn = unsafe { mem::transmute(storage) };
186 let ip = super::ipv4_addr(storage.sin_addr);
187 let a = (ip >> 24) as u8;
188 let b = (ip >> 16) as u8;
189 let c = (ip >> 8) as u8;
190 let d = ip as u8;
191 let sockaddrv4 =
192 SocketAddrV4::new(Ipv4Addr::new(a, b, c, d), ntohs(storage.sin_port));
193 Ok(SocketAddr::V4(sockaddrv4))
194 }
195 AF_INET6 => {
196 assert!(len as usize >= mem::size_of::<SockAddrIn6>());
197 let storage: &SockAddrIn6 = unsafe { mem::transmute(storage) };
198 let arr: [u16; 8] = unsafe { mem::transmute(storage.sin6_addr.s6_addr) };
199 let a = ntohs(arr[0]);
200 let b = ntohs(arr[1]);
201 let c = ntohs(arr[2]);
202 let d = ntohs(arr[3]);
203 let e = ntohs(arr[4]);
204 let f = ntohs(arr[5]);
205 let g = ntohs(arr[6]);
206 let h = ntohs(arr[7]);
207 let ip = Ipv6Addr::new(a, b, c, d, e, f, g, h);
208 Ok(SocketAddr::V6(SocketAddrV6::new(
209 ip,
210 ntohs(storage.sin6_port),
211 u32::from_be(storage.sin6_flowinfo),
212 storage.sin6_scope_id,
213 )))
214 }
215 _ => Err(io::Error::new(
216 io::ErrorKind::InvalidData,
217 "expected IPv4 or IPv6 socket",
218 )),
219 }
220 }
221 }
222
223 use self::public::*;
224
225 #[inline(always)]
226 pub fn ipv4_addr(addr: InAddr) -> InAddrType {
227 (addr.s_addr as InAddrType).to_be()
228 }
229
230 #[inline(always)]
231 pub fn mk_inaddr(addr: u32) -> InAddr {
232 InAddr { s_addr: addr }
233 }
234
235 pub unsafe fn sendto(
236 socket: CSocket,
237 buf: Buf,
238 len: BufLen,
239 flags: libc::c_int,
240 addr: *const SockAddr,
241 addrlen: SockLen,
242 ) -> CouldFail {
243 libc::sendto(socket, buf, len, flags, addr, addrlen)
244 }
245
246 pub unsafe fn recvfrom(
247 socket: CSocket,
248 buf: MutBuf,
249 len: BufLen,
250 flags: libc::c_int,
251 addr: *mut SockAddr,
252 addrlen: *mut SockLen,
253 ) -> CouldFail {
254 libc::recvfrom(socket, buf, len, flags, addr, addrlen)
255 }
256
257 #[inline]
258 pub fn retry<F>(f: &mut F) -> libc::ssize_t
259 where
260 F: FnMut() -> libc::ssize_t,
261 {
262 loop {
263 let ret = f();
264 if ret != -1 || errno() as isize != libc::EINTR as isize {
265 return ret;
266 }
267 }
268 }
269
270 fn errno() -> i32 {
271 io::Error::last_os_error().raw_os_error().unwrap()
272 }
273
274 #[cfg(test)]
275 mod tests {
276 use crate::duration_to_timespec;
277 use std::time::Duration;
278 use crate::timespec_to_duration;
279
280 #[test]
281 fn test_duration_to_timespec() {
282 let d1 = Duration::new(1, 0);
283 let d2 = Duration::from_millis(500);
284
285 let t1 = duration_to_timespec(d1);
286 let t2 = duration_to_timespec(d2);
287
288 let r1 = timespec_to_duration(t1);
289 let r2 = timespec_to_duration(t2);
290
291 assert_eq!(d1, r1);
292 assert_eq!(d2, r2);
293 }
294 }