use std::fmt;
use std::io::{self, Read, Write};
use std::os::unix::net::UnixStream;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use super::ssh::{self, SkipError};
use crate::devsbd::mux::{self, Mux};
use crate::devsbd::proto::{self, caps, channel};
pub const SENTINEL: &str = "devsandbox-agent";
pub const SENTINEL_VERSION: u32 = 1;
const SENTINEL_LIMIT: usize = 64 * 1024;
pub const HELLO_HASH: &str = env!("CARGO_PKG_VERSION");
pub fn write_sentinel(out: &mut impl Write) -> io::Result<()> {
write!(out, "\n{SENTINEL} {SENTINEL_VERSION}\n")?;
out.flush()
}
fn sentinel(line: &[u8]) -> Result<Option<()>, String> {
let line = String::from_utf8_lossy(line);
let Some(version) = line.trim_end_matches('\r').strip_prefix(SENTINEL).and_then(|r| r.strip_prefix(' ')) else {
return Ok(None);
};
if version != SENTINEL_VERSION.to_string() {
return Err(format!(
"the agent relay there speaks `{SENTINEL} {version}`, this devsandbox {SENTINEL_VERSION}: update devsandbox on the older side"
));
}
Ok(Some(()))
}
#[derive(Debug)]
pub enum End {
Handshake(String),
Dead,
Closed,
}
impl fmt::Display for End {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
End::Handshake(why) => write!(f, "agent relay handshake failed: {why}"),
End::Dead => write!(f, "agent relay silent for {}s", mux::KEEPALIVE_TIMEOUT.as_secs()),
End::Closed => write!(f, "agent relay closed"),
}
}
}
pub fn serve(
mut reader: impl Read,
mut writer: impl Write + Send + 'static,
allowed: impl Fn() -> bool,
agent: impl Fn() -> Option<PathBuf>,
on_ready: impl FnOnce(),
on_dead: impl FnOnce() + Send + 'static,
) -> End {
let mut noise = None;
match ssh::skip_lines(&mut reader, SENTINEL_LIMIT, &mut noise, sentinel) {
Ok(()) => {}
Err(e) => {
let why = match e {
SkipError::Eof => "closed before its first line".to_string(),
SkipError::TooLong => format!("no `{SENTINEL}` line in the first {SENTINEL_LIMIT} bytes"),
SkipError::Io(e) => e.to_string(),
SkipError::Refused(why) => why,
};
return End::Handshake(match noise {
Some(printed) => format!("{why}; the login shell printed: {printed}"),
None => why,
});
}
}
if let Err(e) = proto::handshake(&mut reader, &mut writer, HELLO_HASH, caps::SSH_AGENT) {
return End::Handshake(e.to_string());
}
on_ready();
let mux = Mux::new(writer);
let dead = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&dead);
mux.keepalive(mux::KEEPALIVE_INTERVAL, mux::KEEPALIVE_TIMEOUT, move || {
flag.store(true, Ordering::Relaxed);
on_dead();
});
mux.serve(reader, |_, ch| {
if ch != channel::SSH_AGENT || !allowed() {
return None;
}
UnixStream::connect(agent()?).ok().map(Into::into)
});
if dead.load(Ordering::Relaxed) { End::Dead } else { End::Closed }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_sentinel_matcher_takes_only_our_line() {
assert_eq!(sentinel(b"devsandbox-agent 1"), Ok(Some(())));
assert_eq!(sentinel(b"devsandbox-agent 1\r"), Ok(Some(())));
assert_eq!(sentinel(b"welcome to box"), Ok(None));
assert_eq!(sentinel(b"devsandbox-api 1"), Ok(None));
assert!(sentinel(b"devsandbox-agent 2").unwrap_err().contains("update devsandbox"));
}
#[test]
fn noise_before_the_sentinel_is_skipped_and_none_is_a_handshake_failure() {
let mut wire = b"motd line\nno newline".to_vec();
write_sentinel(&mut wire).unwrap();
let mut r = &wire[..];
let mut noise = None;
assert!(ssh::skip_lines(&mut r, SENTINEL_LIMIT, &mut noise, sentinel).is_ok());
assert!(r.is_empty(), "nothing past the sentinel consumed");
assert_eq!(noise.as_deref(), Some("motd line"));
let end = serve(&b"just a motd\n"[..], Vec::new(), || true, || None, || {}, || {});
let End::Handshake(why) = end else { panic!("{end:?}") };
assert!(why.contains("closed before") && why.contains("just a motd"), "{why}");
}
}