git clone https://garage44.eu/jeroen/midas.git.. /src/forward.rs
//! `midas node forward`: the TCP a macOS machine carries for its node VM.
//!
//! A Linux node's container gets its ssh port from pasta. A macOS node is a VM
//! behind the machine's NAT, with an address that changes, so the machine
//! carries three things itself, as the node's user:
//!
//! * the tunnel to the node: `<wireguard address>:<port>` → the VM's sshd;
//! * the node to the hub: `<VM gateway>:4791` → the hub's API, and
//! `<VM gateway>:4792` → the hub's ssh (its git mirror).
//!
//! The second half is also what keeps the hub's address rule working: the hub
//! sees the node's requests coming from this machine's WireGuard address.
use std::io::{Read, Write};
use std::net::{Shutdown, TcpListener, TcpStream};
use std::process::Command;
use std::time::Duration;
use anyhow::{anyhow, Context, Result};
/// `LISTEN=TARGET`, where TARGET may be `vm:PORT`.
pub fn parse_pair(p: &str) -> Result<(String, String)> {
let (l, t) = p.split_once('=').ok_or_else(|| anyhow!("--pair is LISTEN=TARGET, not {p:?}"))?;
l.parse::<std::net::SocketAddrV4>().map_err(|_| anyhow!("{l:?} is not ADDRESS:PORT"))?;
let port_ok = t.rsplit_once(':').is_some_and(|(_, port)| port.parse::<u16>().is_ok());
if !port_ok {
return Err(anyhow!("{t:?} is not ADDRESS:PORT or vm:PORT"));
}
Ok((l.to_string(), t.to_string()))
}
/// The VM's address now, from tart.
fn vm_address(vm: &str) -> Option<String> {
let tart = crate::setup::which("tart")?;
let out = Command::new(tart).args(["ip", vm, "--wait", "5"]).output().ok().filter(|o| o.status.success())?;
Some(String::from_utf8_lossy(&out.stdout).trim().to_string()).filter(|a| !a.is_empty())
}
fn pipe(mut from: TcpStream, mut to: TcpStream) {
let mut buf = [0u8; 64 * 1024];
loop {
match from.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
if to.write_all(&buf[..n]).is_err() {
break;
}
}
}
}
let _ = to.shutdown(Shutdown::Write);
}
fn serve(vm: String, listen: String, target: String) {
// The gateway address exists only while a VM is up, so keep trying to bind.
let listener = loop {
match TcpListener::bind(&listen) {
Ok(l) => break l,
Err(_) => std::thread::sleep(Duration::from_secs(5)),
}
};
eprintln!("midas forward: {listen} → {target}");
for conn in listener.incoming() {
let Ok(client) = conn else { continue };
let (vm, target) = (vm.clone(), target.clone());
std::thread::spawn(move || {
let dest = match target.strip_prefix("vm:") {
Some(port) => match vm_address(&vm) {
Some(a) => format!("{a}:{port}"),
None => return,
},
None => target,
};
let Ok(addr) = dest.parse() else { return };
let Ok(server) = TcpStream::connect_timeout(&addr, Duration::from_secs(10)) else { return };
let (c2, s2) = (client.try_clone(), server.try_clone());
let (Ok(c2), Ok(s2)) = (c2, s2) else { return };
let up = std::thread::spawn(move || pipe(client, server));
pipe(s2, c2);
let _ = up.join();
});
}
}
pub fn forward(vm: &str, pairs: &[String]) -> Result<i32> {
let pairs: Vec<(String, String)> = pairs.iter().map(|p| parse_pair(p)).collect::<Result<_>>()
.context("bad --pair")?;
let handles: Vec<_> = pairs.into_iter().map(|(l, t)| {
let vm = vm.to_string();
std::thread::spawn(move || serve(vm, l, t))
}).collect();
for h in handles {
let _ = h.join();
}
Ok(0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pairs_name_a_listener_and_a_target() {
assert_eq!(parse_pair("10.44.0.4:2226=vm:22").unwrap().1, "vm:22");
assert!(parse_pair("192.168.64.1:4791=10.44.0.1:4791").is_ok());
assert!(parse_pair("nonsense").is_err());
assert!(parse_pair("10.44.0.4:2226=vm").is_err());
}
#[test]
fn it_carries_bytes_both_ways() {
let echo = TcpListener::bind("127.0.0.1:0").unwrap();
let echo_at = echo.local_addr().unwrap().to_string();
std::thread::spawn(move || {
for c in echo.incoming().flatten() {
let mut w = c.try_clone().unwrap();
std::thread::spawn(move || { let _ = std::io::copy(&mut &c, &mut w); });
}
});
let port = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let listen = format!("127.0.0.1:{port}");
let l2 = listen.clone();
std::thread::spawn(move || serve("unused".into(), l2, echo_at));
let mut c = loop {
if let Ok(c) = TcpStream::connect(&listen) { break c; }
std::thread::sleep(Duration::from_millis(50));
};
c.write_all(b"hello node").unwrap();
let mut got = [0u8; 10];
c.read_exact(&mut got).unwrap();
assert_eq!(&got, b"hello node");
}
}