1 // Copyright 2018 The ChromiumOS Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 use std::io;
6 use std::mem::size_of;
7 use std::net::SocketAddrV4;
8 use std::net::SocketAddrV6;
9 use std::os::unix::ffi::OsStrExt;
10 use std::os::unix::net::UnixDatagram;
11 use std::os::unix::net::UnixListener;
12 use std::os::unix::net::UnixStream;
13 use std::path::Path;
14 use std::ptr::null_mut;
15
16 use libc::c_int;
17 use libc::c_void;
18 use libc::close;
19 use libc::fcntl;
20 use libc::in6_addr;
21 use libc::in_addr;
22 use libc::sa_family_t;
23 use libc::setsockopt;
24 use libc::sockaddr_in;
25 use libc::sockaddr_in6;
26 use libc::socklen_t;
27 use libc::AF_INET;
28 use libc::AF_INET6;
29 use libc::FD_CLOEXEC;
30 use libc::F_SETFD;
31 use libc::SOCK_STREAM;
32 use libc::SOL_SOCKET;
33 use libc::SO_NOSIGPIPE;
34
35 use crate::unix::net::socket;
36 use crate::unix::net::socketpair;
37 use crate::unix::net::sun_path_offset;
38 use crate::unix::net::InetVersion;
39 use crate::unix::net::TcpSocket;
40 use crate::AsRawDescriptor;
41 use crate::FromRawDescriptor;
42 use crate::SafeDescriptor;
43 use crate::ScmSocket;
44 use crate::StreamChannel;
45 use crate::UnixSeqpacket;
46 use crate::UnixSeqpacketListener;
47
48 macro_rules! ScmSocketTryFrom {
49 ($name:ident) => {
50 impl TryFrom<$name> for ScmSocket<$name> {
51 type Error = io::Error;
52
53 fn try_from(socket: $name) -> io::Result<Self> {
54 let set = 1;
55 let set_ptr = &set as *const c_int as *const c_void;
56 let size = size_of::<c_int>() as socklen_t;
57 // SAFETY: because we are taking ownership of the file descriptor, and `set_ptr`
58 // has at least `size` data available.
59 let res = unsafe {
60 setsockopt(
61 socket.as_raw_descriptor(),
62 SOL_SOCKET,
63 SO_NOSIGPIPE,
64 set_ptr,
65 size,
66 )
67 };
68 if res < 0 {
69 Err(io::Error::last_os_error())
70 } else {
71 Ok(ScmSocket { socket })
72 }
73 }
74 }
75 };
76 }
77
78 ScmSocketTryFrom!(StreamChannel);
79 ScmSocketTryFrom!(UnixDatagram);
80 ScmSocketTryFrom!(UnixListener);
81 ScmSocketTryFrom!(UnixSeqpacket);
82 ScmSocketTryFrom!(UnixStream);
83
sockaddrv4_to_lib_c(s: &SocketAddrV4) -> sockaddr_in84 pub(crate) fn sockaddrv4_to_lib_c(s: &SocketAddrV4) -> sockaddr_in {
85 sockaddr_in {
86 sin_family: AF_INET as sa_family_t,
87 sin_port: s.port().to_be(),
88 sin_addr: in_addr {
89 s_addr: u32::from_ne_bytes(s.ip().octets()),
90 },
91 sin_zero: [0; 8],
92 sin_len: size_of::<sockaddr_in>() as u8,
93 }
94 }
95
sockaddrv6_to_lib_c(s: &SocketAddrV6) -> sockaddr_in696 pub(crate) fn sockaddrv6_to_lib_c(s: &SocketAddrV6) -> sockaddr_in6 {
97 sockaddr_in6 {
98 sin6_family: AF_INET6 as sa_family_t,
99 sin6_port: s.port().to_be(),
100 sin6_flowinfo: 0,
101 sin6_addr: in6_addr {
102 s6_addr: s.ip().octets(),
103 },
104 sin6_scope_id: 0,
105 sin6_len: size_of::<sockaddr_in6>() as u8,
106 }
107 }
108
cloexec_or_close<Raw: AsRawDescriptor>(raw: Raw) -> io::Result<Raw>109 fn cloexec_or_close<Raw: AsRawDescriptor>(raw: Raw) -> io::Result<Raw> {
110 // SAFETY: `raw` owns a file descriptor, there are no actions with memory. This potentially
111 // races with `fork()` calls in other threads, but on MacOS it's the best we have.
112 let res = unsafe { fcntl(raw.as_raw_descriptor(), F_SETFD, FD_CLOEXEC) };
113 if res >= 0 {
114 Ok(raw)
115 } else {
116 let err = io::Error::last_os_error();
117 // SAFETY: `raw` owns this file descriptor.
118 unsafe { close(raw.as_raw_descriptor()) };
119 Err(err)
120 }
121 }
122
123 // Return `sockaddr_un` for a given `path`
sockaddr_un<P: AsRef<Path>>( path: P, ) -> io::Result<(libc::sockaddr_un, libc::socklen_t)>124 pub(in crate::sys) fn sockaddr_un<P: AsRef<Path>>(
125 path: P,
126 ) -> io::Result<(libc::sockaddr_un, libc::socklen_t)> {
127 let mut addr = libc::sockaddr_un {
128 sun_family: libc::AF_UNIX as libc::sa_family_t,
129 sun_path: std::array::from_fn(|_| 0),
130 sun_len: 0,
131 };
132
133 // Check if the input path is valid. Since
134 // * The pathname in sun_path should be null-terminated.
135 // * The length of the pathname, including the terminating null byte, should not exceed the size
136 // of sun_path.
137 //
138 // and our input is a `Path`, we only need to check
139 // * If the string size of `Path` should less than sizeof(sun_path)
140 // and make sure `sun_path` ends with '\0' by initialized the sun_path with zeros.
141 //
142 // Empty path name is valid since abstract socket address has sun_paht[0] = '\0'
143 let bytes = path.as_ref().as_os_str().as_bytes();
144 if bytes.len() >= addr.sun_path.len() {
145 return Err(io::Error::new(
146 io::ErrorKind::InvalidInput,
147 "Input path size should be less than the length of sun_path.",
148 ));
149 };
150
151 // Copy data from `path` to `addr.sun_path`
152 for (dst, src) in addr.sun_path.iter_mut().zip(bytes) {
153 *dst = *src as libc::c_char;
154 }
155
156 // The addrlen argument that describes the enclosing sockaddr_un structure
157 // should have a value of at least:
158 //
159 // offsetof(struct sockaddr_un, sun_path) + strlen(addr.sun_path) + 1
160 //
161 // or, more simply, addrlen can be specified as sizeof(struct sockaddr_un).
162 addr.sun_len = sun_path_offset() as u8 + bytes.len() as u8 + 1;
163 Ok((addr, addr.sun_len as libc::socklen_t))
164 }
165
166 impl TcpSocket {
new(inet_version: InetVersion) -> io::Result<Self>167 pub fn new(inet_version: InetVersion) -> io::Result<Self> {
168 Ok(TcpSocket {
169 inet_version,
170 descriptor: cloexec_or_close(socket(
171 Into::<sa_family_t>::into(inet_version) as libc::c_int,
172 SOCK_STREAM,
173 0,
174 )?)?,
175 })
176 }
177 }
178
179 impl UnixSeqpacket {
180 /// Creates a pair of connected `SOCK_SEQPACKET` sockets.
181 ///
182 /// Both returned file descriptors have the `CLOEXEC` flag set.
pair() -> io::Result<(UnixSeqpacket, UnixSeqpacket)>183 pub fn pair() -> io::Result<(UnixSeqpacket, UnixSeqpacket)> {
184 let (fd0, fd1) = socketpair(libc::AF_UNIX, libc::SOCK_SEQPACKET, 0)?;
185 let (s0, s1) = (UnixSeqpacket::from(fd0), UnixSeqpacket::from(fd1));
186 Ok((cloexec_or_close(s0)?, cloexec_or_close(s1)?))
187 }
188 }
189
190 impl UnixSeqpacketListener {
191 /// Blocks for and accepts a new incoming connection and returns the socket associated with that
192 /// connection.
193 ///
194 /// The returned socket has the close-on-exec flag set.
accept(&self) -> io::Result<UnixSeqpacket>195 pub fn accept(&self) -> io::Result<UnixSeqpacket> {
196 // SAFETY: we own this fd and the kernel will not write to null pointers.
197 let fd = unsafe { libc::accept(self.as_raw_descriptor(), null_mut(), null_mut()) };
198 match fd {
199 -1 => Err(io::Error::last_os_error()),
200 fd => {
201 // SAFETY: we checked the return value of accept. Therefore, the return value
202 // must be a valid socket.
203 let safe_desc = unsafe { SafeDescriptor::from_raw_descriptor(fd) };
204 Ok(UnixSeqpacket::from(cloexec_or_close(safe_desc)?))
205 }
206 }
207 }
208 }
209