Files
horizon-airdef/crates/horizon-protocol/src/connection.rs
T
Ludovic Marie fa21ea7688 Add horizon-protocol: the 26.3 network protocol (version 777)
Primitive codecs (VarInt/VarLong, strings, positions, LpVec3, BitSets),
VarInt21 framing, zlib threshold compression, AES/CFB8 encryption, MD5
offline UUIDs, network NBT via horizon-world, item stacks with data
component patches, chunk and light payloads with paletted containers,
synched entity data, and typed packets for every connection state in both
directions with round-trip tests. Packet ids are generated from the data
generator's packets report. The probe example logs into a vanilla 26.3
server and decoded ~8000 packets (329 chunks) without errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 15:13:51 +02:00

184 lines
6.2 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]) {
self.reader.decrypt = Some(Cfb8::new(secret, secret));
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();
}
}