//! `wsbx code NAME`: VS Code for a running sandbox. //! Browser (default): `code serve-web` runs in the VM on its localhost, forwarded to the host's localhost //! (like `wsbx forward`) behind a random connection token, and opened in the browser. //! --desktop: desktop VS Code via Remote-SSH. ssh reaches the SSH server in the guest helper (guest/ssh.go) //! through `wsbx exec` as ProxyCommand: no network port, no keys. use crate::exec::{self, sock}; use crate::forward; use crate::util::sq; use anyhow::{Context, Result, bail}; use serde_json::Value; use std::fs; use std::io::Read; use std::net::TcpListener; use std::path::Path; use std::process::Command; use std::time::{Duration, Instant}; /// Guest side of the browser mode: fetch the VS Code CLI once (static musl binary, onto the sandbox disk), /// then serve. The CLI downloads the matching server on first use. $1 port, $2 token. const WEB_SH: &str = r#"set -e B=/.wsbx/busybox D="$HOME/.wsbx-vscode" U=https://update.code.visualstudio.com/latest/cli-alpine-arm64/stable if [ ! -x "$D/code" ]; then echo "wsbx: downloading the VS Code CLI..." $B rm -rf "$D/tmp" && $B mkdir -p "$D/tmp" if command -v curl >/dev/null; then curl -fsSL "$U"; else wget -qO- "$U"; fi | $B tar -xzf - -C "$D/tmp" $B sync && $B mv "$D/tmp/code" "$D/code" && $B rmdir "$D/tmp" # never a half-written code, even if the VM is killed fi exec "$D/code" serve-web --host 127.0.0.1 --port "$1" --connection-token "$2" --accept-server-license-terms "#; pub fn code(h: &Path, name: &str, desktop: bool) -> Result<()> { let sock = sock(h, name)?; // also checks the name and that it's running let meta: Value = serde_json::from_slice(&fs::read(h.join("sandboxes").join(name).join("meta.json"))?)?; let folder = enc(meta["workspace"].as_str().unwrap_or("/")); if desktop { return self::desktop(h, name, &folder); } let l = TcpListener::bind(("127.0.0.1", 0))?; let port = l.local_addr()?.port(); // the same port in the guest: random and high, so most likely free there too let mut t = [0u8; 16]; fs::File::open("/dev/urandom")?.read_exact(&mut t)?; let token = hex::encode(t); eprintln!("wsbx: starting VS Code in {name} (the first start downloads it)"); eprintln!("wsbx: by using it you accept the VS Code Server license: https://aka.ms/vscode-server-license"); let (s, tk) = (sock.clone(), token.clone()); let server = std::thread::spawn(move || exec::stream(&s, &["/.wsbx/busybox", "sh", "-c", WEB_SH, "sh", &port.to_string(), &tk])); let t0 = Instant::now(); while !forward::listening(&sock, port) { if server.is_finished() { let r = server.join().unwrap(); bail!("VS Code server in {name} stopped ({:?})", r.map_err(|e| e.to_string())); } if t0.elapsed() > Duration::from_secs(300) { bail!("VS Code server in {name} didn't start within 5 minutes"); } std::thread::sleep(Duration::from_millis(500)); } let (s, n) = (sock.clone(), name.to_string()); std::thread::spawn(move || forward::serve(&s, &n, vec![(l, port)])); let url = format!("http://127.0.0.1:{port}/?tkn={token}&folder={folder}"); eprintln!("wsbx: VS Code for {name}: {url}\nwsbx: Ctrl-C stops it"); let _ = Command::new("open").arg(&url).status(); match server.join().unwrap()? { Some(c) => bail!("VS Code server in {name} exited with {c}"), None => bail!("lost connection to {name} (VM stopped?)"), } } /// Write ssh config for every sandbox, include it from ~/.ssh/config once, open VS Code on NAME.wsbx. fn desktop(h: &Path, name: &str, folder: &str) -> Result<()> { let exe = std::env::current_exe()?; let mut cfg = String::from("# Written by `wsbx code --desktop`, regenerated each time: don't edit.\n"); for e in fs::read_dir(h.join("sandboxes"))?.flatten().filter(|e| e.path().join("meta.json").exists()) { let n = e.file_name().to_string_lossy().into_owned(); // sandbox names are [a-z0-9-] cfg += &format!( "\nHost {n}.wsbx\n ProxyCommand {} exec {n} -- /.wsbx/host/guest -ssh-stdio\n \ StrictHostKeyChecking no\n UserKnownHostsFile /dev/null\n LogLevel ERROR\n ForwardAgent no\n ForwardX11 no\n", sq(&exe.to_string_lossy()) ); } let ours = h.join("ssh_config"); fs::write(&ours, cfg)?; let home = std::path::PathBuf::from(std::env::var_os("HOME").context("HOME")?); let user_cfg = home.join(".ssh/config"); let include = format!("Include \"{}\"", ours.display()); let cur = match fs::read_to_string(&user_cfg) { Ok(s) => s, Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(), Err(e) => return Err(e).context("~/.ssh/config"), }; if !cur.lines().any(|l| l.trim() == include) { fs::create_dir_all(home.join(".ssh"))?; // At the top: an Include after a `Host` line would only apply to that host. fs::write(&user_cfg, format!("{include}\n\n{cur}"))?; eprintln!("wsbx: added `{include}` to the top of ~/.ssh/config"); } let url = format!("vscode://vscode-remote/ssh-remote+{name}.wsbx{folder}"); eprintln!("wsbx: opening {url} (needs the Remote - SSH extension); plain ssh works too: ssh {name}.wsbx"); if !Command::new("open").arg(&url).status()?.success() { bail!("couldn't open {url} (is VS Code installed?)"); } Ok(()) } /// Percent-encode a path for a URL, keeping '/'. fn enc(p: &str) -> String { p.bytes() .map(|b| if b.is_ascii_alphanumeric() || b"/-._~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }) .collect() } #[cfg(test)] mod tests { #[test] fn enc() { assert_eq!(super::enc("/Users/me/my repo/รค&x"), "/Users/me/my%20repo/%C3%A4%26x"); } }