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::net::SocketAddrV4;
7 use std::net::SocketAddrV6;
8 use std::os::fd::RawFd;
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::in6_addr;
18 use libc::in_addr;
19 use libc::msghdr;
20 use libc::sa_family_t;
21 use libc::sendmsg;
22 use libc::sockaddr_in;
23 use libc::sockaddr_in6;
24 use libc::ssize_t;
25 use libc::AF_INET;
26 use libc::AF_INET6;
27 use libc::MSG_NOSIGNAL;
28 use libc::SOCK_CLOEXEC;
29 use libc::SOCK_STREAM;
30
31 use crate::descriptor::AsRawDescriptor;
32 use crate::descriptor::FromRawDescriptor;
33 use crate::unix::net::socket;
34 use crate::unix::net::socketpair;
35 use crate::unix::net::sun_path_offset;
36 use crate::unix::net::InetVersion;
37 use crate::unix::net::TcpSocket;
38 use crate::SafeDescriptor;
39 use crate::ScmSocket;
40 use crate::StreamChannel;
41 use crate::UnixSeqpacket;
42 use crate::UnixSeqpacketListener;
43
sendmsg_nosignal( fd: RawFd, msg: *const msghdr, flags: c_int, ) -> ssize_t44 pub(in crate::sys) unsafe fn sendmsg_nosignal(
45 fd: RawFd,
46 msg: *const msghdr,
47 flags: c_int,
48 ) -> ssize_t {
49 sendmsg(fd, msg, flags | MSG_NOSIGNAL)
50 }
51
sockaddrv4_to_lib_c(s: &SocketAddrV4) -> sockaddr_in52 pub(in crate::sys) fn sockaddrv4_to_lib_c(s: &SocketAddrV4) -> sockaddr_in {
53 sockaddr_in {
54 sin_family: AF_INET as sa_family_t,
55 sin_port: s.port().to_be(),
56 sin_addr: in_addr {
57 s_addr: u32::from_ne_bytes(s.ip().octets()),
58 },
59 sin_zero: [0; 8],
60 }
61 }
62
sockaddrv6_to_lib_c(s: &SocketAddrV6) -> sockaddr_in663 pub(in crate::sys) fn sockaddrv6_to_lib_c(s: &SocketAddrV6) -> sockaddr_in6 {
64 sockaddr_in6 {
65 sin6_family: AF_INET6 as sa_family_t,
66 sin6_port: s.port().to_be(),
67 sin6_flowinfo: 0,
68 sin6_addr: in6_addr {
69 s6_addr: s.ip().octets(),
70 },
71 sin6_scope_id: 0,
72 }
73 }
74
75 // Return `sockaddr_un` for a given `path`
sockaddr_un<P: AsRef<Path>>( path: P, ) -> io::Result<(libc::sockaddr_un, libc::socklen_t)>76 pub(in crate::sys) fn sockaddr_un<P: AsRef<Path>>(
77 path: P,
78 ) -> io::Result<(libc::sockaddr_un, libc::socklen_t)> {
79 let mut addr = libc::sockaddr_un {
80 sun_family: libc::AF_UNIX as libc::sa_family_t,
81 sun_path: std::array::from_fn(|_| 0),
82 };
83
84 // Check if the input path is valid. Since
85 // * The pathname in sun_path should be null-terminated.
86 // * The length of the pathname, including the terminating null byte, should not exceed the size
87 // of sun_path.
88 //
89 // and our input is a `Path`, we only need to check
90 // * If the string size of `Path` should less than sizeof(sun_path)
91 // and make sure `sun_path` ends with '\0' by initialized the sun_path with zeros.
92 //
93 // Empty path name is valid since abstract socket address has sun_paht[0] = '\0'
94 let bytes = path.as_ref().as_os_str().as_bytes();
95 if bytes.len() >= addr.sun_path.len() {
96 return Err(io::Error::new(
97 io::ErrorKind::InvalidInput,
98 "Input path size should be less than the length of sun_path.",
99 ));
100 };
101
102 // Copy data from `path` to `addr.sun_path`
103 for (dst, src) in addr.sun_path.iter_mut().zip(bytes) {
104 *dst = *src as libc::c_char;
105 }
106
107 // The addrlen argument that describes the enclosing sockaddr_un structure
108 // should have a value of at least:
109 //
110 // offsetof(struct sockaddr_un, sun_path) + strlen(addr.sun_path) + 1
111 //
112 // or, more simply, addrlen can be specified as sizeof(struct sockaddr_un).
113 let len = sun_path_offset() + bytes.len() + 1;
114 Ok((addr, len as libc::socklen_t))
115 }
116
117 impl TcpSocket {
new(inet_version: InetVersion) -> io::Result<Self>118 pub fn new(inet_version: InetVersion) -> io::Result<Self> {
119 Ok(TcpSocket {
120 inet_version,
121 descriptor: socket(
122 Into::<sa_family_t>::into(inet_version) as libc::c_int,
123 SOCK_STREAM | SOCK_CLOEXEC,
124 0,
125 )?,
126 })
127 }
128 }
129
130 impl UnixSeqpacket {
131 /// Creates a pair of connected `SOCK_SEQPACKET` sockets.
132 ///
133 /// Both returned file descriptors have the `CLOEXEC` flag set.
pair() -> io::Result<(UnixSeqpacket, UnixSeqpacket)>134 pub fn pair() -> io::Result<(UnixSeqpacket, UnixSeqpacket)> {
135 socketpair(libc::AF_UNIX, libc::SOCK_SEQPACKET | libc::SOCK_CLOEXEC, 0)
136 .map(|(s0, s1)| (UnixSeqpacket::from(s0), UnixSeqpacket::from(s1)))
137 }
138 }
139
140 impl UnixSeqpacketListener {
141 /// Blocks for and accepts a new incoming connection and returns the socket associated with that
142 /// connection.
143 ///
144 /// The returned socket has the close-on-exec flag set.
accept(&self) -> io::Result<UnixSeqpacket>145 pub fn accept(&self) -> io::Result<UnixSeqpacket> {
146 // SAFETY:
147 // Safe because we own this fd and the kernel will not write to null pointers.
148 match unsafe {
149 libc::accept4(
150 self.as_raw_descriptor(),
151 null_mut(),
152 null_mut(),
153 SOCK_CLOEXEC,
154 )
155 } {
156 -1 => Err(io::Error::last_os_error()),
157 fd => {
158 Ok(UnixSeqpacket::from(
159 // SAFETY: Safe because we checked the return value of accept. Therefore, the
160 // return value must be a valid socket.
161 unsafe { SafeDescriptor::from_raw_descriptor(fd) },
162 ))
163 }
164 }
165 }
166 }
167
168 macro_rules! ScmSocketTryFrom {
169 ($name:ident) => {
170 impl TryFrom<$name> for ScmSocket<$name> {
171 type Error = io::Error;
172
173 fn try_from(socket: $name) -> io::Result<Self> {
174 Ok(ScmSocket { socket })
175 }
176 }
177 };
178 }
179
180 ScmSocketTryFrom!(StreamChannel);
181 ScmSocketTryFrom!(UnixDatagram);
182 ScmSocketTryFrom!(UnixListener);
183 ScmSocketTryFrom!(UnixSeqpacket);
184 ScmSocketTryFrom!(UnixStream);
185