2eb688cc6a
Encrypted bytes that arrived in the same read as the last plain packet stayed in the buffer undecrypted, and the connection then waited forever for a frame it could not parse. The loopback test hit this under load. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
210 lines
7.4 KiB
Rust
210 lines
7.4 KiB
Rust
//! A blocking TCP connection with vanilla's pipeline: optional AES/CFB8
|
|
//! encryption, VarInt21 framing and threshold compression. After login it
|
|
//! splits into a reader (for a receive thread) and a shareable writer.
|
|
use crate::{Error, Result, buf::Reader, crypto::Cfb8, frame};
|
|
use std::{
|
|
io::{Read, Write},
|
|
net::{Shutdown, TcpStream, ToSocketAddrs},
|
|
sync::{
|
|
Arc,
|
|
atomic::{AtomicI64, Ordering},
|
|
},
|
|
time::Duration,
|
|
};
|
|
|
|
/// Packets received/sent and bytes in/out, for the debug screen.
|
|
#[derive(Debug, Default)]
|
|
pub struct Counters {
|
|
pub received: AtomicI64,
|
|
pub sent: AtomicI64,
|
|
pub bytes_in: AtomicI64,
|
|
pub bytes_out: AtomicI64,
|
|
}
|
|
|
|
pub struct ConnReader {
|
|
stream: TcpStream,
|
|
buffer: Vec<u8>,
|
|
decrypt: Option<Cfb8>,
|
|
pub threshold: Option<usize>,
|
|
pub counters: Arc<Counters>,
|
|
}
|
|
pub struct ConnWriter {
|
|
stream: TcpStream,
|
|
encrypt: Option<Cfb8>,
|
|
pub threshold: Option<usize>,
|
|
counters: Arc<Counters>,
|
|
}
|
|
/// Both halves before the split.
|
|
pub struct Connection {
|
|
pub reader: ConnReader,
|
|
pub writer: ConnWriter,
|
|
}
|
|
impl Connection {
|
|
pub fn connect(host: &str, port: u16, timeout: Duration) -> Result<Self> {
|
|
let addrs: Vec<_> = (host, port)
|
|
.to_socket_addrs()
|
|
.map_err(|e| Error::new(format!("Unknown host {host}: {e}")))?
|
|
.collect();
|
|
let mut last = Error::new(format!("Unknown host {host}"));
|
|
for addr in addrs {
|
|
match TcpStream::connect_timeout(&addr, timeout) {
|
|
Ok(stream) => return Self::from_stream(stream),
|
|
Err(e) => last = Error::new(format!("Connection refused: {e}")),
|
|
}
|
|
}
|
|
Err(last)
|
|
}
|
|
pub fn from_stream(stream: TcpStream) -> Result<Self> {
|
|
stream.set_nodelay(true)?;
|
|
let counters = Arc::new(Counters::default());
|
|
let write = stream.try_clone()?;
|
|
Ok(Self {
|
|
reader: ConnReader {
|
|
stream,
|
|
buffer: Vec::new(),
|
|
decrypt: None,
|
|
threshold: None,
|
|
counters: counters.clone(),
|
|
},
|
|
writer: ConnWriter {
|
|
stream: write,
|
|
encrypt: None,
|
|
threshold: None,
|
|
counters,
|
|
},
|
|
})
|
|
}
|
|
/// ClientboundLoginCompressionPacket: negative thresholds disable compression.
|
|
pub fn set_compression(&mut self, threshold: i32) {
|
|
let t = usize::try_from(threshold).ok();
|
|
self.reader.threshold = t;
|
|
self.writer.threshold = t;
|
|
}
|
|
/// Connection.setEncryptionKey: both directions keyed with the shared secret.
|
|
pub fn enable_encryption(&mut self, secret: &[u8; 16]) {
|
|
let mut decrypt = Cfb8::new(secret, secret);
|
|
// Bytes already read past the last packet were sent encrypted.
|
|
decrypt.decrypt(&mut self.reader.buffer);
|
|
self.reader.decrypt = Some(decrypt);
|
|
self.writer.encrypt = Some(Cfb8::new(secret, secret));
|
|
}
|
|
pub fn send(&mut self, body: &[u8]) -> Result<()> {
|
|
self.writer.send(body)
|
|
}
|
|
pub fn recv(&mut self) -> Result<(i32, Vec<u8>)> {
|
|
self.reader.recv()
|
|
}
|
|
pub fn split(self) -> (ConnReader, ConnWriter) {
|
|
(self.reader, self.writer)
|
|
}
|
|
}
|
|
impl ConnReader {
|
|
/// Block until a whole packet arrives: (id, payload).
|
|
pub fn recv(&mut self) -> Result<(i32, Vec<u8>)> {
|
|
loop {
|
|
if let Some(frame) = frame::split(&mut self.buffer)? {
|
|
let body = frame::decompress(frame, self.threshold)?;
|
|
let mut r = Reader::new(&body);
|
|
let id = r.varint()?;
|
|
let start = r.position();
|
|
self.counters.received.fetch_add(1, Ordering::Relaxed);
|
|
return Ok((id, body[start..].to_vec()));
|
|
}
|
|
let mut chunk = [0u8; 16384];
|
|
let n = self.stream.read(&mut chunk)?;
|
|
if n == 0 {
|
|
return Err(Error::new("Connection closed by the server"));
|
|
}
|
|
self.counters
|
|
.bytes_in
|
|
.fetch_add(n as i64, Ordering::Relaxed);
|
|
let data = &mut chunk[..n];
|
|
if let Some(c) = &mut self.decrypt {
|
|
c.decrypt(data);
|
|
}
|
|
self.buffer.extend_from_slice(data);
|
|
}
|
|
}
|
|
pub fn set_read_timeout(&self, timeout: Option<Duration>) -> Result<()> {
|
|
Ok(self.stream.set_read_timeout(timeout)?)
|
|
}
|
|
}
|
|
impl ConnWriter {
|
|
/// Send one packet body (VarInt id + payload).
|
|
pub fn send(&mut self, body: &[u8]) -> Result<()> {
|
|
let mut framed = frame::encode(body, self.threshold)?;
|
|
if let Some(c) = &mut self.encrypt {
|
|
c.encrypt(&mut framed);
|
|
}
|
|
self.stream.write_all(&framed)?;
|
|
self.counters.sent.fetch_add(1, Ordering::Relaxed);
|
|
self.counters
|
|
.bytes_out
|
|
.fetch_add(framed.len() as i64, Ordering::Relaxed);
|
|
Ok(())
|
|
}
|
|
pub fn shutdown(&self) {
|
|
let _ = self.stream.shutdown(Shutdown::Both);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::net::TcpListener;
|
|
|
|
#[test]
|
|
fn loopback_with_compression_and_encryption() {
|
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
|
let port = listener.local_addr().unwrap().port();
|
|
let server = std::thread::spawn(move || {
|
|
let (stream, _) = listener.accept().unwrap();
|
|
let mut c = Connection::from_stream(stream).unwrap();
|
|
let (id, payload) = c.recv().unwrap();
|
|
assert_eq!((id, payload.as_slice()), (0, &b"plain"[..]));
|
|
c.enable_encryption(&[7; 16]);
|
|
c.set_compression(64);
|
|
let (id, payload) = c.recv().unwrap();
|
|
assert_eq!((id, payload.len()), (5, 1000));
|
|
let mut body = vec![9];
|
|
body.extend_from_slice(b"reply");
|
|
c.send(&body).unwrap();
|
|
});
|
|
let mut c = Connection::connect("127.0.0.1", port, Duration::from_secs(5)).unwrap();
|
|
let mut body = vec![0];
|
|
body.extend_from_slice(b"plain");
|
|
c.send(&body).unwrap();
|
|
c.enable_encryption(&[7; 16]);
|
|
c.set_compression(64);
|
|
let mut big = vec![5];
|
|
big.extend(std::iter::repeat_n(3u8, 1000));
|
|
c.send(&big).unwrap();
|
|
let (id, payload) = c.recv().unwrap();
|
|
assert_eq!((id, payload.as_slice()), (9, &b"reply"[..]));
|
|
server.join().unwrap();
|
|
}
|
|
|
|
/// Encrypted bytes that arrive in the same read as the last plain packet
|
|
/// are decrypted once encryption is enabled.
|
|
#[test]
|
|
fn encrypted_bytes_read_before_enabling_encryption() {
|
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
|
let port = listener.local_addr().unwrap().port();
|
|
let (sent, both_sent) = std::sync::mpsc::channel();
|
|
let client = std::thread::spawn(move || {
|
|
let mut c = Connection::connect("127.0.0.1", port, Duration::from_secs(5)).unwrap();
|
|
c.send(&[0, 1, 2]).unwrap();
|
|
c.enable_encryption(&[7; 16]);
|
|
c.send(&[5, 4, 3]).unwrap();
|
|
sent.send(c).unwrap();
|
|
});
|
|
let (stream, _) = listener.accept().unwrap();
|
|
let mut c = Connection::from_stream(stream).unwrap();
|
|
let _keep_open = both_sent.recv().unwrap();
|
|
assert_eq!(c.recv().unwrap(), (0, vec![1, 2]));
|
|
c.enable_encryption(&[7; 16]);
|
|
assert_eq!(c.recv().unwrap(), (5, vec![4, 3]));
|
|
client.join().unwrap();
|
|
}
|
|
}
|