xenet_sys/
unix.rs

1use std::io;
2use std::mem;
3use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
4use std::time::Duration;
5
6pub type CSocket = libc::c_int;
7pub type Buf = *const libc::c_void;
8pub type MutBuf = *mut libc::c_void;
9pub type BufLen = libc::size_t;
10pub type CouldFail = libc::ssize_t;
11pub type SockLen = libc::socklen_t;
12pub type MutSockLen = *mut libc::socklen_t;
13pub type SockAddr = libc::sockaddr;
14pub type SockAddrIn = libc::sockaddr_in;
15pub type SockAddrIn6 = libc::sockaddr_in6;
16pub type SockAddrStorage = libc::sockaddr_storage;
17pub type SockAddrFamily = libc::sa_family_t;
18pub type SockAddrFamily6 = libc::sa_family_t;
19pub type InAddr = libc::in_addr;
20pub type In6Addr = libc::in6_addr;
21
22#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "netbsd")))]
23pub type TvUsecType = libc::c_long;
24#[cfg(any(target_os = "macos", target_os = "ios", target_os = "netbsd"))]
25pub type TvUsecType = libc::c_int;
26
27pub const AF_INET: libc::c_int = libc::AF_INET;
28pub const AF_INET6: libc::c_int = libc::AF_INET6;
29
30pub use libc::{IFF_BROADCAST, IFF_LOOPBACK, IFF_MULTICAST, IFF_POINTOPOINT, IFF_UP};
31
32pub unsafe fn close(sock: CSocket) {
33    let _ = libc::close(sock);
34}
35
36fn ntohs(u: u16) -> u16 {
37    u16::from_be(u)
38}
39
40pub fn sockaddr_to_addr(storage: &SockAddrStorage, len: usize) -> io::Result<SocketAddr> {
41    match storage.ss_family as libc::c_int {
42        AF_INET => {
43            assert!(len as usize >= mem::size_of::<SockAddrIn>());
44            let storage: &SockAddrIn = unsafe { mem::transmute(storage) };
45            let ip = ipv4_addr_int(storage.sin_addr);
46            // octets
47            let o1 = (ip >> 24) as u8;
48            let o2 = (ip >> 16) as u8;
49            let o3 = (ip >> 8) as u8;
50            let o4 = ip as u8;
51            let sockaddrv4 =
52                SocketAddrV4::new(Ipv4Addr::new(o1, o2, o3, o4), ntohs(storage.sin_port));
53            Ok(SocketAddr::V4(sockaddrv4))
54        }
55        AF_INET6 => {
56            assert!(len as usize >= mem::size_of::<SockAddrIn6>());
57            let storage: &SockAddrIn6 = unsafe { mem::transmute(storage) };
58            let arr: [u16; 8] = unsafe { mem::transmute(storage.sin6_addr.s6_addr) };
59            // hextets
60            let h1 = ntohs(arr[0]);
61            let h2 = ntohs(arr[1]);
62            let h3 = ntohs(arr[2]);
63            let h4 = ntohs(arr[3]);
64            let h5 = ntohs(arr[4]);
65            let h6 = ntohs(arr[5]);
66            let h7 = ntohs(arr[6]);
67            let h8 = ntohs(arr[7]);
68            let ip = Ipv6Addr::new(h1, h2, h3, h4, h5, h6, h7, h8);
69            Ok(SocketAddr::V6(SocketAddrV6::new(
70                ip,
71                ntohs(storage.sin6_port),
72                u32::from_be(storage.sin6_flowinfo),
73                storage.sin6_scope_id,
74            )))
75        }
76        _ => Err(io::Error::new(io::ErrorKind::InvalidData, "Not supported")),
77    }
78}
79
80#[inline(always)]
81pub fn ipv4_addr_int(addr: InAddr) -> u32 {
82    (addr.s_addr as u32).to_be()
83}
84
85/// Convert a platform specific `timeval` into a Duration.
86pub fn timeval_to_duration(tv: libc::timeval) -> Duration {
87    Duration::new(tv.tv_sec as u64, (tv.tv_usec as u32) * 1000)
88}
89
90/// Convert a Duration into a platform specific `timeval`.
91pub fn duration_to_timeval(dur: Duration) -> libc::timeval {
92    libc::timeval {
93        tv_sec: dur.as_secs() as libc::time_t,
94        tv_usec: dur.subsec_micros() as TvUsecType,
95    }
96}
97
98/// Convert a platform specific `timespec` into a Duration.
99pub fn timespec_to_duration(ts: libc::timespec) -> Duration {
100    Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32)
101}
102
103/// Convert a Duration into a platform specific `timespec`.
104pub fn duration_to_timespec(dur: Duration) -> libc::timespec {
105    libc::timespec {
106        tv_sec: dur.as_secs() as libc::time_t,
107        tv_nsec: (dur.subsec_nanos() as TvUsecType).into(),
108    }
109}
110
111pub unsafe fn sendto(
112    socket: CSocket,
113    buf: Buf,
114    len: BufLen,
115    flags: libc::c_int,
116    addr: *const SockAddr,
117    addrlen: SockLen,
118) -> CouldFail {
119    libc::sendto(socket, buf, len, flags, addr, addrlen)
120}
121
122pub unsafe fn recvfrom(
123    socket: CSocket,
124    buf: MutBuf,
125    len: BufLen,
126    flags: libc::c_int,
127    addr: *mut SockAddr,
128    addrlen: *mut SockLen,
129) -> CouldFail {
130    libc::recvfrom(socket, buf, len, flags, addr, addrlen)
131}
132
133#[inline]
134pub fn retry<F>(f: &mut F) -> libc::ssize_t
135where
136    F: FnMut() -> libc::ssize_t,
137{
138    loop {
139        let ret = f();
140        if ret != -1 || errno() as isize != libc::EINTR as isize {
141            return ret;
142        }
143    }
144}
145
146fn errno() -> i32 {
147    io::Error::last_os_error().raw_os_error().unwrap()
148}