Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 51 additions & 3 deletions crates/net/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,9 @@ const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(10);
/// How long a refused connection (told `Busy`) has to take the one line it is sent.
const REFUSAL_TIMEOUT: Duration = Duration::from_secs(1);

/// How much of a refused client's input is read and dropped at a time ([`drain`]).
const DRAIN_BUFFER: usize = 4096;

/// How often the listener looks for a connection, a finished session or a stop.
const ACCEPT_POLL: Duration = Duration::from_millis(20);

Expand Down Expand Up @@ -296,6 +299,9 @@ struct Link {
output: Box<dyn Write + Send>,
/// Says goodbye the way the connection allows (a TLS `close_notify`) and closes it.
goodbye: Box<dyn FnOnce() + Send>,
/// Says goodbye the same way and stops writing, but leaves the connection open for reading,
/// for a client that is sent away ([`refuse`]).
finish_writing: Box<dyn FnOnce() + Send>,
/// A handle on the socket, to close it abruptly when the listener stops.
socket: TcpStream,
}
Expand Down Expand Up @@ -534,15 +540,51 @@ fn is_passing(e: &io::Error) -> bool {
/// connection. CNP's `Busy`, with a null id since no request was read. Only a client that is
/// approved gets this far, so what it learns (that the node is in use) is nothing a stranger can
/// ask.
///
/// The connection is closed gently: the node says goodbye and stops writing, reads and drops
/// what the client sends until it hangs up (or [`REFUSAL_TIMEOUT`] passes), and only then
/// closes. A client may well have spoken first (Solrac sends `initialize` as soon as it is
/// connected), and closing a socket with data still unread makes the kernel reset the
/// connection; on Linux a reset makes the client lose what it hadn't read yet, the `Busy` line
/// among it, so it saw "connection reset by peer" instead (macOS keeps the line). This is the
/// lingering close of RFC 7230 §6.6 and Apache's `lingering_close`. The waiting is done on a
/// thread of its own, so the listener goes on accepting.
fn refuse(link: Link) {
let _ = link.socket.set_write_timeout(Some(REFUSAL_TIMEOUT));
let Link {
mut output,
finish_writing,
socket,
..
} = link;
let _ = socket.set_write_timeout(Some(REFUSAL_TIMEOUT));
let error = ResponseError::new(
code::BUSY,
"this cb2026 is serving another client; it serves one at a time",
);
let mut output = link.output;
let _ = write_message(&mut output, &Response::error(None, error).into());
(link.goodbye)();
finish_writing();
drop(output);
// The socket closes when its last handle does: this one, once the client has hung up.
let _ = thread::Builder::new()
.name("cb2026 refusal".into())
.spawn(move || drain(socket, REFUSAL_TIMEOUT));
}

/// Reads and drops what a refused client sends until it hangs up, the connection fails, or
/// `within` passes, so that closing `socket` afterwards finds nothing unread ([`refuse`]).
fn drain(mut socket: TcpStream, within: Duration) {
let until = Instant::now() + within;
let mut sink = [0u8; DRAIN_BUFFER];
loop {
let left = until.saturating_duration_since(Instant::now());
if left.is_zero() || socket.set_read_timeout(Some(left)).is_err() {
return;
}
match socket.read(&mut sink) {
Ok(0) | Err(_) => return,
Ok(_) => {}
}
}
}

/// How greeting a connection ended.
Expand Down Expand Up @@ -579,18 +621,23 @@ fn greet_with(stream: TcpStream, config: &Config) -> Option<Greeted> {
let Some(trust) = &config.trust else {
let writer = stream.try_clone().ok()?;
let closer = stream.try_clone().ok()?;
let half = stream.try_clone().ok()?;
return Some(Greeted::Link(Link {
input: FirstMessage::new(Box::new(BufReader::new(gate)), control, deadline),
output: Box::new(writer),
goodbye: Box::new(move || {
let _ = closer.shutdown(Shutdown::Both);
}),
finish_writing: Box::new(move || {
let _ = half.shutdown(Shutdown::Write);
}),
socket,
}));
};
let (reader, mut writer, fingerprint) =
tls::accept(gate, stream, Arc::clone(&trust.tls)).ok()?;
let goodbye = writer.closer().ok()?;
let half = writer.closer().ok()?;
let mut input = FirstMessage::new(Box::new(reader), control, deadline);
if !trust.store.is_approved(&fingerprint) {
// A client that isn't approved may only ask to pair, and only while a window is open.
Expand All @@ -606,6 +653,7 @@ fn greet_with(stream: TcpStream, config: &Config) -> Option<Greeted> {
input,
output: Box::new(writer),
goodbye: Box::new(move || goodbye.close()),
finish_writing: Box::new(move || half.finish_writing()),
socket,
}))
}
Expand Down
13 changes: 13 additions & 0 deletions crates/net/src/tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -384,4 +384,17 @@ impl TlsCloser {
let _ = send_pending(&mut connection, &self.socket);
let _ = self.socket.shutdown(std::net::Shutdown::Both);
}

/// Says goodbye to the peer and stops writing, but keeps reading: the half of [`close`]
/// that leaves what the peer is still sending to be read, so the connection can then close
/// without a reset (see `refuse` in the crate root).
///
/// [`close`]: TlsCloser::close
pub(crate) fn finish_writing(&self) {
let _ = self.socket.set_write_timeout(Some(Duration::from_secs(1)));
let mut connection = lock(&self.connection);
connection.send_close_notify();
let _ = send_pending(&mut connection, &self.socket);
let _ = self.socket.shutdown(std::net::Shutdown::Write);
}
}
28 changes: 28 additions & 0 deletions crates/net/tests/tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,34 @@ fn a_second_approved_client_is_told_busy_and_the_first_is_not_disturbed() {
node.finish();
}

/// A client told Busy reads it even when it spoke first, as Solrac's connection check does: it
/// sends `initialize` as soon as it is connected. A node that closed with that request unread
/// made the kernel reset the connection, and Linux drops what the client hadn't read yet when a
/// reset arrives, the Busy line included: the client read "connection reset by peer" instead
/// (macOS keeps the line, so this only ever failed on Linux).
#[test]
fn a_client_that_speaks_first_still_reads_busy() {
let node = Node::start();
let (a, b) = (node.approved_client("a"), node.approved_client("b"));
let mut first = node.connect(&a);
initialize(&mut first);
let mut second = node.connect(&b);
// The node may have closed already, so the write may fail; what there is to read says why.
let _ = second.send_line(INITIALIZE);
// Long enough for the node to have sent Busy and closed, and for a reset to have come.
thread::sleep(Duration::from_millis(300));
let line = second
.read_line()
.expect("the connection wasn't reset")
.expect("a refusal is sent");
assert!(
line.contains(r#""id":null"#) && line.contains(r#""error""#),
"{line}"
);
assert!(is_closed_silently(&mut second));
node.finish();
}

#[test]
fn a_stranger_holding_a_connection_does_not_keep_an_approved_client_out() {
let node = Node::start();
Expand Down
Loading