use std::io::{self, Read, Write};
use std::net::Shutdown;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::{mpsc, Arc, Mutex};
use std::time::Duration;
use anyhow::{bail, Context, Result};
use crate::devsbd::mux::{self, Conn, Mux};
use crate::devsbd::proto::{self, caps, channel};
use crate::serve::machines::ssh::{self, SkipError};
use super::proof::{self, Auth, Proven, Side};
#[cfg(test)]
use super::transfer::Receivers;
#[derive(Debug, Clone, Copy)]
pub struct Spec {
pub name: &'static str,
pub serves: &'static str,
pub sentinel: &'static str,
pub sentinel_version: u32,
pub channel: u8,
pub hello: &'static str,
}
pub const fn cap_of(channel: u8) -> Option<u32> {
match channel {
channel::SSH_AGENT => Some(caps::SSH_AGENT),
channel::API => Some(caps::API),
channel::TRANSFER => Some(caps::TRANSFER),
channel::PTY => Some(caps::PTY),
channel::TUNNEL => Some(caps::TUNNEL),
channel::AGENT => Some(caps::AGENT),
channel::ROUTE => Some(caps::ROUTE),
_ => None,
}
}
fn advertised(caps: u32, channel: u8) -> bool {
cap_of(channel).is_some_and(|cap| caps & cap != 0)
}
pub type Handler<'a> = Box<dyn Fn() -> Option<Conn> + Send + Sync + 'a>;
#[derive(Default)]
pub struct Serves<'a> {
table: Vec<(u8, Handler<'a>)>,
}
impl<'a> Serves<'a> {
pub fn with(mut self, channel: u8, handler: impl Fn() -> Option<Conn> + Send + Sync + 'a) -> Self {
assert!(cap_of(channel).is_some(), "channel {channel} isn't a link channel");
self.table.retain(|(c, _)| *c != channel);
self.table.push((channel, Box::new(handler)));
self
}
#[cfg(test)]
pub fn transfers(self, receivers: Arc<Receivers>) -> Self {
self.with(channel::TRANSFER, move || receivers.accept())
}
fn caps(&self) -> u32 {
self.table.iter().filter_map(|(c, _)| cap_of(*c)).fold(0, |all, cap| all | cap)
}
fn answer(&self, channel: u8) -> Option<Conn> {
self.table.iter().find(|(c, _)| *c == channel).and_then(|(_, open)| open())
}
}
#[derive(Default)]
pub struct Endpoint<'a, 's> {
pub socket: Option<&'a Path>,
pub serves: Serves<'s>,
pub outlet: Option<&'a Outlet>,
pub auth: Option<Auth>,
}
pub struct Ready<'p> {
pub peer: &'p proto::Peer,
pub proven: Option<Proven>,
}
impl std::ops::Deref for Ready<'_> {
type Target = proto::Peer;
fn deref(&self) -> &proto::Peer {
self.peer
}
}
fn prove(side: Side, auth: Option<&Auth>, r: &mut impl Read, w: &mut impl Write, ours: (&str, u32), peer: &proto::Peer) -> Result<Option<Proven>> {
auth.map(|auth| proof::prove(side, r, w, auth, ours, (&peer.hash, peer.caps))).transpose()
}
pub const SENTINEL_LIMIT: usize = 64 * 1024;
const POLL: Duration = Duration::from_millis(200);
const CHANNEL_WAIT: Duration = Duration::from_secs(10);
pub fn connect(socket: &Path, channel: u8) -> io::Result<UnixStream> {
let mut stream = UnixStream::connect(socket)?;
stream.write_all(&[channel])?;
Ok(stream)
}
pub fn write_sentinel(spec: &Spec, out: &mut impl Write) -> io::Result<()> {
write!(out, "\n{} {}\n", spec.sentinel, spec.sentinel_version)?;
out.flush()
}
pub fn match_sentinel(spec: &Spec, line: &[u8]) -> Result<Option<()>, String> {
let line = String::from_utf8_lossy(line);
let Some(version) = line.trim_end_matches('\r').strip_prefix(spec.sentinel).and_then(|r| r.strip_prefix(' ')) else {
return Ok(None);
};
if version != spec.sentinel_version.to_string() {
return Err(format!(
"the {} there speaks `{} {version}`, this devsandbox {}: update devsandbox on the older side",
spec.name, spec.sentinel, spec.sentinel_version
));
}
Ok(Some(()))
}
enum Ending {
Closed,
Dead,
Write,
Accept(io::Error),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Role {
Opener,
Answerer,
}
struct Out {
mux: Arc<Mux>,
role: Role,
theirs: u32,
next: Mutex<u32>,
}
impl Out {
fn next_id(&self) -> u32 {
next_stream_id(&mut self.next.lock().unwrap())
}
fn open(&self, channel: u8) -> Result<Conn> {
if !advertised(self.theirs, channel) {
bail!("the peer serves no channel {channel}");
}
let opened = match self.role {
Role::Answerer => self.mux.open_host(channel, |_| {}).map(|(_, conn)| conn),
Role::Opener if !channel::flows(channel) => {
Err(io::Error::new(io::ErrorKind::InvalidInput, format!("channel {channel} is not a flowing channel")))
}
Role::Opener => UnixStream::pair().and_then(|(ours, theirs)| {
self.mux.attach(self.next_id(), ours, Some(channel))?;
Ok(theirs.into())
}),
};
opened.with_context(|| format!("cannot open a channel {channel} stream"))
}
fn relay(&self, channel: u8, conn: UnixStream) {
if !advertised(self.theirs, channel) {
return;
}
match self.role {
Role::Opener => {
let _ = self.mux.attach(self.next_id(), conn, Some(channel));
}
Role::Answerer => {
if let Ok(stream) = self.open(channel) {
splice(conn, stream);
}
}
}
}
}
#[derive(Default)]
pub struct Outlet {
up: Mutex<Option<Arc<Out>>>,
end: Mutex<Option<mpsc::Sender<Ending>>>,
}
impl Outlet {
pub fn open(&self, channel: u8) -> Result<Conn> {
let out = self.up.lock().unwrap().clone().context("no link is up")?;
out.open(channel)
}
pub fn is_up(&self) -> bool {
self.up.lock().unwrap().is_some()
}
pub fn hang_up(&self) {
if let Some(end) = self.end.lock().unwrap().as_ref() {
let _ = end.send(Ending::Closed);
}
}
fn set(&self, up: Option<(Arc<Out>, mpsc::Sender<Ending>)>) {
let (up, end) = up.unzip();
*self.up.lock().unwrap() = up;
*self.end.lock().unwrap() = end;
}
}
#[cfg(test)]
pub fn opener(
spec: &Spec,
reader: impl Read + Send + 'static,
writer: impl Write + Send + 'static,
socket: &Path,
on_ready: impl FnOnce(&Ready) -> Result<()>,
) -> Result<()> {
opener_with(spec, reader, writer, Endpoint { socket: Some(socket), ..Endpoint::default() }, on_ready)
}
pub fn opener_with(
spec: &Spec,
mut reader: impl Read + Send + 'static,
writer: impl Write + Send + 'static,
endpoint: Endpoint<'_, 'static>,
on_ready: impl FnOnce(&Ready) -> Result<()>,
) -> Result<()> {
let bound = endpoint.socket.map(Socket::bind).transpose()?;
let (tx, ended) = mpsc::channel();
let mut writer = Reporting { inner: writer, failed: tx.clone() };
write_sentinel(spec, &mut writer).context("cannot write to stdout")?;
let peer = proto::handshake(&mut reader, &mut writer, spec.hello, endpoint.serves.caps())
.with_context(|| format!("{} handshake failed", spec.name))?;
if !advertised(peer.caps, spec.channel) {
bail!("the peer serves no {}", spec.serves);
}
let proven = prove(Side::Opener, endpoint.auth.as_ref(), &mut reader, &mut writer, (spec.hello, endpoint.serves.caps()), &peer)?;
on_ready(&Ready { peer: &peer, proven })?;
let mux = Mux::new(writer);
let serves = Arc::new(endpoint.serves);
mux.on_host_open(Arc::new(move |_, ch| serves.answer(ch)));
let reading = Arc::clone(&mux);
let read = move |done: mpsc::Sender<Ending>| {
std::thread::spawn(move || {
reading.serve(reader, |_, _| None);
let _ = done.send(Ending::Closed);
});
};
let (end, _) = run(&mux, Role::Opener, peer.caps, bound, endpoint.outlet, (tx, ended), || {}, read);
match end {
Ending::Closed | Ending::Write => Ok(()),
Ending::Dead => bail!("no frame from the peer for {}s", mux::KEEPALIVE_TIMEOUT.as_secs()),
Ending::Accept(e) => Err(e).with_context(|| format!("{} socket", spec.name)),
}
}
#[derive(Debug)]
pub enum End {
Handshake(String),
Refused(String),
Dead,
Closed,
}
#[cfg(test)]
pub fn answerer(
spec: &Spec,
reader: impl Read,
writer: impl Write + Send + 'static,
open: impl Fn() -> Option<Conn> + Send + Sync,
on_ready: impl FnOnce(),
on_dead: impl FnOnce() + Send + 'static,
) -> End {
answerer_with(
spec,
reader,
writer,
Endpoint { serves: Serves::default().with(spec.channel, open), ..Endpoint::default() },
|_| {
on_ready();
Ok(())
},
on_dead,
)
}
pub fn answerer_with(
spec: &Spec,
mut reader: impl Read,
writer: impl Write + Send + 'static,
endpoint: Endpoint<'_, '_>,
on_ready: impl FnOnce(&Ready) -> Result<(), String>,
on_dead: impl FnOnce() + Send + 'static,
) -> End {
let mut noise = None;
if let Err(e) = ssh::skip_lines(&mut reader, SENTINEL_LIMIT, &mut noise, |l: &[u8]| match_sentinel(spec, l)) {
let why = match e {
SkipError::Eof => "closed before its first line".to_string(),
SkipError::TooLong => format!("no `{}` line in the first {SENTINEL_LIMIT} bytes", spec.sentinel),
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,
});
}
let bound = match endpoint.socket.map(Socket::bind).transpose() {
Ok(bound) => bound,
Err(e) => return End::Handshake(format!("{e:#}")),
};
let (tx, ended) = mpsc::channel();
let mut writer = Reporting { inner: writer, failed: tx.clone() };
let peer = match proto::handshake(&mut reader, &mut writer, spec.hello, endpoint.serves.caps()) {
Ok(peer) => peer,
Err(e) => return End::Handshake(e.to_string()),
};
let proven = match prove(Side::Answerer, endpoint.auth.as_ref(), &mut reader, &mut writer, (spec.hello, endpoint.serves.caps()), &peer) {
Ok(proven) => proven,
Err(e) => return End::Refused(format!("{e:#}")),
};
if let Err(why) = on_ready(&Ready { peer: &peer, proven }) {
return End::Refused(why);
}
let mux = Mux::new(writer);
let serves = &endpoint.serves;
let read = |done: mpsc::Sender<Ending>| {
mux.serve(reader, |_, ch| serves.answer(ch));
let _ = done.send(Ending::Closed);
};
let (_, dead) = run(&mux, Role::Answerer, peer.caps, bound, endpoint.outlet, (tx, ended), on_dead, read);
if dead { End::Dead } else { End::Closed }
}
#[allow(clippy::too_many_arguments)]
fn run(
mux: &Arc<Mux>,
role: Role,
theirs: u32,
bound: Option<Socket>,
outlet: Option<&Outlet>,
(tx, ended): (mpsc::Sender<Ending>, mpsc::Receiver<Ending>),
on_dead: impl FnOnce() + Send + 'static,
read: impl FnOnce(mpsc::Sender<Ending>),
) -> (Ending, bool) {
let out = Arc::new(Out { mux: Arc::clone(mux), role, theirs, next: Mutex::new(1) });
if let Some(outlet) = outlet {
outlet.set(Some((Arc::clone(&out), tx.clone())));
}
let dead = Arc::new(AtomicBool::new(false));
{
let (flag, tx) = (Arc::clone(&dead), tx.clone());
mux.keepalive(mux::KEEPALIVE_INTERVAL, mux::KEEPALIVE_TIMEOUT, move || {
flag.store(true, Ordering::Relaxed);
let _ = tx.send(Ending::Dead);
on_dead();
});
}
let stop = AtomicBool::new(false);
let first = std::thread::scope(|s| {
if let Some(bound) = bound {
let (out, stop, tx) = (&out, &stop, tx.clone());
s.spawn(move || {
if let Err(e) = accept(bound, out, stop) {
let _ = tx.send(Ending::Accept(e));
}
});
}
read(tx);
let first = ended.recv().unwrap_or(Ending::Closed);
stop.store(true, Ordering::Relaxed);
first
});
if let Some(outlet) = outlet {
outlet.set(None);
}
mux.close_all();
(first, dead.load(Ordering::Relaxed))
}
fn accept(bound: Socket, out: &Arc<Out>, stop: &AtomicBool) -> io::Result<()> {
while !stop.load(Ordering::Relaxed) {
if let Some((_, conn)) = crate::serve::endpoint::accept_any(&[&bound.listener], POLL)? {
let out = Arc::clone(out);
let _ = std::thread::Builder::new().name("link-accept".into()).spawn(move || {
if let Some(channel) = read_channel(&conn) {
out.relay(channel, conn);
}
});
}
}
Ok(())
}
pub(crate) fn read_channel(conn: &UnixStream) -> Option<u8> {
conn.set_read_timeout(Some(CHANNEL_WAIT)).ok()?;
let mut byte = [0u8; 1];
(&*conn).read_exact(&mut byte).ok()?;
conn.set_read_timeout(None).ok()?;
Some(byte[0])
}
pub(crate) fn splice(client: UnixStream, stream: Conn) {
let (Ok(client2), Ok(stream2)) = (client.try_clone(), stream.try_clone()) else { return };
let up = move || {
let _ = io::copy(&mut &client, &mut &stream);
let _ = stream.shutdown(Shutdown::Write);
};
let down = move || {
let _ = io::copy(&mut &stream2, &mut &client2);
let _ = client2.shutdown(Shutdown::Write);
};
let _ = std::thread::Builder::new().name("link-splice-up".into()).spawn(up);
let _ = std::thread::Builder::new().name("link-splice-down".into()).spawn(down);
}
fn next_stream_id(next: &mut u32) -> u32 {
let id = *next;
*next = if id >= (1 << 31) - 1 { 1 } else { id + 1 };
id
}
struct Reporting<W> {
inner: W,
failed: mpsc::Sender<Ending>,
}
impl<W> Reporting<W> {
fn check<T>(&self, r: io::Result<T>) -> io::Result<T> {
if r.is_err() {
let _ = self.failed.send(Ending::Write);
}
r
}
}
impl<W: Write> Write for Reporting<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let r = self.inner.write(buf);
self.check(r)
}
fn flush(&mut self) -> io::Result<()> {
let r = self.inner.flush();
self.check(r)
}
}
pub(crate) struct Socket {
pub(crate) listener: UnixListener,
path: PathBuf,
id: (u64, u64),
}
impl Socket {
pub(crate) fn bind(path: &Path) -> Result<Socket> {
static SEQ: AtomicU32 = AtomicU32::new(0);
let dir = path.parent().unwrap_or(Path::new("."));
let tmp = dir.join(format!(".link-{}-{}.tmp", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed)));
let _ = std::fs::remove_file(&tmp);
let listener = UnixListener::bind(&tmp).with_context(|| format!("cannot bind {}", tmp.display()))?;
let placed = (|| {
std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600))?;
let meta = std::fs::symlink_metadata(&tmp)?;
listener.set_nonblocking(true)?;
std::fs::rename(&tmp, path)?;
Ok::<_, io::Error>((meta.dev(), meta.ino()))
})();
match placed {
Ok(id) => Ok(Socket { listener, path: path.to_path_buf(), id }),
Err(e) => {
let _ = std::fs::remove_file(&tmp);
Err(e).with_context(|| format!("cannot set up {}", path.display()))
}
}
}
}
impl Drop for Socket {
fn drop(&mut self) {
let ours = std::fs::symlink_metadata(&self.path).is_ok_and(|m| (m.dev(), m.ino()) == self.id);
if ours {
let _ = std::fs::remove_file(&self.path);
}
}
}
#[cfg(test)]
mod tests {
use std::io::{Read, Write};
use std::os::unix::net::UnixStream;
use std::time::Instant;
use serde_json::Value;
use super::*;
use crate::devsbd::proto::{caps, channel, Frame};
use crate::serve::client::{self, Hello};
use crate::serve::daemon::Exit;
use crate::serve::daemon::tests::{opts, scratch, spawn_daemon};
use crate::serve::endpoint;
use crate::serve::fleet::LINK;
use crate::serve::proto::Version;
fn wait_for(mut cond: impl FnMut() -> bool, what: &str) {
let start = Instant::now();
while !cond() {
assert!(start.elapsed() < Duration::from_secs(5), "timed out waiting: {what}");
std::thread::sleep(Duration::from_millis(20));
}
}
fn link(socket: &Path, open: impl Fn() -> Option<Conn> + Send + Sync + 'static) {
let (a_r, o_w) = std::io::pipe().unwrap();
let (o_r, a_w) = std::io::pipe().unwrap();
let path = socket.to_path_buf();
std::thread::spawn(move || opener(&LINK, o_r, o_w, &path, |_| Ok(())));
std::thread::spawn(move || answerer(&LINK, a_r, a_w, open, || {}, || {}));
wait_for(|| UnixStream::connect(socket).is_ok(), "the opener's socket accepts");
}
#[test]
fn a_conn_through_the_link_reaches_the_daemon() {
let dir = scratch("fleet-link");
std::fs::create_dir_all(&dir).unwrap();
let daemon = spawn_daemon(&dir, opts(1, 1000));
let socket = dir.join("fleet-w.sock");
let daemon_dir = dir.clone();
link(&socket, move || endpoint::connect(&daemon_dir).ok().map(Into::into));
let mode = std::fs::metadata(&socket).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
let (stream, hello) = {
let deadline = Instant::now() + Duration::from_secs(5);
loop {
let mut stream = dial(&socket, channel::API);
match client::hello(&mut stream, &Version { semver: "0.0.0".into(), build: 0 }, "test") {
Ok(Hello::Ready(reply)) => break (stream, reply),
other => assert!(Instant::now() < deadline, "no hello through the link: {other:?}"),
}
std::thread::sleep(Duration::from_millis(20));
}
};
assert_eq!((hello.version.as_str(), hello.protocol), ("0.6.0", crate::serve::proto::PROTOCOL));
stream.set_read_timeout(None).unwrap();
let mut conn = client::Conn::new(stream, hello).unwrap();
let r = conn.call("nope", Value::Null).unwrap();
assert_eq!(r.error.unwrap().code, "unknown-method");
drop(conn);
assert_eq!(daemon.join().unwrap().unwrap(), Exit::Idle);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_answerer_refuses_other_channels() {
let (a_r, mut o_w) = std::io::pipe().unwrap();
let (mut o_r, a_w) = std::io::pipe().unwrap();
let (ours, theirs) = UnixStream::pair().unwrap();
let theirs = std::sync::Mutex::new(Some(theirs));
std::thread::spawn(move || {
answerer(&LINK, a_r, a_w, move || theirs.lock().unwrap().take().map(Into::into), || {}, || {})
});
write_sentinel(&LINK, &mut o_w).unwrap();
let peer = proto::handshake(&mut o_r, &mut o_w, "test", 0).unwrap();
assert_eq!(peer.caps, caps::API);
for ch in [channel::SSH_AGENT, channel::RPC] {
proto::write_frame(&mut o_w, &Frame::Open { stream: 1, channel: ch }).unwrap();
match proto::read_frame(&mut o_r).unwrap() {
Some(Frame::Close { stream: 1, .. }) => {}
other => panic!("channel {ch}: {other:?}"),
}
}
proto::write_frame(&mut o_w, &Frame::Open { stream: 3, channel: channel::API }).unwrap();
proto::write_frame(&mut o_w, &Frame::Data { stream: 3, bytes: b"hi".to_vec() }).unwrap();
let mut ours = ours;
ours.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut got = [0; 2];
ours.read_exact(&mut got).unwrap();
assert_eq!(&got, b"hi");
ours.write_all(b"yo").unwrap();
loop {
match proto::read_frame(&mut o_r).unwrap() {
Some(Frame::Data { stream: 3, bytes }) => {
assert_eq!(bytes, b"yo");
break;
}
Some(Frame::Window { .. } | Frame::Ping(_) | Frame::Pong(_)) => {}
other => panic!("{other:?}"),
}
}
}
#[test]
fn a_newer_opener_replaces_the_socket_and_keeps_it() {
let dir = scratch("fleet-newer");
std::fs::create_dir_all(&dir).unwrap();
let socket = dir.join("fleet-w.sock");
let tagged = |tag: &'static [u8]| {
move || {
let (ours, theirs) = UnixStream::pair().ok()?;
std::thread::spawn(move || {
let mut ours = ours;
let _ = ours.write_all(tag);
});
Some(theirs.into())
}
};
link(&socket, tagged(b"old"));
let old_ino = std::fs::metadata(&socket).unwrap().ino();
link(&socket, tagged(b"new"));
wait_for(|| std::fs::metadata(&socket).is_ok_and(|m| m.ino() != old_ino), "the newer socket in place");
let mut c = dial(&socket, channel::API);
let mut got = [0; 3];
c.read_exact(&mut got).unwrap();
assert_eq!(&got, b"new");
let leftovers: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name()).collect();
assert_eq!(leftovers, ["fleet-w.sock"], "no temp names left");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn transfers_cross_the_link_both_ways() {
use crate::serve::fleet::transfer::{self, Header, Received};
let dir = scratch("fleet-transfer");
let (hub_dir, worker_dir) = (dir.join("hub"), dir.join("worker"));
std::fs::create_dir_all(&hub_dir).unwrap();
let receivers = |into: PathBuf, tx: mpsc::Sender<Received>| {
let tx = std::sync::Mutex::new(tx);
Arc::new(Receivers::new(|_| {}).with(
"root-tar",
1 << 20,
move |h: &Header| Ok(into.join(&h.name)),
move |r| tx.lock().unwrap().send(r).unwrap(),
))
};
let (hub_tx, hub_rx) = mpsc::channel();
let (worker_tx, worker_rx) = mpsc::channel();
let socket = endpoint::fleet_socket(&hub_dir, "w");
let ours = Serves::default().transfers(receivers(hub_dir.join("in"), hub_tx));
let theirs = Serves::default().with(channel::API, || None).transfers(receivers(worker_dir.clone(), worker_tx));
let outlet = Arc::new(Outlet::default());
let (a_r, o_w) = std::io::pipe().unwrap();
let (o_r, a_w) = std::io::pipe().unwrap();
let path = socket.clone();
std::thread::spawn(move || opener_with(&LINK, o_r, o_w, Endpoint { socket: Some(&path), serves: ours, outlet: None, auth: None }, |_| Ok(())));
let answering = Arc::clone(&outlet);
std::thread::spawn(move || {
answerer_with(&LINK, a_r, a_w, Endpoint { serves: theirs, outlet: Some(&answering), ..Endpoint::default() }, |_| Ok(()), || {})
});
wait_for(|| UnixStream::connect(&socket).is_ok(), "the socket accepts");
let xfer = || connect(&socket, channel::TRANSFER).unwrap();
let body: Vec<u8> = (0..600_000u32).map(|i| i as u8).collect();
let (size, sha256) = transfer::digest(&body[..]).unwrap();
let header = Header { kind: "root-tar".into(), name: "cfg.tar".into(), size, sha256, to: None, repo: None, refs: None };
transfer::send(xfer(), &header, &body[..]).unwrap();
let got = worker_rx.recv_timeout(Duration::from_secs(5)).unwrap();
assert_eq!(got.path, worker_dir.join("cfg.tar"));
assert_eq!(std::fs::read(&got.path).unwrap(), body);
let other = Header { kind: "binary".into(), ..header.clone() };
let err = transfer::send(xfer(), &other, &body[..]).unwrap_err();
assert_eq!(format!("{err:#}"), "transfer refused: nothing here receives `binary` transfers");
let bad = Header { sha256: "0".repeat(64), ..header.clone() };
let err = transfer::send(xfer(), &bad, &body[..]).unwrap_err();
assert!(format!("{err:#}").starts_with("transfer refused: the body's sha256 is"), "{err:#}");
let mut long = body.clone();
long.extend_from_slice(&[0; 1000]);
let err = transfer::send(xfer(), &header, &long[..]).unwrap_err();
assert!(format!("{err:#}").contains("the body is longer than its 600000 bytes"), "{err:#}");
assert_eq!(std::fs::read_dir(&worker_dir).unwrap().count(), 1, "only cfg.tar, no temp files");
wait_for(|| outlet.is_up(), "the outlet is up");
transfer::send(outlet.open(channel::TRANSFER).unwrap(), &header, &body[..]).unwrap();
let got = hub_rx.recv_timeout(Duration::from_secs(5)).unwrap();
assert_eq!(got.path, hub_dir.join("in/cfg.tar"));
assert_eq!(std::fs::read(&got.path).unwrap(), body);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_answerer_may_refuse_the_opener_it_hears() {
let dir = scratch("fleet-refuse");
std::fs::create_dir_all(&dir).unwrap();
let (a_r, o_w) = std::io::pipe().unwrap();
let (o_r, a_w) = std::io::pipe().unwrap();
let socket = dir.join("fleet-w.sock");
let opener = std::thread::spawn(move || opener(&LINK, o_r, o_w, &socket, |_| Ok(())));
let serves = Serves::default().with(channel::API, || None);
let end = answerer_with(&LINK, a_r, a_w, Endpoint { serves, ..Endpoint::default() }, |peer| Err(format!("not {}", peer.hash)), || {});
match end {
End::Refused(why) => assert_eq!(why, format!("not {}", LINK.hello)),
other => panic!("{other:?}"),
}
opener.join().unwrap().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
fn tagged(tag: &'static [u8]) -> impl Fn() -> Option<Conn> + Send + Sync + 'static {
move || {
let (mut ours, theirs) = UnixStream::pair().ok()?;
std::thread::spawn(move || {
let _ = ours.write_all(tag);
});
Some(theirs.into())
}
}
fn read_all(mut c: impl Read) -> Vec<u8> {
let mut got = Vec::new();
let _ = c.read_to_end(&mut got);
got
}
fn timed(c: Conn) -> UnixStream {
let Conn::Unix(c) = c else { panic!("an outlet's stream is a socket pair") };
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
c
}
fn dial(socket: &Path, channel: u8) -> UnixStream {
let c = connect(socket, channel).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
c
}
fn two_way(dir: &Path) -> (PathBuf, Arc<Outlet>) {
std::fs::create_dir_all(dir).unwrap();
let socket = endpoint::fleet_socket(dir, "w");
let path = socket.clone();
let ours = Serves::default().with(channel::PTY, tagged(b"hub pty"));
let theirs = Serves::default().with(channel::API, tagged(b"worker api")).with(channel::PTY, tagged(b"worker pty"));
let outlet = Arc::new(Outlet::default());
let (a_r, o_w) = std::io::pipe().unwrap();
let (o_r, a_w) = std::io::pipe().unwrap();
std::thread::spawn(move || opener_with(&LINK, o_r, o_w, Endpoint { socket: Some(&path), serves: ours, outlet: None, auth: None }, |_| Ok(())));
let answering = Arc::clone(&outlet);
std::thread::spawn(move || {
answerer_with(&LINK, a_r, a_w, Endpoint { serves: theirs, outlet: Some(&answering), ..Endpoint::default() }, |_| Ok(()), || {})
});
wait_for(|| outlet.is_up(), "the outlet is up");
wait_for(|| UnixStream::connect(&socket).is_ok(), "the opener's socket accepts");
(socket, outlet)
}
#[test]
fn a_second_channel_reaches_the_peers_handler_both_ways() {
let dir = scratch("fleet-two-way");
let (socket, outlet) = two_way(&dir);
assert_eq!(read_all(dial(&socket, channel::PTY)), b"worker pty");
assert_eq!(read_all(dial(&socket, channel::API)), b"worker api");
assert_eq!(read_all(timed(outlet.open(channel::PTY).unwrap())), b"hub pty");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_channel_the_peer_doesnt_serve_is_refused_and_the_link_stays_up() {
let dir = scratch("fleet-unserved");
let (socket, outlet) = two_way(&dir);
assert_eq!(read_all(dial(&socket, channel::TUNNEL)), b"");
assert_eq!(read_all(dial(&socket, 0xff)), b"");
let mut silent = UnixStream::connect(&socket).unwrap();
silent.shutdown(Shutdown::Write).unwrap();
silent.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
assert_eq!(read_all(&mut silent), b"");
for ch in [channel::API, channel::TUNNEL] {
let err = outlet.open(ch).err().expect("refused");
assert_eq!(format!("{err:#}"), format!("the peer serves no channel {ch}"));
}
assert!(outlet.open(channel::SSH_AGENT).is_err());
assert_eq!(read_all(dial(&socket, channel::API)), b"worker api");
assert_eq!(read_all(timed(outlet.open(channel::PTY).unwrap())), b"hub pty");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_opener_refuses_peer_opens_it_doesnt_serve() {
let dir = scratch("fleet-opener-refuses");
std::fs::create_dir_all(&dir).unwrap();
let (mut a_r, o_w) = std::io::pipe().unwrap();
let (o_r, mut a_w) = std::io::pipe().unwrap();
let socket = dir.join("fleet-w.sock");
let ours = Serves::default().with(channel::PTY, tagged(b"hub pty"));
let path = socket.clone();
std::thread::spawn(move || opener_with(&LINK, o_r, o_w, Endpoint { socket: Some(&path), serves: ours, outlet: None, auth: None }, |_| Ok(())));
let mut noise = None;
ssh::skip_lines(&mut a_r, SENTINEL_LIMIT, &mut noise, |l: &[u8]| match_sentinel(&LINK, l)).unwrap();
let peer = proto::handshake(&mut a_r, &mut a_w, "test", caps::API).unwrap();
assert_eq!(peer.caps, caps::PTY);
let high = 1 << 31;
for (stream, ch) in [(high | 1, channel::TUNNEL), (high | 2, channel::API), (3, channel::PTY)] {
proto::write_frame(&mut a_w, &Frame::Open { stream, channel: ch }).unwrap();
loop {
match proto::read_frame(&mut a_r).unwrap() {
Some(Frame::Close { stream: s, .. }) if s == stream => break,
Some(Frame::Ping(_) | Frame::Pong(_)) => {}
other => panic!("channel {ch}: {other:?}"),
}
}
}
proto::write_frame(&mut a_w, &Frame::Open { stream: high | 4, channel: channel::PTY }).unwrap();
let mut got = Vec::new();
while got != b"hub pty" {
match proto::read_frame(&mut a_r).unwrap() {
Some(Frame::Data { stream, bytes }) if stream == high | 4 => got.extend(bytes),
Some(Frame::Window { .. } | Frame::Ping(_) | Frame::Pong(_)) => {}
other => panic!("{other:?}"),
}
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_answerer_binds_sockets_and_the_opener_has_an_outlet() {
let dir = scratch("fleet-swapped");
std::fs::create_dir_all(&dir).unwrap();
let (theirs_sock, api) = (dir.join("a.sock"), dir.join("o.sock"));
let ours = Serves::default().with(channel::PTY, tagged(b"opener pty"));
let theirs = Serves::default().with(channel::API, tagged(b"answerer api")).with(channel::TRANSFER, tagged(b"answerer xfer"));
let (opening, answering) = (Arc::new(Outlet::default()), Arc::new(Outlet::default()));
let (a_r, o_w) = std::io::pipe().unwrap();
let (o_r, a_w) = std::io::pipe().unwrap();
{
let (api, opening) = (api.clone(), Arc::clone(&opening));
std::thread::spawn(move || opener_with(&LINK, o_r, o_w, Endpoint { socket: Some(&api), serves: ours, outlet: Some(&opening), auth: None }, |_| Ok(())));
}
{
let (path, answering) = (theirs_sock.clone(), Arc::clone(&answering));
std::thread::spawn(move || {
let endpoint = Endpoint { socket: Some(&path), serves: theirs, outlet: Some(&answering), auth: None };
answerer_with(&LINK, a_r, a_w, endpoint, |_| Ok(()), || {})
});
}
wait_for(|| opening.is_up() && answering.is_up(), "both outlets are up");
assert_eq!(read_all(dial(&theirs_sock, channel::PTY)), b"opener pty");
assert_eq!(read_all(dial(&theirs_sock, channel::PTY)), b"opener pty");
assert_eq!(read_all(dial(&theirs_sock, channel::TUNNEL)), b"");
assert_eq!(read_all(dial(&api, channel::API)), b"answerer api");
assert_eq!(read_all(timed(opening.open(channel::TRANSFER).unwrap())), b"answerer xfer");
assert_eq!(read_all(timed(opening.open(channel::API).unwrap())), b"answerer api");
let err = opening.open(channel::PTY).err().expect("refused");
assert_eq!(format!("{err:#}"), format!("the peer serves no channel {}", channel::PTY));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_outlet_hangs_up_its_link() {
let dir = scratch("fleet-hang-up");
std::fs::create_dir_all(&dir).unwrap();
let socket = dir.join("fleet-w.sock");
let outlet = Arc::new(Outlet::default());
outlet.hang_up();
let (a_r, o_w) = std::io::pipe().unwrap();
let (o_r, a_w) = std::io::pipe().unwrap();
let opener = {
let (outlet, path) = (Arc::clone(&outlet), socket.clone());
std::thread::spawn(move || opener_with(&LINK, o_r, o_w, Endpoint { socket: Some(&path), outlet: Some(&outlet), ..Endpoint::default() }, |_| Ok(())))
};
std::thread::spawn(move || answerer(&LINK, a_r, a_w, || None, || {}, || {}));
wait_for(|| outlet.is_up(), "the outlet is up");
outlet.hang_up();
opener.join().unwrap().unwrap();
assert!(!outlet.is_up());
assert!(!socket.exists(), "unlinked");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn link_channels_flow_and_have_caps() {
for ch in [channel::API, channel::TRANSFER, channel::PTY, channel::TUNNEL, channel::AGENT, channel::ROUTE] {
assert!(proto::channel::flows(ch), "{ch}");
assert!(cap_of(ch).is_some(), "{ch}");
}
assert!(!proto::channel::flows(channel::SSH_AGENT));
assert_eq!(cap_of(channel::SSH_AGENT), Some(caps::SSH_AGENT));
assert_eq!(cap_of(channel::RPC), None);
let all = [channel::API, channel::TRANSFER, channel::PTY, channel::TUNNEL, channel::AGENT, channel::ROUTE, channel::SSH_AGENT]
.map(|c| cap_of(c).unwrap());
assert_eq!(all.iter().fold(0, |a, c| a | c).count_ones(), all.len() as u32, "distinct bits");
}
#[test]
fn the_sentinel_matcher_takes_only_its_line() {
assert_eq!(match_sentinel(&LINK, b"devsandbox-fleet 2"), Ok(Some(())));
assert_eq!(match_sentinel(&LINK, b"devsandbox-fleet 2\r"), Ok(Some(())));
assert_eq!(match_sentinel(&LINK, b"devsandbox-agent 2"), Ok(None));
let err = match_sentinel(&LINK, b"devsandbox-fleet 1").unwrap_err();
assert!(err.starts_with("the fleet link there speaks `devsandbox-fleet 1`"), "{err}");
assert!(err.ends_with("update devsandbox on the older side"), "{err}");
}
#[test]
fn stream_ids_stay_in_the_daemon_space() {
let mut next = 1;
assert_eq!(next_stream_id(&mut next), 1);
assert_eq!(next_stream_id(&mut next), 2);
let mut top = (1 << 31) - 1;
assert_eq!(next_stream_id(&mut top), (1 << 31) - 1);
assert_eq!(next_stream_id(&mut top), 1);
}
}