use std::error::Error;
use std::fmt;
use std::io::{self, Read, Write};
pub const VERSION: u32 = 1;
pub const MISMATCH_EXIT: i32 = 3;
pub const MAX_PAYLOAD: u32 = 1 << 20;
pub mod channel {
pub const SSH_AGENT: u8 = 1;
pub const HTTP_PROXY: u8 = 2;
pub const NOTIFY: u8 = 3;
pub const CONTROL: u8 = 4;
pub const RPC: u8 = 5;
pub const API: u8 = 6;
pub const TRANSFER: u8 = 7;
pub const PTY: u8 = 8;
pub const TUNNEL: u8 = 9;
pub const AGENT: u8 = 10;
pub const ROUTE: u8 = 11;
pub const fn flows(channel: u8) -> bool {
matches!(channel, HTTP_PROXY | RPC | API | TRANSFER | PTY | TUNNEL | AGENT | ROUTE)
}
}
const KIND_HELLO: u8 = 0;
const KIND_OPEN: u8 = 1;
const KIND_DATA: u8 = 2;
const KIND_CLOSE: u8 = 3;
const KIND_PING: u8 = 4;
const KIND_PONG: u8 = 5;
const KIND_QUIT: u8 = 6;
const KIND_CONNECT: u8 = 7;
const KIND_WINDOW: u8 = 8;
const KIND_EOF: u8 = 9;
const KIND_CAPS: u8 = 10;
const KIND_PORT_QUERY: u8 = 11;
const KIND_PORT_INFO: u8 = 12;
const HEADER_LEN: usize = 9;
pub mod caps {
pub const TCP_FORWARD: u32 = 1 << 0;
pub const SSH_AGENT: u32 = 1 << 1;
pub const NOTIFY: u32 = 1 << 2;
pub const CONTROL: u32 = 1 << 3;
pub const PORT_INFO: u32 = 1 << 4;
pub const RPC: u32 = 1 << 5;
#[allow(dead_code)] pub const API: u32 = 1 << 6;
#[allow(dead_code)] pub const TRANSFER: u32 = 1 << 7;
#[allow(dead_code)] pub const PTY: u32 = 1 << 8;
#[allow(dead_code)] pub const TUNNEL: u32 = 1 << 9;
#[allow(dead_code)] pub const AGENT: u32 = 1 << 10;
#[allow(dead_code)] pub const ROUTE: u32 = 1 << 11;
pub const HTTP_PROXY: u32 = 1 << 12;
}
pub const MAX_PROXY_HEADER: usize = 300;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProxyHeader {
BaseUrl { upstream: String, listener: u16 },
Intercept { host: String, port: u16 },
Lfs { listener: u16 },
}
impl ProxyHeader {
pub fn encode(&self) -> Vec<u8> {
let (mode, host, port) = match self {
ProxyHeader::BaseUrl { upstream, listener } => ("base-url", upstream, listener),
ProxyHeader::Intercept { host, port } => ("intercept", host, port),
ProxyHeader::Lfs { listener } => return format!("lfs {listener}\n").into_bytes(),
};
format!("{mode} {host} {port}\n").into_bytes()
}
pub fn parse(line: &[u8]) -> Result<ProxyHeader, String> {
if line.len() > MAX_PROXY_HEADER {
return Err(format!("proxy header longer than {MAX_PROXY_HEADER} bytes"));
}
let text = std::str::from_utf8(line).map_err(|_| "proxy header is not utf-8".to_string())?;
let text = text.strip_suffix('\n').ok_or("proxy header without its newline")?;
let fields: Vec<&str> = text.split(' ').collect();
if let ["lfs", port] = fields[..] {
return parse_port(port).map(|listener| ProxyHeader::Lfs { listener });
}
let [mode, host, port] = fields[..] else {
return Err(format!("proxy header `{text}`: want `<mode> <host> <port>`"));
};
let host_ok = !host.is_empty() && host.len() <= 255 && host.bytes().all(|b| b.is_ascii_graphic());
if !host_ok {
return Err(format!("proxy header host `{host}`"));
}
let port = parse_port(port)?;
let host = host.to_string();
match mode {
"base-url" => Ok(ProxyHeader::BaseUrl { upstream: host, listener: port }),
"intercept" => Ok(ProxyHeader::Intercept { host, port }),
_ => Err(format!("proxy header mode `{mode}`")),
}
}
pub fn read(r: &mut impl Read) -> io::Result<ProxyHeader> {
let mut line = Vec::new();
let mut byte = [0u8; 1];
while line.last() != Some(&b'\n') {
if line.len() == MAX_PROXY_HEADER {
return Err(invalid(&format!("no proxy header in the first {MAX_PROXY_HEADER} bytes")));
}
match r.read(&mut byte) {
Ok(0) => return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "stream ended inside its proxy header")),
Ok(_) => line.push(byte[0]),
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
ProxyHeader::parse(&line).map_err(|e| invalid(&e))
}
}
fn parse_port(port: &str) -> Result<u16, String> {
match port.parse::<u16>() {
Ok(p) if p != 0 && port.bytes().all(|b| b.is_ascii_digit()) && !port.starts_with('0') => Ok(p),
_ => Err(format!("proxy header port `{port}`")),
}
}
pub const MAX_PORT_PROCS: usize = 64;
pub const INITIAL_WINDOW: u32 = 256 * 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Frame {
Hello { version: u32, hash: String, caps: u32 },
Open { stream: u32, channel: u8 },
Data { stream: u32, bytes: Vec<u8> },
Close { stream: u32, reason: String },
Connect { stream: u32, host: String, port: u16 },
Window { stream: u32, credit: u32 },
Eof { stream: u32 },
Caps(u32),
PortQuery { id: u32, port: u16 },
PortInfo { id: u32, procs: Vec<(u32, String)> },
Ping(Vec<u8>),
Pong(Vec<u8>),
Quit,
}
impl Frame {
pub fn encode(&self) -> Vec<u8> {
let (stream, kind, payload): (u32, u8, Vec<u8>) = match self {
Frame::Hello { version, hash, caps } => {
let mut p = version.to_le_bytes().to_vec();
p.push(hash.len() as u8);
p.extend_from_slice(hash.as_bytes());
p.extend_from_slice(&caps.to_le_bytes());
(0, KIND_HELLO, p)
}
Frame::Open { stream, channel } => (*stream, KIND_OPEN, vec![*channel]),
Frame::Data { stream, bytes } => (*stream, KIND_DATA, bytes.clone()),
Frame::Close { stream, reason } => (*stream, KIND_CLOSE, reason.clone().into_bytes()),
Frame::Connect { stream, host, port } => {
let mut p = port.to_le_bytes().to_vec();
p.push(host.len() as u8);
p.extend_from_slice(host.as_bytes());
(*stream, KIND_CONNECT, p)
}
Frame::Window { stream, credit } => (*stream, KIND_WINDOW, credit.to_le_bytes().to_vec()),
Frame::Eof { stream } => (*stream, KIND_EOF, Vec::new()),
Frame::Caps(c) => (0, KIND_CAPS, c.to_le_bytes().to_vec()),
Frame::PortQuery { id, port } => {
let mut p = id.to_le_bytes().to_vec();
p.extend_from_slice(&port.to_le_bytes());
(0, KIND_PORT_QUERY, p)
}
Frame::PortInfo { id, procs } => {
let mut p = id.to_le_bytes().to_vec();
for (pid, comm) in procs.iter().take(MAX_PORT_PROCS) {
let comm = truncate_utf8(comm, u8::MAX as usize);
p.extend_from_slice(&pid.to_le_bytes());
p.push(comm.len() as u8);
p.extend_from_slice(comm.as_bytes());
}
(0, KIND_PORT_INFO, p)
}
Frame::Ping(p) => (0, KIND_PING, p.clone()),
Frame::Pong(p) => (0, KIND_PONG, p.clone()),
Frame::Quit => (0, KIND_QUIT, Vec::new()),
};
let mut out = Vec::with_capacity(HEADER_LEN + payload.len());
out.extend_from_slice(&stream.to_le_bytes());
out.push(kind);
out.extend_from_slice(&(payload.len() as u32).to_le_bytes());
out.extend_from_slice(&payload);
out
}
fn decode(stream: u32, kind: u8, payload: Vec<u8>) -> io::Result<Option<Frame>> {
Ok(Some(match kind {
KIND_HELLO => {
if payload.len() < 4 {
return Err(invalid("short Hello"));
}
let version = u32::from_le_bytes(payload[..4].try_into().unwrap());
if version != VERSION {
return Ok(Some(Frame::Hello { version, hash: String::new(), caps: 0 }));
}
let Some((&hash_len, rest)) = payload[4..].split_first() else {
return Err(invalid("truncated Hello"));
};
let hash_len = hash_len as usize;
if rest.len() < hash_len + 4 {
return Err(invalid("truncated Hello"));
}
let hash = String::from_utf8(rest[..hash_len].to_vec())
.map_err(|_| invalid("Hello hash is not utf-8"))?;
let caps = u32::from_le_bytes(rest[hash_len..hash_len + 4].try_into().unwrap());
Frame::Hello { version, hash, caps }
}
KIND_OPEN => match payload[..] {
[channel] => Frame::Open { stream, channel },
_ => return Err(invalid("Open payload must be one channel byte")),
},
KIND_DATA => Frame::Data { stream, bytes: payload },
KIND_CLOSE => Frame::Close {
stream,
reason: String::from_utf8_lossy(&payload).into_owned(),
},
KIND_CONNECT => {
if payload.len() < 3 {
return Err(invalid("short Connect"));
}
let port = u16::from_le_bytes(payload[..2].try_into().unwrap());
let host_len = payload[2] as usize;
if payload.len() != 3 + host_len {
return Err(invalid("Connect host length mismatch"));
}
let host = String::from_utf8(payload[3..].to_vec())
.map_err(|_| invalid("Connect host is not utf-8"))?;
if host.is_empty() {
return Err(invalid("Connect host is empty"));
}
if port == 0 {
return Err(invalid("Connect port is 0"));
}
Frame::Connect { stream, host, port }
}
KIND_WINDOW => match payload[..].try_into() {
Ok(b) => Frame::Window { stream, credit: u32::from_le_bytes(b) },
Err(_) => return Err(invalid("Window payload must be four bytes")),
},
KIND_EOF => Frame::Eof { stream },
KIND_CAPS => match payload[..].try_into() {
Ok(b) => Frame::Caps(u32::from_le_bytes(b)),
Err(_) => return Err(invalid("Caps payload must be four bytes")),
},
KIND_PORT_QUERY => match payload[..] {
[a, b, c, d, p0, p1] => Frame::PortQuery {
id: u32::from_le_bytes([a, b, c, d]),
port: u16::from_le_bytes([p0, p1]),
},
_ => return Err(invalid("PortQuery payload must be six bytes")),
},
KIND_PORT_INFO => {
let Some((id, mut rest)) = payload.split_first_chunk::<4>() else {
return Err(invalid("short PortInfo"));
};
let mut procs = Vec::new();
while !rest.is_empty() {
let Some((pid, after)) = rest.split_first_chunk::<4>() else {
return Err(invalid("truncated PortInfo"));
};
let Some((&len, after)) = after.split_first() else {
return Err(invalid("truncated PortInfo"));
};
let Some((comm, after)) = after.split_at_checked(len as usize) else {
return Err(invalid("truncated PortInfo"));
};
if procs.len() == MAX_PORT_PROCS {
return Err(invalid("PortInfo lists too many processes"));
}
procs.push((u32::from_le_bytes(*pid), String::from_utf8_lossy(comm).into_owned()));
rest = after;
}
Frame::PortInfo { id: u32::from_le_bytes(*id), procs }
}
KIND_PING => Frame::Ping(payload),
KIND_PONG => Frame::Pong(payload),
KIND_QUIT => Frame::Quit,
_ => return Ok(None),
}))
}
}
fn truncate_utf8(s: &str, max: usize) -> &str {
let mut end = s.len().min(max);
while !s.is_char_boundary(end) {
end -= 1;
}
&s[..end]
}
fn invalid(msg: &str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, msg.to_string())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VersionMismatch {
pub peer: u32,
pub ours: u32,
}
impl fmt::Display for VersionMismatch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "protocol version {} (peer) != {} (ours)", self.peer, self.ours)
}
}
impl Error for VersionMismatch {}
pub fn version_mismatch(e: &io::Error) -> Option<&VersionMismatch> {
e.get_ref()?.downcast_ref::<VersionMismatch>()
}
pub fn write_frame(w: &mut impl Write, frame: &Frame) -> io::Result<()> {
w.write_all(&frame.encode())?;
w.flush()
}
pub fn read_frame(r: &mut impl Read) -> io::Result<Option<Frame>> {
loop {
let mut header = [0u8; HEADER_LEN];
let mut filled = 0;
while filled < HEADER_LEN {
match r.read(&mut header[filled..]) {
Ok(0) if filled == 0 => return Ok(None),
Ok(0) => return Err(io::ErrorKind::UnexpectedEof.into()),
Ok(n) => filled += n,
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
let stream = u32::from_le_bytes(header[0..4].try_into().unwrap());
let kind = header[4];
let len = u32::from_le_bytes(header[5..9].try_into().unwrap());
if len > MAX_PAYLOAD {
return Err(invalid(&format!("frame payload {len} exceeds {MAX_PAYLOAD} bytes")));
}
let mut payload = vec![0u8; len as usize];
r.read_exact(&mut payload)?;
if let Some(frame) = Frame::decode(stream, kind, payload)? {
return Ok(Some(frame));
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Peer {
pub hash: String,
pub caps: u32,
}
pub fn handshake(r: &mut impl Read, w: &mut impl Write, hash: &str, caps: u32) -> io::Result<Peer> {
write_frame(w, &Frame::Hello { version: VERSION, hash: hash.to_string(), caps })?;
match read_frame(r)? {
Some(Frame::Hello { version: VERSION, hash, caps }) => Ok(Peer { hash, caps }),
Some(Frame::Hello { version, .. }) => Err(io::Error::new(
io::ErrorKind::InvalidData,
VersionMismatch { peer: version, ours: VERSION },
)),
Some(other) => Err(invalid(&format!("expected Hello, got {other:?}"))),
None => Err(io::Error::new(io::ErrorKind::UnexpectedEof, "peer closed before Hello")),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
fn all_kinds() -> Vec<Frame> {
vec![
Frame::Hello { version: VERSION, hash: "ab".repeat(32), caps: 0 },
Frame::Open { stream: 7, channel: channel::SSH_AGENT },
Frame::Open { stream: 9, channel: channel::NOTIFY },
Frame::Open { stream: 11, channel: channel::CONTROL },
Frame::Data { stream: 7, bytes: b"\x00\x00\x00\x01\x0b".to_vec() },
Frame::Data { stream: u32::MAX, bytes: Vec::new() },
Frame::Close { stream: 7, reason: String::new() },
Frame::Close { stream: 8, reason: "connection refused".into() },
Frame::Connect { stream: 0x8000_0001, host: "postgres".into(), port: 5432 },
Frame::Window { stream: 7, credit: INITIAL_WINDOW },
Frame::Eof { stream: 7 },
Frame::Caps(caps::TCP_FORWARD | caps::SSH_AGENT | caps::NOTIFY | caps::CONTROL | caps::PORT_INFO),
Frame::PortQuery { id: 1, port: 8080 },
Frame::PortInfo { id: 1, procs: Vec::new() },
Frame::PortInfo { id: u32::MAX, procs: vec![(412, "node".into()), (7, "nginx: worker".into())] },
Frame::Ping(b"t".to_vec()),
Frame::Pong(Vec::new()),
Frame::Quit,
]
}
#[test]
fn frames_roundtrip_back_to_back() {
let mut wire = Vec::new();
for f in all_kinds() {
write_frame(&mut wire, &f).unwrap();
}
let mut r = Cursor::new(wire);
for f in all_kinds() {
assert_eq!(read_frame(&mut r).unwrap(), Some(f));
}
assert_eq!(read_frame(&mut r).unwrap(), None);
}
#[test]
fn header_layout_is_little_endian() {
let wire = Frame::Data { stream: 0x0102_0304, bytes: b"hi".to_vec() }.encode();
assert_eq!(wire, [4, 3, 2, 1, KIND_DATA, 2, 0, 0, 0, b'h', b'i']);
}
#[test]
fn frozen_frames_keep_their_bytes() {
assert_eq!(Frame::Quit.encode(), [0, 0, 0, 0, 6, 0, 0, 0, 0]);
let hello = Frame::Hello { version: 1, hash: "h".into(), caps: 0 }.encode();
assert_eq!(hello[..HEADER_LEN + 4], [0, 0, 0, 0, 0, 10, 0, 0, 0, 1, 0, 0, 0]);
assert_eq!(hello[HEADER_LEN + 4..], [1, b'h', 0, 0, 0, 0]);
}
#[test]
fn connect_byte_layout() {
let wire = Frame::Connect { stream: 0x8000_0002, host: "db".into(), port: 5432 }.encode();
assert_eq!(
wire,
[
0x02, 0x00, 0x00, 0x80, KIND_CONNECT,
5, 0, 0, 0, 0x38, 0x15, 2, b'd', b'b',
]
);
}
#[test]
fn port_query_and_info_byte_layout() {
let q = Frame::PortQuery { id: 2, port: 8080 }.encode();
assert_eq!(q, [0, 0, 0, 0, KIND_PORT_QUERY, 6, 0, 0, 0, 2, 0, 0, 0, 0x90, 0x1f]);
let info = Frame::PortInfo { id: 2, procs: vec![(412, "nc".into())] }.encode();
#[rustfmt::skip]
let want = [
0, 0, 0, 0, KIND_PORT_INFO,
11, 0, 0, 0, 2, 0, 0, 0, 0x9c, 0x01, 0, 0, 2, b'n', b'c', ];
assert_eq!(info, want);
}
#[test]
fn port_info_comm_is_bounded_and_lossy() {
let long = "é".repeat(200); let wire = Frame::PortInfo { id: 1, procs: vec![(1, long)] }.encode();
let Some(Frame::PortInfo { procs, .. }) = read_frame(&mut Cursor::new(wire)).unwrap() else {
panic!("want PortInfo")
};
assert_eq!(procs[0].1, "é".repeat(127));
let wire = vec![0, 0, 0, 0, KIND_PORT_INFO, 10, 0, 0, 0, 1, 0, 0, 0, 5, 0, 0, 0, 1, 0xff];
assert_eq!(
read_frame(&mut Cursor::new(wire)).unwrap(),
Some(Frame::PortInfo { id: 1, procs: vec![(5, "\u{fffd}".into())] })
);
}
#[test]
fn malformed_port_frames_rejected() {
let mut short_query = Frame::PortQuery { id: 1, port: 1 }.encode();
short_query[5] = 5;
short_query.truncate(HEADER_LEN + 5);
let short_info = vec![0, 0, 0, 0, KIND_PORT_INFO, 3, 0, 0, 0, 1, 0, 0];
let truncated = vec![0, 0, 0, 0, KIND_PORT_INFO, 9, 0, 0, 0, 1, 0, 0, 0, 5, 0, 0, 0, 9];
let too_many = {
let procs = vec![(1u32, String::new()); MAX_PORT_PROCS + 1];
let mut p = 1u32.to_le_bytes().to_vec();
for (pid, _) in &procs {
p.extend_from_slice(&pid.to_le_bytes());
p.push(0);
}
let mut w = vec![0, 0, 0, 0, KIND_PORT_INFO];
w.extend_from_slice(&(p.len() as u32).to_le_bytes());
w.extend_from_slice(&p);
w
};
for wire in [short_query, short_info, truncated, too_many] {
let err = read_frame(&mut Cursor::new(wire)).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
}
}
#[test]
fn window_byte_layout() {
let wire = Frame::Window { stream: 7, credit: INITIAL_WINDOW }.encode();
#[rustfmt::skip]
let want = [
7, 0, 0, 0, KIND_WINDOW,
4, 0, 0, 0, 0x00, 0x00, 0x04, 0x00, ];
assert_eq!(wire, want);
}
#[test]
fn close_reason_is_backward_compatible() {
let bare = Frame::Close { stream: 4, reason: String::new() }.encode();
assert_eq!(bare, [4, 0, 0, 0, KIND_CLOSE, 0, 0, 0, 0]);
let with_reason = Frame::Close { stream: 4, reason: "refused".into() }.encode();
assert_eq!(
read_frame(&mut Cursor::new(with_reason)).unwrap(),
Some(Frame::Close { stream: 4, reason: "refused".into() })
);
assert_eq!(
read_frame(&mut Cursor::new(bare)).unwrap(),
Some(Frame::Close { stream: 4, reason: String::new() })
);
}
#[test]
fn close_reason_non_utf8_decodes_lossily() {
let mut wire = vec![4, 0, 0, 0, KIND_CLOSE, 2, 0, 0, 0];
wire.extend_from_slice(&[0xff, 0xfe]);
assert_eq!(
read_frame(&mut Cursor::new(wire)).unwrap(),
Some(Frame::Close { stream: 4, reason: "\u{fffd}\u{fffd}".into() })
);
}
#[test]
fn malformed_connect_and_window_rejected() {
let base = Frame::Connect { stream: 0x8000_0001, host: "db".into(), port: 80 }.encode();
let mut short = base.clone();
short[5..9].copy_from_slice(&2u32.to_le_bytes());
short.truncate(HEADER_LEN + 2);
let empty_host = {
let mut w = vec![0x01, 0x00, 0x00, 0x80, KIND_CONNECT, 3, 0, 0, 0];
w.extend_from_slice(&80u16.to_le_bytes());
w.push(0);
w
};
let bad_utf8 = {
let mut w = vec![0x01, 0x00, 0x00, 0x80, KIND_CONNECT, 4, 0, 0, 0];
w.extend_from_slice(&80u16.to_le_bytes());
w.push(1);
w.push(0xff);
w
};
let mut port_zero = base.clone();
port_zero[HEADER_LEN..HEADER_LEN + 2].copy_from_slice(&0u16.to_le_bytes());
let mut bad_window = Frame::Window { stream: 1, credit: 1 }.encode();
bad_window[5..9].copy_from_slice(&3u32.to_le_bytes());
bad_window.truncate(HEADER_LEN + 3);
for wire in [short, empty_host, bad_utf8, port_zero, bad_window] {
let err = read_frame(&mut Cursor::new(wire)).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
}
}
struct Trickle(Cursor<Vec<u8>>);
impl Read for Trickle {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let n = buf.len().min(1);
self.0.read(&mut buf[..n])
}
}
#[test]
fn short_reads_reassemble() {
let f = Frame::Data { stream: 3, bytes: vec![9; 100] };
let mut r = Trickle(Cursor::new(f.encode()));
assert_eq!(read_frame(&mut r).unwrap(), Some(f));
assert_eq!(read_frame(&mut r).unwrap(), None);
}
#[test]
fn truncated_frames_are_unexpected_eof() {
let wire = Frame::Data { stream: 1, bytes: b"abc".to_vec() }.encode();
for cut in [1, HEADER_LEN - 1, HEADER_LEN, wire.len() - 1] {
let err = read_frame(&mut Cursor::new(&wire[..cut])).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof, "cut at {cut}");
}
}
#[test]
fn rejects_oversized_and_malformed() {
let mut big = Frame::Data { stream: 1, bytes: Vec::new() }.encode();
big[5..9].copy_from_slice(&(MAX_PAYLOAD + 1).to_le_bytes());
let mut open = Frame::Open { stream: 1, channel: 1 }.encode();
open[5] = 2;
open.push(0);
let banner = b"Welcome to Ubuntu 24.04 LTS\n".to_vec();
let mut bare_hello = vec![0, 0, 0, 0, KIND_HELLO, 4, 0, 0, 0];
bare_hello.extend_from_slice(&VERSION.to_le_bytes());
for wire in [big, open, banner, bare_hello] {
let err = read_frame(&mut Cursor::new(wire)).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
}
}
#[test]
fn unknown_kinds_are_skipped_mid_stream() {
let mut unknown = Frame::Data { stream: 9, bytes: b"future".to_vec() }.encode();
unknown[4] = 99; let mut wire = Frame::Ping(b"a".to_vec()).encode();
wire.extend_from_slice(&unknown);
wire.extend_from_slice(&Frame::Pong(b"b".to_vec()).encode());
let mut r = Cursor::new(wire);
assert_eq!(read_frame(&mut r).unwrap(), Some(Frame::Ping(b"a".to_vec())));
assert_eq!(read_frame(&mut r).unwrap(), Some(Frame::Pong(b"b".to_vec())));
assert_eq!(read_frame(&mut r).unwrap(), None);
assert_eq!(read_frame(&mut Cursor::new(unknown)).unwrap(), None);
}
#[test]
fn hello_ignores_trailing_bytes() {
let mut wire = Frame::Hello { version: VERSION, hash: "h".into(), caps: 3 }.encode();
let extra = b"future-field";
let new_len = (wire.len() - HEADER_LEN + extra.len()) as u32;
wire[5..9].copy_from_slice(&new_len.to_le_bytes());
wire.extend_from_slice(extra);
assert_eq!(
read_frame(&mut Cursor::new(wire)).unwrap(),
Some(Frame::Hello { version: VERSION, hash: "h".into(), caps: 3 })
);
}
#[test]
fn mismatch_hello_decodes_version_over_garbage() {
let mut payload = (VERSION + 7).to_le_bytes().to_vec();
payload.extend_from_slice(&[0xff, 0xfe, 0x00]); let mut wire = Vec::new();
wire.extend_from_slice(&0u32.to_le_bytes());
wire.push(KIND_HELLO);
wire.extend_from_slice(&(payload.len() as u32).to_le_bytes());
wire.extend_from_slice(&payload);
assert_eq!(
read_frame(&mut Cursor::new(wire)).unwrap(),
Some(Frame::Hello { version: VERSION + 7, hash: String::new(), caps: 0 })
);
}
#[test]
fn version_mismatch_is_a_downcastable_typed_error() {
let mut stale = Vec::new();
write_frame(&mut stale, &Frame::Hello { version: VERSION + 1, hash: String::new(), caps: 0 }).unwrap();
let err = handshake(&mut Cursor::new(stale), &mut Vec::new(), "", 0).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
let vm = version_mismatch(&err).expect("typed VersionMismatch");
assert_eq!(*vm, VersionMismatch { peer: VERSION + 1, ours: VERSION });
assert!(version_mismatch(&invalid("nope")).is_none());
}
#[test]
fn handshake_returns_peer_hash_and_caps() {
let mut peer = Vec::new();
write_frame(
&mut peer,
&Frame::Hello { version: VERSION, hash: "peer".into(), caps: caps::TCP_FORWARD },
)
.unwrap();
let mut sent = Vec::new();
let got = handshake(&mut Cursor::new(peer), &mut sent, "mine", caps::SSH_AGENT).unwrap();
assert_eq!(got, Peer { hash: "peer".into(), caps: caps::TCP_FORWARD });
assert_eq!(
read_frame(&mut Cursor::new(sent)).unwrap(),
Some(Frame::Hello { version: VERSION, hash: "mine".into(), caps: caps::SSH_AGENT })
);
}
#[test]
fn handshake_rejects_version_mismatch_and_non_hello() {
let mut stale = Vec::new();
write_frame(&mut stale, &Frame::Hello { version: VERSION + 1, hash: String::new(), caps: 0 }).unwrap();
let err = handshake(&mut Cursor::new(stale), &mut Vec::new(), "", 0).unwrap_err();
assert!(version_mismatch(&err).is_some(), "{err}");
let mut ping = Vec::new();
write_frame(&mut ping, &Frame::Ping(Vec::new())).unwrap();
assert!(handshake(&mut Cursor::new(ping), &mut Vec::new(), "", 0).is_err());
let err = handshake(&mut Cursor::new(Vec::new()), &mut Vec::new(), "", 0).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
}
#[cfg(unix)]
#[test]
fn handshake_and_stream_over_pipes() {
let (mut a_r, mut b_w) = std::io::pipe().unwrap();
let (mut b_r, mut a_w) = std::io::pipe().unwrap();
let helper = std::thread::spawn(move || {
handshake(&mut b_r, &mut b_w, "helper", 0).unwrap();
let Some(Frame::Ping(p)) = read_frame(&mut b_r).unwrap() else { panic!("want Ping") };
write_frame(&mut b_w, &Frame::Pong(p)).unwrap();
write_frame(&mut b_w, &Frame::Open { stream: 1, channel: channel::SSH_AGENT }).unwrap();
write_frame(&mut b_w, &Frame::Data { stream: 1, bytes: b"req".to_vec() }).unwrap();
write_frame(&mut b_w, &Frame::Close { stream: 1, reason: String::new() }).unwrap();
});
assert_eq!(handshake(&mut a_r, &mut a_w, "host", 0).unwrap().hash, "helper");
write_frame(&mut a_w, &Frame::Ping(b"1".to_vec())).unwrap();
assert_eq!(read_frame(&mut a_r).unwrap(), Some(Frame::Pong(b"1".to_vec())));
assert_eq!(read_frame(&mut a_r).unwrap(), Some(Frame::Open { stream: 1, channel: 1 }));
assert_eq!(read_frame(&mut a_r).unwrap(), Some(Frame::Data { stream: 1, bytes: b"req".to_vec() }));
assert_eq!(read_frame(&mut a_r).unwrap(), Some(Frame::Close { stream: 1, reason: String::new() }));
helper.join().unwrap();
assert_eq!(read_frame(&mut a_r).unwrap(), None);
}
#[test]
fn proxy_header_round_trips() {
let base = ProxyHeader::BaseUrl { upstream: "sentry.io".into(), listener: 41001 };
assert_eq!(base.encode(), b"base-url sentry.io 41001\n");
let intercept = ProxyHeader::Intercept { host: "[::1]".into(), port: 443 };
assert_eq!(intercept.encode(), b"intercept [::1] 443\n");
let lfs = ProxyHeader::Lfs { listener: 29005 };
assert_eq!(lfs.encode(), b"lfs 29005\n");
for h in [base, intercept, lfs] {
assert_eq!(ProxyHeader::parse(&h.encode()), Ok(h.clone()));
let mut wire = Cursor::new([h.encode(), b"GET / HTTP/1.1\r\n".to_vec()].concat());
assert_eq!(ProxyHeader::read(&mut wire).unwrap(), h);
assert_eq!(&wire.get_ref()[wire.position() as usize..], b"GET / HTTP/1.1\r\n");
}
}
#[test]
fn proxy_header_parse_is_strict() {
for bad in [
&b"base-url sentry.io 41001"[..],
b"base-url sentry.io 41001\r\n",
b"base-url sentry.io 41001\n",
b"base-url sentry.io\n",
b"base-url sentry.io 41001 x\n",
b"socks sentry.io 41001\n",
b"base-url sentry.io 0\n",
b"base-url sentry.io 041001\n",
b"base-url sentry.io +4100\n",
b"base-url sentry.io 70000\n",
b"base-url sentr\x01y.io 1\n",
b"base-url \xff 1\n",
b"base-url sentry.io 1\nextra",
b"lfs\n",
b"lfs 0\n",
b"lfs 029005\n",
b"lfs 29005 x\n",
b"lfs 29005\n",
b"lfs x 29005\n",
b"LFS 29005\n",
] {
assert!(ProxyHeader::parse(bad).is_err(), "{:?}", String::from_utf8_lossy(bad));
}
let long = format!("base-url {} 1\n", "a".repeat(MAX_PROXY_HEADER));
assert!(ProxyHeader::parse(long.as_bytes()).is_err());
assert!(ProxyHeader::read(&mut Cursor::new(long.into_bytes())).unwrap_err().to_string().contains("first"));
let cut = ProxyHeader::read(&mut Cursor::new(b"base-url sentry.io".to_vec())).unwrap_err();
assert_eq!(cut.kind(), io::ErrorKind::UnexpectedEof);
}
}