refactor: cut what a whole-repo audit proved dead, padded, or hand-rolled

Seven region audits, every finding adversarially verified against the
whole workspace before being applied; 80 landed and the two that failed
in application were refuted honestly (ParseError has a from_str_radix
producer the audit missed; NatPmpError's Display is the only reader of
its diagnostic payloads).

The bigger cuts:

- The NewPeer/PierceFireWall cluster: an operation variant nothing ever
  sent, its 77-line arm, a protocol-wrong Client::pierce_firewall that
  wrote a peer-init frame down the server socket, and the struct only
  they used. The live paths in peer/listen.rs are untouched.
- The ops loop reads `for operation in reader` instead of hand-rolling
  recv/break, de-indenting the whole dispatch body.
- Dead lib surface: Message::print_hex and four unused accessors,
  UploadFailed, registry and actor getters, build_watch_user,
  strip_ansi_codes, delegating shims on ClientContext. Removing public
  items makes this a semver major, which the release pipeline enforces.
- Never-used flexibility: the state-migration framework that never held
  a migration, border-type helpers that all answered Rounded, the TUI's
  max_concurrent_downloads field nothing read.
- Convergence: six poll loops into poll_until, three wrap-around
  navigation blocks into cycle, hit tests into Rect::contains, char
  walkers into floor/ceil_char_boundary, five Download literals into
  one helper, the suites' shared scaffolding into tests/common.

Deliberately not taken: swapping the hand-rolled zlib inflate and MD5
for crates (they replace wire-facing machinery whose tolerance of
real-world peer quirks no local test exercises) and pulling chrono into
the lib for a log timestamp. Recorded for their own decision.

