tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

167 lignes · 6576 octetsBrut · Historique
1//! Writing to a socket without SIGPIPE, for rustls (`std/tls`, ADR 0038;
2//! the distribution transport, ADR 0072).
3//!
4//! A Louise program's `main` is C: nothing ignores SIGPIPE, as a Rust
5//! `main` would, so a write to a socket whose peer closed would end the
6//! program. [`NoSigPipe`] sends with `MSG_NOSIGNAL`, which makes that an
7//! `EPIPE` error instead. It writes vectored, with one `sendmsg`: rustls's
8//! `write_tls` hands over every pending record at once (up to 64), and
9//! takes back the count written.
10//!
11//! The runtime runs on Linux only (ADR 0011, `fiber.rs`). Elsewhere, a
12//! port would set `SO_NOSIGPIPE` on each socket and use `writev`.
13
14use std::io::{self, ErrorKind, IoSlice, Write};
15use std::os::fd::{AsFd, AsRawFd, BorrowedFd};
16
17/// `MSG_DONTWAIT` too: the runtime's sockets are non-blocking already,
18/// and a send must never wait either way.
19const FLAGS: libc::c_int = libc::MSG_NOSIGNAL | libc::MSG_DONTWAIT;
20
21/// A socket, as rustls writes to it.
22pub(crate) struct NoSigPipe<'a>(BorrowedFd<'a>);
23
24impl<'a> NoSigPipe<'a> {
25 pub(crate) fn new(sock: &'a impl AsFd) -> NoSigPipe<'a> {
26 NoSigPipe(sock.as_fd())
27 }
28}
29
30impl Write for NoSigPipe<'_> {
31 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
32 self.write_vectored(&[IoSlice::new(buf)])
33 }
34
35 /// One `sendmsg` of the first `UIO_MAXIOV` slices (more is `EMSGSIZE`),
36 /// again if a signal interrupts it. A full socket is `WouldBlock`.
37 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
38 let bufs = &bufs[..bufs.len().min(libc::UIO_MAXIOV as usize)];
39 // SAFETY: `msghdr` is plain data; all zeros is no address and no
40 // control data.
41 let mut msg: libc::msghdr = unsafe { std::mem::zeroed() };
42 // `IoSlice` is ABI-compatible with `iovec` on Unix (its docs), and
43 // `sendmsg` only reads the slices.
44 msg.msg_iov = bufs.as_ptr().cast_mut().cast::<libc::iovec>();
45 msg.msg_iovlen = bufs.len();
46 loop {
47 // SAFETY: `msg` points to `bufs`, live for the call; the
48 // descriptor is borrowed, so open.
49 let sent = unsafe { libc::sendmsg(self.0.as_raw_fd(), &msg, FLAGS) };
50 if let Ok(sent) = usize::try_from(sent) {
51 return Ok(sent);
52 }
53 let e = io::Error::last_os_error();
54 if e.kind() != ErrorKind::Interrupted {
55 return Err(e);
56 }
57 }
58 }
59
60 fn flush(&mut self) -> io::Result<()> {
61 Ok(())
62 }
63}
64
65#[cfg(test)]
66mod tests {
67 use std::io::Read;
68 use std::net::{TcpListener, TcpStream};
69 use std::time::Duration;
70
71 use super::*;
72
73 /// A connected pair over loopback: (writer, reader).
74 fn pair() -> (TcpStream, TcpStream) {
75 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
76 let writer = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
77 let (reader, _) = listener.accept().unwrap();
78 (writer, reader)
79 }
80
81 #[test]
82 fn several_slices_go_in_one_call() {
83 let (writer, mut reader) = pair();
84 let slices = [
85 IoSlice::new(b"ab"),
86 IoSlice::new(b"cd"),
87 IoSlice::new(b"ef"),
88 ];
89 assert_eq!(NoSigPipe::new(&writer).write_vectored(&slices).unwrap(), 6);
90 let mut got = [0; 6];
91 reader.read_exact(&mut got).unwrap();
92 assert_eq!(&got, b"abcdef");
93 }
94
95 #[test]
96 fn more_slices_than_the_kernel_takes_are_cut() {
97 let (writer, _reader) = pair();
98 let slices = vec![IoSlice::new(b"x"); libc::UIO_MAXIOV as usize + 10];
99 let sent = NoSigPipe::new(&writer).write_vectored(&slices).unwrap();
100 assert_eq!(sent, libc::UIO_MAXIOV as usize);
101 }
102
103 /// Whether SIGPIPE is pending on this thread.
104 fn sigpipe_pending() -> bool {
105 // SAFETY: `set` is written by `sigpending` before it is read.
106 unsafe {
107 let mut set: libc::sigset_t = std::mem::zeroed();
108 assert_eq!(libc::sigpending(&mut set), 0);
109 libc::sigismember(&set, libc::SIGPIPE) == 1
110 }
111 }
112
113 /// Block or unblock SIGPIPE on this thread (`how`), so that one raised
114 /// here stays pending, where [`sigpipe_pending`] sees it, instead of
115 /// being ignored (the test harness's `main` is Rust).
116 fn mask_sigpipe(how: libc::c_int) {
117 // SAFETY: `set` is initialized by `sigemptyset` before use.
118 unsafe {
119 let mut set: libc::sigset_t = std::mem::zeroed();
120 libc::sigemptyset(&mut set);
121 libc::sigaddset(&mut set, libc::SIGPIPE);
122 assert_eq!(libc::pthread_sigmask(how, &set, std::ptr::null_mut()), 0);
123 }
124 }
125
126 #[test]
127 fn a_closed_peer_is_an_error_not_a_signal() {
128 let (writer, reader) = pair();
129 drop(reader);
130 mask_sigpipe(libc::SIG_BLOCK);
131 assert!(!sigpipe_pending());
132 // The first sends may go before the peer's reset arrives.
133 let chunk = [0u8; 1024];
134 let slices = [IoSlice::new(&chunk), IoSlice::new(&chunk)];
135 let mut error = None;
136 for _ in 0..100 {
137 match NoSigPipe::new(&writer).write_vectored(&slices) {
138 Ok(_) => std::thread::sleep(Duration::from_millis(10)),
139 Err(e) if e.kind() == ErrorKind::BrokenPipe => {
140 error = Some(e);
141 break;
142 }
143 // Reported once, then the socket is closed: `EPIPE`.
144 Err(e) if e.kind() == ErrorKind::ConnectionReset => {}
145 Err(e) => panic!("{e}"),
146 }
147 }
148 assert!(error.is_some(), "no broken pipe");
149 assert!(!sigpipe_pending(), "SIGPIPE raised");
150 // The check sees the signal: a plain `send` raises it.
151 // SAFETY: `chunk` is live for the call; `writer` is open.
152 let sent = unsafe { libc::send(writer.as_raw_fd(), chunk.as_ptr().cast(), chunk.len(), 0) };
153 assert_eq!(sent, -1);
154 assert!(sigpipe_pending(), "a plain send raised no SIGPIPE");
155 // Take it, so unblocking does not deliver it.
156 // SAFETY: as in `mask_sigpipe`; `sigwait` writes `signal`.
157 unsafe {
158 let mut set: libc::sigset_t = std::mem::zeroed();
159 libc::sigemptyset(&mut set);
160 libc::sigaddset(&mut set, libc::SIGPIPE);
161 let mut signal = 0;
162 assert_eq!(libc::sigwait(&set, &mut signal), 0);
163 assert_eq!(signal, libc::SIGPIPE);
164 }
165 mask_sigpipe(libc::SIG_UNBLOCK);
166 }
167}