//! Writing to a socket without SIGPIPE, for rustls (`std/tls`, ADR 0038; //! the distribution transport, ADR 0072). //! //! A Louise program's `main` is C: nothing ignores SIGPIPE, as a Rust //! `main` would, so a write to a socket whose peer closed would end the //! program. [`NoSigPipe`] sends with `MSG_NOSIGNAL`, which makes that an //! `EPIPE` error instead. It writes vectored, with one `sendmsg`: rustls's //! `write_tls` hands over every pending record at once (up to 64), and //! takes back the count written. //! //! The runtime runs on Linux only (ADR 0011, `fiber.rs`). Elsewhere, a //! port would set `SO_NOSIGPIPE` on each socket and use `writev`. use std::io::{self, ErrorKind, IoSlice, Write}; use std::os::fd::{AsFd, AsRawFd, BorrowedFd}; /// `MSG_DONTWAIT` too: the runtime's sockets are non-blocking already, /// and a send must never wait either way. const FLAGS: libc::c_int = libc::MSG_NOSIGNAL | libc::MSG_DONTWAIT; /// A socket, as rustls writes to it. pub(crate) struct NoSigPipe<'a>(BorrowedFd<'a>); impl<'a> NoSigPipe<'a> { pub(crate) fn new(sock: &'a impl AsFd) -> NoSigPipe<'a> { NoSigPipe(sock.as_fd()) } } impl Write for NoSigPipe<'_> { fn write(&mut self, buf: &[u8]) -> io::Result { self.write_vectored(&[IoSlice::new(buf)]) } /// One `sendmsg` of the first `UIO_MAXIOV` slices (more is `EMSGSIZE`), /// again if a signal interrupts it. A full socket is `WouldBlock`. fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result { let bufs = &bufs[..bufs.len().min(libc::UIO_MAXIOV as usize)]; // SAFETY: `msghdr` is plain data; all zeros is no address and no // control data. let mut msg: libc::msghdr = unsafe { std::mem::zeroed() }; // `IoSlice` is ABI-compatible with `iovec` on Unix (its docs), and // `sendmsg` only reads the slices. msg.msg_iov = bufs.as_ptr().cast_mut().cast::(); msg.msg_iovlen = bufs.len(); loop { // SAFETY: `msg` points to `bufs`, live for the call; the // descriptor is borrowed, so open. let sent = unsafe { libc::sendmsg(self.0.as_raw_fd(), &msg, FLAGS) }; if let Ok(sent) = usize::try_from(sent) { return Ok(sent); } let e = io::Error::last_os_error(); if e.kind() != ErrorKind::Interrupted { return Err(e); } } } fn flush(&mut self) -> io::Result<()> { Ok(()) } } #[cfg(test)] mod tests { use std::io::Read; use std::net::{TcpListener, TcpStream}; use std::time::Duration; use super::*; /// A connected pair over loopback: (writer, reader). fn pair() -> (TcpStream, TcpStream) { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let writer = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); let (reader, _) = listener.accept().unwrap(); (writer, reader) } #[test] fn several_slices_go_in_one_call() { let (writer, mut reader) = pair(); let slices = [ IoSlice::new(b"ab"), IoSlice::new(b"cd"), IoSlice::new(b"ef"), ]; assert_eq!(NoSigPipe::new(&writer).write_vectored(&slices).unwrap(), 6); let mut got = [0; 6]; reader.read_exact(&mut got).unwrap(); assert_eq!(&got, b"abcdef"); } #[test] fn more_slices_than_the_kernel_takes_are_cut() { let (writer, _reader) = pair(); let slices = vec![IoSlice::new(b"x"); libc::UIO_MAXIOV as usize + 10]; let sent = NoSigPipe::new(&writer).write_vectored(&slices).unwrap(); assert_eq!(sent, libc::UIO_MAXIOV as usize); } /// Whether SIGPIPE is pending on this thread. fn sigpipe_pending() -> bool { // SAFETY: `set` is written by `sigpending` before it is read. unsafe { let mut set: libc::sigset_t = std::mem::zeroed(); assert_eq!(libc::sigpending(&mut set), 0); libc::sigismember(&set, libc::SIGPIPE) == 1 } } /// Block or unblock SIGPIPE on this thread (`how`), so that one raised /// here stays pending, where [`sigpipe_pending`] sees it, instead of /// being ignored (the test harness's `main` is Rust). fn mask_sigpipe(how: libc::c_int) { // SAFETY: `set` is initialized by `sigemptyset` before use. unsafe { let mut set: libc::sigset_t = std::mem::zeroed(); libc::sigemptyset(&mut set); libc::sigaddset(&mut set, libc::SIGPIPE); assert_eq!(libc::pthread_sigmask(how, &set, std::ptr::null_mut()), 0); } } #[test] fn a_closed_peer_is_an_error_not_a_signal() { let (writer, reader) = pair(); drop(reader); mask_sigpipe(libc::SIG_BLOCK); assert!(!sigpipe_pending()); // The first sends may go before the peer's reset arrives. let chunk = [0u8; 1024]; let slices = [IoSlice::new(&chunk), IoSlice::new(&chunk)]; let mut error = None; for _ in 0..100 { match NoSigPipe::new(&writer).write_vectored(&slices) { Ok(_) => std::thread::sleep(Duration::from_millis(10)), Err(e) if e.kind() == ErrorKind::BrokenPipe => { error = Some(e); break; } // Reported once, then the socket is closed: `EPIPE`. Err(e) if e.kind() == ErrorKind::ConnectionReset => {} Err(e) => panic!("{e}"), } } assert!(error.is_some(), "no broken pipe"); assert!(!sigpipe_pending(), "SIGPIPE raised"); // The check sees the signal: a plain `send` raises it. // SAFETY: `chunk` is live for the call; `writer` is open. let sent = unsafe { libc::send(writer.as_raw_fd(), chunk.as_ptr().cast(), chunk.len(), 0) }; assert_eq!(sent, -1); assert!(sigpipe_pending(), "a plain send raised no SIGPIPE"); // Take it, so unblocking does not deliver it. // SAFETY: as in `mask_sigpipe`; `sigwait` writes `signal`. unsafe { let mut set: libc::sigset_t = std::mem::zeroed(); libc::sigemptyset(&mut set); libc::sigaddset(&mut set, libc::SIGPIPE); let mut signal = 0; assert_eq!(libc::sigwait(&set, &mut signal), 0); assert_eq!(signal, libc::SIGPIPE); } mask_sigpipe(libc::SIG_UNBLOCK); } }