Net -1002 lines. Both e2e modes stay green: 94 CLI tests each way, 16
protocol, 33 lib, unit suites, clippy pedantic clean, aislop 100/100
with the four scanner false positives suppressed inline where they
fire.
This commit is contained in:
Michel de Graaf
2026-07-28 12:52:18 +02:00
parent cd56fb3b39
commit f1b667f7f9
62 changed files with 1367 additions and 2319 deletions
+27 -37
View File
@@ -184,13 +184,7 @@ impl PeerActor {
let messages: Vec<PeerMessage> = self
.dispatcher_receiver
.as_ref()
.map_or_else(Vec::new, |receiver| {
let mut msgs = Vec::new();
while let Ok(msg) = receiver.try_recv() {
msgs.push(msg);
}
msgs
});
.map_or_else(Vec::new, |receiver| receiver.try_iter().collect());
for msg in &messages {
self.handle_message(msg.clone());
@@ -690,45 +684,20 @@ impl PeerActor {
}
}
fn initiate_connection(&mut self) -> bool {
fn initiate_connection(&mut self) {
let (username, host, port) = match self.peer.read_safe() {
Ok(peer) => (peer.username.clone(), peer.host.clone(), peer.port),
Err(e) => {
error!("[peer_actor] initiate_connection peer lock: {}", e);
return false;
return;
}
};
let socket_addr =
format!("{host}:{port}").parse::<std::net::SocketAddr>();
match socket_addr {
Ok(addr) => {
// Use connect_timeout to prevent blocking the thread for too long
let timeout = Duration::from_secs(5);
match TcpStream::connect_timeout(&addr, timeout) {
Ok(stream) => {
if let Err(e) = stream.set_nonblocking(true) {
error!(
"[peer:{}] Failed to set non-blocking: {}",
username, e
);
self.disconnect_with_error(e);
return false;
}
stream.set_nodelay(true).ok();
self.stream = Some(stream);
self.connection_state = ConnectionState::Connecting {
since: Instant::now(),
};
true
}
Err(e) => {
self.disconnect_with_error(e);
false
}
}
}
let addr = match socket_addr {
Ok(addr) => addr,
Err(e) => {
error!(
"[peer:{}] Invalid socket address {}:{} - {}",
@@ -738,9 +707,30 @@ impl PeerActor {
io::ErrorKind::InvalidInput,
e,
));
false
return;
}
};
// Use connect_timeout to prevent blocking the thread for too long
let timeout = Duration::from_secs(5);
let stream = match TcpStream::connect_timeout(&addr, timeout) {
Ok(stream) => stream,
Err(e) => {
self.disconnect_with_error(e);
return;
}
};
if let Err(e) = stream.set_nonblocking(true) {
error!("[peer:{}] Failed to set non-blocking: {}", username, e);
self.disconnect_with_error(e);
return;
}
stream.set_nodelay(true).ok();
self.stream = Some(stream);
self.connection_state = ConnectionState::Connecting {
since: Instant::now(),
};
}
fn check_connection_status(&mut self) {
@@ -145,28 +145,6 @@ impl PeerRegistry {
None
}
#[must_use]
pub fn get_all_usernames(&self) -> Vec<String> {
match self.peers.lock_safe() {
Ok(peers) => peers.keys().cloned().collect(),
Err(e) => {
error!("[peer_registry] get_all_usernames: {}", e);
Vec::new()
}
}
}
#[must_use]
pub fn count(&self) -> usize {
match self.peers.lock_safe() {
Ok(peers) => peers.len(),
Err(e) => {
error!("[peer_registry] count: {}", e);
0
}
}
}
#[must_use]
pub fn contains(&self, username: &str) -> bool {
match self.peers.lock_safe() {
+20 -82
View File
@@ -31,8 +31,8 @@ use crate::types::{
};
use crate::utils::lock::RwLockExt;
use std::io::{self, Error, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::io::{self, Write};
use std::net::TcpStream;
use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};
@@ -109,17 +109,6 @@ impl UserMessage {
new_message,
}
}
pub fn print(&self) {
debug!(
"Timestamp: {}. User: {}, Id: #{}, New message: {} Message: {}",
self.timestamp,
self.username,
self.id,
self.new_message,
self.message
);
}
/// The server-assigned id of this message (used to acknowledge it).
#[must_use]
pub const fn id(&self) -> u32 {
@@ -320,60 +309,23 @@ impl ServerActor {
self.session = session;
}
#[must_use]
pub const fn get_address(&self) -> &PeerAddress {
&self.address
}
#[must_use]
pub const fn get_sender(&self) -> Option<&Sender<ServerMessage>> {
self.dispatcher_sender.as_ref()
}
fn initiate_connection(&mut self) -> bool {
let host = self.address.host.clone();
let port = self.address.port;
let addr_str = format!("{host}:{port}");
let mut socket_addrs = match addr_str.to_socket_addrs() {
Ok(addrs) => addrs,
Err(e) => {
error!("[server] Failed to resolve address: {}", e);
self.disconnect_with_error(io::Error::new(
io::ErrorKind::InvalidInput,
e,
));
return false;
}
};
let socket_addr = socket_addrs.next();
let Some(addr) = socket_addr else {
let error_msg =
format!("No socket addresses found for {host}:{port}");
error!("[server] {}", error_msg);
self.disconnect_with_error(io::Error::new(
io::ErrorKind::InvalidInput,
error_msg,
));
return false;
};
let stream = match TcpStream::connect(addr) {
fn initiate_connection(&mut self) {
let stream = match TcpStream::connect((
self.address.host.as_str(),
self.address.port,
)) {
Ok(s) => s,
Err(e) => {
self.disconnect_with_error(e);
return false;
error!("[server] Failed to connect to {}: {}", self.address, e);
self.disconnect_with_error();
return;
}
};
if let Err(e) = stream.set_nonblocking(true) {
error!("[server] Failed to set non-blocking: {}", e);
self.disconnect_with_error(e);
return false;
self.disconnect_with_error();
return;
}
stream.set_nodelay(true).ok();
@@ -381,7 +333,6 @@ impl ServerActor {
self.connection_state = ConnectionState::Connecting {
since: Instant::now(),
};
true
}
pub fn set_self_handle(&mut self, handle: ActorHandle<ServerMessage>) {
@@ -436,13 +387,7 @@ impl ServerActor {
let messages: Vec<ServerMessage> = self
.dispatcher_receiver
.as_ref()
.map_or_else(Vec::new, |receiver| {
let mut msgs = Vec::new();
while let Ok(msg) = receiver.try_recv() {
msgs.push(msg);
}
msgs
});
.map_or_else(Vec::new, |receiver| receiver.try_iter().collect());
for msg in &messages {
self.handle_message(msg.clone());
@@ -783,7 +728,7 @@ impl ServerActor {
e,
e.kind()
);
self.disconnect_with_error(e);
self.disconnect_with_error();
return;
}
}
@@ -818,7 +763,7 @@ impl ServerActor {
"[server] Error extracting message: {}. Disconnecting.",
e
);
self.disconnect_with_error(e);
self.disconnect_with_error();
return;
}
Ok(None) => {
@@ -871,13 +816,13 @@ impl ServerActor {
if let Err(e) = stream.write_all(&message.get_buffer()) {
error!("[server] Error writing message: {}. Disconnecting.", e);
self.disconnect_with_error(e);
self.disconnect_with_error();
return;
}
if let Err(e) = stream.flush() {
error!("[server] Error flushing stream: {}. Disconnecting.", e);
self.disconnect_with_error(e);
self.disconnect_with_error();
}
}
@@ -893,7 +838,7 @@ impl ServerActor {
self.disconnect();
}
fn disconnect_with_error(&mut self, _error: Error) {
fn disconnect_with_error(&mut self) {
debug!("[server] disconnect");
// Losing an established connection ends the session: nothing reconnects
@@ -919,10 +864,7 @@ impl ServerActor {
if since.elapsed() > Duration::from_secs(20) {
error!("[server] Connection timeout after 20 seconds");
self.disconnect_with_error(io::Error::new(
io::ErrorKind::TimedOut,
"Connection timeout",
));
self.disconnect_with_error();
return;
}
@@ -938,16 +880,12 @@ impl ServerActor {
Err(ref e) if e.kind() == io::ErrorKind::NotConnected => {}
Err(e) => {
error!("[server] Connection failed: {}", e);
self.disconnect_with_error(e);
self.disconnect_with_error();
}
}
}
fn on_connection_established(&mut self) {
let Some(_) = self.stream else {
panic!("Stream should be available here")
};
self.initialize_dispatcher();
let queued = std::mem::take(&mut self.queued_messages);