Debian Codegraph @

src/raw_socket.rs

raw symbols SCIP
1 use std::{
2 io::IoSliceMut,
3 os::fd::{AsRawFd, RawFd},
4 };
5
6 use libc::{c_void, sockaddr, sockaddr_storage};
7
8 use crate::{
9 cerr,
10 control_message::{
11 empty_msghdr, zeroed_sockaddr_storage, ControlMessage, ControlMessageIterator, MessageQueue,
12 },
13 };
14
15 #[cfg(target_os = "freebsd")]
16 mod freebsd;
17 #[cfg(target_os = "linux")]
18 mod linux;
19 #[cfg(target_os = "macos")]
20 mod macos;
21
22 // A struct providing safe wrappers around various socket api calls
23 #[derive(Debug, Hash)]
24 pub(crate) struct RawSocket {
25 fd: RawFd,
26 }
27
28 impl AsRawFd for RawSocket {
29 fn as_raw_fd(&self) -> RawFd {
30 self.fd
31 }
32 }
33
34 impl RawSocket {
35 pub(crate) fn open(
36 domain: libc::c_int,
37 ty: libc::c_int,
38 protocol: libc::c_int,
39 ) -> std::io::Result<Self> {
40 // Safety: libc::socket is always safe to call
41 Ok(RawSocket {
42 fd: cerr(unsafe { libc::socket(domain, ty, protocol) })?,
43 })
44 }
45
46 pub(crate) fn bind(&self, addr: sockaddr_storage) -> std::io::Result<()> {
47 // Per posix, it may be invalid to specify a length larger than that of the family.
48 let len = sockaddr_len(addr);
49
50 // Safety: socket is valid for the duration of the call, addr lives for the duration of
51 // the call and len is at most the length of addr.
52 cerr(unsafe { libc::bind(self.fd, &addr as *const _ as *const _, len) })?;
53 Ok(())
54 }
55
56 pub(crate) fn connect(&self, addr: sockaddr_storage) -> std::io::Result<()> {
57 // Per posix, it may be invalid to specify a length larger than that of the family.
58 let len = sockaddr_len(addr);
59
60 // Safety: socket is valid for the duration of the call, addr lives for the duration of
61 // the call and len is at most the length of addr.
62 cerr(unsafe { libc::connect(self.fd, &addr as *const _ as *const _, len) })?;
63 Ok(())
64 }
65
66 pub(crate) fn set_nonblocking(&self, nonblocking: bool) -> std::io::Result<()> {
67 let nonblocking = nonblocking as libc::c_int;
68 // Safety: nonblocking lives for the duration of the call, and is 4 bytes long as expected for FIONBIO
69 cerr(unsafe { libc::ioctl(self.fd, libc::FIONBIO, &nonblocking) }).map(drop)
70 }
71
72 #[cfg(target_os = "linux")]
73 pub(crate) fn reuse_addr(&self) -> std::io::Result<()> {
74 let options = 1u32;
75
76 // Safety:
77 //
78 // the pointer argument is valid, the size is accurate
79 unsafe {
80 cerr(libc::setsockopt(
81 self.fd,
82 libc::SOL_SOCKET,
83 libc::SO_REUSEADDR,
84 &options as *const _ as *const libc::c_void,
85 std::mem::size_of_val(&options) as libc::socklen_t,
86 ))?;
87 }
88
89 Ok(())
90 }
91
92 pub(crate) fn receive_message<'a>(
93 &self,
94 packet_buf: &mut [u8],
95 control_buf: &'a mut [u8],
96 queue: MessageQueue,
97 ) -> std::io::Result<(
98 usize,
99 impl Iterator<Item = ControlMessage> + 'a,
100 sockaddr_storage,
101 )> {
102 let mut buf_slice = IoSliceMut::new(packet_buf);
103 let mut addr = zeroed_sockaddr_storage();
104
105 let mut mhdr = empty_msghdr();
106
107 mhdr.msg_control = control_buf.as_mut_ptr().cast::<libc::c_void>();
108 mhdr.msg_controllen = control_buf.len() as _;
109 mhdr.msg_iov = (&mut buf_slice as *mut IoSliceMut).cast::<libc::iovec>();
110 mhdr.msg_iovlen = 1;
111 mhdr.msg_flags = 0;
112 mhdr.msg_name = (&mut addr as *mut libc::sockaddr_storage).cast::<libc::c_void>();
113 mhdr.msg_namelen = std::mem::size_of::<libc::sockaddr_storage>() as u32;
114
115 let receive_flags = match queue {
116 MessageQueue::Normal => 0,
117 #[cfg(target_os = "linux")]
118 MessageQueue::Error => libc::MSG_ERRQUEUE,
119 };
120
121 // Safety:
122 // We have a mutable reference to the control buffer for the duration of the
123 // call, and controllen is also set to it's length.
124 // IoSliceMut is ABI compatible with iovec, and we only have 1 which matches
125 // iovlen msg_name is initialized to point to an owned sockaddr_storage and
126 // msg_namelen is the size of sockaddr_storage
127 // If one of the buffers is too small, recvmsg cuts off data at appropriate
128 // boundary
129 let received_bytes = loop {
130 match cerr(unsafe { libc::recvmsg(self.fd, &mut mhdr, receive_flags) } as _) {
131 Err(e) if std::io::ErrorKind::Interrupted == e.kind() => {
132 // retry when the recv was interrupted
133 continue;
134 }
135 Err(e) => return Err(e),
136 Ok(sent) => break sent as usize,
137 }
138 };
139
140 if mhdr.msg_flags & libc::MSG_TRUNC > 0 {
141 tracing::info!(
142 "truncated packet because it was larger than expected: {} bytes",
143 packet_buf.len(),
144 );
145 }
146
147 if mhdr.msg_flags & libc::MSG_CTRUNC > 0 {
148 tracing::info!("truncated control messages");
149 }
150
151 // Clear out the fields for which we are giving up the reference
152 mhdr.msg_iov = std::ptr::null_mut();
153 mhdr.msg_iovlen = 0;
154 mhdr.msg_name = std::ptr::null_mut();
155 mhdr.msg_namelen = 0;
156
157 // Safety:
158 // recvmsg ensures that the control buffer contains
159 // a set of valid control messages and that controllen is
160 // the length these take up in the buffer.
161 Ok((
162 received_bytes,
163 unsafe { ControlMessageIterator::new(mhdr) },
164 addr,
165 ))
166 }
167
168 pub(crate) fn send_to(&self, msg: &[u8], addr: sockaddr_storage) -> std::io::Result<()> {
169 // Per posix, it may be invalid to specify a length larger than that of the family.
170 let len = sockaddr_len(addr);
171
172 // Safety:
173 // the socket will outlive the call.
174 // msg points to a block of memory of length msg.len()
175 // addr points to a block of memory of length at least len
176 // with flags=0, the other arguments don't matter for safety
177 cerr(unsafe {
178 libc::sendto(
179 self.fd,
180 msg as *const _ as *const c_void,
181 msg.len(),
182 0,
183 &addr as *const _ as *const sockaddr,
184 len,
185 ) as _
186 })?;
187 Ok(())
188 }
189
190 pub(crate) fn send(&self, msg: &[u8]) -> std::io::Result<()> {
191 // Safety:
192 // msg points to a block of memory of length msg.len()
193 // with flags=0, the other arguments don't matter for safety
194 cerr(unsafe { libc::send(self.fd, msg as *const _ as *const c_void, msg.len(), 0) as _ })?;
195 Ok(())
196 }
197
198 pub(crate) fn getsockname(&self) -> std::io::Result<sockaddr_storage> {
199 let mut addr = zeroed_sockaddr_storage();
200 let mut addr_len: libc::socklen_t = std::mem::size_of_val(&addr) as _;
201 // Safety:
202 // the socket will outlive the call.
203 // addr points to a block of memory of length addr_len
204 // addr_len will outlive the call.
205 cerr(unsafe {
206 libc::getsockname(
207 self.fd,
208 &mut addr as *mut _ as *mut _,
209 &mut addr_len as *mut _,
210 )
211 })?;
212 Ok(addr)
213 }
214
215 pub(crate) fn getpeername(&self) -> std::io::Result<sockaddr_storage> {
216 let mut addr = zeroed_sockaddr_storage();
217 let mut addr_len: libc::socklen_t = std::mem::size_of_val(&addr) as _;
218 // Safety:
219 // the socket will outlive the call.
220 // addr points to a block of memory of length addr_len
221 // addr_len will outlive the call.
222 cerr(unsafe {
223 libc::getpeername(
224 self.fd,
225 &mut addr as *mut _ as *mut _,
226 &mut addr_len as *mut _,
227 )
228 })?;
229 Ok(addr)
230 }
231 }
232
233 fn sockaddr_len(addr: sockaddr_storage) -> u32 {
234 let len: libc::socklen_t = std::mem::size_of_val(&addr) as _;
235
236 len.min(match addr.ss_family as _ {
237 libc::AF_INET => std::mem::size_of::<libc::sockaddr_in>() as _,
238 libc::AF_INET6 => std::mem::size_of::<libc::sockaddr_in6>() as _,
239 _ => len,
240 })
241 }
242
243 impl Drop for RawSocket {
244 fn drop(&mut self) {
245 // Safety: close is always safe to call on a file descriptor
246 unsafe { libc::close(self.fd) };
247 }
248 }