use std::collections::HashMap;
use std::io::{self, Read, Write};
use std::net::Shutdown;
use std::os::unix::net::UnixStream;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use super::proto::{self, Frame};
const CHUNK: usize = 16 * 1024;
pub const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
pub const KEEPALIVE_TIMEOUT: Duration = Duration::from_secs(45);
fn is_dead(since_last_inbound: Duration, timeout: Duration) -> bool {
since_last_inbound >= timeout
}
const MAX_STREAMS: usize = 64;
const HOST_ID_BIT: u32 = 1 << 31;
pub struct Mux {
out: Mutex<Box<dyn Write + Send>>,
streams: Mutex<HashMap<u32, Arc<UnixStream>>>,
last_inbound: Mutex<Instant>,
ended: AtomicBool,
}
impl Mux {
pub fn new(out: impl Write + Send + 'static) -> Arc<Mux> {
Arc::new(Mux {
out: Mutex::new(Box::new(out)),
streams: Mutex::new(HashMap::new()),
last_inbound: Mutex::new(Instant::now()),
ended: AtomicBool::new(false),
})
}
pub fn keepalive(
self: &Arc<Self>,
interval: Duration,
timeout: Duration,
on_dead: impl FnOnce() + Send + 'static,
) {
let mux = Arc::clone(self);
std::thread::spawn(move || {
let mut on_dead = Some(on_dead);
while !mux.ended.load(Ordering::Relaxed) {
std::thread::sleep(interval);
if mux.ended.load(Ordering::Relaxed) {
return;
}
let idle = mux.last_inbound.lock().unwrap().elapsed();
if is_dead(idle, timeout) {
if let Some(f) = on_dead.take() {
f();
}
return;
}
if let Ok(mut out) = mux.out.try_lock() {
let _ = proto::write_frame(&mut *out, &Frame::Ping(Vec::new()));
}
}
});
}
pub fn send(&self, frame: &Frame) -> io::Result<()> {
proto::write_frame(&mut *self.out.lock().unwrap(), frame)
}
pub fn attach(self: &Arc<Self>, stream: u32, conn: UnixStream, open: Option<u8>) -> io::Result<()> {
let reader = conn.try_clone()?;
self.streams.lock().unwrap().insert(stream, Arc::new(conn));
if let Some(channel) = open {
if let Err(e) = self.send(&Frame::Open { stream, channel }) {
self.streams.lock().unwrap().remove(&stream);
return Err(e);
}
}
let mux = Arc::clone(self);
std::thread::spawn(move || mux.pump(stream, reader));
Ok(())
}
fn pump(&self, stream: u32, mut conn: UnixStream) {
let mut buf = vec![0u8; CHUNK];
loop {
match conn.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
if self.send(&Frame::Data { stream, bytes: buf[..n].to_vec() }).is_err() {
break;
}
}
}
}
if self.drop_stream(stream) {
let _ = self.send(&Frame::Close { stream });
}
}
fn drop_stream(&self, stream: u32) -> bool {
match self.streams.lock().unwrap().remove(&stream) {
Some(conn) => {
let _ = conn.shutdown(Shutdown::Both);
true
}
None => false,
}
}
pub fn serve(
self: &Arc<Self>,
mut reader: impl Read,
on_open: impl Fn(u32, u8) -> Option<UnixStream>,
) {
while let Ok(Some(frame)) = proto::read_frame(&mut reader) {
*self.last_inbound.lock().unwrap() = Instant::now();
match frame {
Frame::Data { stream, bytes } => {
let conn = self.streams.lock().unwrap().get(&stream).cloned();
let failed = match conn {
Some(conn) => (&*conn).write_all(&bytes).is_err(),
None => false,
};
if failed && self.drop_stream(stream) {
let _ = self.send(&Frame::Close { stream });
}
}
Frame::Close { stream } => {
self.drop_stream(stream);
}
Frame::Ping(payload) => {
let _ = self.send(&Frame::Pong(payload));
}
Frame::Open { stream, channel } => {
let attached = {
let live = self.streams.lock().unwrap();
let allowed = stream & HOST_ID_BIT == 0
&& !live.contains_key(&stream)
&& live.len() < MAX_STREAMS;
drop(live);
allowed
&& match on_open(stream, channel) {
Some(conn) => self.attach(stream, conn, None).is_ok(),
None => false,
}
};
if !attached {
let _ = self.send(&Frame::Close { stream });
}
}
Frame::Hello { .. } | Frame::Pong(_) | Frame::Quit => {}
}
}
self.ended.store(true, Ordering::Relaxed);
self.close_all();
}
pub fn close_all(&self) {
for (_, conn) in self.streams.lock().unwrap().drain() {
let _ = conn.shutdown(Shutdown::Both);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use proto::channel;
use std::io::{BufRead, BufReader};
use std::time::Duration;
fn echo_agent(conn: UnixStream) {
std::thread::spawn(move || {
let mut w = conn.try_clone().unwrap();
for line in BufReader::new(conn).lines() {
let Ok(line) = line else { break };
if writeln!(w, "re:{line}").is_err() {
break;
}
}
});
}
fn pair() -> Arc<Mux> {
let (d_r, h_w) = std::io::pipe().unwrap();
let (h_r, d_w) = std::io::pipe().unwrap();
let daemon = Mux::new(d_w);
let host = Mux::new(h_w);
let d = Arc::clone(&daemon);
std::thread::spawn(move || d.serve(d_r, |_, _| None));
std::thread::spawn(move || {
host.serve(h_r, |_, ch| {
(ch == channel::SSH_AGENT).then(|| {
let (ours, agent) = UnixStream::pair().unwrap();
echo_agent(agent);
ours
})
})
});
daemon
}
fn client(daemon: &Arc<Mux>, stream: u32, channel: u8) -> BufReader<UnixStream> {
let (ours, theirs) = UnixStream::pair().unwrap();
daemon.attach(stream, theirs, Some(channel)).unwrap();
ours.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
BufReader::new(ours)
}
#[test]
fn streams_relay_independently() {
let daemon = pair();
let mut a = client(&daemon, 1, channel::SSH_AGENT);
let mut b = client(&daemon, 2, channel::SSH_AGENT);
let roundtrip = |c: &mut BufReader<UnixStream>, msg: &str| {
writeln!(c.get_mut(), "{msg}").unwrap();
let mut line = String::new();
c.read_line(&mut line).unwrap();
assert_eq!(line, format!("re:{msg}\n"));
};
roundtrip(&mut a, "one");
roundtrip(&mut b, "two");
roundtrip(&mut a, "three");
}
#[test]
fn refused_open_closes_the_client() {
let daemon = pair();
let mut c = client(&daemon, 1, channel::HTTP_PROXY);
let mut buf = String::new();
assert_eq!(c.read_line(&mut buf).unwrap(), 0, "EOF after refusal");
assert!(daemon.streams.lock().unwrap().is_empty());
}
#[test]
fn client_close_is_forwarded_and_unregistered() {
let daemon = pair();
let c = client(&daemon, 1, channel::SSH_AGENT);
drop(c);
for _ in 0..100 {
if daemon.streams.lock().unwrap().is_empty() {
return;
}
std::thread::sleep(Duration::from_millis(10));
}
panic!("stream still registered after client closed");
}
#[test]
fn peer_loss_shuts_every_stream() {
let (d_r, h_w) = std::io::pipe().unwrap();
let (_h_r, d_w) = std::io::pipe().unwrap();
let daemon = Mux::new(d_w);
let mut c = client(&daemon, 1, channel::SSH_AGENT);
drop(h_w); daemon.serve(d_r, |_, _| None);
let mut buf = String::new();
assert_eq!(c.read_line(&mut buf).unwrap(), 0);
}
#[derive(Clone)]
struct Sink(Arc<Mutex<Vec<u8>>>);
impl Write for Sink {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
fn refused_opens(opens: &[u32]) -> Vec<u32> {
let mut wire = Vec::new();
for &stream in opens {
proto::write_frame(&mut wire, &Frame::Open { stream, channel: channel::SSH_AGENT }).unwrap();
}
let out = Arc::new(Mutex::new(Vec::new()));
let mux = Mux::new(Sink(Arc::clone(&out)));
let peers = Mutex::new(Vec::new());
mux.serve(io::Cursor::new(wire), |_, _| {
let (ours, theirs) = UnixStream::pair().unwrap();
peers.lock().unwrap().push(theirs);
Some(ours)
});
let mut r = io::Cursor::new(std::mem::take(&mut *out.lock().unwrap()));
let mut closed = Vec::new();
while let Ok(Some(frame)) = proto::read_frame(&mut r) {
if let Frame::Close { stream } = frame {
closed.push(stream);
}
}
closed
}
#[test]
fn is_dead_fires_only_after_the_timeout() {
let timeout = Duration::from_secs(45);
assert!(!is_dead(Duration::from_secs(0), timeout));
assert!(!is_dead(Duration::from_secs(44), timeout));
assert!(is_dead(Duration::from_secs(45), timeout));
assert!(is_dead(Duration::from_secs(90), timeout));
}
#[test]
fn keepalive_calls_on_dead_when_peer_stops_answering() {
let (mux_r, peer_w) = std::io::pipe().unwrap();
let (peer_r, mux_w) = std::io::pipe().unwrap();
let mux = Mux::new(mux_w);
std::thread::spawn(move || {
let mut sink = peer_r;
let mut buf = [0u8; 256];
while let Ok(n) = sink.read(&mut buf) {
if n == 0 {
break;
}
}
});
let (tx, rx) = std::sync::mpsc::channel();
mux.keepalive(Duration::from_millis(5), Duration::from_millis(30), move || {
let _ = tx.send(());
});
let m = Arc::clone(&mux);
std::thread::spawn(move || m.serve(mux_r, |_, _| None));
rx.recv_timeout(Duration::from_secs(2)).expect("on_dead fired");
drop(peer_w);
}
#[test]
fn keepalive_stops_once_serve_returns_without_calling_on_dead() {
let (mux_r, peer_w) = std::io::pipe().unwrap();
let (_peer_r, mux_w) = std::io::pipe().unwrap();
let mux = Mux::new(mux_w);
let fired = Arc::new(AtomicBool::new(false));
let f = Arc::clone(&fired);
mux.keepalive(Duration::from_millis(5), Duration::from_secs(30), move || {
f.store(true, Ordering::Relaxed);
});
drop(peer_w);
mux.serve(mux_r, |_, _| None);
std::thread::sleep(Duration::from_millis(40));
assert!(!fired.load(Ordering::Relaxed), "on_dead must not fire after serve ended");
}
#[test]
fn open_with_high_bit_is_refused() {
assert_eq!(refused_opens(&[HOST_ID_BIT, HOST_ID_BIT | 5]), vec![HOST_ID_BIT, HOST_ID_BIT | 5]);
}
#[test]
fn duplicate_open_id_is_refused() {
assert_eq!(refused_opens(&[1, 1]), vec![1]);
}
#[test]
fn opens_past_the_stream_cap_are_refused() {
let opens: Vec<u32> = (1..=(MAX_STREAMS as u32 + 2)).collect();
let over = vec![MAX_STREAMS as u32 + 1, MAX_STREAMS as u32 + 2];
assert_eq!(refused_opens(&opens), over);
}
}