Skip to content

armgit / muxin

Public Imported from GitHub
0

All your machines, one app. For you and your AI agents: agent sessions, desktops, files, logs and GitHub across your Macs, Linux and Windows machines, with an MCP server.

Windows: the agent, managed Windows machines, and the app on Windows

Adib Hanna62dddb82d1ce
diff --git a/AGENTS.md b/AGENTS.md
index 7f122ad..5cdd848 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -123,8 +123,8 @@ The CLI equivalents are `muxen session ls|start|read|question|answer|send|attach
- `machine_connection` says how Muxen reaches a machine: `direct` (QUIC), `ssh` (one live ssh connection) or `none`, with a measured round trip and the `network` it goes over ("Local network", "Tailscale", ...). `direct_connection(machine_id, enabled)` pairs for direct connections (it installs a user service on the machine; only when asked).
- Tailscale, when it's on this computer, keeps machines reachable away from home: Muxen uses the local network when the machine is on it and Tailscale otherwise, and switches by itself when the network changes. A machine's `tailnet` (in `get_machine` and `machine_connection`) says whether Tailscale sees it online and whether traffic goes peer-to-peer (`path: "direct"`) or through a slower relay (`"relay"`). An `unreachable.kind` of `"tailscale-off"` means Tailscale is off or signed out on this computer: tell the user to turn it on; Muxen never changes Tailscale's settings.
- `machine_ports(machine_id)` lists what's listening on a machine: each port with its program or Docker container, and for web servers (`web: true`) their status and page title. To show the user a server running there, they open it from the machine's page in the app (Servers › Open, at `localhost` on their computer) or run `muxen forward <machine> <port>`; you can check it from the machine itself with `workspace_exec(command: "curl -sS localhost:<port>")`.
-- `desktop_screenshot(machine_id)` returns a picture of the machine's screen (Linux with X11, and Macs). `desktop_input(machine_id, events)` clicks, types, scrolls and presses keys there, in that picture's pixels: look first, act, then look again. It's the user's real screen: only when asked, and never type passwords.
-- A machine can have several monitors. `desktop_displays(machine_id)` lists them (each with an `id`; Muxen's virtual ones have `virtual: true`); pass `display` to `desktop_screenshot` and `desktop_input` to use one. `desktop_add_display(machine_id, width?, height?, name?)` adds a virtual monitor to the desktop, as if another screen were plugged in, and `desktop_remove_display(machine_id, display)` takes it away. `desktop_set_display(machine_id, display, width?, height?, scale?)` changes a monitor's resolution (one of its `modes`) or the desktop's scale on it (`scales`; on Linux X11 one scale for all monitors): a 4K monitor at scale 2 reads like 1080p and stays sharp. They change the user's real desktop: only when asked.
+- `desktop_screenshot(machine_id)` returns a picture of the machine's screen (Linux with X11, Macs, and Windows with someone signed in). `desktop_input(machine_id, events)` clicks, types, scrolls and presses keys there, in that picture's pixels: look first, act, then look again. It's the user's real screen: only when asked, and never type passwords.
+- A machine can have several monitors. `desktop_displays(machine_id)` lists them (each with an `id`; Muxen's virtual ones have `virtual: true`); pass `display` to `desktop_screenshot` and `desktop_input` to use one. `desktop_add_display(machine_id, width?, height?, name?)` adds a virtual monitor to the desktop (Linux and Macs), as if another screen were plugged in, and `desktop_remove_display(machine_id, display)` takes it away. `desktop_set_display(machine_id, display, width?, height?, scale?)` changes a monitor's resolution (one of its `modes`) or the desktop's scale on it (`scales`; on Linux X11 one scale for all monitors): a 4K monitor at scale 2 reads like 1080p and stays sharp. They change the user's real desktop: only when asked.
## Cloud machines
diff --git a/Cargo.lock b/Cargo.lock
index 19d2857..2432e44 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3608,6 +3608,8 @@ dependencies = [
"tracing",
"tracing-subscriber",
"unicode-segmentation",
+ "windows-sys 0.61.2",
+ "winresource",
]
[[package]]
@@ -3616,6 +3618,7 @@ version = "0.2.7"
dependencies = [
"alacritty_terminal",
"anyhow",
+ "base64 0.22.1",
"cc",
"jpeg-encoder",
"libc",
@@ -3627,6 +3630,7 @@ dependencies = [
"serde_json",
"socket2",
"tokio",
+ "windows-sys 0.61.2",
"x11rb",
]
@@ -7507,6 +7511,16 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "winresource"
+version = "0.1.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b"
+dependencies = [
+ "toml 1.1.7+spec-1.1.0",
+ "version_check",
+]
+
[[package]]
name = "winsafe"
version = "0.0.19"
diff --git a/Cargo.toml b/Cargo.toml
index c175a25..fac0424 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -51,6 +51,14 @@ raw-window-handle = { version = "0.6", optional = true }
# Already in the tree (through reqwest/native roots): the Keychain, for cloud sign-ins.
security-framework = "3"
+# The icon and name in the Windows executable (build.rs).
+[target.'cfg(windows)'.build-dependencies]
+winresource = "0.1"
+
+# Starting without a console window (see main.rs `without_console_window`).
+[target.'cfg(windows)'.dependencies]
+windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Console", "Win32_UI_WindowsAndMessaging", "Win32_Security_Credentials"] }
+
[workspace]
members = [".", "agent"]
diff --git a/README.md b/README.md
index fadb1a4..ce4daa0 100644
--- a/README.md
+++ b/README.md
@@ -332,7 +332,7 @@ muxen checkouts --machine beelink --path ~/code/api --git pull
Start an AI agent on one of your machines and come back to it whenever you like, from the app, from your own terminal, or through another agent.
- **Keeps running.** Sessions live in Muxen's agent on the machine (`~/.muxen/bin/muxen-agent`), a small background program that holds each session's terminal, the way tmux would. Closing the app, sleeping your laptop or losing the network only detaches; the agent keeps working until you end the session, and reopening it shows the screen as it is with its recent scrollback. A restart of the machine ends its sessions, as with tmux.
-- **Nothing to install.** When Muxen connects to a machine it uploads the agent build for that OS and CPU (macOS and Linux, x86_64 and arm64; static binaries, about 1 MB) and keeps it up to date. Windows machines run sessions in the app's terminal for now, so they end with the window.
+- **Nothing to install.** When Muxen connects to a machine it uploads the agent build for that OS and CPU (macOS and Linux, x86_64 and arm64, and Windows x64; a few MB) and keeps it up to date.
- **Split panes.** ⌘D splits a terminal to the right, ⇧⌘D below it (or the buttons in its header): a new shell on the same machine, in the same folder. ⌥⌘← and ⌥⌘→ move between panes, or click one. Each pane is a session of its own, so it keeps running like any other; type `exit` to close it, or × on its bar to take it out of the split. Splits come back when you reopen Muxen.
- **A real terminal in the app.** Everything goes to the agent: Esc, Ctrl-C, Tab, arrows, Option/Shift+Enter for newlines. ⌘C copies a selection, ⌘V pastes, the wheel scrolls back. Nerd Font icons (Neovim's file icons, prompt glyphs) show with any terminal font: Muxen brings the symbols. Right-click a machine for a new terminal or agent session.
- **Names you choose.** Right-click a machine or a session and pick **Rename…** (or ⇧⌘P › Rename on its page). A machine keeps its id, so its runners, sessions and favorites stay with it; `config.toml` gets `id = "<old id>"` when the new name would give a different one. A session's title is kept by the agent on its machine (`~/.muxen/titles.json`), so every Muxen sees it; an empty title goes back to the one it started with.
@@ -365,7 +365,7 @@ Muxen first reaches a machine with `ssh`, installs its small agent there, and fr
**Servers.** A machine's page lists what's listening there: web servers first, with their page's title (a dev server, a Docker container's site), then its other ports. **Open** puts one on this computer at `localhost` (the same port number when it's free) and opens it in your browser; no desktop needed. Each connection goes through the machine's live connection, so it works over ssh or direct alike, even for servers that listen only on the machine itself. Open ports are listed under their machine in the sidebar (click to open, × to close) and come back when Muxen starts. **Open a port** takes any port number. From a terminal: `muxen ports <machine>` and `muxen forward <machine> <port>`.
-**Desktop.** On a Linux machine with an X11 desktop, or a Mac, **Show desktop** (on its page, or its right-click menu) shows its screen live and sends your mouse and keyboard to it. On Linux ⌘ works as Ctrl; on a Mac it stays ⌘. An open desktop is listed under its machine in the sidebar (and keeps streaming while you look elsewhere); close it there.
+**Desktop.** On a Linux machine with an X11 desktop, a Mac, or a Windows PC someone is signed in to, **Show desktop** (on its page, or its right-click menu) shows its screen live and sends your mouse and keyboard to it. On Linux ⌘ works as Ctrl; on a Mac it stays ⌘. An open desktop is listed under its machine in the sidebar (and keeps streaming while you look elsewhere); close it there.
**Monitors, real and virtual.** A machine with more than one monitor gets a picker above its desktop: show one monitor at a time (on Linux, or all of them). **Add monitor** (or **Add virtual monitor…** in the machine's right-click menu) plugs in a monitor that isn't there, the way [DeskPad](https://github.com/Stengo/DeskPad) does on a Mac: pick a name and a size (720p to 4K), and it joins the desktop like a real one, to the right of the others. Windows move onto it, the machine's own tools (System Settings, RustDesk) see it, and while the machine's desktop is open, Muxen lists it under the Desktop item in the sidebar to open it directly. It starts at the main monitor's size and offers every common one (720p to 4K). Above a monitor, pick its resolution, and on Linux desktops that offer it, its scale: 200% makes things twice as big and just as sharp, so a 4K monitor reads like 1080p (the stream is always the screen's own size, so it stays crisp). Right-click a monitor (in the picker or the sidebar) to rename or remove it, and in the all-screens view, click a monitor's name to open it. On Cinnamon each virtual monitor gets copies of the main monitor's panels (menu, clock, dock with the same pinned apps), so it's usable on its own. It stays until you remove it (**Remove monitor**) or the machine restarts. Handy on a machine with no screen (a dummy HDMI plug, a server), or to give an agent a monitor of its own. On a Mac it's a CGVirtualDisplay. On Linux (X11) it's a software dummy plug: Muxen plugs a made-up monitor (at the size you picked) into a video output with nothing connected, and the desktop sets it up like a real one. That takes root, so when sudo wants a password Muxen asks for yours, only then, sends it to sudo over its encrypted connection, and keeps it in memory only until you quit. Nothing is installed.
@@ -489,6 +489,20 @@ muxen cloud destroy dev-1
- Registration and removal tokens are masked in all output and never logged.
- `ssh` runs with `BatchMode=yes`, so a machine that needs a password just shows up as unreachable. Make sure `ssh <host>` works with keys first.
+## Windows
+
+**Windows machines** are managed like the others, over OpenSSH (Settings › System › Optional features › OpenSSH Server, then key-based login; an administrator account for services and runners). Muxen installs its agent in `%USERPROFILE%\.muxen\bin` and works with PowerShell or cmd as sshd's shell:
+
+- **Sessions** keep running after Muxen closes (ConPTY, in the agent's session server).
+- **Desktop and clipboard:** the screen, mouse and keyboard of whoever is signed in; Muxen starts its helper in their session through a one-off scheduled task (no window flashes).
+- **Pages:** Processes and GPUs, Services (Windows services; "at boot" is the startup type), Servers, Logs (the System, Application and Security event logs, a service's events, files), Usage, Copy files, git, Run (PowerShell), workspaces (sync copies through the agent; it doesn't delete).
+- **Checks** report admin rights, Docker, the network card (for Wake on LAN), pending reboots and failed services.
+- **Direct connections** run `listen` as a scheduled task at sign-in, with a Windows Firewall rule for the agent.
+
+Not yet on Windows: Docker runners and Docker workspaces, adding virtual monitors.
+
+**The app on Windows** is built on Windows (GPUI compiles its shaders with the Windows SDK's `fxc.exe`): install Rust and Visual Studio's C++ build tools with the Windows SDK, run `scripts/build-agents.sh` on a Mac or Linux (it makes the Windows agent too, with `cargo-zigbuild`), then `scripts\package-windows.ps1` on Windows. That makes `dist\Muxen-windows-x64.zip`: `muxen.exe` and its `agents\`. Started from Explorer it shows no console window; from a terminal it's the same CLI as elsewhere. Secrets go in Windows' Credential Manager.
+
## Develop
```sh
diff --git a/agent/Cargo.toml b/agent/Cargo.toml
index d8baab4..2450901 100644
--- a/agent/Cargo.toml
+++ b/agent/Cargo.toml
@@ -9,6 +9,7 @@ publish = false
[dependencies]
alacritty_terminal = "0.26"
anyhow = "1"
+base64 = "0.22"
libc = "0.2"
portable-pty = "0.9"
serde_json = "1"
@@ -24,6 +25,21 @@ tokio = { version = "1", features = ["rt-multi-thread", "net", "io-util", "macro
[target.'cfg(target_os = "linux")'.dependencies]
x11rb = { version = "0.13", features = ["xtest", "shm", "xfixes", "randr"] }
+# The console in raw mode for `attach`, on Windows.
+[target.'cfg(windows)'.dependencies]
+windows-sys = { version = "0.61", features = [
+ "Win32_Foundation",
+ "Win32_System_Console",
+ "Win32_Graphics_Gdi",
+ "Win32_UI_WindowsAndMessaging",
+ "Win32_UI_Input_KeyboardAndMouse",
+ "Win32_UI_HiDpi",
+ "Win32_System_RemoteDesktop",
+ "Win32_System_DataExchange",
+ "Win32_System_Memory",
+] }
+jpeg-encoder = "0.6"
+
[target.'cfg(any(target_os = "linux", target_os = "macos"))'.dependencies]
jpeg-encoder = "0.6"
diff --git a/agent/src/client.rs b/agent/src/client.rs
index 07dca48..3279dd1 100644
--- a/agent/src/client.rs
+++ b/agent/src/client.rs
@@ -2,28 +2,28 @@
//! `attach` (this terminal becomes a window onto a session).
use std::io::{self, Read, Write};
-use std::os::unix::net::UnixStream;
-use std::os::unix::process::CommandExt;
-use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use serde_json::{Value, json};
-use crate::{detect, home_dir, now, proto, socket_path};
+use crate::sys::{self, Stream};
+use crate::{detect, home_dir, now, proto};
/// Connects to the session server, starting it first when asked.
-fn connect(start: bool) -> io::Result<UnixStream> {
- match UnixStream::connect(socket_path()) {
+pub fn connect(start: bool) -> io::Result<Stream> {
+ match sys::connect() {
Ok(s) => Ok(s),
Err(e) if !start => Err(e),
Err(_) => {
- spawn_server()?;
+ // In the background, so it outlives this ssh connection (logging to ~/.muxen/agent.log).
+ sys::spawn_background(&["serve"], home_dir().join("agent.log"))?;
let mut last = None;
- for _ in 0..100 {
+ // Windows takes a moment longer (the server starts through WMI).
+ for _ in 0..200 {
thread::sleep(Duration::from_millis(30));
- match UnixStream::connect(socket_path()) {
+ match sys::connect() {
Ok(s) => return Ok(s),
Err(e) => last = Some(e),
}
@@ -33,23 +33,6 @@ fn connect(start: bool) -> io::Result<UnixStream> {
}
}
-/// Starts `serve` in the background, in its own session so it outlives this
-/// ssh connection, logging to ~/.muxen/agent.log.
-fn spawn_server() -> io::Result<()> {
- let exe = std::env::current_exe()?;
- let log = std::fs::OpenOptions::new().create(true).append(true).open(home_dir().join("agent.log"))?;
- let mut cmd = Command::new(exe);
- cmd.arg("serve").stdin(Stdio::null()).stdout(log.try_clone()?).stderr(log).current_dir(home_dir());
- unsafe {
- cmd.pre_exec(|| {
- libc::setsid();
- Ok(())
- });
- }
- cmd.spawn()?;
- Ok(())
-}
-
fn request(req: &Value, start: bool) -> Value {
let mut stream = match connect(start) {
Ok(s) => s,
@@ -92,11 +75,20 @@ pub fn handle(req: &Value) -> Value {
},
"start" => request(&req, true),
"rename" => rename(&req),
+ #[cfg(unix)]
"displays" => crate::displays::list(),
+ #[cfg(unix)]
"display_create" => crate::displays::create(&req),
+ #[cfg(unix)]
"display_remove" => crate::displays::remove(&req),
+ #[cfg(unix)]
"display_rename" => crate::displays::rename(&req),
+ #[cfg(unix)]
"display_set" => crate::displays::set(&req),
+ #[cfg(windows)]
+ "displays" => windows_displays(),
+ #[cfg(windows)]
+ "display_create" | "display_remove" | "display_rename" | "display_set" => json!({ "ok": false, "error": "Muxen can't add or change monitors on Windows yet." }),
"log_sources" => crate::logs::sources(),
"logs_read" => crate::logs::read(&req),
"services" => crate::services::list(&req),
@@ -114,6 +106,22 @@ pub fn handle(req: &Value) -> Value {
}
}
+/// Windows' monitors, as the signed-in desktop sees them (sshd's session has none).
+#[cfg(windows)]
+fn windows_displays() -> Value {
+ if crate::win_screen::in_desktop_session() {
+ return crate::win_screen::displays();
+ }
+ let mut stream = match crate::win_screen::start_in_desktop(&["displays".to_string()]) {
+ Ok(s) => s,
+ Err(e) => return json!({ "ok": false, "error": e }),
+ };
+ let _ = stream.set_read_timeout(Some(Duration::from_secs(10)));
+ let mut text = String::new();
+ let _ = stream.read_to_string(&mut text);
+ serde_json::from_str(text.trim()).unwrap_or_else(|_| json!({ "ok": false, "error": "Windows didn't list its monitors." }))
+}
+
/// Titles the user gave sessions, by session name (`~/.muxen/titles.json`).
/// Kept here rather than in the session server, which goes on running the
/// build it started with across agent updates, so renaming works with any.
@@ -185,7 +193,7 @@ fn discover(req: &Value) -> Value {
let dirs = if names.is_empty() { Vec::new() } else { detect::path_dirs() };
let agents = if names.is_empty() { Vec::new() } else { detect::agents(&names, &dirs) };
let gh = if names.is_empty() { Value::Null } else { crate::repos::gh_status(&dirs) };
- let running = UnixStream::connect(socket_path()).is_ok();
+ let running = sys::connect().is_ok();
let list = if running { request(&json!({ "op": "list" }), false) } else { json!({}) };
let mut sessions = list.get("sessions").cloned().unwrap_or_else(|| json!([]));
let mut titles = read_titles();
@@ -211,8 +219,10 @@ fn discover(req: &Value) -> Value {
}
/// Saves the terminal's settings and puts it in raw mode; restores on drop.
+#[cfg(unix)]
struct RawMode(Option<libc::termios>);
+#[cfg(unix)]
impl RawMode {
fn enable() -> RawMode {
unsafe {
@@ -239,12 +249,46 @@ impl RawMode {
}
}
+/// Windows: the console's modes, saved; keys go through one by one as VT
+/// sequences, and output's escape sequences are drawn.
+#[cfg(windows)]
+struct RawMode(Option<(u32, u32)>);
+
+#[cfg(windows)]
+impl RawMode {
+ fn enable() -> RawMode {
+ use windows_sys::Win32::System::Console::*;
+ unsafe {
+ let (input, output) = (GetStdHandle(STD_INPUT_HANDLE), GetStdHandle(STD_OUTPUT_HANDLE));
+ let (mut in_mode, mut out_mode) = (0u32, 0u32);
+ if GetConsoleMode(input, &mut in_mode) == 0 {
+ return RawMode(None);
+ }
+ GetConsoleMode(output, &mut out_mode);
+ SetConsoleMode(input, (in_mode & !(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT)) | ENABLE_VIRTUAL_TERMINAL_INPUT);
+ SetConsoleMode(output, out_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
+ RawMode(Some((in_mode, out_mode)))
+ }
+ }
+
+ fn restore(&self) {
+ use windows_sys::Win32::System::Console::*;
+ if let Some((in_mode, out_mode)) = self.0 {
+ unsafe {
+ SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), in_mode);
+ SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), out_mode);
+ }
+ }
+ }
+}
+
impl Drop for RawMode {
fn drop(&mut self) {
self.restore();
}
}
+#[cfg(unix)]
fn window_size() -> Option<(u16, u16)> {
unsafe {
let mut ws: libc::winsize = std::mem::zeroed();
@@ -252,6 +296,20 @@ fn window_size() -> Option<(u16, u16)> {
}
}
+#[cfg(windows)]
+fn window_size() -> Option<(u16, u16)> {
+ use windows_sys::Win32::System::Console::*;
+ unsafe {
+ let mut info: CONSOLE_SCREEN_BUFFER_INFO = std::mem::zeroed();
+ if GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &mut info) == 0 {
+ return None;
+ }
+ let w = info.srWindow;
+ let (cols, rows) = ((w.Right - w.Left + 1) as u16, (w.Bottom - w.Top + 1) as u16);
+ (cols > 0).then_some((cols, rows))
+ }
+}
+
/// Bridges this terminal and a session until the session ends, the
/// connection drops, or (for people, not the app) Ctrl-] then d detaches.
pub fn attach(name: &str) -> i32 {
diff --git a/agent/src/clipboard.rs b/agent/src/clipboard.rs
index 5cd2a22..e54375b 100644
--- a/agent/src/clipboard.rs
+++ b/agent/src/clipboard.rs
@@ -6,6 +6,7 @@
use std::io::{self, Write};
use std::sync::mpsc;
use std::thread;
+#[cfg(unix)]
use std::time::Duration;
/// A clipboard's text (the frame kind on the link and on stdin/stdout).
@@ -43,10 +44,10 @@ pub fn run() -> i32 {
mac::run(rx, changed);
0
}
- #[cfg(not(any(target_os = "linux", target_os = "macos")))]
+ #[cfg(windows)]
{
- let _ = (rx, changed);
- 1
+ crate::win_screen::clip(rx, changed);
+ 0
}
}
diff --git a/agent/src/daemon.rs b/agent/src/daemon.rs
index 70b55cd..11052db 100644
--- a/agent/src/daemon.rs
+++ b/agent/src/daemon.rs
@@ -6,7 +6,6 @@
use std::collections::VecDeque;
use std::io::{Read, Write};
-use std::os::unix::net::{UnixListener, UnixStream};
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
@@ -20,7 +19,8 @@ use alacritty_terminal::vte::ansi::Processor;
use portable_pty::{Child, CommandBuilder, MasterPty, PtySize, native_pty_system};
use serde_json::{Value, json};
-use crate::{detect, now, proto, screen, socket_path};
+use crate::sys::{self, Stream};
+use crate::{detect, now, proto, screen};
/// With no sessions and no connections for this long, the server exits.
const IDLE_EXIT: Duration = Duration::from_secs(120);
@@ -83,7 +83,7 @@ struct Inner {
writer: Option<Box<dyn Write + Send>>,
master: Option<Box<dyn MasterPty + Send>>,
child: Option<Box<dyn Child + Send + Sync>>,
- clients: Vec<(u64, UnixStream)>,
+ clients: Vec<(u64, Stream)>,
cols: u16,
rows: u16,
exit: Option<i32>,
@@ -134,26 +134,18 @@ impl State {
}
pub fn serve() -> i32 {
- unsafe {
- libc::signal(libc::SIGHUP, libc::SIG_IGN);
- }
- let path = socket_path();
- if UnixStream::connect(&path).is_ok() {
+ sys::ignore_hangup();
+ if sys::connect().is_ok() {
return 0; // already running
}
- let _ = std::fs::remove_file(&path);
- let listener = match UnixListener::bind(&path) {
- Ok(l) => l,
+ let listener = match sys::Listener::bind() {
+ Ok(l) => Arc::new(l),
Err(e) => {
- eprintln!("muxen-agent: can't listen on {}: {e}", path.display());
+ eprintln!("muxen-agent: can't listen for sessions: {e}");
return 1;
}
};
- {
- use std::os::unix::fs::PermissionsExt;
- let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
- }
- eprintln!("muxen-agent {} serving on {}", crate::VERSION, path.display());
+ eprintln!("muxen-agent {} serving sessions", crate::VERSION);
let state = Arc::new(State {
sessions: Mutex::new(Vec::new()),
events: Mutex::new(VecDeque::new()),
@@ -164,32 +156,33 @@ pub fn serve() -> i32 {
// Exit once nothing has been running or connected for a while.
let idle = state.clone();
- let sock = path.clone();
thread::spawn(move || loop {
thread::sleep(Duration::from_secs(10));
let busy = !idle.sessions.lock().unwrap().is_empty() || idle.connections.load(Ordering::Relaxed) > 0;
if busy {
*idle.last_activity.lock().unwrap() = Instant::now();
} else if idle.last_activity.lock().unwrap().elapsed() > IDLE_EXIT {
- let _ = std::fs::remove_file(&sock);
+ sys::unlisten();
std::process::exit(0);
}
});
- for stream in listener.incoming() {
- let Ok(stream) = stream else { continue };
- let state = state.clone();
+ loop {
+ let Ok(mut stream) = listener.accept() else { continue };
+ let (state, listener) = (state.clone(), listener.clone());
thread::spawn(move || {
+ if !listener.admit(&mut stream) {
+ return;
+ }
state.connections.fetch_add(1, Ordering::Relaxed);
handle(&state, stream);
state.connections.fetch_sub(1, Ordering::Relaxed);
*state.last_activity.lock().unwrap() = Instant::now();
});
}
- 0
}
-fn handle(state: &Arc<State>, mut stream: UnixStream) {
+fn handle(state: &Arc<State>, mut stream: Stream) {
let Ok(req) = proto::read_line(&mut stream) else { return };
let op = req["op"].as_str().unwrap_or("");
if op == "attach" {
@@ -241,24 +234,15 @@ fn list(state: &State) -> Value {
json!({ "sessions": sessions, "events": events, "now": now() })
}
-fn expand_home(dir: &str) -> PathBuf {
- let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/"));
- match dir.trim() {
- "" | "~" => home,
- d if d.starts_with("~/") => home.join(&d[2..]),
- d => PathBuf::from(d),
- }
-}
-
fn start(state: &Arc<State>, req: &Value) -> Result<Value, String> {
let name = str_of(req, "name").to_string();
- if name.is_empty() || name.contains('/') {
+ if name.is_empty() || name.contains('/') || name.contains('\\') {
return Err("a session needs a name without slashes".into());
}
if state.find(&name).is_some() {
return Err(format!("there's already a session called {name}"));
}
- let cwd = expand_home(str_of(req, "cwd"));
+ let cwd = sys::expand_home(str_of(req, "cwd"));
if !cwd.is_dir() {
return Err(format!("{} isn't a folder on this machine.", cwd.display()));
}
@@ -301,18 +285,26 @@ fn launch(state: &Arc<State>, s: &Arc<Session>) -> anyhow::Result<()> {
};
let pair = native_pty_system().openpty(PtySize { rows, cols, pixel_width: 0, pixel_height: 0 })?;
// The user's own shell as an interactive login shell, so the agent sees
- // the same PATH and setup as in their terminal.
+ // the same PATH and setup as in their terminal (PowerShell on Windows,
+ // with its profile).
let shell = detect::user_shell();
let mut cmd = CommandBuilder::new(&shell);
- if s.run.is_empty() {
- cmd.arg("-l");
+ if cfg!(windows) {
+ cmd.arg("-NoLogo");
+ if !s.run.is_empty() {
+ cmd.args(["-Command", s.run.as_str()]);
+ }
} else {
- cmd.args(["-l", "-i", "-c", s.run.as_str()]);
+ if s.run.is_empty() {
+ cmd.arg("-l");
+ } else {
+ cmd.args(["-l", "-i", "-c", s.run.as_str()]);
+ }
+ cmd.env("TERM", "xterm-256color");
+ cmd.env("SHELL", &shell);
}
cmd.cwd(&s.cwd);
- cmd.env("TERM", "xterm-256color");
cmd.env("COLORTERM", "truecolor");
- cmd.env("SHELL", &shell);
cmd.env("MUXEN_SESSION", &s.name);
cmd.env_remove("TMUX");
let child = pair.slave.spawn_command(cmd)?;
@@ -488,7 +480,7 @@ fn read(state: &State, req: &Value) -> Result<Value, String> {
/// Connects a client terminal: resize to it, send the current screen, then
/// stream both ways until it goes away.
-fn attach(state: &State, mut stream: UnixStream, req: &Value) {
+fn attach(state: &State, mut stream: Stream, req: &Value) {
let name = str_of(req, "name");
let Some(s) = state.find(name) else {
let _ = proto::write_line(&mut stream, &json!({ "ok": false, "error": format!("no session called {name}") }));
diff --git a/agent/src/desktop.rs b/agent/src/desktop.rs
index d957f9c..8e65b0d 100644
--- a/agent/src/desktop.rs
+++ b/agent/src/desktop.rs
@@ -15,7 +15,7 @@
//! Coordinates are in frame pixels; the screen may be scaled down to fit
//! `max_width`, and input is mapped back onto it.
-#[cfg(not(target_os = "macos"))]
+#[cfg(target_os = "linux")]
use std::path::PathBuf;
use serde_json::Value;
@@ -28,7 +28,7 @@ pub const TILES: u8 = 23;
/// DISPLAY and XAUTHORITY of this user's graphical session: our own when set,
/// else borrowed from a process in that session.
-#[cfg(not(target_os = "macos"))]
+#[cfg(target_os = "linux")]
pub fn session_env() -> Option<Vec<(String, String)>> {
let get = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());
if let Some(display) = get("DISPLAY") {
@@ -64,9 +64,9 @@ pub fn session_env() -> Option<Vec<(String, String)>> {
auth.exists().then(|| vec![("DISPLAY".into(), ":0".into()), ("XAUTHORITY".into(), auth.display().to_string())])
}
-#[cfg(target_os = "macos")]
+#[cfg(not(target_os = "linux"))]
pub fn session_env() -> Option<Vec<(String, String)>> {
- // The Mac's screen needs nothing from the environment.
+ // A Mac's or Windows' screen needs nothing from the environment.
Some(Vec::new())
}
@@ -107,11 +107,15 @@ pub fn run(args: &[String]) -> i32 {
}
}
}
- #[cfg(not(any(target_os = "linux", target_os = "macos")))]
+ #[cfg(windows)]
{
- let _ = (fps, quality, max_width, tiles, display);
- hello(&serde_json::json!({ "error": "Showing the desktop works on Linux and macOS so far." }));
- 1
+ match crate::win_screen::WinScreen::open(display) {
+ Ok(screen) => stream(screen, fps, quality as u8, max_width, tiles),
+ Err(e) => {
+ hello(&serde_json::json!({ "error": e }));
+ 1
+ }
+ }
}
}
@@ -123,7 +127,6 @@ fn hello(value: &Value) {
}
/// A screen to stream: frames of it, and input applied to it.
-#[cfg(any(target_os = "linux", target_os = "macos"))]
trait Screen {
/// Its size in the pixels `grab` returns.
fn size(&self) -> (usize, usize);
@@ -144,7 +147,6 @@ trait Screen {
}
}
-#[cfg(any(target_os = "linux", target_os = "macos"))]
mod frames {
/// How the screen maps onto the frame: frame pixel x covers source columns
/// `xs[x]..xs[x + 1]` (and the same for rows).
@@ -220,10 +222,23 @@ mod frames {
pub const TILE: usize = 64;
}
+/// Windows: GDI captures and SendInput (see win_screen.rs).
+#[cfg(windows)]
+impl Screen for crate::win_screen::WinScreen {
+ fn size(&self) -> (usize, usize) {
+ crate::win_screen::WinScreen::size(self)
+ }
+ fn grab(&mut self) -> Option<Option<&[u8]>> {
+ crate::win_screen::WinScreen::grab(self)
+ }
+ fn apply(&mut self, e: &Value, frame: (usize, usize)) {
+ crate::win_screen::WinScreen::apply(self, e, frame)
+ }
+}
+
/// Streams a screen: `tiles`, only what changed as JPEG strips (the live
/// view); otherwise the whole frame as one JPEG whenever anything changed
/// (screenshots). Input arrives on stdin as it happens.
-#[cfg(any(target_os = "linux", target_os = "macos"))]
fn stream(mut screen: impl Screen, fps: u32, quality: u8, max_width: u32, tiles: bool) -> i32 {
use std::io::Write;
use std::sync::mpsc;
diff --git a/agent/src/detect.rs b/agent/src/detect.rs
index b6f1cd3..144d264 100644
--- a/agent/src/detect.rs
+++ b/agent/src/detect.rs
@@ -1,11 +1,27 @@
//! What's installed: the user's login shell, and which agent CLIs are on the
//! PATH their interactive shell sets up (nvm, fnm, asdf live in rc files).
+#[cfg(unix)]
use std::io::Read;
+#[cfg(unix)]
use std::process::{Command, Stdio};
+#[cfg(unix)]
use std::time::{Duration, Instant};
+/// The user's shell on Windows: PowerShell 7 when it's installed, else
+/// Windows PowerShell.
+#[cfg(windows)]
+pub fn user_shell() -> String {
+ let dirs: Vec<String> = std::env::var("PATH").map(|p| p.split(';').map(String::from).collect()).unwrap_or_default();
+ let installed = dirs.iter().chain([r"C:\Program Files\PowerShell\7".to_string()].iter()).map(|d| std::path::Path::new(d).join("pwsh.exe")).find(|p| p.is_file());
+ match installed {
+ Some(p) => p.display().to_string(),
+ None => std::env::var("SystemRoot").map(|r| format!(r"{r}\System32\WindowsPowerShell\v1.0\powershell.exe")).unwrap_or_else(|_| "powershell.exe".into()),
+ }
+}
+
/// The user's login shell: $SHELL, else the password database, else /bin/sh.
+#[cfg(unix)]
pub fn user_shell() -> String {
if let Some(s) = std::env::var("SHELL").ok().filter(|s| !s.is_empty()) {
return s;
@@ -23,7 +39,14 @@ pub fn user_shell() -> String {
"/bin/sh".into()
}
+/// The PATH folders (Windows keeps the user's in the environment, no rc files).
+#[cfg(windows)]
+pub fn path_dirs() -> Vec<String> {
+ std::env::var("PATH").map(|p| p.split(';').filter(|d| !d.is_empty()).map(String::from).collect()).unwrap_or_default()
+}
+
/// The PATH an interactive login shell sets up, then this process's own.
+#[cfg(unix)]
pub fn path_dirs() -> Vec<String> {
let mut dirs: Vec<String> = interactive_path().map(|p| p.split(':').map(String::from).collect()).unwrap_or_default();
if let Ok(p) = std::env::var("PATH") {
@@ -39,17 +62,33 @@ pub fn agents(names: &[String], dirs: &[String]) -> Vec<String> {
.filter(|n| {
dirs.iter().any(|d| {
let f = std::path::Path::new(d).join(n);
- std::fs::metadata(&f).is_ok_and(|m| m.is_file() && {
- use std::os::unix::fs::PermissionsExt;
- m.permissions().mode() & 0o111 != 0
- })
+ runnable(&f)
})
})
.cloned()
.collect()
}
+/// Whether a command is there and can run (on Windows, with one of the
+/// extensions that run: claude.cmd, codex.exe, ...).
+#[cfg(unix)]
+fn runnable(f: &std::path::Path) -> bool {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::metadata(f).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
+}
+
+#[cfg(windows)]
+fn runnable(f: &std::path::Path) -> bool {
+ let exts = std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into());
+ exts.split(';').filter(|e| !e.is_empty()).chain([".ps1"]).any(|e| {
+ let mut name = f.as_os_str().to_owned();
+ name.push(e.to_ascii_lowercase());
+ std::path::Path::new(&name).is_file()
+ })
+}
+
/// Asks an interactive login shell for its PATH, giving up after a few seconds.
+#[cfg(unix)]
fn interactive_path() -> Option<String> {
let mut child = Command::new(user_shell())
.args(["-l", "-i", "-c", "printf '__OR_PATH=%s\\n' \"$PATH\""])
diff --git a/agent/src/direct.rs b/agent/src/direct.rs
index 94cd5f0..a98ace1 100644
--- a/agent/src/direct.rs
+++ b/agent/src/direct.rs
@@ -13,7 +13,6 @@
use std::collections::HashSet;
use std::io::Write;
use std::net::{Ipv6Addr, SocketAddr};
-use std::os::unix::net::UnixStream;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::{Arc, RwLock};
@@ -57,9 +56,16 @@ fn identity() -> Result<(CertificateDer<'static>, PrivateKeyDer<'static>), Strin
Ok((CertificateDer::from(cert), PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key))))
}
+/// Writes a file only this user can read (on Windows, the user's profile already is).
fn write_private(path: &PathBuf, bytes: &[u8]) -> Result<(), String> {
- use std::os::unix::fs::OpenOptionsExt;
- let mut f = std::fs::OpenOptions::new().create(true).truncate(true).write(true).mode(0o600).open(path).map_err(|e| e.to_string())?;
+ let mut options = std::fs::OpenOptions::new();
+ options.create(true).truncate(true).write(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+ let mut f = options.open(path).map_err(|e| e.to_string())?;
f.write_all(bytes).map_err(|e| e.to_string())
}
@@ -109,6 +115,7 @@ impl ClientCertVerifier for PairedApps {
/// `muxen-agent listen`: serves links over QUIC until stopped.
pub fn listen() -> i32 {
// Programs that need the logged-in session start here (see gui.rs).
+ #[cfg(unix)]
crate::gui::serve();
let runtime = match tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build() {
Ok(r) => r,
@@ -158,9 +165,18 @@ async fn accept_loop() -> Result<(), String> {
// reconnect instead of waiting for silence.
let closing = endpoint.clone();
tokio::spawn(async move {
- use tokio::signal::unix::{SignalKind, signal};
- let (Ok(mut term), Ok(mut int)) = (signal(SignalKind::terminate()), signal(SignalKind::interrupt())) else { return };
- tokio::select! { _ = term.recv() => {}, _ = int.recv() => {} }
+ #[cfg(unix)]
+ {
+ use tokio::signal::unix::{SignalKind, signal};
+ let (Ok(mut term), Ok(mut int)) = (signal(SignalKind::terminate()), signal(SignalKind::interrupt())) else { return };
+ tokio::select! { _ = term.recv() => {}, _ = int.recv() => {} }
+ }
+ #[cfg(windows)]
+ {
+ if tokio::signal::ctrl_c().await.is_err() {
+ return;
+ }
+ }
closing.close(0u32.into(), b"restarting");
let _ = tokio::time::timeout(Duration::from_millis(500), closing.wait_idle()).await;
std::process::exit(0);
@@ -193,11 +209,14 @@ fn udp_socket(addr: SocketAddr) -> std::io::Result<std::net::UdpSocket> {
}
async fn bridge(mut send: quinn::SendStream, mut recv: quinn::RecvStream) {
- let Ok((ours, theirs)) = UnixStream::pair() else { return };
+ let Ok((ours, theirs)) = stream_pair() else { return };
let Ok(theirs_out) = theirs.try_clone() else { return };
std::thread::spawn(move || crate::link::serve(Box::new(theirs), Box::new(theirs_out)));
let _ = ours.set_nonblocking(true);
+ #[cfg(unix)]
let Ok(ours) = tokio::net::UnixStream::from_std(ours) else { return };
+ #[cfg(windows)]
+ let Ok(ours) = tokio::net::TcpStream::from_std(ours) else { return };
let (mut from_link, mut to_link) = ours.into_split();
// The app's side ending (closed, or gone quiet past the idle timeout) ends
// the link's input too, so it lets go of what the connection had open
@@ -216,6 +235,27 @@ async fn bridge(mut send: quinn::SendStream, mut recv: quinn::RecvStream) {
let _ = tokio::join!(up, down);
}
+/// Two connected streams: one for the QUIC side, one for the link.
+#[cfg(unix)]
+fn stream_pair() -> std::io::Result<(std::os::unix::net::UnixStream, std::os::unix::net::UnixStream)> {
+ std::os::unix::net::UnixStream::pair()
+}
+
+/// Windows has no socket pairs: a loopback connection, taking only the one we made.
+#[cfg(windows)]
+fn stream_pair() -> std::io::Result<(std::net::TcpStream, std::net::TcpStream)> {
+ let listener = std::net::TcpListener::bind(("127.0.0.1", 0))?;
+ let ours = std::net::TcpStream::connect(listener.local_addr()?)?;
+ loop {
+ let (theirs, from) = listener.accept()?;
+ if from == ours.local_addr()? {
+ let _ = ours.set_nodelay(true);
+ let _ = theirs.set_nodelay(true);
+ return Ok((ours, theirs));
+ }
+ }
+}
+
/// `{"op": "pair", "client": "<app fingerprint>"}` on a link (so over ssh):
/// trusts the app, makes sure `listen` runs as a service, and says how to
/// reach it.
@@ -253,7 +293,35 @@ pub fn tailnet_addresses() -> Vec<String> {
addresses().1
}
+/// (local network, tailnet) addresses, as Windows lists them.
+#[cfg(windows)]
+fn addresses() -> (Vec<String>, Vec<String>) {
+ let (mut lan, mut tailnet) = (Vec::new(), Vec::new());
+ let rows = crate::win::ps_json("Get-NetIPAddress -AddressState Preferred | Where-Object { $_.InterfaceAlias -notmatch 'Loopback' } | Select-Object IPAddress, InterfaceAlias | ConvertTo-Json -Compress").unwrap_or_default();
+ for r in rows {
+ let (Some(ip), alias) = (r["IPAddress"].as_str().and_then(|a| a.parse::<std::net::IpAddr>().ok()), r["InterfaceAlias"].as_str().unwrap_or("")) else { continue };
+ if is_tailnet(ip) && (alias.contains("Tailscale") || ip.is_ipv6()) {
+ if !tailnet.contains(&ip.to_string()) {
+ tailnet.push(ip.to_string());
+ }
+ continue;
+ }
+ // Not WSL's, Hyper-V's or Docker's virtual switches, nor VPNs.
+ if ["vEthernet", "WSL", "Docker", "Hyper-V", "VirtualBox", "VMware", "Tailscale", "ZeroTier", "WireGuard"].iter().any(|p| alias.contains(p)) {
+ continue;
+ }
+ if let std::net::IpAddr::V4(v4) = ip {
+ if v4.is_private() && !lan.contains(&v4.to_string()) {
+ lan.push(v4.to_string());
+ }
+ }
+ }
+ tailnet.sort_by_key(|a| a.contains(':'));
+ (lan, tailnet)
+}
+
/// (local network, tailnet) addresses.
+#[cfg(unix)]
fn addresses() -> (Vec<String>, Vec<String>) {
let (mut lan, mut tailnet) = (Vec::new(), Vec::new());
unsafe {
@@ -318,7 +386,10 @@ fn is_tailnet(ip: std::net::IpAddr) -> bool {
/// from before the rename (OpenRunner) becomes Muxen's, and an installed one
/// is brought up to date.
pub fn migrate() -> i32 {
- let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
+ if cfg!(windows) {
+ return 0;
+ }
+ let home = crate::sys::user_home();
let old_unit = home.join(".config/systemd/user/openrunner-agent.service");
let old_plist = home.join("Library/LaunchAgents/com.lumarylabs.openrunner-agent.plist");
if old_unit.exists() {
@@ -326,8 +397,7 @@ pub fn migrate() -> i32 {
let _ = std::fs::remove_file(&old_unit);
let _ = run("systemctl", &["--user", "daemon-reload"]);
} else if old_plist.exists() {
- let uid = unsafe { libc::getuid() };
- let _ = run("launchctl", &["bootout", &format!("gui/{uid}/com.lumarylabs.openrunner-agent")]);
+ let _ = run("launchctl", &["bootout", &format!("gui/{}/com.lumarylabs.openrunner-agent", uid())]);
let _ = std::fs::remove_file(&old_plist);
} else {
refresh_unit();
@@ -346,6 +416,18 @@ pub fn unpair() -> Value {
json!({ "ok": true })
}
+/// This user's id (launchd's domains are by user).
+fn uid() -> u32 {
+ #[cfg(unix)]
+ {
+ unsafe { libc::getuid() }
+ }
+ #[cfg(not(unix))]
+ {
+ 0
+ }
+}
+
fn run(program: &str, args: &[&str]) -> bool {
Command::new(program).args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).status().is_ok_and(|s| s.success())
}
@@ -368,6 +450,9 @@ fn systemd_unit() -> String {
/// restart after an update already leaves sessions alone.
fn refresh_unit() {
let Ok(home) = std::env::var("HOME") else { return };
+ if cfg!(windows) {
+ return;
+ }
let path = PathBuf::from(home).join(format!(".config/systemd/user/{SERVICE}.service"));
let Ok(current) = std::fs::read_to_string(&path) else { return };
let wanted = systemd_unit();
@@ -378,12 +463,49 @@ fn refresh_unit() {
/// Starts the background service (installing it when needed), for what has
/// to run in the logged-in session (see gui.rs).
+#[cfg_attr(windows, allow(dead_code))]
pub fn start_service() {
let _ = install_service();
}
+/// The scheduled task that runs `listen` on Windows.
+#[cfg(windows)]
+const TASK: &str = "Muxen agent";
+
/// Runs `listen` as a service of this user: (how, a note when it couldn't).
fn install_service() -> (&'static str, Option<String>) {
+ #[cfg(windows)]
+ {
+ // A task at sign-in, in the user's own desktop session (where the
+ // screen and clipboard are), started now too; and a way in through
+ // Windows' firewall for the agent (administrators only).
+ let script = format!(
+ "$exe = {exe}\n\
+ $action = New-ScheduledTaskAction -Execute $exe -Argument 'listen'\n\
+ $trigger = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME\n\
+ $principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive -RunLevel Limited\n\
+ $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -MultipleInstances IgnoreNew\n\
+ Register-ScheduledTask -TaskName {task} -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null\n\
+ try {{ Remove-NetFirewallRule -DisplayName {task} -ErrorAction SilentlyContinue; New-NetFirewallRule -DisplayName {task} -Direction Inbound -Program $exe -Protocol UDP -Action Allow -Profile Any -ErrorAction Stop | Out-Null; $fw = 'yes' }} catch {{ $fw = 'no' }}\n\
+ Get-CimInstance Win32_Process -Filter \"Name='muxen-agent.exe'\" | Where-Object {{ $_.CommandLine -match ' listen' }} | ForEach-Object {{ Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }}\n\
+ Start-ScheduledTask -TaskName {task}\n\
+ Start-Sleep -Milliseconds 800\n\
+ $running = @(Get-CimInstance Win32_Process -Filter \"Name='muxen-agent.exe'\" | Where-Object {{ $_.CommandLine -match ' listen' }}).Count -gt 0\n\
+ \"fw=$fw running=$running\"",
+ exe = crate::win::quote(&exe()),
+ task = crate::win::quote(TASK)
+ );
+ return match crate::win::ps(&script) {
+ Ok(out) if out.contains("running=True") => ("task", (!out.contains("fw=yes")).then(|| "Windows' firewall may block it: allow muxen-agent.exe, or pair as an administrator".to_string())),
+ // Nobody signed in to the desktop: the task waits for that; meanwhile, run it until restart.
+ Ok(_) => match crate::sys::spawn_background(&["listen"], dir().join("listen.log")) {
+ Ok(()) => ("task", Some("starts when you sign in to Windows; running now until then".into())),
+ Err(e) => ("none", Some(format!("couldn't start it: {e}"))),
+ },
+ Err(e) => ("none", Some(format!("couldn't set up the task: {e}"))),
+ };
+ }
+ #[allow(unreachable_code)]
let home = std::env::var("HOME").unwrap_or_default();
if cfg!(target_os = "macos") {
let plist_dir = PathBuf::from(&home).join("Library/LaunchAgents");
@@ -407,8 +529,7 @@ fn install_service() -> (&'static str, Option<String>) {
if std::fs::write(&plist, body).is_err() {
return ("none", Some("couldn't write the launchd agent".into()));
}
- let uid = unsafe { libc::getuid() };
- let domain = format!("gui/{uid}");
+ let domain = format!("gui/{}", uid());
let _ = run("launchctl", &["bootout", &format!("{domain}/{LAUNCHD_LABEL}")]);
if run("launchctl", &["bootstrap", &domain, &plist.display().to_string()]) {
return ("launchd", None);
@@ -425,30 +546,25 @@ fn install_service() -> (&'static str, Option<String>) {
}
}
// No service manager for this user: run it in the background until reboot.
- let spawned = {
- use std::os::unix::process::CommandExt;
- let log = std::fs::OpenOptions::new().create(true).append(true).open(dir().join("listen.log"));
- let mut cmd = Command::new(exe());
- cmd.arg("listen").stdin(Stdio::null()).stdout(Stdio::null());
- if let Ok(l) = log {
- cmd.stderr(l);
- }
- unsafe {
- cmd.pre_exec(|| {
- libc::setsid();
- Ok(())
- });
- }
- cmd.spawn().is_ok()
- };
+ let spawned = crate::sys::spawn_background(&["listen"], dir().join("listen.log")).is_ok();
if spawned { ("background", Some("runs until the machine restarts".into())) } else { ("none", Some("couldn't start it".into())) }
}
fn remove_service() {
+ #[cfg(windows)]
+ {
+ let task = crate::win::quote(TASK);
+ let _ = crate::win::ps(&format!(
+ "Unregister-ScheduledTask -TaskName {task} -Confirm:$false -ErrorAction SilentlyContinue\n\
+ Remove-NetFirewallRule -DisplayName {task} -ErrorAction SilentlyContinue\n\
+ Get-CimInstance Win32_Process -Filter \"Name='muxen-agent.exe'\" | Where-Object {{ $_.CommandLine -match ' listen' }} | ForEach-Object {{ Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }}"
+ ));
+ return;
+ }
+ #[allow(unreachable_code)]
let home = std::env::var("HOME").unwrap_or_default();
if cfg!(target_os = "macos") {
- let uid = unsafe { libc::getuid() };
- let _ = run("launchctl", &["bootout", &format!("gui/{uid}/{LAUNCHD_LABEL}")]);
+ let _ = run("launchctl", &["bootout", &format!("gui/{}/{LAUNCHD_LABEL}", uid())]);
let _ = std::fs::remove_file(PathBuf::from(&home).join(format!("Library/LaunchAgents/{LAUNCHD_LABEL}.plist")));
} else {
let _ = run("systemctl", &["--user", "disable", "--now", &format!("{SERVICE}.service")]);
diff --git a/agent/src/files.rs b/agent/src/files.rs
index 4b6307c..b571fda 100644
--- a/agent/src/files.rs
+++ b/agent/src/files.rs
@@ -29,12 +29,7 @@ const WINDOW: u64 = 8 << 20;
const MAX_ENTRIES: usize = 5000;
pub fn expand_home(path: &str) -> PathBuf {
- let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/"));
- match path.trim() {
- "" | "~" => home,
- p if p.starts_with("~/") => home.join(&p[2..]),
- p => PathBuf::from(p),
- }
+ crate::sys::expand_home(path)
}
/// `{"op": "files", "path": "~/x"}`: what's in a folder, folders first.
@@ -154,7 +149,7 @@ pub fn pack(req: &Value, send: Send) -> Result<(Value, Arc<Credit>), String> {
let channel = req["channel"].as_u64().unwrap_or(0) as u32;
let dir = expand_home(req["dir"].as_str().unwrap_or("~"));
let names: Vec<String> = req["names"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default();
- if names.is_empty() || names.iter().any(|n| n.is_empty() || n.contains('/') || n == "." || n == "..") {
+ if names.is_empty() || names.iter().any(|n| n.is_empty() || n.contains('/') || n.contains('\\') || n == "." || n == "..") {
return Err("Name the files and folders to copy (inside the folder, without slashes).".into());
}
if let Some(missing) = names.iter().find(|n| dir.join(n).symlink_metadata().is_err()) {
@@ -299,9 +294,7 @@ fn finish(child: &mut Child, failed: Option<String>, errors: &Arc<Mutex<String>>
}
pub fn kill(pid: u32) {
- unsafe {
- libc::kill(pid as i32, libc::SIGTERM);
- }
+ crate::sys::kill_one(pid, true);
}
#[cfg(test)]
diff --git a/agent/src/gui.rs b/agent/src/gui.rs
index 82b43bd..76957ba 100644
--- a/agent/src/gui.rs
+++ b/agent/src/gui.rs
@@ -6,24 +6,32 @@
//! Mac's Local Network privacy doesn't come into it.
use std::io::{self, Read, Write};
+#[cfg(unix)]
use std::os::unix::net::{UnixListener, UnixStream};
+#[cfg(unix)]
use std::path::PathBuf;
+#[cfg(unix)]
use std::process::{Command, Stdio};
+#[cfg(unix)]
use std::thread;
+#[cfg(unix)]
use std::time::{Duration, Instant};
use serde_json::{Value, json};
+#[cfg(unix)]
fn socket() -> PathBuf {
crate::home_dir().join("gui.sock")
}
+#[cfg(unix)]
/// Whether programs that need the desktop session must be started by the
/// background service: a Mac, from a link that came in over ssh.
pub fn needed() -> bool {
cfg!(target_os = "macos") && std::env::var_os("SSH_CONNECTION").is_some()
}
+#[cfg(unix)]
/// Serves the socket from the background service, on a thread of its own.
pub fn serve() {
let path = socket();
@@ -46,6 +54,7 @@ pub fn serve() {
});
}
+#[cfg(unix)]
/// One connection: `{"run": ["screen", ...]}`, then the program's stdin and
/// stdout are the connection, until either side closes.
fn run(mut conn: UnixStream) {
@@ -87,6 +96,7 @@ fn run(mut conn: UnixStream) {
let _ = child.wait();
}
+#[cfg(unix)]
/// Runs a program in the logged-in session (see `needed`): its stdin and
/// stdout, as a socket. Starts the background service when it isn't running.
pub fn connect(args: &[String]) -> Result<UnixStream, String> {
diff --git a/agent/src/link.rs b/agent/src/link.rs
index 834a0cb..1ccf78d 100644
--- a/agent/src/link.rs
+++ b/agent/src/link.rs
@@ -17,8 +17,6 @@
use std::collections::HashMap;
use std::io::{self, BufWriter, Read, Write};
-use std::os::unix::net::UnixStream;
-use std::os::unix::process::CommandExt;
use std::process::{Command, Stdio};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
@@ -27,7 +25,8 @@ use std::time::{Duration, Instant};
use serde_json::{Value, json};
-use crate::{client, detect, now, proto, socket_path};
+use crate::sys::{self, Stream};
+use crate::{client, detect, now, proto};
/// Channel 0: requests, replies and events.
pub const CONTROL: u32 = 0;
@@ -71,7 +70,7 @@ fn read_frame(r: &mut impl Read) -> io::Result<(u32, u8, Vec<u8>)> {
/// What a channel is connected to.
enum Sink {
/// A terminal attached to a session (the session server connection).
- Session(UnixStream),
+ Session(Stream),
/// The desktop: a `screen` program (its stdin takes input).
Desktop(Program),
/// Files going out (a tar stream; ACKs let more through).
@@ -105,7 +104,7 @@ impl Sink {
}
Sink::Logs(mut child) => {
// Its whole process group (`log stream` runs under a shell).
- unsafe { libc::kill(-(child.id() as i32), libc::SIGTERM) };
+ sys::kill_tree(child.id(), true);
let _ = child.kill();
let _ = child.wait();
}
@@ -116,7 +115,8 @@ impl Sink {
type Attached = Arc<Mutex<HashMap<u32, Sink>>>;
/// A program run for a channel (`screen`, `clip`): here, or in the logged-in
-/// session through the background service (see gui.rs).
+/// session through the background service (see gui.rs), or on Windows
+/// through a scheduled task (see win_screen.rs).
struct Program {
input: Box<dyn Write + Send>,
stop: Stop,
@@ -124,14 +124,21 @@ struct Program {
enum Stop {
Child(std::process::Child),
+ #[cfg(unix)]
Socket(std::os::unix::net::UnixStream),
+ #[cfg(windows)]
+ Socket(std::net::TcpStream),
}
impl Program {
/// Starts `muxen-agent <args>`; returns it and what it prints.
fn start(args: &[String], env: Vec<(String, String)>) -> Result<(Program, Box<dyn Read + Send>), String> {
- if crate::gui::needed() {
- let stream = crate::gui::connect(args)?;
+ #[cfg(unix)]
+ let elsewhere = crate::gui::needed().then(|| crate::gui::connect(args));
+ #[cfg(windows)]
+ let elsewhere = (!crate::win_screen::in_desktop_session()).then(|| crate::win_screen::start_in_desktop(args));
+ if let Some(stream) = elsewhere {
+ let stream = stream?;
let reader = stream.try_clone().map_err(|e| e.to_string())?;
let writer = stream.try_clone().map_err(|e| e.to_string())?;
return Ok((Program { input: Box::new(writer), stop: Stop::Socket(stream) }, Box::new(reader)));
@@ -140,6 +147,7 @@ impl Program {
let log = std::fs::OpenOptions::new().create(true).append(true).open(crate::home_dir().join("screen.log"));
let mut cmd = Command::new(exe);
cmd.args(args).envs(env).stdin(Stdio::piped()).stdout(Stdio::piped());
+ sys::no_window(&mut cmd);
match log {
Ok(l) => cmd.stderr(l),
Err(_) => cmd.stderr(Stdio::null()),
@@ -266,25 +274,29 @@ fn run_script(req: &Value) -> Value {
let timeout = Duration::from_secs(req["timeout"].as_u64().unwrap_or(120).clamp(1, 3600));
let login = req["login"].as_bool().unwrap_or(true);
let shell = detect::user_shell();
- let name = shell.rsplit('/').next().unwrap_or("");
- let program = if login && ["bash", "zsh", "sh", "ksh", "dash"].contains(&name) { shell.clone() } else { "/bin/sh".to_string() };
- let mut cmd = Command::new(program);
- cmd.args(if login { &["-l", "-s"][..] } else { &["-s"][..] }).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
- if let Some(home) = std::env::var_os("HOME") {
- cmd.current_dir(home);
- }
+ let mut cmd = if cfg!(windows) {
+ // PowerShell reads the whole script, then runs it (with the user's profile unless `login` is off).
+ let mut c = Command::new(&shell);
+ if !login {
+ c.arg("-NoProfile");
+ }
+ c.args(["-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", "[Console]::In.ReadToEnd() | Invoke-Expression"]);
+ c
+ } else {
+ let name = shell.rsplit('/').next().unwrap_or("");
+ let program = if login && ["bash", "zsh", "sh", "ksh", "dash"].contains(&name) { shell.clone() } else { "/bin/sh".to_string() };
+ let mut c = Command::new(program);
+ c.args(if login { &["-l", "-s"][..] } else { &["-s"][..] });
+ c
+ };
+ cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).current_dir(sys::user_home());
// Its own process group, so a timeout takes down whatever it started.
- unsafe {
- cmd.pre_exec(|| {
- libc::setsid();
- Ok(())
- });
- }
+ sys::own_group(&mut cmd);
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(e) => return json!({ "ok": false, "error": format!("couldn't start a shell: {e}") }),
};
- let pid = child.id() as i32;
+ let pid = child.id();
if let Some(mut stdin) = child.stdin.take() {
thread::spawn(move || {
let _ = stdin.write_all(script.as_bytes());
@@ -320,9 +332,7 @@ fn run_script(req: &Value) -> Value {
Ok(None) if started.elapsed() < timeout => thread::sleep(Duration::from_millis(5)),
_ => {
timed_out = true;
- unsafe {
- libc::kill(-pid, libc::SIGKILL);
- }
+ sys::kill_tree(pid, false);
let _ = child.wait();
break None;
}
@@ -340,7 +350,7 @@ fn attach(req: &Value, out: &Out, attached: &Attached) -> Value {
if channel == CONTROL {
return json!({ "ok": false, "error": "attach needs a channel" });
}
- let mut stream = match UnixStream::connect(socket_path()) {
+ let mut stream = match sys::connect() {
Ok(s) => s,
Err(_) => return json!({ "ok": false, "error": "no sessions are running on this machine" }),
};
@@ -441,12 +451,7 @@ fn logs(req: &Value, out: &Out, attached: &Attached) -> Value {
};
let mut cmd = Command::new(&program);
cmd.args(&args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
- unsafe {
- cmd.pre_exec(|| {
- libc::setsid();
- Ok(())
- });
- }
+ sys::own_group(&mut cmd);
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(e) => return json!({ "ok": false, "error": format!("couldn't run {program}: {e}") }),
@@ -635,7 +640,7 @@ fn watch(out: Out) {
let mut last = String::new();
loop {
let now = now();
- let signature = match UnixStream::connect(socket_path()) {
+ let signature = match sys::connect() {
Err(_) => "no server".to_string(),
Ok(mut s) => {
let list = proto::write_line(&mut s, &json!({ "op": "list" })).and_then(|_| proto::read_line(&mut s)).unwrap_or(Value::Null);
@@ -674,8 +679,10 @@ mod tests {
f
}
+ #[cfg(unix)]
#[test]
fn answers_requests_and_runs_scripts() {
+ use std::os::unix::net::UnixStream;
let (mut app, agent) = UnixStream::pair().unwrap();
let agent_out = agent.try_clone().unwrap();
let server = thread::spawn(move || serve(Box::new(agent), Box::new(agent_out)));
diff --git a/agent/src/logs.rs b/agent/src/logs.rs
index 42bfe81..14103fb 100644
--- a/agent/src/logs.rs
+++ b/agent/src/logs.rs
@@ -24,6 +24,19 @@ const MAX_LINES: u64 = 5000;
/// `{"op": "log_sources"}`: what there is to read here.
pub fn sources() -> Value {
+ if cfg!(windows) {
+ let (docker, docker_note) = containers();
+ return json!({
+ "ok": true,
+ "system": crate::win::event_logs(),
+ "system_note": Value::Null,
+ "files": files(),
+ "docker": docker,
+ "docker_note": docker_note,
+ "services": crate::win::service_sources(),
+ "services_note": "A service's events from Windows' System and Application logs.",
+ });
+ }
let mac = cfg!(target_os = "macos");
let journal = !mac && which("journalctl");
let mut system = Vec::new();
@@ -75,7 +88,7 @@ pub(crate) fn quick(program: &str, args: &[&str]) -> Option<String> {
}
fn journal_groups() -> bool {
- let root = unsafe { libc::getuid() } == 0;
+ let root = crate::sys::is_root();
root || quick("id", &["-Gn"]).is_some_and(|g| g.split_whitespace().any(|g| ["systemd-journal", "adm", "wheel", "sudo"].contains(&g)))
}
@@ -155,7 +168,7 @@ fn containers() -> (Vec<Value>, Option<String>) {
/// Log files worth offering: the usual places, and ones written lately under
/// the home folder (an app's storage/logs, a runner's _diag), newest first.
fn files() -> Vec<Value> {
- let home = std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default());
+ let home = crate::sys::user_home();
let mut found: Vec<std::path::PathBuf> = Vec::new();
// A big home folder takes long to look through: a couple of seconds at most.
let deadline = Instant::now() + Duration::from_secs(2);
@@ -168,7 +181,11 @@ fn files() -> Vec<Value> {
}
});
};
- add_dir(std::path::Path::new("/var/log"), 2, false);
+ if cfg!(windows) {
+ add_dir(&std::path::PathBuf::from(std::env::var("ProgramData").unwrap_or_else(|_| r"C:\ProgramData".into())), 3, true);
+ } else {
+ add_dir(std::path::Path::new("/var/log"), 2, false);
+ }
add_dir(&home.join(".muxen"), 1, false);
if cfg!(target_os = "macos") {
add_dir(&home.join("Library/Logs"), 3, true);
@@ -181,7 +198,7 @@ fn files() -> Vec<Value> {
let meta = std::fs::metadata(&p).ok()?;
let modified = meta.modified().ok()?;
let readable = std::fs::File::open(&p).is_ok();
- let shown = p.strip_prefix(&home).map(|r| format!("~/{}", r.display())).unwrap_or_else(|_| p.display().to_string());
+ let shown = p.strip_prefix(&home).map(|r| format!("~{}{}", std::path::MAIN_SEPARATOR, r.display())).unwrap_or_else(|_| p.display().to_string());
let name = p.file_name()?.to_string_lossy().into_owned();
Some((modified, json!({ "kind": "file", "target": p.display().to_string(), "name": name, "detail": shown, "size": meta.len(), "modified": modified.duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0), "readable": readable })))
})
@@ -224,6 +241,10 @@ pub fn command(source: &Value, lines: u64, follow: bool) -> Result<(String, Vec<
let target = source["target"].as_str().unwrap_or("").to_string();
let s = |v: &str| v.to_string();
let mac = cfg!(target_os = "macos");
+ if cfg!(windows) && matches!(source["kind"].as_str(), Some("system" | "kernel" | "service" | "file")) {
+ let script = crate::win::log_script(source["kind"].as_str().unwrap_or(""), &target, lines.parse().unwrap_or(500), follow)?;
+ return Ok(crate::win::log_command(script));
+ }
let journal = |extra: Vec<String>| {
let mut args = vec![s("--no-pager"), s("-o"), s("short-iso"), s("-n"), lines.clone()];
args.extend(extra);
diff --git a/agent/src/main.rs b/agent/src/main.rs
index 5c67891..2b0f37c 100644
--- a/agent/src/main.rs
+++ b/agent/src/main.rs
@@ -14,15 +14,10 @@
//! muxen-agent serve the session server (started on demand)
//! ```
-#[cfg(unix)]
mod client;
-#[cfg(unix)]
mod clipboard;
-#[cfg(unix)]
mod daemon;
-#[cfg(unix)]
mod detect;
-#[cfg(unix)]
mod desktop;
#[cfg(unix)]
mod displays;
@@ -33,20 +28,18 @@ mod usage;
mod wake;
mod root;
mod services;
-#[cfg(unix)]
mod direct;
-#[cfg(unix)]
mod files;
-#[cfg(unix)]
mod gui;
-#[cfg(unix)]
mod link;
-#[cfg(unix)]
mod proto;
-#[cfg(unix)]
mod repos;
-#[cfg(unix)]
mod screen;
+mod sys;
+#[cfg_attr(not(windows), allow(dead_code))]
+mod win;
+#[cfg(windows)]
+mod win_screen;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
@@ -64,29 +57,29 @@ fn main() {
println!("{}", self_hash());
0
}
- #[cfg(unix)]
Some("ctl") => client::ctl(),
- #[cfg(unix)]
Some("link") => link::run(),
- #[cfg(unix)]
Some("listen") => direct::listen(),
- #[cfg(unix)]
Some("migrate") => direct::migrate(),
- #[cfg(unix)]
Some("screen") => desktop::run(&args[1..]),
#[cfg(unix)]
Some("displays") => displays::run_list(),
+ #[cfg(windows)]
+ Some("displays") => {
+ println!("{}", win_screen::displays());
+ 0
+ }
+ #[cfg(windows)]
+ Some("gui-serve") => win_screen::gui_serve(),
#[cfg(target_os = "macos")]
Some("vdisplay") => displays::run_holder(&args[1..]),
#[cfg(target_os = "macos")]
Some("display-mode") => displays::run_mode(&args[1..]),
Some("clip") => clipboard::run(),
- #[cfg(unix)]
Some("attach") => match args.get(1) {
Some(name) => client::attach(name),
None => usage(),
},
- #[cfg(unix)]
Some("serve") => daemon::serve(),
_ => usage(),
};
@@ -116,8 +109,7 @@ pub fn fnv(bytes: &[u8]) -> u64 {
/// `~/.muxen`, private to the user.
pub fn home_dir() -> PathBuf {
- let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/tmp"));
- let dir = home.join(".muxen");
+ let dir = sys::user_home().join(".muxen");
let _ = std::fs::create_dir_all(&dir);
#[cfg(unix)]
{
@@ -129,6 +121,8 @@ pub fn home_dir() -> PathBuf {
/// The session server's socket: `~/.muxen/agent.sock`, or a private
/// folder under /tmp when the home path is too long for a Unix socket.
+/// (Windows: see sys.rs.)
+#[cfg(unix)]
pub fn socket_path() -> PathBuf {
let path = home_dir().join("agent.sock");
if path.as_os_str().len() < 100 {
diff --git a/agent/src/ports.rs b/agent/src/ports.rs
index 88b574b..e80de62 100644
--- a/agent/src/ports.rs
+++ b/agent/src/ports.rs
@@ -32,7 +32,7 @@ struct Listening {
/// `{"op": "ports"}`: the TCP ports something listens on, web servers first.
pub fn list() -> Value {
- let found = if cfg!(target_os = "macos") { lsof() } else { ss() };
+ let found = listeners();
// One entry a port (IPv4 and IPv6 are usually both there), the one with a name.
let mut by_port: HashMap<u16, Listening> = HashMap::new();
for l in found {
@@ -88,13 +88,24 @@ pub fn list() -> Value {
/// `{"op": "listening"}`: just the port numbers something listens on (no
/// asking around: cheap enough to look every few seconds).
pub fn listening() -> Value {
- let found = if cfg!(target_os = "macos") { lsof() } else { ss() };
+ let found = listeners();
let mut ports: Vec<u16> = found.into_iter().map(|l| l.port).collect();
ports.sort_unstable();
ports.dedup();
json!({ "ok": true, "ports": ports })
}
+/// What listens here, by the system's own tool.
+fn listeners() -> Vec<Listening> {
+ if cfg!(windows) {
+ crate::win::listening().into_iter().map(|(port, address, process, pid)| Listening { port, address, process, pid }).collect()
+ } else if cfg!(target_os = "macos") {
+ lsof()
+ } else {
+ ss()
+ }
+}
+
/// Where to connect for a port listening on `address`: itself, or this
/// machine for one listening everywhere.
fn connect_host(address: &str) -> String {
diff --git a/agent/src/procs.rs b/agent/src/procs.rs
index 34d3318..eee8860 100644
--- a/agent/src/procs.rs
+++ b/agent/src/procs.rs
@@ -9,13 +9,34 @@ use std::collections::HashMap;
use serde_json::{Value, json};
use crate::logs::quick;
-use crate::root::{as_root, tool};
+#[cfg(unix)]
+use crate::root::as_root;
+use crate::root::tool;
/// Processes sent back: the busiest.
const MOST: usize = 300;
/// `{"op": "processes"}`: processes (busiest first) and GPUs.
pub fn list() -> Value {
+ #[cfg(windows)]
+ {
+ let mut procs = match crate::win::processes() {
+ Ok(p) => p,
+ Err(e) => return json!({ "ok": false, "error": e }),
+ };
+ let gpu_mem = nvidia_apps();
+ for p in &mut procs {
+ if let Some(m) = p["pid"].as_u64().and_then(|pid| gpu_mem.get(&(pid as u32))) {
+ p["gpu_memory"] = json!(m);
+ }
+ }
+ let total = procs.len();
+ procs.sort_by(|a, b| b["cpu"].as_f64().unwrap_or(0.).total_cmp(&a["cpu"].as_f64().unwrap_or(0.)).then(b["memory"].as_u64().cmp(&a["memory"].as_u64())));
+ procs.truncate(MOST);
+ let cores = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
+ return json!({ "ok": true, "processes": procs, "total": total, "cores": cores, "gpus": gpus() });
+ }
+ #[allow(unreachable_code)]
let me = std::env::var("USER").or_else(|_| std::env::var("LOGNAME")).unwrap_or_default();
let gpu_mem = nvidia_apps();
let mut procs = ps();
@@ -125,6 +146,9 @@ pub fn gpus() -> Vec<Value> {
if cfg!(target_os = "macos") {
out.extend(apple());
}
+ if cfg!(windows) {
+ out.extend(crate::win::gpus());
+ }
out
}
@@ -176,13 +200,33 @@ pub fn signal(req: &Value) -> Value {
let Some(pid) = req["pid"].as_u64().filter(|p| *p > 1).map(|p| p as i32) else {
return json!({ "ok": false, "error": "Which process?" });
};
+ if pid as u32 == std::process::id() {
+ return json!({ "ok": false, "error": "That's Muxen's agent itself." });
+ }
+ #[cfg(windows)]
+ {
+ // Windows has no polite stop for a program without a window: both end it.
+ let out = crate::sys::no_window(std::process::Command::new("taskkill").args(["/F", "/PID", &pid.to_string()])).output();
+ return match out {
+ Ok(o) if o.status.success() => json!({ "ok": true }),
+ Ok(o) => {
+ let text = String::from_utf8_lossy(&o.stderr).trim().to_string();
+ let error = if text.contains("not found") { "It has already ended.".to_string() } else if text.is_empty() { "Windows didn't end it.".to_string() } else { text };
+ json!({ "ok": false, "error": error })
+ }
+ Err(e) => json!({ "ok": false, "error": e.to_string() }),
+ };
+ }
+ #[cfg(unix)]
+ signal_unix(req, pid)
+}
+
+#[cfg(unix)]
+fn signal_unix(req: &Value, pid: i32) -> Value {
let (sig, name) = match req["signal"].as_str().unwrap_or("TERM") {
"KILL" => (libc::SIGKILL, "KILL"),
_ => (libc::SIGTERM, "TERM"),
};
- if pid as u32 == std::process::id() {
- return json!({ "ok": false, "error": "That's Muxen's agent itself." });
- }
if unsafe { libc::kill(pid, sig) } == 0 {
return json!({ "ok": true });
}
diff --git a/agent/src/repos.rs b/agent/src/repos.rs
index e0a6179..4901543 100644
--- a/agent/src/repos.rs
+++ b/agent/src/repos.rs
@@ -18,7 +18,7 @@ const SKIP: &[&str] = &[
const MAX_REPOS: usize = 300;
fn home() -> PathBuf {
- std::env::var_os("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/"))
+ crate::sys::user_home()
}
fn expand(dir: &str) -> PathBuf {
@@ -163,9 +163,7 @@ fn run_with_timeout(cmd: &mut Command, limit: Duration) -> Result<(bool, String,
return Ok((out.status.success(), String::from_utf8_lossy(&out.stdout).into_owned(), String::from_utf8_lossy(&out.stderr).into_owned()));
}
if started.elapsed() > limit {
- unsafe {
- libc::kill(id as i32, libc::SIGKILL);
- }
+ crate::sys::kill_one(id, false);
return Err(format!("timed out after {}s", limit.as_secs()));
}
thread::sleep(Duration::from_millis(50));
diff --git a/agent/src/root.rs b/agent/src/root.rs
index 1770a92..018dfe7 100644
--- a/agent/src/root.rs
+++ b/agent/src/root.rs
@@ -56,9 +56,17 @@ fn last_line(text: &str) -> String {
/// and snap put them (the agent's background service starts with a bare PATH).
pub fn tool(name: &str) -> Option<String> {
let path = std::env::var("PATH").unwrap_or_default();
- let dirs = path.split(':').map(str::to_string).chain(["/opt/homebrew/bin", "/usr/local/bin", "/home/linuxbrew/.linuxbrew/bin", "/snap/bin", "/usr/bin", "/bin"].map(String::from));
- for dir in dirs.filter(|d| !d.is_empty()) {
- let p = std::path::Path::new(&dir).join(name);
+ #[cfg(windows)]
+ let (dirs, file): (Vec<String>, String) = {
+ let program_files = std::env::var("ProgramFiles").unwrap_or_else(|_| r"C:\Program Files".into());
+ let extra = [format!(r"{program_files}\Docker\Docker\resources\bin"), format!(r"{program_files}\NVIDIA Corporation\NVSMI")];
+ (path.split(';').map(str::to_string).chain(extra).collect(), format!("{name}.exe"))
+ };
+ #[cfg(not(windows))]
+ let (dirs, file): (Vec<String>, String) =
+ (path.split(':').map(str::to_string).chain(["/opt/homebrew/bin", "/usr/local/bin", "/home/linuxbrew/.linuxbrew/bin", "/snap/bin", "/usr/bin", "/bin"].map(String::from)).collect(), name.to_string());
+ for dir in dirs.iter().filter(|d| !d.is_empty()) {
+ let p = std::path::Path::new(dir).join(&file);
if std::fs::metadata(&p).is_ok_and(|m| m.is_file()) {
return Some(p.display().to_string());
}
diff --git a/agent/src/services.rs b/agent/src/services.rs
index 1b5975c..313eee6 100644
--- a/agent/src/services.rs
+++ b/agent/src/services.rs
@@ -22,7 +22,7 @@ pub fn list(req: &Value) -> Value {
// of seconds): `"stats": false` answers at once without it.
let stats = req["stats"].as_bool() != Some(false);
let ((services, services_note), (containers, containers_note), images, compose) = std::thread::scope(|scope| {
- let svc = scope.spawn(|| if mac { brew(stats) } else { systemd(stats) });
+ let svc = scope.spawn(|| if cfg!(windows) { crate::win::services(stats) } else if mac { brew(stats) } else { systemd(stats) });
let ctr = scope.spawn(|| containers(stats));
let img = scope.spawn(|| docker.as_deref().map(images).unwrap_or_default());
let cmp = scope.spawn(|| docker.as_deref().map(compose_projects).unwrap_or_default());
@@ -194,7 +194,7 @@ fn systemd(stats: bool) -> (Vec<Value>, Option<String>) {
}
/// Failed first (what needs looking at), then running, then the rest.
-fn rank(state: Option<&str>) -> u8 {
+pub(crate) fn rank(state: Option<&str>) -> u8 {
match state {
Some("failed" | "error") => 0,
Some("running" | "started") => 1,
@@ -296,6 +296,7 @@ pub fn act(req: &Value) -> Value {
return json!({ "ok": false, "error": "That name has odd characters." });
}
let done = match (kind, action) {
+ ("service", "start" | "stop" | "restart" | "enable" | "disable") if cfg!(windows) => crate::win::service_action(target, action),
("service", "start" | "stop" | "restart" | "enable" | "disable") if user => run("systemctl", &["--user", action, "--", target]),
// The system's: as root. The action and unit arrive as $1 and $2.
("service", "start" | "stop" | "restart" | "enable" | "disable") => as_root("exec systemctl \"$1\" -- \"$2\"", &[action, target], password),
diff --git a/agent/src/sys.rs b/agent/src/sys.rs
new file mode 100644
index 0000000..635b3a3
--- /dev/null
+++ b/agent/src/sys.rs
@@ -0,0 +1,273 @@
+//! What differs between Unix and Windows: the user's home, the session
+//! server's local connection, and starting and ending processes.
+//!
+//! The session server listens on a Unix socket (`~/.muxen/agent.sock`) on
+//! Unix. Windows gets a port on 127.0.0.1 instead, written with a random
+//! token to `~/.muxen/agent.port` (in the user's profile, which only they
+//! can read): a client sends the token first, and the server hangs up on
+//! anyone who doesn't.
+
+use std::io;
+use std::path::PathBuf;
+use std::process::Command;
+
+/// The user's home folder.
+pub fn user_home() -> PathBuf {
+ let var = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
+ std::env::var_os(var)
+ .or_else(|| std::env::var_os("HOME"))
+ .filter(|h| !h.is_empty())
+ .map(PathBuf::from)
+ .unwrap_or_else(|| PathBuf::from(if cfg!(windows) { "C:\\" } else { "/tmp" }))
+}
+
+/// `~` and `~/x` (or `~\x`) under the user's home; anything else as it is.
+pub fn expand_home(dir: &str) -> PathBuf {
+ match dir.trim() {
+ "" | "~" => user_home(),
+ d if d.starts_with("~/") || d.starts_with("~\\") => user_home().join(&d[2..]),
+ d => PathBuf::from(d),
+ }
+}
+
+/// Whether this runs as the superuser (root; on Windows, never: an
+/// administrator's elevated session is its own thing).
+pub fn is_root() -> bool {
+ #[cfg(unix)]
+ {
+ unsafe { libc::getuid() == 0 }
+ }
+ #[cfg(not(unix))]
+ {
+ false
+ }
+}
+
+/// Keeps going when the terminal that started this hangs up.
+pub fn ignore_hangup() {
+ #[cfg(unix)]
+ unsafe {
+ libc::signal(libc::SIGHUP, libc::SIG_IGN);
+ }
+}
+
+#[cfg(windows)]
+const CREATE_NO_WINDOW: u32 = 0x0800_0000;
+#[cfg(windows)]
+const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
+
+/// No console window for a program started on Windows (nothing on Unix).
+#[cfg_attr(unix, allow(dead_code))]
+pub fn no_window(cmd: &mut Command) -> &mut Command {
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ cmd.creation_flags(CREATE_NO_WINDOW);
+ }
+ cmd
+}
+
+/// Runs a child in its own process group (its own session on Unix), so it
+/// can be ended with everything it starts, and a hangup here doesn't reach it.
+pub fn own_group(cmd: &mut Command) -> &mut Command {
+ #[cfg(unix)]
+ unsafe {
+ use std::os::unix::process::CommandExt;
+ cmd.pre_exec(|| {
+ libc::setsid();
+ Ok(())
+ });
+ }
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ cmd.creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW);
+ }
+ cmd
+}
+
+/// Ends a process started with `own_group` and everything it started.
+/// `gently`: asks first (SIGTERM) where that exists.
+pub fn kill_tree(pid: u32, gently: bool) {
+ #[cfg(unix)]
+ unsafe {
+ libc::kill(-(pid as i32), if gently { libc::SIGTERM } else { libc::SIGKILL });
+ }
+ #[cfg(windows)]
+ {
+ let _ = gently;
+ let _ = no_window(Command::new("taskkill").args(["/T", "/F", "/PID", &pid.to_string()]))
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .status();
+ }
+}
+
+/// Ends one process (SIGTERM when `gently`, else SIGKILL; on Windows, at once).
+pub fn kill_one(pid: u32, gently: bool) {
+ #[cfg(unix)]
+ unsafe {
+ libc::kill(pid as i32, if gently { libc::SIGTERM } else { libc::SIGKILL });
+ }
+ #[cfg(windows)]
+ {
+ let _ = gently;
+ let _ = no_window(Command::new("taskkill").args(["/F", "/PID", &pid.to_string()]))
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .status();
+ }
+}
+
+/// Starts `muxen-agent <args>` in the background so it outlives this
+/// connection: in its own session on Unix (logging to `log`); on Windows
+/// through WMI, since sshd ends everything a session started when it closes.
+pub fn spawn_background(args: &[&str], log: PathBuf) -> io::Result<()> {
+ let exe = std::env::current_exe()?;
+ let home = crate::home_dir();
+ #[cfg(unix)]
+ {
+ use std::process::Stdio;
+ let log = std::fs::OpenOptions::new().create(true).append(true).open(log)?;
+ let mut cmd = Command::new(exe);
+ cmd.args(args).stdin(Stdio::null()).stdout(log.try_clone()?).stderr(log).current_dir(home);
+ own_group(&mut cmd).spawn().map(|_| ())
+ }
+ #[cfg(windows)]
+ {
+ let _ = log;
+ let quote = |s: &str| s.replace('\'', "''");
+ let line = std::iter::once(format!("\"{}\"", exe.display())).chain(args.iter().map(|a| a.to_string())).collect::<Vec<_>>().join(" ");
+ let script = format!(
+ "$r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{{ CommandLine = '{}'; CurrentDirectory = '{}' }}; exit $r.ReturnValue",
+ quote(&line),
+ quote(&home.display().to_string())
+ );
+ let status = no_window(Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-Command", &script]))
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .status()?;
+ if status.success() { Ok(()) } else { Err(io::Error::other(format!("Windows didn't start it ({:?})", status.code()))) }
+ }
+}
+
+// --- The session server's local connection ---------------------------------
+
+#[cfg(unix)]
+pub type Stream = std::os::unix::net::UnixStream;
+#[cfg(windows)]
+pub type Stream = std::net::TcpStream;
+
+/// Connects to the session server.
+pub fn connect() -> io::Result<Stream> {
+ #[cfg(unix)]
+ {
+ Stream::connect(crate::socket_path())
+ }
+ #[cfg(windows)]
+ {
+ use std::io::Write;
+ let text = std::fs::read_to_string(port_file())?;
+ let (port, token) = text.trim().split_once(' ').ok_or_else(|| io::Error::other("agent.port is damaged"))?;
+ let port: u16 = port.parse().map_err(|_| io::Error::other("agent.port is damaged"))?;
+ let mut s = Stream::connect(("127.0.0.1", port))?;
+ s.write_all(format!("{token}\n").as_bytes())?;
+ Ok(s)
+ }
+}
+
+#[cfg(windows)]
+fn port_file() -> PathBuf {
+ crate::home_dir().join("agent.port")
+}
+
+/// The session server's listening end.
+pub struct Listener {
+ #[cfg(unix)]
+ inner: std::os::unix::net::UnixListener,
+ #[cfg(windows)]
+ inner: std::net::TcpListener,
+ #[cfg(windows)]
+ token: String,
+}
+
+impl Listener {
+ /// Starts listening where `connect` looks (replacing what a stopped server left).
+ pub fn bind() -> io::Result<Listener> {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let path = crate::socket_path();
+ let _ = std::fs::remove_file(&path);
+ let inner = std::os::unix::net::UnixListener::bind(&path)?;
+ let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
+ Ok(Listener { inner })
+ }
+ #[cfg(windows)]
+ {
+ use ring::rand::SecureRandom;
+ let inner = std::net::TcpListener::bind(("127.0.0.1", 0))?;
+ let port = inner.local_addr()?.port();
+ let mut bytes = [0u8; 24];
+ ring::rand::SystemRandom::new().fill(&mut bytes).map_err(|_| io::Error::other("no randomness"))?;
+ let token: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
+ let tmp = port_file().with_extension(format!("port.{}", std::process::id()));
+ std::fs::write(&tmp, format!("{port} {token}"))?;
+ std::fs::rename(&tmp, port_file())?;
+ Ok(Listener { inner, token })
+ }
+ }
+
+ /// The next connection (not yet admitted: see `admit`).
+ pub fn accept(&self) -> io::Result<Stream> {
+ self.inner.accept().map(|(s, _)| s)
+ }
+
+ /// Whether a new connection may talk to the server (on Windows: it sent the token).
+ pub fn admit(&self, stream: &mut Stream) -> bool {
+ #[cfg(unix)]
+ {
+ let _ = stream;
+ true
+ }
+ #[cfg(windows)]
+ {
+ use std::io::Read;
+ let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(5)));
+ let mut line = Vec::new();
+ let mut byte = [0u8; 1];
+ while line.len() <= self.token.len() {
+ match stream.read(&mut byte) {
+ Ok(1) if byte[0] == b'\n' => break,
+ Ok(1) => line.push(byte[0]),
+ _ => return false,
+ }
+ }
+ let _ = stream.set_read_timeout(None);
+ line == self.token.as_bytes()
+ }
+ }
+}
+
+/// Removes what `Listener::bind` left for clients (the server is stopping).
+pub fn unlisten() {
+ #[cfg(unix)]
+ let _ = std::fs::remove_file(crate::socket_path());
+ #[cfg(windows)]
+ let _ = std::fs::remove_file(port_file());
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn expands_home() {
+ assert_eq!(expand_home("~"), user_home());
+ assert_eq!(expand_home("~/code"), user_home().join("code"));
+ assert_eq!(expand_home("/srv"), PathBuf::from("/srv"));
+ }
+}
diff --git a/agent/src/usage.rs b/agent/src/usage.rs
index db06fe7..d24bb77 100644
--- a/agent/src/usage.rs
+++ b/agent/src/usage.rs
@@ -68,7 +68,7 @@ pub fn usage(req: &Value) -> Value {
let since = SystemTime::now() - Duration::from_secs(days * 86_400);
let cutoff = utc_hour(since);
// The user's home (crate::home_dir is the agent's own ~/.muxen).
- let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default();
+ let home = crate::sys::user_home();
let mut tally = Tally::default();
let mut found = Vec::new();
diff --git a/agent/src/win.rs b/agent/src/win.rs
new file mode 100644
index 0000000..faf56d4
--- /dev/null
+++ b/agent/src/win.rs
@@ -0,0 +1,303 @@
+//! Windows' side of the machine's pages: its services, processes and GPUs,
+//! listening ports and event logs, in the same shapes the Linux and macOS
+//! code answers with. Windows keeps these behind PowerShell and WMI, so each
+//! asks PowerShell once and reads its JSON.
+
+use std::collections::HashMap;
+use std::process::{Command, Stdio};
+
+use serde_json::{Value, json};
+
+use crate::sys::no_window;
+
+/// Runs a PowerShell script (encoded, so nothing on the way changes it) and
+/// returns what it printed.
+pub fn ps(script: &str) -> Result<String, String> {
+ use base64::Engine as _;
+ let full = format!("$ProgressPreference = 'SilentlyContinue'; $ErrorActionPreference = 'Stop'; [Console]::OutputEncoding = [Text.Encoding]::UTF8\n{script}");
+ let utf16: Vec<u8> = full.encode_utf16().flat_map(u16::to_le_bytes).collect();
+ let encoded = base64::engine::general_purpose::STANDARD.encode(utf16);
+ let out = no_window(Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", &encoded]))
+ .stdin(Stdio::null())
+ .output()
+ .map_err(|e| format!("couldn't run PowerShell: {e}"))?;
+ let text = String::from_utf8_lossy(&out.stdout).into_owned();
+ if out.status.success() {
+ Ok(text)
+ } else {
+ Err(clixml_error(&String::from_utf8_lossy(&out.stderr)).unwrap_or_else(|| "PowerShell couldn't do that.".into()))
+ }
+}
+
+/// The JSON a script printed (`ConvertTo-Json`): always an array.
+pub fn ps_json(script: &str) -> Result<Vec<Value>, String> {
+ let text = ps(script)?;
+ let text = text.trim();
+ if text.is_empty() {
+ return Ok(Vec::new());
+ }
+ match serde_json::from_str::<Value>(text).map_err(|e| format!("PowerShell said something unexpected: {e}"))? {
+ Value::Array(a) => Ok(a),
+ v => Ok(vec![v]),
+ }
+}
+
+/// The message in PowerShell's error output (CLIXML when it isn't a terminal).
+fn clixml_error(stderr: &str) -> Option<String> {
+ let line = stderr.split("<S S=\"Error\">").nth(1).map(|s| s.split("</S>").next().unwrap_or(s))?;
+ let text = line.replace("_x000D__x000A_", " ").replace("&apos;", "'").replace("&quot;", "\"").replace("&lt;", "<").replace("&gt;", ">").replace("&amp;", "&");
+ Some(text.trim().to_string()).filter(|t| !t.is_empty())
+}
+
+/// A PowerShell string literal.
+pub fn quote(s: &str) -> String {
+ format!("'{}'", s.replace('\'', "''"))
+}
+
+// --- Processes --------------------------------------------------------------
+
+/// What each process uses right now: CPU (percent of one core, as `ps`
+/// counts it) and private memory, by pid.
+fn usage() -> HashMap<u32, (f64, u64)> {
+ let rows = ps_json("Get-CimInstance Win32_PerfFormattedData_PerfProc_Process | Where-Object { $_.IDProcess -ne 0 } | Select-Object IDProcess, PercentProcessorTime, WorkingSetPrivate | ConvertTo-Json -Compress").unwrap_or_default();
+ rows.iter()
+ .filter_map(|r| Some((r["IDProcess"].as_u64()? as u32, (r["PercentProcessorTime"].as_f64().unwrap_or(0.), r["WorkingSetPrivate"].as_u64().unwrap_or(0)))))
+ .collect()
+}
+
+/// Every process: pid, parent, user, name, command line, CPU, memory, seconds running.
+pub fn processes() -> Result<Vec<Value>, String> {
+ let (usage, rows) = std::thread::scope(|scope| {
+ let u = scope.spawn(usage);
+ // Owners need an elevated session; without one they're left out.
+ let rows = ps_json(
+ "$owners = @{}; try { Get-Process -IncludeUserName -ErrorAction Stop | ForEach-Object { $owners[$_.Id] = $_.UserName } } catch {}
+ $now = Get-Date
+ Get-CimInstance Win32_Process | ForEach-Object { [pscustomobject]@{ pid = [int]$_.ProcessId; ppid = [int]$_.ParentProcessId; name = $_.Name; command = $_.CommandLine; seconds = $(if ($_.CreationDate) { [Math]::Max([int64]0, [int64]($now - $_.CreationDate).TotalSeconds) } else { 0 }); user = $owners[[int]$_.ProcessId] } } | ConvertTo-Json -Compress",
+ );
+ (u.join().unwrap_or_default(), rows)
+ });
+ let me = std::env::var("USERNAME").unwrap_or_default().to_lowercase();
+ let agent = std::process::id() as u64;
+ Ok(rows?
+ .into_iter()
+ // Not the PowerShell this asked (its parent is the agent).
+ .filter(|r| r["pid"].as_u64().is_some_and(|p| p != 0) && r["ppid"].as_u64() != Some(agent))
+ .map(|r| {
+ let pid = r["pid"].as_u64().unwrap_or(0) as u32;
+ let (cpu, memory) = usage.get(&pid).copied().unwrap_or((0., 0));
+ let user = r["user"].as_str().unwrap_or("").to_string();
+ let short = user.rsplit('\\').next().unwrap_or("").to_lowercase();
+ let name = r["name"].as_str().unwrap_or("").trim_end_matches(".exe").to_string();
+ let command = r["command"].as_str().filter(|c| !c.is_empty()).map(str::to_string).unwrap_or_else(|| name.clone());
+ let user = user.rsplit('\\').next().unwrap_or("").to_string();
+ json!({ "pid": pid, "ppid": r["ppid"], "user": user, "name": name, "command": command, "cpu": cpu, "memory": memory, "seconds": r["seconds"], "yours": !me.is_empty() && short == me })
+ })
+ .collect())
+}
+
+/// The GPUs: NVIDIA's through nvidia-smi (see procs.rs); the others through
+/// Windows' own counters (how busy, dedicated memory in use).
+pub fn gpus() -> Vec<Value> {
+ let rows = ps_json(
+ "$busy = @{}; $mem = @{}
+ try { (Get-Counter '\\GPU Engine(*)\\Utilization Percentage' -ErrorAction Stop).CounterSamples | ForEach-Object { if ($_.InstanceName -match 'luid_(0x[0-9a-f]+_0x[0-9a-f]+)') { $busy[$matches[1]] += $_.CookedValue } } } catch {}
+ try { (Get-Counter '\\GPU Adapter Memory(*)\\Dedicated Usage' -ErrorAction Stop).CounterSamples | ForEach-Object { if ($_.InstanceName -match 'luid_(0x[0-9a-f]+_0x[0-9a-f]+)') { $mem[$matches[1]] = $_.CookedValue } } } catch {}
+ $top = ($busy.Values | Measure-Object -Maximum).Maximum
+ $used = ($mem.Values | Measure-Object -Maximum).Maximum
+ Get-CimInstance Win32_VideoController | Where-Object { $_.Name -notmatch 'Basic Display|Basic Render|Remote Display|Hyper-V' } | ForEach-Object { [pscustomobject]@{ name = $_.Name; memory_total = [int64]$_.AdapterRAM; busy = $top; memory_used = $used } } | ConvertTo-Json -Compress",
+ )
+ .unwrap_or_default();
+ rows.into_iter()
+ .filter(|r| !r["name"].as_str().unwrap_or("").contains("NVIDIA"))
+ .map(|r| {
+ let vendor = match r["name"].as_str().unwrap_or("") {
+ n if n.contains("AMD") || n.contains("Radeon") => "amd",
+ n if n.contains("Intel") => "intel",
+ _ => "other",
+ };
+ // AdapterRAM is 32 bits: 4 GB and more reads as 4 GB or less; leave those out.
+ let total = r["memory_total"].as_u64().filter(|t| *t > 0 && *t < 0xFFFF_0000);
+ json!({ "vendor": vendor, "name": r["name"], "busy": r["busy"].as_f64().map(|b| b.min(100.)), "memory_used": r["memory_used"].as_f64().map(|m| m as u64), "memory_total": total })
+ })
+ .collect()
+}
+
+// --- Services ---------------------------------------------------------------
+
+/// Windows services: name, what it is, state, whether it starts at boot, and
+/// what its process uses.
+pub fn services(stats: bool) -> (Vec<Value>, Option<String>) {
+ let rows = match ps_json("Get-CimInstance Win32_Service | Select-Object Name, DisplayName, State, StartMode, ProcessId, ExitCode, DelayedAutoStart | ConvertTo-Json -Compress") {
+ Ok(r) => r,
+ Err(e) => return (Vec::new(), Some(format!("Couldn't list Windows' services: {e}"))),
+ };
+ let usage = if stats { usage() } else { HashMap::new() };
+ let mut out: Vec<Value> = rows
+ .iter()
+ .map(|r| {
+ let start = r["StartMode"].as_str().unwrap_or("");
+ let exit = r["ExitCode"].as_u64().unwrap_or(0);
+ let state = match r["State"].as_str().unwrap_or("") {
+ "Running" => "running",
+ "Stopped" if start == "Auto" && exit != 0 && exit != 1077 && r["DelayedAutoStart"] != true => "failed",
+ "Stopped" => "stopped",
+ "Start Pending" => "starting",
+ "Stop Pending" => "stopping",
+ "Paused" => "paused",
+ _ => "unknown",
+ };
+ let at_boot = match start {
+ "Auto" => "enabled",
+ "Disabled" => "masked",
+ _ => "disabled",
+ };
+ let pid = r["ProcessId"].as_u64().unwrap_or(0) as u32;
+ let (cpu, memory) = (state == "running" && pid != 0).then(|| usage.get(&pid).copied()).flatten().map(|(c, m)| (Some(c), Some(m))).unwrap_or((None, None));
+ json!({
+ "kind": "service",
+ "target": r["Name"],
+ "name": r["Name"],
+ "detail": r["DisplayName"],
+ "state": state,
+ "at_boot": at_boot,
+ "user": false,
+ "cpu": cpu,
+ "memory": memory,
+ })
+ })
+ .collect();
+ out.sort_by_key(|u| (crate::services::rank(u["state"].as_str()), u["name"].as_str().unwrap_or("").to_lowercase()));
+ (out, None)
+}
+
+/// Starts, stops or restarts a service; `enable` starts it at boot, `disable` leaves it to start by hand.
+pub fn service_action(name: &str, action: &str) -> Result<(), String> {
+ let n = quote(name);
+ let script = match action {
+ "start" => format!("Start-Service -Name {n}"),
+ "stop" => format!("Stop-Service -Name {n} -Force"),
+ "restart" => format!("Restart-Service -Name {n} -Force"),
+ "enable" => format!("Set-Service -Name {n} -StartupType Automatic"),
+ "disable" => format!("Set-Service -Name {n} -StartupType Manual"),
+ other => return Err(format!("Can't {other} a service.")),
+ };
+ ps(&script).map(|_| ()).map_err(|e| if e.contains("ccess is denied") || e.contains("ermission") { "Windows wants an administrator for that.".into() } else { e })
+}
+
+// --- Ports ------------------------------------------------------------------
+
+/// TCP ports something listens on: (port, address, program, pid).
+pub fn listening() -> Vec<(u16, String, String, Option<u32>)> {
+ let rows = ps_json(
+ "$names = @{}; Get-Process | ForEach-Object { $names[$_.Id] = $_.ProcessName }
+ Get-NetTCPConnection -State Listen | ForEach-Object { [pscustomobject]@{ port = [int]$_.LocalPort; address = $_.LocalAddress; pid = [int]$_.OwningProcess; process = $names[[int]$_.OwningProcess] } } | ConvertTo-Json -Compress",
+ )
+ .unwrap_or_default();
+ rows.into_iter()
+ .filter_map(|r| {
+ let port = r["port"].as_u64()? as u16;
+ let pid = r["pid"].as_u64().map(|p| p as u32).filter(|p| *p > 4);
+ // The system itself (pid 4) answers SMB, RPC and http.sys's ports.
+ let process = if r["pid"].as_u64() == Some(4) { "System".into() } else { r["process"].as_str().unwrap_or("").to_string() };
+ Some((port, r["address"].as_str().unwrap_or("").to_string(), process, pid))
+ })
+ .collect()
+}
+
+// --- Logs -------------------------------------------------------------------
+
+/// The event logs worth reading, as log sources.
+pub fn event_logs() -> Vec<Value> {
+ [("System", "Windows' system events"), ("Application", "Programs' events"), ("Security", "Sign-ins and audits (administrators)")]
+ .iter()
+ .map(|(log, detail)| json!({ "kind": "system", "target": log, "name": log, "detail": detail }))
+ .collect()
+}
+
+/// Windows services, to read their events (System log, by service).
+pub fn service_sources() -> Vec<Value> {
+ let rows = ps_json("Get-CimInstance Win32_Service | Where-Object { $_.State -eq 'Running' -or $_.StartMode -eq 'Auto' } | Select-Object Name, DisplayName, State | ConvertTo-Json -Compress").unwrap_or_default();
+ let mut out: Vec<Value> = rows
+ .iter()
+ .map(|r| json!({ "kind": "service", "target": r["Name"], "name": r["Name"], "detail": r["DisplayName"], "user": false, "state": if r["State"] == "Running" { "running" } else { "stopped" } }))
+ .collect();
+ out.sort_by_key(|u| u["name"].as_str().unwrap_or("").to_lowercase());
+ out
+}
+
+/// The PowerShell that prints a log's last `lines` (then, when `follow`,
+/// what comes, checking every second): an event log, a service's events, a file.
+pub fn log_script(kind: &str, target: &str, lines: u64, follow: bool) -> Result<String, String> {
+ // An event as one line: time, level, source, message.
+ let show = "ForEach-Object { '{0} {1,-7} {2}: {3}' -f $_.TimeCreated.ToString('yyyy-MM-ddTHH:mm:ss'), $_.LevelDisplayName, $_.ProviderName, (($_.Message -replace '\\s+', ' ').Trim()) }";
+ let events = |filter: String| {
+ let mut s = format!("$f = {filter}\n$e = @(Get-WinEvent -FilterHashtable $f -MaxEvents {lines} -ErrorAction SilentlyContinue)\n[array]::Reverse($e)\n$e | {show}\n");
+ if follow {
+ s.push_str(&format!("$last = if ($e.Count) {{ $e[-1].RecordId }} else {{ 0 }}\nwhile ($true) {{ Start-Sleep 1; $new = @(Get-WinEvent -FilterHashtable $f -MaxEvents 200 -ErrorAction SilentlyContinue | Where-Object {{ $_.RecordId -gt $last }}); if ($new.Count) {{ [array]::Reverse($new); $new | {show}; $last = $new[-1].RecordId }} }}\n"));
+ }
+ s
+ };
+ match kind {
+ "system" | "kernel" => {
+ let log = if target.is_empty() { "System" } else { target };
+ if !log.chars().all(|c| c.is_ascii_alphanumeric() || "-/ ".contains(c)) {
+ return Err("That log's name has odd characters.".into());
+ }
+ Ok(events(format!("@{{ LogName = {} }}", quote(log))))
+ }
+ "service" => {
+ if target.is_empty() || !target.chars().all(|c| c.is_ascii_alphanumeric() || "._-$".contains(c)) {
+ return Err("Which service?".into());
+ }
+ // Its events: the Service Control Manager's about it (started,
+ // stopped, failed), and its own when it writes any, by time.
+ // (Asking for a source that has never written one fails, so each is asked alone.)
+ let script = format!(
+ "$n = {name}\n\
+ $disp = (Get-Service -Name $n -ErrorAction SilentlyContinue).DisplayName; if (-not $disp) {{ $disp = $n }}\n\
+ function Get-Its($since, $max) {{\n\
+ $a = @(Get-WinEvent -FilterHashtable @{{ LogName = 'System'; ProviderName = 'Service Control Manager'; StartTime = $since }} -MaxEvents 3000 -ErrorAction SilentlyContinue | Where-Object {{ $_.Message -match [regex]::Escape($disp) }} | Select-Object -First $max)\n\
+ $b = @(try {{ Get-WinEvent -FilterHashtable @{{ LogName = 'System', 'Application'; ProviderName = $n; StartTime = $since }} -MaxEvents $max -ErrorAction Stop }} catch {{ }})\n\
+ @($a + $b) | Sort-Object TimeCreated | Select-Object -Last $max\n\
+ }}\n\
+ $e = @(Get-Its ([datetime]::MinValue) {lines})\n\
+ $e | {show}\n",
+ name = quote(target)
+ );
+ let follow_part = format!("$last = if ($e.Count) {{ $e[-1].TimeCreated }} else {{ Get-Date }}\nwhile ($true) {{ Start-Sleep 2; $new = @(Get-Its $last.AddMilliseconds(1) 200); if ($new.Count) {{ $new | {show}; $last = $new[-1].TimeCreated }} }}\n");
+ Ok(if follow { script + &follow_part } else { script })
+ }
+ "file" => {
+ let path = crate::sys::expand_home(target);
+ std::fs::File::open(&path).map_err(|e| match e.kind() {
+ std::io::ErrorKind::PermissionDenied => format!("{target} is readable only by administrators."),
+ std::io::ErrorKind::NotFound => format!("There's no {target} on this machine."),
+ _ => format!("Couldn't open {target}: {e}"),
+ })?;
+ let wait = if follow { " -Wait" } else { "" };
+ Ok(format!("Get-Content -LiteralPath {} -Tail {lines}{wait}", quote(&path.display().to_string())))
+ }
+ other => Err(format!("No log source called \"{other}\".")),
+ }
+}
+
+/// The program and arguments that run a log script (for `logs::command`).
+pub fn log_command(script: String) -> (String, Vec<String>) {
+ use base64::Engine as _;
+ let full = format!("$ProgressPreference = 'SilentlyContinue'; [Console]::OutputEncoding = [Text.Encoding]::UTF8\n{script}");
+ let utf16: Vec<u8> = full.encode_utf16().flat_map(u16::to_le_bytes).collect();
+ ("powershell".into(), vec!["-NoProfile".into(), "-NonInteractive".into(), "-EncodedCommand".into(), base64::engine::general_purpose::STANDARD.encode(utf16)])
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn reads_powershell_errors() {
+ let err = "#< CLIXML\r\n<Objs Version=\"1.1.0.1\"><S S=\"Error\">Cannot find any service with service name 'nope'._x000D__x000A_</S></Objs>";
+ assert_eq!(clixml_error(err).as_deref(), Some("Cannot find any service with service name 'nope'."));
+ assert_eq!(quote("it's"), "'it''s'");
+ }
+}
diff --git a/agent/src/win_screen.rs b/agent/src/win_screen.rs
new file mode 100644
index 0000000..268799a
--- /dev/null
+++ b/agent/src/win_screen.rs
@@ -0,0 +1,610 @@
+//! Windows' screen and clipboard, for the desktop view: GDI captures,
+//! `SendInput` for the mouse and keyboard, the clipboard's Unicode text. And
+//! getting there: sshd runs links in session 0, which has no desktop, so
+//! programs that need the screen start in the signed-in user's own session
+//! through a one-off scheduled task, and connect back on 127.0.0.1 with a
+//! token (see `start_in_desktop` and `gui_run`).
+
+use std::io::{self, Read, Write};
+use std::net::{TcpListener, TcpStream};
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+
+use serde_json::{Value, json};
+use windows_sys::Win32::Foundation::{LPARAM, RECT};
+use windows_sys::Win32::Graphics::Gdi::*;
+use windows_sys::Win32::UI::Input::KeyboardAndMouse::*;
+use windows_sys::Win32::UI::WindowsAndMessaging::*;
+
+/// Physical pixels, not the scaled ones (a 150% display is its real size).
+fn dpi_aware() {
+ unsafe {
+ windows_sys::Win32::UI::HiDpi::SetProcessDpiAwarenessContext(windows_sys::Win32::UI::HiDpi::DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
+ }
+}
+
+/// The monitors: (name, rect, primary).
+fn monitors() -> Vec<(String, RECT, bool)> {
+ unsafe extern "system" fn each(m: HMONITOR, _: HDC, _: *mut RECT, data: LPARAM) -> i32 {
+ let out = unsafe { &mut *(data as *mut Vec<(String, RECT, bool)>) };
+ let mut info: MONITORINFOEXW = unsafe { std::mem::zeroed() };
+ info.monitorInfo.cbSize = std::mem::size_of::<MONITORINFOEXW>() as u32;
+ if unsafe { GetMonitorInfoW(m, &mut info as *mut MONITORINFOEXW as *mut MONITORINFO) } != 0 {
+ let name = String::from_utf16_lossy(&info.szDevice).trim_end_matches('\0').trim_start_matches(r"\\.\").to_string();
+ out.push((name, info.monitorInfo.rcMonitor, info.monitorInfo.dwFlags & MONITORINFOF_PRIMARY != 0));
+ }
+ 1
+ }
+ let mut out: Vec<(String, RECT, bool)> = Vec::new();
+ unsafe { EnumDisplayMonitors(std::ptr::null_mut(), std::ptr::null(), Some(each), &mut out as *mut _ as LPARAM) };
+ out
+}
+
+fn virtual_screen() -> RECT {
+ unsafe {
+ let (x, y) = (GetSystemMetrics(SM_XVIRTUALSCREEN), GetSystemMetrics(SM_YVIRTUALSCREEN));
+ RECT { left: x, top: y, right: x + GetSystemMetrics(SM_CXVIRTUALSCREEN), bottom: y + GetSystemMetrics(SM_CYVIRTUALSCREEN) }
+ }
+}
+
+/// `muxen-agent displays` on Windows: each monitor, and "all" when there are several.
+pub fn displays() -> Value {
+ dpi_aware();
+ let ms = monitors();
+ let mut out: Vec<Value> = ms
+ .iter()
+ .enumerate()
+ .map(|(i, (name, r, primary))| json!({ "id": (i + 1).to_string(), "name": if *primary { format!("{name} (main)") } else { name.clone() }, "x": r.left, "y": r.top, "width": r.right - r.left, "height": r.bottom - r.top, "main": primary }))
+ .collect();
+ if ms.len() > 1 {
+ let v = virtual_screen();
+ out.push(json!({ "id": "all", "name": "All screens", "x": v.left, "y": v.top, "width": v.right - v.left, "height": v.bottom - v.top, "main": false }));
+ }
+ json!({ "ok": true, "displays": out })
+}
+
+/// A display, captured with GDI.
+pub struct WinScreen {
+ rect: RECT,
+ screen_dc: HDC,
+ mem_dc: HDC,
+ bitmap: HBITMAP,
+ bits: *mut u8,
+ frame: Vec<u8>,
+ held: Vec<u16>,
+ buttons: Vec<u64>,
+}
+
+impl WinScreen {
+ /// `display`: a monitor's number from `displays`, "all", or None for the main one.
+ pub fn open(display: Option<&str>) -> Result<WinScreen, String> {
+ dpi_aware();
+ let ms = monitors();
+ let rect = match display {
+ Some("all") => virtual_screen(),
+ Some(n) => ms.get(n.parse::<usize>().map_err(|_| format!("No display called {n}."))?.saturating_sub(1)).map(|m| m.1).ok_or_else(|| format!("No display called {n}."))?,
+ None => ms.iter().find(|m| m.2).or(ms.first()).map(|m| m.1).unwrap_or_else(virtual_screen),
+ };
+ let (w, h) = (rect.right - rect.left, rect.bottom - rect.top);
+ if w <= 0 || h <= 0 {
+ return Err("Windows has no screen here (nobody signed in?).".into());
+ }
+ unsafe {
+ let screen_dc = GetDC(std::ptr::null_mut());
+ if screen_dc.is_null() {
+ return Err("Can't reach the screen (nobody signed in to the desktop?).".into());
+ }
+ let mem_dc = CreateCompatibleDC(screen_dc);
+ let mut bmi: BITMAPINFO = std::mem::zeroed();
+ bmi.bmiHeader.biSize = std::mem::size_of::<BITMAPINFOHEADER>() as u32;
+ bmi.bmiHeader.biWidth = w;
+ bmi.bmiHeader.biHeight = -h; // top-down
+ bmi.bmiHeader.biPlanes = 1;
+ bmi.bmiHeader.biBitCount = 32;
+ bmi.bmiHeader.biCompression = BI_RGB;
+ let mut bits: *mut std::ffi::c_void = std::ptr::null_mut();
+ let bitmap = CreateDIBSection(mem_dc, &bmi, DIB_RGB_COLORS, &mut bits, std::ptr::null_mut(), 0);
+ if bitmap.is_null() || bits.is_null() {
+ return Err("Can't make room for the screen.".into());
+ }
+ SelectObject(mem_dc, bitmap as HGDIOBJ);
+ Ok(WinScreen { rect, screen_dc, mem_dc, bitmap, bits: bits as *mut u8, frame: vec![0; (w * h * 4) as usize], held: Vec::new(), buttons: Vec::new() })
+ }
+ }
+
+ pub fn size(&self) -> (usize, usize) {
+ ((self.rect.right - self.rect.left) as usize, (self.rect.bottom - self.rect.top) as usize)
+ }
+
+ /// The screen now, with the mouse pointer drawn in.
+ pub fn grab(&mut self) -> Option<Option<&[u8]>> {
+ let (w, h) = self.size();
+ unsafe {
+ // Fails while the secure desktop is up (a UAC prompt, the lock
+ // screen): keep showing the last frame.
+ if BitBlt(self.mem_dc, 0, 0, w as i32, h as i32, self.screen_dc, self.rect.left, self.rect.top, SRCCOPY | CAPTUREBLT) == 0 {
+ return Some(None);
+ }
+ let mut ci: CURSORINFO = std::mem::zeroed();
+ ci.cbSize = std::mem::size_of::<CURSORINFO>() as u32;
+ if GetCursorInfo(&mut ci) != 0 && ci.flags & CURSOR_SHOWING != 0 {
+ let mut ii: ICONINFO = std::mem::zeroed();
+ if GetIconInfo(ci.hCursor, &mut ii) != 0 {
+ let (x, y) = (ci.ptScreenPos.x - self.rect.left - ii.xHotspot as i32, ci.ptScreenPos.y - self.rect.top - ii.yHotspot as i32);
+ DrawIconEx(self.mem_dc, x, y, ci.hCursor, 0, 0, 0, std::ptr::null_mut(), DI_NORMAL);
+ if !ii.hbmMask.is_null() {
+ DeleteObject(ii.hbmMask as HGDIOBJ);
+ }
+ if !ii.hbmColor.is_null() {
+ DeleteObject(ii.hbmColor as HGDIOBJ);
+ }
+ }
+ }
+ GdiFlush();
+ std::ptr::copy_nonoverlapping(self.bits, self.frame.as_mut_ptr(), self.frame.len());
+ }
+ Some(Some(&self.frame))
+ }
+
+ /// The desktop's coordinates, as SendInput wants them (0..65535 across all screens).
+ fn absolute(&self, e: &Value, frame: (usize, usize)) -> (i32, i32) {
+ let (w, h) = self.size();
+ let x = self.rect.left as f64 + e["x"].as_f64().unwrap_or(0.) * w as f64 / frame.0 as f64;
+ let y = self.rect.top as f64 + e["y"].as_f64().unwrap_or(0.) * h as f64 / frame.1 as f64;
+ let v = virtual_screen();
+ let nx = ((x - v.left as f64) * 65535. / ((v.right - v.left - 1).max(1)) as f64).round() as i32;
+ let ny = ((y - v.top as f64) * 65535. / ((v.bottom - v.top - 1).max(1)) as f64).round() as i32;
+ (nx, ny)
+ }
+
+ pub fn apply(&mut self, e: &Value, frame: (usize, usize)) {
+ match e["t"].as_str().unwrap_or("") {
+ "move" => {
+ let (x, y) = self.absolute(e, frame);
+ send(&[mouse(x, y, 0, MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK)]);
+ }
+ "button" => {
+ let (x, y) = self.absolute(e, frame);
+ let b = e["b"].as_u64().unwrap_or(1);
+ let down = e["down"].as_bool().unwrap_or(false);
+ let flag = match (b, down) {
+ (1, true) => MOUSEEVENTF_LEFTDOWN,
+ (1, false) => MOUSEEVENTF_LEFTUP,
+ (2, true) => MOUSEEVENTF_MIDDLEDOWN,
+ (2, false) => MOUSEEVENTF_MIDDLEUP,
+ (3, true) => MOUSEEVENTF_RIGHTDOWN,
+ (3, false) => MOUSEEVENTF_RIGHTUP,
+ _ => return,
+ };
+ let at = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK;
+ // A release from the app's "let go of everything" carries no position.
+ if down || e["x"].as_f64().unwrap_or(0.) != 0. || e["y"].as_f64().unwrap_or(0.) != 0. {
+ send(&[mouse(x, y, 0, at), mouse(0, 0, 0, flag)]);
+ } else {
+ send(&[mouse(0, 0, 0, flag)]);
+ }
+ self.buttons.retain(|x| *x != b);
+ if down {
+ self.buttons.push(b);
+ }
+ }
+ "scroll" => {
+ let (x, y) = self.absolute(e, frame);
+ let at = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK;
+ let (dy, dx) = (e["dy"].as_i64().unwrap_or(0).clamp(-20, 20), e["dx"].as_i64().unwrap_or(0).clamp(-20, 20));
+ let mut events = vec![mouse(x, y, 0, at)];
+ // Down is positive here, negative for Windows' wheel.
+ if dy != 0 {
+ events.push(mouse(0, 0, (-dy * WHEEL_DELTA as i64) as i32, MOUSEEVENTF_WHEEL));
+ }
+ if dx != 0 {
+ events.push(mouse(0, 0, (dx * WHEEL_DELTA as i64) as i32, MOUSEEVENTF_HWHEEL));
+ }
+ send(&events);
+ }
+ "text" => {
+ let mut events = Vec::new();
+ for unit in e["s"].as_str().unwrap_or("").encode_utf16() {
+ match unit {
+ 0x0a | 0x0d => {
+ events.push(key(VK_RETURN, 0, 0));
+ events.push(key(VK_RETURN, 0, KEYEVENTF_KEYUP));
+ }
+ 0x09 => {
+ events.push(key(VK_TAB, 0, 0));
+ events.push(key(VK_TAB, 0, KEYEVENTF_KEYUP));
+ }
+ u => {
+ // The key that types it (with Shift, Ctrl, Alt as the layout
+ // needs), as a keyboard would; else the character itself.
+ let scan = unsafe { VkKeyScanW(u) };
+ if scan != -1 && u < 0x80 {
+ let vk = (scan as u16) & 0xff;
+ let mods: Vec<VIRTUAL_KEY> = [(0x100, VK_SHIFT), (0x200, VK_CONTROL), (0x400, VK_MENU)].iter().filter(|(bit, _)| scan as u16 & bit != 0).map(|(_, k)| *k).collect();
+ events.extend(mods.iter().map(|m| key(*m, 0, 0)));
+ events.push(key(vk, 0, 0));
+ events.push(key(vk, 0, KEYEVENTF_KEYUP));
+ events.extend(mods.iter().rev().map(|m| key(*m, 0, KEYEVENTF_KEYUP)));
+ } else {
+ events.push(key(0, u, KEYEVENTF_UNICODE));
+ events.push(key(0, u, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP));
+ }
+ }
+ }
+ }
+ send(&events);
+ }
+ "key" => {
+ let sym = e["keysym"].as_u64().unwrap_or(0) as u32;
+ let down = e["down"].as_bool().unwrap_or(false);
+ let Some((vk, extended)) = vk_of(sym) else { return };
+ let mut flags = if extended { KEYEVENTF_EXTENDEDKEY } else { 0 };
+ if !down {
+ flags |= KEYEVENTF_KEYUP;
+ }
+ send(&[key(vk, 0, flags)]);
+ self.held.retain(|x| *x != vk);
+ if down {
+ self.held.push(vk);
+ }
+ }
+ _ => {}
+ }
+ }
+}
+
+impl Drop for WinScreen {
+ fn drop(&mut self) {
+ // Nothing stays held down when the view goes away.
+ let keys: Vec<INPUT> = self.held.iter().map(|vk| key(*vk, 0, KEYEVENTF_KEYUP)).collect();
+ send(&keys);
+ for b in self.buttons.clone() {
+ let flag = match b {
+ 1 => MOUSEEVENTF_LEFTUP,
+ 2 => MOUSEEVENTF_MIDDLEUP,
+ _ => MOUSEEVENTF_RIGHTUP,
+ };
+ send(&[mouse(0, 0, 0, flag)]);
+ }
+ unsafe {
+ DeleteObject(self.bitmap as HGDIOBJ);
+ DeleteDC(self.mem_dc);
+ ReleaseDC(std::ptr::null_mut(), self.screen_dc);
+ }
+ }
+}
+
+fn mouse(dx: i32, dy: i32, data: i32, flags: MOUSE_EVENT_FLAGS) -> INPUT {
+ INPUT { r#type: INPUT_MOUSE, Anonymous: INPUT_0 { mi: MOUSEINPUT { dx, dy, mouseData: data as u32, dwFlags: flags, time: 0, dwExtraInfo: 0 } } }
+}
+
+fn key(vk: VIRTUAL_KEY, scan: u16, flags: KEYBD_EVENT_FLAGS) -> INPUT {
+ INPUT { r#type: INPUT_KEYBOARD, Anonymous: INPUT_0 { ki: KEYBDINPUT { wVk: vk, wScan: scan, dwFlags: flags, time: 0, dwExtraInfo: 0 } } }
+}
+
+fn send(events: &[INPUT]) {
+ if !events.is_empty() {
+ unsafe { SendInput(events.len() as u32, events.as_ptr(), std::mem::size_of::<INPUT>() as i32) };
+ }
+}
+
+/// An X keysym's Windows virtual key, and whether it's an extended key.
+fn vk_of(sym: u32) -> Option<(VIRTUAL_KEY, bool)> {
+ Some(match sym {
+ 0xff08 => (VK_BACK, false),
+ 0xff09 => (VK_TAB, false),
+ 0xff0d => (VK_RETURN, false),
+ 0xff1b => (VK_ESCAPE, false),
+ 0x20 => (VK_SPACE, false),
+ 0xffff => (VK_DELETE, true),
+ 0xff63 => (VK_INSERT, true),
+ 0xff50 => (VK_HOME, true),
+ 0xff57 => (VK_END, true),
+ 0xff55 => (VK_PRIOR, true),
+ 0xff56 => (VK_NEXT, true),
+ 0xff51 => (VK_LEFT, true),
+ 0xff52 => (VK_UP, true),
+ 0xff53 => (VK_RIGHT, true),
+ 0xff54 => (VK_DOWN, true),
+ 0xffe1 => (VK_LSHIFT, false),
+ 0xffe2 => (VK_RSHIFT, false),
+ 0xffe3 => (VK_LCONTROL, false),
+ 0xffe4 => (VK_RCONTROL, true),
+ 0xffe9 => (VK_LMENU, false),
+ 0xffea => (VK_RMENU, true),
+ 0xffeb | 0xffe7 => (VK_LWIN, true),
+ 0xffec | 0xffe8 => (VK_RWIN, true),
+ 0xffbe..=0xffc9 => (VK_F1 + (sym - 0xffbe) as u16, false),
+ _ => {
+ let c = char::from_u32(sym)?;
+ if c.is_ascii_alphabetic() {
+ (c.to_ascii_uppercase() as u16, false)
+ } else if c.is_ascii_digit() {
+ (c as u16, false)
+ } else {
+ // Punctuation: the key it's on, in this keyboard's layout (Shift comes on its own).
+ let mut units = [0u16; 2];
+ let n = c.encode_utf16(&mut units).len();
+ if n != 1 {
+ return None;
+ }
+ let scan = unsafe { VkKeyScanW(units[0]) };
+ if scan == -1 {
+ return None;
+ }
+ ((scan as u16) & 0xff, false)
+ }
+ }
+ })
+}
+
+// --- The clipboard -----------------------------------------------------------
+
+const CF_UNICODETEXT: u32 = 13;
+
+/// The clipboard's text, if it has any.
+fn clipboard_text() -> Option<String> {
+ use windows_sys::Win32::System::DataExchange::*;
+ use windows_sys::Win32::System::Memory::*;
+ unsafe {
+ if IsClipboardFormatAvailable(CF_UNICODETEXT) == 0 || OpenClipboard(std::ptr::null_mut()) == 0 {
+ return None;
+ }
+ let h = GetClipboardData(CF_UNICODETEXT);
+ let text = if h.is_null() {
+ None
+ } else {
+ let p = GlobalLock(h as _) as *const u16;
+ if p.is_null() {
+ None
+ } else {
+ let mut n = 0;
+ while *p.add(n) != 0 {
+ n += 1;
+ }
+ let s = String::from_utf16_lossy(std::slice::from_raw_parts(p, n));
+ GlobalUnlock(h as _);
+ Some(s)
+ }
+ };
+ CloseClipboard();
+ text
+ }
+}
+
+fn set_clipboard_text(text: &str) -> bool {
+ use windows_sys::Win32::System::DataExchange::*;
+ use windows_sys::Win32::System::Memory::*;
+ let units: Vec<u16> = text.encode_utf16().chain(std::iter::once(0)).collect();
+ unsafe {
+ if OpenClipboard(std::ptr::null_mut()) == 0 {
+ return false;
+ }
+ EmptyClipboard();
+ let h = GlobalAlloc(GMEM_MOVEABLE, units.len() * 2);
+ let ok = !h.is_null() && {
+ let p = GlobalLock(h) as *mut u16;
+ !p.is_null() && {
+ std::ptr::copy_nonoverlapping(units.as_ptr(), p, units.len());
+ GlobalUnlock(h);
+ !SetClipboardData(CF_UNICODETEXT, h as _).is_null()
+ }
+ };
+ CloseClipboard();
+ ok
+ }
+}
+
+/// `muxen-agent clip` on Windows: what's copied here goes out; what the app
+/// sends is put on the clipboard. Windows numbers clipboard changes, so a
+/// look every few hundred milliseconds sees each one.
+pub fn clip(rx: std::sync::mpsc::Receiver<String>, changed: impl Fn(&str) -> bool) {
+ use windows_sys::Win32::System::DataExchange::GetClipboardSequenceNumber;
+ let mut seen = unsafe { GetClipboardSequenceNumber() };
+ loop {
+ match rx.recv_timeout(Duration::from_millis(300)) {
+ Ok(text) => {
+ let text: String = text.chars().take(super::clipboard::MAX).collect();
+ if set_clipboard_text(&text) {
+ seen = unsafe { GetClipboardSequenceNumber() };
+ }
+ }
+ Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => return,
+ Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
+ }
+ let now = unsafe { GetClipboardSequenceNumber() };
+ if now != seen {
+ seen = now;
+ if let Some(text) = clipboard_text().filter(|t| !t.is_empty() && t.len() <= super::clipboard::MAX)
+ && !changed(&text)
+ {
+ return;
+ }
+ }
+ }
+}
+
+// --- Running in the signed-in user's desktop session ------------------------
+
+/// Whether this process runs in the session on the screen (not sshd's session 0).
+pub fn in_desktop_session() -> bool {
+ use windows_sys::Win32::System::RemoteDesktop::{ProcessIdToSessionId, WTSGetActiveConsoleSessionId};
+ let mut session = 0u32;
+ unsafe { ProcessIdToSessionId(std::process::id(), &mut session) != 0 && session != 0 && session == WTSGetActiveConsoleSessionId() }
+}
+
+/// Where the desktop session's helper listens: "port token".
+fn gui_port_file() -> std::path::PathBuf {
+ crate::home_dir().join("gui.port")
+}
+
+/// Asks the helper in the desktop session to run `muxen-agent <args>`; its
+/// stdin and stdout, as the connection.
+fn ask_gui_server(args: &[String]) -> io::Result<TcpStream> {
+ let text = std::fs::read_to_string(gui_port_file())?;
+ let (port, token) = text.trim().split_once(' ').ok_or_else(|| io::Error::other("gui.port is damaged"))?;
+ let port: u16 = port.parse().map_err(|_| io::Error::other("gui.port is damaged"))?;
+ let mut s = TcpStream::connect(("127.0.0.1", port))?;
+ s.write_all(format!("{token}\n{}\n", json!({ "run": args })).as_bytes())?;
+ Ok(s)
+}
+
+/// Starts `muxen-agent <args>` in the signed-in user's desktop session; its
+/// stdin and stdout, as a connection. A helper there (`gui-serve`) runs them;
+/// the first time, a one-off scheduled task starts it (through a windowless
+/// console, so nothing flashes on their screen), and it stays a while.
+pub fn start_in_desktop(args: &[String]) -> Result<TcpStream, String> {
+ if let Ok(s) = ask_gui_server(args) {
+ return Ok(s);
+ }
+ let exe = std::env::current_exe().map_err(|e| e.to_string())?;
+ let task = format!("Muxen desktop {}", std::process::id());
+ let q = crate::win::quote;
+ let script = format!(
+ "$action = New-ScheduledTaskAction -Execute 'conhost.exe' -Argument {argument}\n\
+ $principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive -RunLevel Limited\n\
+ $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero)\n\
+ Register-ScheduledTask -TaskName {task} -Action $action -Principal $principal -Settings $settings -Force | Out-Null\n\
+ Start-ScheduledTask -TaskName {task}\n",
+ argument = q(&format!("--headless \"{}\" gui-serve", exe.display())),
+ task = q(&task)
+ );
+ let started = crate::win::ps(&script);
+ // It's up within a few seconds when someone is signed in.
+ let deadline = Instant::now() + Duration::from_secs(12);
+ let result = match started {
+ Err(e) => Err(format!("couldn't start a helper in the desktop session: {e}")),
+ Ok(_) => loop {
+ match ask_gui_server(args) {
+ Ok(s) => break Ok(s),
+ Err(_) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(150)),
+ Err(_) => break Err("Nobody is signed in to Windows' desktop here, so there's no screen to show.".to_string()),
+ }
+ },
+ };
+ let _ = crate::win::ps(&format!("Unregister-ScheduledTask -TaskName {} -Confirm:$false -ErrorAction SilentlyContinue", q(&task)));
+ result
+}
+
+/// With nothing running for this long, the helper goes.
+const GUI_IDLE: Duration = Duration::from_secs(30 * 60);
+
+/// `muxen-agent gui-serve`, in the desktop session: runs what links ask for
+/// (`screen`, `clip`, `displays`) with each connection as the program's stdin
+/// and stdout. A connection sends the token from gui.port, then
+/// `{"run": [args]}`.
+pub fn gui_serve() -> i32 {
+ use ring::rand::SecureRandom;
+ use std::sync::Arc;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ if ask_gui_server(&["version".to_string()]).is_ok() {
+ return 0; // one's already here
+ }
+ let Ok(listener) = TcpListener::bind(("127.0.0.1", 0)) else { return 1 };
+ let Ok(port) = listener.local_addr().map(|a| a.port()) else { return 1 };
+ let mut bytes = [0u8; 24];
+ if ring::rand::SystemRandom::new().fill(&mut bytes).is_err() {
+ return 1;
+ }
+ let token: Arc<String> = Arc::new(bytes.iter().map(|b| format!("{b:02x}")).collect());
+ let tmp = gui_port_file().with_extension(format!("port.{}", std::process::id()));
+ if std::fs::write(&tmp, format!("{port} {token}")).and_then(|_| std::fs::rename(&tmp, gui_port_file())).is_err() {
+ return 1;
+ }
+ let active = Arc::new(AtomicUsize::new(0));
+ let last = Arc::new(std::sync::Mutex::new(Instant::now()));
+ {
+ let (active, last) = (active.clone(), last.clone());
+ std::thread::spawn(move || loop {
+ std::thread::sleep(Duration::from_secs(30));
+ if active.load(Ordering::Relaxed) == 0 && last.lock().unwrap().elapsed() > GUI_IDLE {
+ let _ = std::fs::remove_file(gui_port_file());
+ std::process::exit(0);
+ }
+ });
+ }
+ for conn in listener.incoming().flatten() {
+ let (token, active, last) = (token.clone(), active.clone(), last.clone());
+ std::thread::spawn(move || {
+ let mut conn = conn;
+ let _ = conn.set_read_timeout(Some(Duration::from_secs(5)));
+ let line = |c: &mut TcpStream| -> Option<String> {
+ let mut out = Vec::new();
+ let mut byte = [0u8; 1];
+ while out.len() < 64 * 1024 {
+ match c.read(&mut byte) {
+ Ok(1) if byte[0] == b'\n' => return String::from_utf8(out).ok(),
+ Ok(1) => out.push(byte[0]),
+ _ => return None,
+ }
+ }
+ None
+ };
+ if line(&mut conn).as_deref() != Some(token.as_str()) {
+ return;
+ }
+ let Some(req) = line(&mut conn).and_then(|l| serde_json::from_str::<Value>(&l).ok()) else { return };
+ let args: Vec<String> = req["run"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default();
+ // Only the programs that need the desktop session.
+ if !matches!(args.first().map(String::as_str), Some("screen" | "clip" | "displays" | "version")) {
+ return;
+ }
+ let _ = conn.set_read_timeout(None);
+ active.fetch_add(1, Ordering::Relaxed);
+ serve_program(conn, &args);
+ active.fetch_sub(1, Ordering::Relaxed);
+ *last.lock().unwrap() = Instant::now();
+ });
+ }
+ 0
+}
+
+/// Runs `muxen-agent <args>` with the connection as its stdin and stdout, until either ends.
+fn serve_program(mut conn: TcpStream, args: &[String]) {
+ let Ok(exe) = std::env::current_exe() else { return };
+ let log = std::fs::OpenOptions::new().create(true).append(true).open(crate::home_dir().join("screen.log"));
+ let mut cmd = Command::new(exe);
+ cmd.args(args).stdin(Stdio::piped()).stdout(Stdio::piped());
+ match log {
+ Ok(l) => cmd.stderr(l),
+ Err(_) => cmd.stderr(Stdio::null()),
+ };
+ crate::sys::no_window(&mut cmd);
+ let Ok(mut child) = cmd.spawn() else { return };
+ let (Some(mut stdin), Some(mut stdout)) = (child.stdin.take(), child.stdout.take()) else {
+ let _ = child.kill();
+ return;
+ };
+ let Ok(mut from_link) = conn.try_clone() else {
+ let _ = child.kill();
+ return;
+ };
+ // The link side's end shows here as the end of its input.
+ let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
+ std::thread::spawn(move || {
+ let _ = io::copy(&mut from_link, &mut stdin);
+ let _ = done_tx.send(());
+ });
+ let _ = io::copy(&mut stdout, &mut conn);
+ let _ = child.kill();
+ let _ = child.wait();
+ // Close our side properly and let the other read everything first: a
+ // socket closed abruptly is reset, and a reset loses whatever the other
+ // side hadn't read yet.
+ let _ = conn.shutdown(std::net::Shutdown::Write);
+ let _ = done_rx.recv_timeout(Duration::from_secs(10));
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn maps_keys() {
+ assert_eq!(vk_of('a' as u32), Some((0x41, false)));
+ assert_eq!(vk_of('A' as u32), Some((0x41, false)));
+ assert_eq!(vk_of(0xff0d), Some((VK_RETURN, false)));
+ assert_eq!(vk_of(0xff51), Some((VK_LEFT, true)));
+ assert_eq!(vk_of(0xffbe), Some((VK_F1, false)));
+ }
+}
diff --git a/build.rs b/build.rs
new file mode 100644
index 0000000..5b7680e
--- /dev/null
+++ b/build.rs
@@ -0,0 +1,17 @@
+//! Windows: the app's icon (resource 1, which GPUI gives the window) and
+//! its name in the executable's properties. Nothing to do elsewhere.
+
+fn main() {
+ println!("cargo:rerun-if-changed=assets/brand/muxen.ico");
+ #[cfg(windows)]
+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
+ let mut res = winresource::WindowsResource::new();
+ res.set_icon_with_id("assets/brand/muxen.ico", "1");
+ res.set("ProductName", "Muxen");
+ res.set("FileDescription", "Muxen");
+ res.set("CompanyName", "Lumary Labs");
+ if let Err(e) = res.compile() {
+ println!("cargo:warning=couldn't embed the icon: {e}");
+ }
+ }
+}
diff --git a/scripts/build-agents.sh b/scripts/build-agents.sh
index c3eab33..0406459 100755
--- a/scripts/build-agents.sh
+++ b/scripts/build-agents.sh
@@ -4,17 +4,18 @@
# to each machine (~/.muxen/bin) when it connects.
#
# Needs: rustup targets (x86_64-apple-darwin, aarch64-apple-darwin,
-# x86_64-unknown-linux-musl, aarch64-unknown-linux-musl), cargo-zigbuild and zig
-# for the Linux builds (static musl binaries that run on any distro).
+# x86_64-unknown-linux-musl, aarch64-unknown-linux-musl, x86_64-pc-windows-gnu),
+# cargo-zigbuild and zig for the Linux builds (static musl binaries that run on
+# any distro) and the Windows one.
set -eu
cd "$(dirname "$0")/.."
out=dist/agents
mkdir -p "$out"
-build() { # <target> <name> <cargo subcommand>
+build() { # <target> <name> <cargo subcommand> [<.exe>]
echo "▸ $2"
cargo "$3" --release -p muxen-agent --target "$1" --quiet
- cp "target/$1/release/muxen-agent" "$out/muxen-agent-$2"
+ cp "target/$1/release/muxen-agent${4:-}" "$out/muxen-agent-$2${4:-}"
}
case "$(uname -s)" in
@@ -37,4 +38,5 @@ case "$(uname -s)" in
esac
build x86_64-unknown-linux-musl linux-x86_64 zigbuild
build aarch64-unknown-linux-musl linux-aarch64 zigbuild
+build x86_64-pc-windows-gnu windows-x86_64 zigbuild .exe
ls -lh "$out"
diff --git a/scripts/package-windows.ps1 b/scripts/package-windows.ps1
new file mode 100644
index 0000000..7bdd8f7
--- /dev/null
+++ b/scripts/package-windows.ps1
@@ -0,0 +1,31 @@
+# Builds Muxen for Windows and packs it: dist\Muxen-windows-x64.zip, with
+# muxen.exe and, beside it in agents\, the agent builds it sets up on each
+# machine (made on a Mac or Linux by scripts/build-agents.sh).
+#
+# Needs: Rust, Visual Studio's C++ build tools and the Windows SDK (for
+# GPUI's shaders and the icon).
+param([switch]$SkipBuild)
+$ErrorActionPreference = 'Stop'
+Set-Location (Split-Path $PSScriptRoot -Parent)
+# GPUI compiles its shaders with the Windows SDK's fxc.exe.
+if (-not $env:GPUI_FXC_PATH -and -not (Get-Command fxc.exe -ErrorAction SilentlyContinue)) {
+ $fxc = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin" -Recurse -Filter fxc.exe -ErrorAction SilentlyContinue | Where-Object { $_.FullName -match '\\x64\\' } | Sort-Object FullName -Descending | Select-Object -First 1
+ if (-not $fxc) { throw "The Windows SDK's fxc.exe isn't installed (Visual Studio Installer > Windows SDK)." }
+ $env:GPUI_FXC_PATH = $fxc.FullName
+}
+if (-not $SkipBuild) {
+ cargo build --release
+ if ($LASTEXITCODE) { exit $LASTEXITCODE }
+}
+$agents = @(Get-ChildItem dist\agents -Filter 'muxen-agent-*' -ErrorAction SilentlyContinue)
+if ($agents.Count -eq 0) { throw 'No agent builds in dist\agents: run scripts/build-agents.sh on a Mac or Linux first.' }
+$root = 'dist\windows'
+$out = Join-Path $root 'Muxen'
+Remove-Item -Recurse -Force $root -ErrorAction SilentlyContinue
+New-Item -ItemType Directory -Force (Join-Path $out 'agents') | Out-Null
+Copy-Item target\release\muxen.exe $out
+$agents | Copy-Item -Destination (Join-Path $out 'agents')
+Copy-Item README.md, LICENSE, THIRD_PARTY_NOTICES.md $out
+$zip = 'dist\Muxen-windows-x64.zip'
+Compress-Archive -Path $out -DestinationPath $zip -Force
+"Built $zip ($([math]::Round((Get-Item $zip).Length / 1MB, 1)) MB)"
diff --git a/src/api.rs b/src/api.rs
index bd8098f..22cfbbd 100644
--- a/src/api.rs
+++ b/src/api.rs
@@ -2780,7 +2780,7 @@ pub async fn github_accounts(engine: &Arc<Engine>) -> ApiResult<AccountsOut> {
.current()
.machines
.iter()
- .filter(|m| m.host != "local" && m.gh.is_none() && m.status == "online" && !m.platform.starts_with("windows"))
+ .filter(|m| m.host != "local" && m.gh.is_none() && m.status == "online")
.map(|m| m.id.clone())
.collect();
let (accounts, viewer, orgs, _) = futures::join!(
diff --git a/src/cloud/secrets.rs b/src/cloud/secrets.rs
index c08e5b2..51e2381 100644
--- a/src/cloud/secrets.rs
+++ b/src/cloud/secrets.rs
@@ -1,8 +1,10 @@
-//! Secrets Muxen keeps for the user (cloud tokens): in the macOS Keychain, or
-//! elsewhere in a file only the user can read, next to config.toml.
+//! Secrets Muxen keeps for the user (cloud tokens): in the macOS Keychain, in
+//! Windows' Credential Manager, or elsewhere in a file only the user can
+//! read, next to config.toml.
use std::path::{Path, PathBuf};
+#[cfg(any(target_os = "macos", windows))]
const SERVICE: &str = "Muxen";
/// Stores a secret under a name ("digitalocean-token").
@@ -12,7 +14,12 @@ pub fn set(dir: &Path, name: &str, value: &str) -> Result<(), String> {
let _ = dir;
security_framework::passwords::set_generic_password(SERVICE, name, value.as_bytes()).map_err(|e| format!("Couldn't save to the Keychain: {e}"))
}
- #[cfg(not(target_os = "macos"))]
+ #[cfg(windows)]
+ {
+ let _ = dir;
+ credentials::set(name, value).map_err(|e| format!("Couldn't save to Windows' Credential Manager: {e}"))
+ }
+ #[cfg(not(any(target_os = "macos", windows)))]
{
let mut all = read_file(dir);
all.insert(name.to_string(), value.to_string());
@@ -26,7 +33,12 @@ pub fn get(dir: &Path, name: &str) -> Option<String> {
let _ = dir;
security_framework::passwords::get_generic_password(SERVICE, name).ok().and_then(|b| String::from_utf8(b).ok()).filter(|s| !s.is_empty())
}
- #[cfg(not(target_os = "macos"))]
+ #[cfg(windows)]
+ {
+ let _ = dir;
+ credentials::get(name).filter(|s| !s.is_empty())
+ }
+ #[cfg(not(any(target_os = "macos", windows)))]
{
read_file(dir).remove(name).filter(|s| !s.is_empty())
}
@@ -38,7 +50,12 @@ pub fn delete(dir: &Path, name: &str) {
let _ = dir;
let _ = security_framework::passwords::delete_generic_password(SERVICE, name);
}
- #[cfg(not(target_os = "macos"))]
+ #[cfg(windows)]
+ {
+ let _ = dir;
+ credentials::delete(name);
+ }
+ #[cfg(not(any(target_os = "macos", windows)))]
{
let mut all = read_file(dir);
if all.remove(name).is_some() {
@@ -47,17 +64,70 @@ pub fn delete(dir: &Path, name: &str) {
}
}
+/// Windows' Credential Manager: generic credentials named "Muxen/<name>",
+/// for this user, kept on this computer.
+#[cfg(windows)]
+mod credentials {
+ use windows_sys::Win32::Foundation::FILETIME;
+ use windows_sys::Win32::Security::Credentials::*;
+
+ fn target(name: &str) -> Vec<u16> {
+ format!("{}/{name}", super::SERVICE).encode_utf16().chain(std::iter::once(0)).collect()
+ }
+
+ pub fn set(name: &str, value: &str) -> Result<(), String> {
+ let mut target = target(name);
+ let mut user: Vec<u16> = "Muxen".encode_utf16().chain(std::iter::once(0)).collect();
+ let mut blob = value.as_bytes().to_vec();
+ let cred = CREDENTIALW {
+ Flags: 0,
+ Type: CRED_TYPE_GENERIC,
+ TargetName: target.as_mut_ptr(),
+ Comment: std::ptr::null_mut(),
+ LastWritten: FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 },
+ CredentialBlobSize: blob.len() as u32,
+ CredentialBlob: blob.as_mut_ptr(),
+ Persist: CRED_PERSIST_LOCAL_MACHINE,
+ AttributeCount: 0,
+ Attributes: std::ptr::null_mut(),
+ TargetAlias: std::ptr::null_mut(),
+ UserName: user.as_mut_ptr(),
+ };
+ if unsafe { CredWriteW(&cred, 0) } != 0 { Ok(()) } else { Err(std::io::Error::last_os_error().to_string()) }
+ }
+
+ pub fn get(name: &str) -> Option<String> {
+ let target = target(name);
+ let mut found: *mut CREDENTIALW = std::ptr::null_mut();
+ if unsafe { CredReadW(target.as_ptr(), CRED_TYPE_GENERIC, 0, &mut found) } == 0 || found.is_null() {
+ return None;
+ }
+ let value = unsafe {
+ let c = &*found;
+ let bytes = std::slice::from_raw_parts(c.CredentialBlob, c.CredentialBlobSize as usize);
+ String::from_utf8(bytes.to_vec()).ok()
+ };
+ unsafe { CredFree(found as *const std::ffi::c_void) };
+ value
+ }
+
+ pub fn delete(name: &str) {
+ let target = target(name);
+ unsafe { CredDeleteW(target.as_ptr(), CRED_TYPE_GENERIC, 0) };
+ }
+}
+
#[allow(dead_code)]
fn file(dir: &Path) -> PathBuf {
dir.join("secrets.json")
}
-#[cfg(not(target_os = "macos"))]
+#[cfg(not(any(target_os = "macos", windows)))]
fn read_file(dir: &Path) -> std::collections::BTreeMap<String, String> {
std::fs::read_to_string(file(dir)).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
}
-#[cfg(not(target_os = "macos"))]
+#[cfg(not(any(target_os = "macos", windows)))]
fn write_file(dir: &Path, all: &std::collections::BTreeMap<String, String>) -> Result<(), String> {
let path = file(dir);
let bytes = serde_json::to_vec_pretty(all).map_err(|e| e.to_string())?;
diff --git a/src/fleet/code.rs b/src/fleet/code.rs
index cd9fdf7..7aa8043 100644
--- a/src/fleet/code.rs
+++ b/src/fleet/code.rs
@@ -12,7 +12,7 @@ use super::Engine;
use super::model::Checkout;
use super::sessions::agent;
use crate::github::hub::repo_name;
-use crate::ops::remote::{sh_quote, shell_for};
+use crate::ops::remote::{ps_quote, sh_quote, shell_for};
use crate::probe::Shell;
impl Engine {
@@ -22,7 +22,7 @@ impl Engine {
if self.demo_world().is_some() {
return Ok(self.checkouts_of(&spec.id));
}
- if !spec.is_checkable() || matches!(shell_for(&spec, probe.as_ref()), Shell::Powershell) {
+ if !spec.is_checkable() {
return Ok(Vec::new());
}
agent::ensure(&spec, probe.as_ref()).await?;
@@ -87,6 +87,17 @@ for f in "$HOME"/.ssh/id_*; do case "$f" in *.pub) ;; *) [ -f "$f" ] && echo "ke
exit 0
"#;
+/// The same, from PowerShell (Windows).
+const GIT_STATUS_PS1: &str = r#"$g = Get-Command git -ErrorAction SilentlyContinue
+if (-not $g) { 'git='; return }
+'git=' + ((git --version) -replace '^git version ', '' -replace '\.windows.*$', '')
+Set-Location $env:USERPROFILE
+'name=' + (git config user.name)
+'email=' + (git config user.email)
+git config --get-regexp '^credential\.' 2>$null | ForEach-Object { 'cred=' + $_ }
+Get-ChildItem (Join-Path $env:USERPROFILE '.ssh') -Filter 'id_*' -ErrorAction SilentlyContinue | Where-Object { $_.Extension -ne '.pub' } | ForEach-Object { 'key=' + $_.Name }
+"#;
+
impl Engine {
/// Reads how git is set up on a machine.
pub async fn git_setup_status(self: &Arc<Self>, machine_id: &str) -> Result<GitSetup, String> {
@@ -94,10 +105,14 @@ impl Engine {
if self.demo_world().is_some() {
return Ok(GitSetup { git: Some("2.47.0".into()), ..Default::default() });
}
- if !spec.is_checkable() || matches!(shell_for(&spec, probe.as_ref()), Shell::Powershell) {
- return Err(format!("Setting up git on {} isn't supported yet.", spec.name));
+ if !spec.is_checkable() {
+ return Err(format!("{} has no host to connect to.", spec.name));
}
- let out = agent::run_sh(&spec, GIT_STATUS_SH, std::time::Duration::from_secs(25)).await?;
+ let out = if matches!(shell_for(&spec, probe.as_ref()), Shell::Powershell) {
+ agent::run_ps(&spec, GIT_STATUS_PS1, std::time::Duration::from_secs(25)).await?
+ } else {
+ agent::run_sh(&spec, GIT_STATUS_SH, std::time::Duration::from_secs(25)).await?
+ };
Ok(parse_git_setup(&out))
}
@@ -105,17 +120,19 @@ impl Engine {
/// makes git use the machine's GitHub CLI login for github.com
/// (`gh auth setup-git`). Returns the new state.
pub async fn git_setup_apply(self: &Arc<Self>, machine_id: &str, identity: Option<(String, String)>, credentials: bool) -> Result<GitSetup, String> {
- let (spec, _) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
+ let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
if self.demo_world().is_some() {
return Ok(GitSetup { git: Some("2.47.0".into()), uses_gh: credentials, ..Default::default() });
}
- let mut script = String::from("set -e\n");
+ let windows = matches!(shell_for(&spec, probe.as_ref()), Shell::Powershell);
+ let q = |s: &str| if windows { ps_quote(s) } else { sh_quote(s) };
+ let mut script = String::from(if windows { "$ErrorActionPreference = 'Stop'\n" } else { "set -e\n" });
if let Some((name, email)) = &identity {
let bad = |s: &str| s.trim().is_empty() || s.len() > 200 || s.chars().any(char::is_control);
if bad(name) || bad(email) || !email.contains('@') || email.contains(char::is_whitespace) {
return Err("Give a name and an email address (like [email protected]).".into());
}
- script.push_str(&format!("git config --global user.name {}\ngit config --global user.email {}\n", sh_quote(name.trim()), sh_quote(email.trim())));
+ script.push_str(&format!("git config --global user.name {}\ngit config --global user.email {}\n", q(name.trim()), q(email.trim())));
}
if credentials {
let gh = self.sessions_of(&spec.id).and_then(|s| s.gh);
@@ -123,10 +140,14 @@ impl Engine {
return Err(format!("Sign in to the GitHub CLI on {} first; git will then use that login.", spec.name));
}
let gh = gh.and_then(|g| g.path).unwrap_or_else(|| "gh".into());
- script.push_str(&format!("{} auth setup-git --hostname github.com\n", sh_quote(&gh)));
+ script.push_str(&format!("{}{} auth setup-git --hostname github.com\n", if windows { "& " } else { "" }, q(&gh)));
}
if identity.is_some() || credentials {
- agent::run_sh(&spec, &script, std::time::Duration::from_secs(30)).await?;
+ if windows {
+ agent::run_ps(&spec, &script, std::time::Duration::from_secs(30)).await?;
+ } else {
+ agent::run_sh(&spec, &script, std::time::Duration::from_secs(30)).await?;
+ }
}
self.git_setup_status(&spec.id).await
}
diff --git a/src/fleet/command.rs b/src/fleet/command.rs
index 749de14..39f74d8 100644
--- a/src/fleet/command.rs
+++ b/src/fleet/command.rs
@@ -23,10 +23,19 @@ fn sh_script(command: &str) -> String {
)
}
-/// PowerShell, for Windows machines.
+/// PowerShell, for Windows machines: the command in a script file of its
+/// own, run by its own PowerShell from the home folder, as in a terminal (its
+/// output formatted as text, its `exit` its exit status).
fn ps_script(command: &str) -> String {
format!(
- "$OR_CMD = '{}'\nSet-Location $HOME\n$global:LASTEXITCODE = 0\ntry {{ & ([ScriptBlock]::Create($OR_CMD)) 2>&1 | ForEach-Object {{ \"$_\" }}; $c = if ($?) {{ $LASTEXITCODE }} else {{ 1 }} }} catch {{ [Console]::Error.WriteLine(\"error: $_\"); $c = 1 }}\n[Console]::Error.WriteLine(\"${{OR_MARK}}:exit=$c\")\n",
+ "$OR_CMD = '{}'\n\
+ $f = Join-Path ([IO.Path]::GetTempPath()) (\"muxen-run-$PID.ps1\")\n\
+ Set-Content -LiteralPath $f -Value $OR_CMD -Encoding UTF8\n\
+ Set-Location $env:USERPROFILE\n\
+ & powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $f\n\
+ $c = $LASTEXITCODE\n\
+ Remove-Item -LiteralPath $f -Force -ErrorAction SilentlyContinue\n\
+ [Console]::Error.WriteLine(\"${{OR_MARK}}:exit=$c\")\n",
command.replace('\'', "''")
)
}
diff --git a/src/fleet/editor.rs b/src/fleet/editor.rs
index 97d61de..225ba43 100644
--- a/src/fleet/editor.rs
+++ b/src/fleet/editor.rs
@@ -34,7 +34,13 @@ pub fn installed() -> Vec<Editor> {
.map(|d| d.join(cmd))
.find(|f| f.is_file())
};
+ #[cfg(not(windows))]
let find = |app: &str, inside: &str, cmd: &str| apps(app).into_iter().map(|a| a.join(inside)).find(|p| p.is_file()).or_else(|| on_path(cmd));
+ #[cfg(windows)]
+ let find = |_: &str, _: &str, cmd: &str| {
+ let _ = (&apps, &on_path);
+ windows_editor(cmd)
+ };
let mut out = Vec::new();
for (id, name, app, inside, cmd) in [
("zed", "Zed", "Zed.app", "Contents/MacOS/cli", "zed"),
@@ -48,6 +54,25 @@ pub fn installed() -> Vec<Editor> {
out
}
+/// Windows: an editor's command (`code.cmd`, `cursor.cmd`, `zed.exe`) on
+/// PATH, or where its installer puts it for this user or everyone.
+#[cfg(windows)]
+fn windows_editor(cmd: &str) -> Option<PathBuf> {
+ let local = std::env::var_os("LOCALAPPDATA").map(PathBuf::from).unwrap_or_default();
+ let program_files = std::env::var_os("ProgramFiles").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(r"C:\Program Files"));
+ let known: Vec<PathBuf> = match cmd {
+ "code" => vec![local.join(r"Programs\Microsoft VS Code\bin\code.cmd"), program_files.join(r"Microsoft VS Code\bin\code.cmd")],
+ "cursor" => vec![local.join(r"Programs\cursor\resources\app\bin\cursor.cmd")],
+ "zed" => vec![local.join(r"Programs\Zed\bin\zed.exe"), local.join(r"Programs\Zed\Zed.exe")],
+ _ => Vec::new(),
+ };
+ let on_path = std::env::var_os("PATH")
+ .into_iter()
+ .flat_map(|p| std::env::split_paths(&p).collect::<Vec<_>>())
+ .flat_map(|d| [format!("{cmd}.cmd"), format!("{cmd}.exe")].map(|f| d.join(f)));
+ known.into_iter().chain(on_path).find(|p| p.is_file())
+}
+
/// The editor to use: the one chosen (by id) when it's here, else the first one here.
pub fn pick(chosen: &str) -> Option<Editor> {
let all = installed();
@@ -143,6 +168,12 @@ impl Engine {
let home = dirs::home_dir().unwrap_or_default();
let rest = path.trim_start_matches('~').trim_start_matches('/');
home.join(rest).display().to_string()
+ } else if super::sessions::agent::is_windows(&spec) {
+ // "C:\Users\me\code" as "/c:/Users/me/code", as Remote - SSH names Windows folders.
+ let rest = path.trim_start_matches('~').trim_start_matches(['/', '\\']);
+ let script = format!("(Resolve-Path -LiteralPath (Join-Path $env:USERPROFILE {})).Path", crate::ops::remote::ps_quote(rest));
+ let found = super::sessions::agent::run_ps(&spec, &script, Duration::from_secs(15)).await.map_err(|e| format!("Couldn't find {path} on {}: {e}", spec.name))?;
+ windows_path(found.trim())
} else {
let rest = path.trim_start_matches('~').trim_start_matches('/');
let script = if rest.is_empty() { "cd ~ && pwd".to_string() } else { format!("cd ~/{} && pwd", crate::ops::remote::sh_quote(rest)) };
@@ -158,6 +189,15 @@ impl Engine {
}
}
+/// A Windows path as a URI path: `C:\x\y` as `/c:/x/y`.
+fn windows_path(p: &str) -> String {
+ let p = p.replace('\\', "/");
+ match p.split_once(':') {
+ Some((drive, rest)) if drive.len() == 1 => format!("/{}:{}", drive.to_ascii_lowercase(), rest.trim_end_matches('/')),
+ _ => p,
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -177,5 +217,7 @@ mod tests {
assert_eq!(args(&zed, &spec("box.lan", Some("me"), Some(2222)), "/srv"), ["ssh://[email protected]:2222/srv"]);
assert_eq!(args(&code, &spec("beelink", None, None), "/home/adib/api"), ["--folder-uri", "vscode-remote://ssh-remote+beelink/home/adib/api"]);
assert_eq!(args(&code, &spec("local", None, None), "/Users/me/x"), ["/Users/me/x"]);
+ assert_eq!(windows_path(r"C:\Users\adib\Downloads"), "/c:/Users/adib/Downloads");
+ assert_eq!(args(&code, &spec("win11", None, None), "/c:/Users/adib"), ["--folder-uri", "vscode-remote://ssh-remote+win11/c:/Users/adib"]);
}
}
diff --git a/src/fleet/engine.rs b/src/fleet/engine.rs
index 65da59a..d6e4100 100644
--- a/src/fleet/engine.rs
+++ b/src/fleet/engine.rs
@@ -113,6 +113,9 @@ impl Engine {
)
}
};
+ for (id, p) in &persisted.probes {
+ crate::fleet::sessions::agent::note_os(id, p.os.as_deref());
+ }
let state = State {
inventory,
inventory_info,
@@ -960,6 +963,7 @@ impl Engine {
let result = result.after(st.probes.get(&id));
// Its monitors are worth knowing when it has a desktop to show.
let desktop = result.os.as_deref() == Some("darwin") || result.desktop == Some(true);
+ crate::fleet::sessions::agent::note_os(&id, result.os.as_deref());
st.probes.insert(id.clone(), result);
self.publish(&mut st);
drop(st);
diff --git a/src/fleet/files.rs b/src/fleet/files.rs
index d10565a..9ecc53e 100644
--- a/src/fleet/files.rs
+++ b/src/fleet/files.rs
@@ -78,7 +78,7 @@ impl Engine {
if self.demo_world().is_some() {
return Ok(demo_listing(&spec, path));
}
- let l = self.files_link(&spec).await.ok_or_else(|| format!("Browsing {} needs Muxen's agent there (Linux or macOS).", spec.name))?;
+ let l = self.files_link(&spec).await.ok_or_else(|| format!("Browsing {} needs Muxen's agent there.", spec.name))?;
let r = l.request(json!({ "op": "files", "path": if path.trim().is_empty() { "~" } else { path } }), Duration::from_secs(20)).await?;
if r["ok"].as_bool() != Some(true) {
return Err(r["error"].as_str().unwrap_or("Couldn't list that folder.").to_string());
@@ -134,7 +134,7 @@ impl Engine {
/// Copies and waits; returns the bytes moved (the tar stream's size).
#[allow(clippy::too_many_arguments)]
- async fn run_copy(self: &Arc<Self>, id: u64, from: &MachineSpec, dir: &str, names: &[String], to: &MachineSpec, to_dir: &str, cancel: &AtomicBool) -> Result<u64, String> {
+ pub(crate) async fn run_copy(self: &Arc<Self>, id: u64, from: &MachineSpec, dir: &str, names: &[String], to: &MachineSpec, to_dir: &str, cancel: &AtomicBool) -> Result<u64, String> {
let src_place = format!("{}:{}", from.id, dir);
let dst_place = format!("{}:{}", to.id, to_dir);
self.op_log(id, format!("{} → {}", names.iter().map(|n| format!("{src_place}/{n}")).collect::<Vec<_>>().join(", "), dst_place));
diff --git a/src/fleet/link.rs b/src/fleet/link.rs
index 0a07cdd..04ccae0 100644
--- a/src/fleet/link.rs
+++ b/src/fleet/link.rs
@@ -272,7 +272,8 @@ pub fn reset(machine_id: &str) {
}
fn local_agent() -> PathBuf {
- dirs::home_dir().unwrap_or_default().join(".muxen/bin/muxen-agent")
+ let bin = dirs::home_dir().unwrap_or_default().join(".muxen").join("bin");
+ bin.join(if cfg!(windows) { "muxen-agent.exe" } else { "muxen-agent" })
}
/// Directly when the machine is paired and reachable, else over ssh.
@@ -310,7 +311,7 @@ async fn connect_ssh(spec: &MachineSpec) -> Result<Arc<Link>, String> {
} else {
let mut c = Command::new("ssh");
c.args(probe::ssh_args(spec));
- c.arg(format!("{} link", super::sessions::agent::REMOTE_PATH));
+ c.arg(super::sessions::agent::command(spec, "link"));
c
};
cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).kill_on_drop(true);
diff --git a/src/fleet/sessions/agent.rs b/src/fleet/sessions/agent.rs
index bc523dc..b1dbeac 100644
--- a/src/fleet/sessions/agent.rs
+++ b/src/fleet/sessions/agent.rs
@@ -20,6 +20,7 @@ use crate::ops::remote::sh_quote;
use crate::probe::{self, ProbeResult};
/// Where the agent lives on every machine (and how attach commands name it).
+/// Windows: `%USERPROFILE%\.muxen\bin\muxen-agent.exe` (see `command`).
pub const REMOTE_PATH: &str = "~/.muxen/bin/muxen-agent";
const CTL_TIMEOUT: Duration = Duration::from_secs(25);
const UPLOAD_TIMEOUT: Duration = Duration::from_secs(180);
@@ -30,6 +31,7 @@ pub fn target(probe: Option<&ProbeResult>) -> Option<String> {
let os = match p.os.as_deref()? {
"darwin" | "macos" => "darwin",
"linux" => "linux",
+ "windows" => "windows",
_ => return None,
};
let arch = match p.arch.as_deref()?.to_ascii_lowercase().as_str() {
@@ -56,10 +58,16 @@ pub fn builds_dir() -> Option<PathBuf> {
dir.ancestors().map(|a| a.join("dist/agents")).find(|c| c.is_dir())
}
+/// Where the build for `target` is.
+fn build_path(target: &str) -> Result<PathBuf, String> {
+ let dir = builds_dir().ok_or("Muxen can't find its agent builds (run scripts/build-agents.sh in a source checkout).")?;
+ let exe = if target.starts_with("windows") { ".exe" } else { "" };
+ Ok(dir.join(format!("muxen-agent-{target}{exe}")))
+}
+
/// The build for `target` and its hash (what `muxen-agent hash` prints).
fn build(target: &str) -> Result<(Vec<u8>, String), String> {
- let dir = builds_dir().ok_or("Muxen can't find its agent builds (run scripts/build-agents.sh in a source checkout).")?;
- let path = dir.join(format!("muxen-agent-{target}"));
+ let path = build_path(target)?;
let bytes = std::fs::read(&path).map_err(|_| format!("Muxen has no agent build for {target} machines yet."))?;
let hash = format!("{:016x}", fnv(&bytes));
Ok((bytes, hash))
@@ -74,6 +82,42 @@ fn fnv(bytes: &[u8]) -> u64 {
h
}
+/// Which machines run Windows, by machine id, as their last check said (so
+/// links and requests know how to name the agent there).
+fn windows_machines() -> &'static Mutex<HashMap<String, bool>> {
+ static OS: OnceLock<Mutex<HashMap<String, bool>>> = OnceLock::new();
+ OS.get_or_init(Default::default)
+}
+
+/// Remembers a machine's OS from its check.
+pub fn note_os(machine_id: &str, os: Option<&str>) {
+ if let Some(os) = os {
+ windows_machines().lock().unwrap().insert(machine_id.to_string(), os == "windows");
+ }
+}
+
+/// Whether a machine runs Windows (as far as its last check says).
+pub fn is_windows(spec: &MachineSpec) -> bool {
+ if spec.is_local() {
+ return cfg!(windows);
+ }
+ windows_machines().lock().unwrap().get(&spec.id).copied().unwrap_or(false)
+}
+
+/// The command line ssh hands the machine's shell to run `muxen-agent <args>`.
+/// On Windows it's PowerShell with an encoded command, which reads the same
+/// whether sshd's shell is cmd.exe or PowerShell.
+pub fn command(spec: &MachineSpec, args: &str) -> String {
+ if is_windows(spec) {
+ use base64::Engine as _;
+ let call = format!("& (Join-Path $env:USERPROFILE '.muxen\\bin\\muxen-agent.exe') {args}");
+ let utf16: Vec<u8> = call.encode_utf16().flat_map(u16::to_le_bytes).collect();
+ format!("powershell -NoProfile -NonInteractive -EncodedCommand {}", base64::engine::general_purpose::STANDARD.encode(utf16))
+ } else {
+ format!("{REMOTE_PATH} {args}")
+ }
+}
+
/// Machines already checked to have the right build, by machine id.
fn verified() -> &'static Mutex<HashMap<String, String>> {
static VERIFIED: OnceLock<Mutex<HashMap<String, String>>> = OnceLock::new();
@@ -101,10 +145,17 @@ pub async fn ensure(spec: &MachineSpec, probe: Option<&ProbeResult>) -> Result<(
if verified().lock().unwrap().get(&spec.id) == Some(&hash) {
return Ok(());
}
- let installed = run_sh(spec, &format!("a={REMOTE_PATH}; if [ -x \"$a\" ]; then \"$a\" hash; else echo none; fi"), CTL_TIMEOUT).await?;
+ let windows = target.starts_with("windows");
+ note_os(&spec.id, Some(if windows { "windows" } else { "unix" }));
+ let installed = if windows {
+ run_ps(spec, "$a = Join-Path $env:USERPROFILE '.muxen\\bin\\muxen-agent.exe'; if (Test-Path $a) { & $a hash } else { 'none' }", CTL_TIMEOUT).await?
+ } else {
+ run_sh(spec, &format!("a={REMOTE_PATH}; if [ -x \"$a\" ]; then \"$a\" hash; else echo none; fi"), CTL_TIMEOUT).await?
+ };
if installed.trim() != hash {
tracing::info!("installing muxen-agent ({target}) on {}", spec.name);
- let got = upload(spec, bytes).await?;
+ // Boxed: these futures are big, and `ensure` sits inside nearly every request's.
+ let got = if windows { Box::pin(upload_windows(spec, &build_path(&target)?)).await? } else { Box::pin(upload(spec, bytes)).await? };
if got.trim() != hash {
return Err(format!("The agent didn't install correctly on {} (got {}).", spec.name, got.trim()));
}
@@ -157,10 +208,73 @@ async fn upload(spec: &MachineSpec, bytes: Vec<u8>) -> Result<String, String> {
tokio::time::timeout(UPLOAD_TIMEOUT, work).await.map_err(|_| format!("{} took too long to receive the agent.", spec.name))?
}
+/// Copies the build into place on Windows and prints its hash. The file goes
+/// over sftp (Windows' sshd stalls on a few hundred KB through a program's
+/// stdin), then PowerShell puts it in place. A running agent holds its file,
+/// but Windows lets it be renamed: the old one moves aside and goes once
+/// nothing runs it.
+async fn upload_windows(spec: &MachineSpec, build: &std::path::Path) -> Result<String, String> {
+ let fail = |e: String| format!("couldn't install the agent on {}: {e}", spec.name);
+ if spec.is_local() {
+ return Err(fail("Muxen doesn't set up its agent on this Windows computer yet.".into()));
+ }
+ // sftp takes ssh's options, but its own spelling of the port and user.
+ let mut args: Vec<String> = Vec::new();
+ let mut ssh = probe::ssh_args(spec).into_iter().filter(|a| a != "-T").peekable();
+ while let Some(a) = ssh.next() {
+ match a.as_str() {
+ "-p" => args.extend(["-P".into(), ssh.next().unwrap_or_default()]),
+ "-l" => args.extend(["-o".into(), format!("User={}", ssh.next().unwrap_or_default())]),
+ _ => args.push(a),
+ }
+ }
+ let batch = format!("-mkdir .muxen\n-mkdir .muxen/bin\nput \"{}\" .muxen/bin/muxen-agent.upload.exe\n", build.display());
+ let mut cmd = Command::new("sftp");
+ cmd.args(["-q", "-b", "-"]).args(&args).stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::piped()).kill_on_drop(true);
+ let mut child = cmd.spawn().map_err(|e| fail(format!("couldn't run sftp: {e}")))?;
+ let mut stdin = child.stdin.take().ok_or("no stdin")?;
+ let mut stderr = child.stderr.take().ok_or("no stderr")?;
+ let sent = async move {
+ stdin.write_all(batch.as_bytes()).await.map_err(|e| e.to_string())?;
+ drop(stdin);
+ let mut err = String::new();
+ let _ = stderr.read_to_string(&mut err).await;
+ let status = child.wait().await.map_err(|e| e.to_string())?;
+ if status.success() { Ok(()) } else { Err(err.lines().last().unwrap_or("sftp failed").trim().to_string()) }
+ };
+ tokio::time::timeout(UPLOAD_TIMEOUT, sent).await.map_err(|_| fail("the copy took too long".into()))?.map_err(fail)?;
+ let script = "$ErrorActionPreference = 'Stop'\n\
+ $d = Join-Path $env:USERPROFILE '.muxen\\bin'\n\
+ $t = Join-Path $d 'muxen-agent.exe'\n\
+ if (Test-Path $t) { Move-Item -Force $t (Join-Path $d \"muxen-agent.old.$PID.exe\") }\n\
+ Move-Item -Force (Join-Path $d 'muxen-agent.upload.exe') $t\n\
+ Get-CimInstance Win32_Process -Filter \"Name='muxen-agent.exe'\" | Where-Object { $_.CommandLine -match ' gui-serve' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }\n\
+ Get-ChildItem $d -Filter 'muxen-agent.old.*.exe' | ForEach-Object { Remove-Item -Force $_.FullName -ErrorAction SilentlyContinue }\n\
+ & $t hash\n";
+ run_ps(spec, script, CTL_TIMEOUT).await.map_err(fail)
+}
+
+/// Runs a short PowerShell script on a Windows machine (with the user's profile, like workspace commands).
+pub(crate) async fn run_ps(spec: &MachineSpec, script: &str, timeout: Duration) -> Result<String, String> {
+ let marker = transport::new_marker();
+ let limits = Limits { head: 1 << 20, tail: 1 << 20, line: 1 << 20 };
+ let out = Box::pin(transport::run(spec, true, &marker, transport::with_marker(&marker, true, script), timeout, limits, &[], None)).await?;
+ if out.timed_out {
+ return Err(format!("{} is unreachable: no answer within {}s.", spec.name, timeout.as_secs()));
+ }
+ if !out.started {
+ return Err(format!("{} is unreachable: {}", spec.name, out.reason()));
+ }
+ match out.status {
+ Some(0) => Ok(out.stdout),
+ _ => Err(out.reason()),
+ }
+}
+
/// Runs a short sh script on the machine (login shell, like workspace commands).
pub(crate) async fn run_sh(spec: &MachineSpec, script: &str, timeout: Duration) -> Result<String, String> {
let marker = transport::new_marker();
- let out = transport::run(spec, false, &marker, transport::with_marker(&marker, false, script), timeout, Limits::OUTPUT, &[], None).await?;
+ let out = Box::pin(transport::run(spec, false, &marker, transport::with_marker(&marker, false, script), timeout, Limits::OUTPUT, &[], None)).await?;
if out.timed_out {
return Err(format!("{} is unreachable: no answer within {}s.", spec.name, timeout.as_secs()));
}
@@ -177,8 +291,13 @@ pub(crate) async fn run_sh(spec: &MachineSpec, script: &str, timeout: Duration)
/// same ssh connection as everything else and is never logged. (Not `--user`:
/// on Linux that goes to the keyring, which can wait forever without a desktop.)
pub async fn gh_token(spec: &MachineSpec, gh: &str, hostname: &str) -> Result<String, String> {
- let script = format!("{} auth token --hostname {}\n", sh_quote(gh), sh_quote(hostname));
- let token = run_sh(spec, &script, CTL_TIMEOUT).await?.trim().to_string();
+ let token = if is_windows(spec) {
+ let q = crate::ops::remote::ps_quote;
+ run_ps(spec, &format!("& {} auth token --hostname {}\n", q(gh), q(hostname)), CTL_TIMEOUT).await?
+ } else {
+ run_sh(spec, &format!("{} auth token --hostname {}\n", sh_quote(gh), sh_quote(hostname)), CTL_TIMEOUT).await?
+ };
+ let token = token.trim().to_string();
if token.is_empty() || token.contains(char::is_whitespace) {
return Err(format!("The GitHub CLI on {} gave no token. Sign it in again.", spec.name));
}
@@ -206,8 +325,14 @@ pub async fn ctl_reply(spec: &MachineSpec, request: &Value) -> Result<Value, Str
}
}
let json = request.to_string();
- let script = format!("{REMOTE_PATH} ctl <<'__OR_REQUEST__'\n{json}\n__OR_REQUEST__\n");
- let out = run_sh(spec, &script, CTL_TIMEOUT).await;
+ let out = if is_windows(spec) {
+ // UTF-8 to the agent (PowerShell 5.1 pipes in the console's code page otherwise).
+ let script = format!("$OutputEncoding = New-Object Text.UTF8Encoding $false\n$a = Join-Path $env:USERPROFILE '.muxen\\bin\\muxen-agent.exe'\n@'\n{json}\n'@ | & $a ctl\n");
+ run_ps(spec, &script, CTL_TIMEOUT).await
+ } else {
+ let script = format!("{REMOTE_PATH} ctl <<'__OR_REQUEST__'\n{json}\n__OR_REQUEST__\n");
+ run_sh(spec, &script, CTL_TIMEOUT).await
+ };
let out = match out {
Ok(o) => o,
Err(e) => {
diff --git a/src/fleet/sessions/mod.rs b/src/fleet/sessions/mod.rs
index d4fb4c7..74e16fe 100644
--- a/src/fleet/sessions/mod.rs
+++ b/src/fleet/sessions/mod.rs
@@ -189,15 +189,6 @@ impl Engine {
return Err(format!("{} has no host to connect to.", spec.name));
}
spec.refuse_if_disconnected()?;
- if matches!(shell_for(&spec, probe.as_ref()), Shell::Powershell) {
- let found = MachineSessions {
- checked_at: Some(Utc::now()),
- error: Some("Sessions on Windows run while Muxen is open; they can't keep running in the background yet.".into()),
- ..Default::default()
- };
- self.set_sessions(&spec.id, found.clone());
- return Ok(found);
- }
let previous = self.sessions_of(&spec.id);
let detect = previous.as_ref().and_then(|p| p.agents_checked_at).is_none_or(|t| Utc::now() - t > AGENTS_EVERY);
let agents: Vec<&str> = if detect { AGENTS.iter().map(|a| a.command).filter(|c| !c.is_empty()).collect() } else { Vec::new() };
@@ -275,7 +266,7 @@ impl Engine {
let title = unique_title(&title, &taken);
let windows = matches!(shell_for(&spec, probe.as_ref()), Shell::Powershell);
- if req.direct || windows {
+ if req.direct {
return Ok(self.start_direct(&spec, kind, name, cwd, title, &req, windows));
}
if let Some(world) = self.demo_world() {
@@ -292,7 +283,7 @@ impl Engine {
let run_line = match (&req.command, kind.command, prompt) {
(Some(c), _, _) => c.clone(),
(None, "", _) => String::new(),
- (None, c, Some(p)) if kind.prompt_arg => format!("{c} {}", sh_quote(p)),
+ (None, c, Some(p)) if kind.prompt_arg => format!("{c} {}", if windows { ps_quote(p) } else { sh_quote(p) }),
(None, c, _) => c.to_string(),
};
let request = json!({
@@ -453,7 +444,7 @@ impl Engine {
// Same connection options as checks, but with a terminal.
let mut args: Vec<String> = probe::ssh_args(&spec).into_iter().map(|a| if a == "-T" { "-tt".into() } else { a }).collect();
args.push("--".into());
- args.push(format!("{} attach {} --app", agent::REMOTE_PATH, sh_quote(name)));
+ args.push(if agent::is_windows(&spec) { agent::command(&spec, &format!("attach {name} --app")) } else { format!("{} attach {} --app", agent::REMOTE_PATH, sh_quote(name)) });
Ok(AttachCommand { program: "ssh".into(), args })
}
@@ -535,6 +526,16 @@ fn direct_command(spec: &MachineSpec, d: &DirectSession) -> AttachCommand {
} else {
format!("powershell -NoLogo -Command \"Set-Location {dir}; {}\"", d.run.replace('"', "\\\""))
};
+ // This computer: PowerShell itself.
+ if spec.is_local() {
+ let mut args = vec!["-NoLogo".to_string()];
+ if d.run.is_empty() {
+ args.extend(["-NoExit".into(), "-Command".into(), format!("Set-Location {dir}")]);
+ } else {
+ args.extend(["-Command".into(), format!("Set-Location {dir}; {}", d.run)]);
+ }
+ return AttachCommand { program: "powershell".into(), args };
+ }
let mut args: Vec<String> = probe::ssh_args(spec).into_iter().map(|a| if a == "-T" { "-tt".into() } else { a }).collect();
args.push("--".into());
args.push(script);
@@ -607,7 +608,7 @@ fn split_id(id: &str) -> Result<(&str, &str), String> {
/// The paste-into-your-terminal attach command (detach with Ctrl-] then d).
fn user_attach_command(spec: &MachineSpec, name: &str) -> String {
- let attach = format!("{} attach {name}", agent::REMOTE_PATH);
+ let attach = if agent::is_windows(spec) { agent::command(spec, &format!("attach {name}")) } else { format!("{} attach {name}", agent::REMOTE_PATH) };
if spec.is_local() {
return attach;
}
diff --git a/src/fleet/usage.rs b/src/fleet/usage.rs
index f62b077..b1453b2 100644
--- a/src/fleet/usage.rs
+++ b/src/fleet/usage.rs
@@ -191,7 +191,7 @@ impl Engine {
/// Every reachable machine's, side by side (a machine that can't say is left out, with why).
pub async fn usage_all(self: &Arc<Self>, days: u32) -> Vec<(String, Result<MachineUsage, String>)> {
// Not just the ones checked already: a machine not reached yet says why.
- let ids: Vec<String> = self.current().machines.iter().filter(|m| !m.is_down() && !m.host.is_empty() && !m.platform.starts_with("windows")).map(|m| m.id.clone()).collect();
+ let ids: Vec<String> = self.current().machines.iter().filter(|m| !m.is_down() && !m.host.is_empty()).map(|m| m.id.clone()).collect();
let results = futures::future::join_all(ids.iter().map(|id| self.usage(id, days))).await;
ids.into_iter().zip(results).collect()
}
diff --git a/src/fleet/workspaces/mod.rs b/src/fleet/workspaces/mod.rs
index 55f4ecb..e740e3b 100644
--- a/src/fleet/workspaces/mod.rs
+++ b/src/fleet/workspaces/mod.rs
@@ -479,7 +479,7 @@ impl Engine {
}
/// rsync between a folder on this computer and the workspace. Returns rsync's summary.
- pub async fn workspace_sync(&self, id: &str, local_path: &str, direction: SyncDirection, delete: bool) -> Result<String, String> {
+ pub async fn workspace_sync(self: &Arc<Self>, id: &str, local_path: &str, direction: SyncDirection, delete: bool) -> Result<String, String> {
let rec = self.ready_workspace(id)?;
let local = expand_home(local_path.trim());
if local.as_os_str().is_empty() {
@@ -490,10 +490,11 @@ impl Engine {
self.touch_workspace(&rec.info.id);
return Ok(summary);
}
+ let spec = self.workspace_machine(&rec)?;
if rec.windows {
- return Err("Sync uses rsync, which Muxen doesn't support for Windows machines. Use workspace_write_file or git instead.".into());
+ // Boxed: a copy's future is big, and this one sits inside every caller's.
+ return Box::pin(self.sync_through_agent(&rec, &spec, &local, direction, delete)).await;
}
- let spec = self.workspace_machine(&rec)?;
let have_rsync = tokio::process::Command::new("rsync")
.arg("--version")
.stdout(std::process::Stdio::null())
@@ -526,6 +527,41 @@ impl Engine {
Ok(lines[lines.len().saturating_sub(16)..].join("\n"))
}
+ /// Sync with a Windows machine (no rsync there): the folder's contents
+ /// copied over through the agents, as Copy files does. Files are added and
+ /// replaced; nothing is deleted.
+ async fn sync_through_agent(self: &Arc<Self>, rec: &WorkspaceRecord, spec: &MachineSpec, local: &std::path::Path, direction: SyncDirection, delete: bool) -> Result<String, String> {
+ if delete {
+ return Err(format!("Syncing with {} adds and replaces files but doesn't delete any (it's a Windows machine): sync without delete.", spec.name));
+ }
+ let here = crate::config::Inventory::parse("[[machine]]\nname = \"This computer\"\nhost = \"local\"\n").map_err(|e| e.to_string())?.machines.remove(0);
+ let here = self.current().machines.iter().find(|m| m.local).and_then(|m| self.machine(&m.id)).map(|(s, _)| s).unwrap_or(here);
+ let skip = [".muxen", ".git", "node_modules", "target"];
+ let (from, dir, to, to_dir) = match direction {
+ SyncDirection::Push => {
+ if !local.is_dir() {
+ return Err(format!("{} isn't a folder on this computer.", local.display()));
+ }
+ (here.clone(), local.display().to_string(), spec.clone(), rec.info.path.clone())
+ }
+ SyncDirection::Pull => {
+ std::fs::create_dir_all(local).map_err(|e| format!("Couldn't create {}: {e}", local.display()))?;
+ (spec.clone(), rec.info.path.clone(), here.clone(), local.display().to_string())
+ }
+ };
+ let listing = self.list_files(&from.id, &dir).await?;
+ let names: Vec<String> = listing.entries.iter().map(|e| e.name.clone()).filter(|n| !skip.contains(&n.as_str())).collect();
+ if names.is_empty() {
+ return Ok("Nothing to copy.".into());
+ }
+ let op = self.begin_op("copy", format!("Sync {} with {}", rec.info.id, spec.name), Some(spec.id.clone()), None);
+ let result = self.run_copy(op, &from, &dir, &names, &to, &to_dir, &std::sync::atomic::AtomicBool::new(false)).await;
+ self.op_finish(op, result.as_ref().map(|_| ()).map_err(|e| e.clone()));
+ let bytes = result?;
+ self.touch_workspace(&rec.info.id);
+ Ok(format!("Copied {} item{} ({}) {} {}.", names.len(), if names.len() == 1 { "" } else { "s" }, crate::util::bytes(bytes), if matches!(direction, SyncDirection::Push) { "to" } else { "from" }, spec.name))
+ }
+
/// Stops background commands and removes the workspace (and its folder unless `keep_files`).
pub async fn destroy_workspace(self: &Arc<Self>, id: &str, keep_files: bool) -> Result<(), String> {
self.refresh_from_disk();
@@ -759,7 +795,8 @@ impl Engine {
let timeout_s = timeout.to_string();
let log_s = log.clone().unwrap_or_default();
let shell = if rec.windows { Shell::Powershell } else { Shell::Sh };
- let params = [
+ let exports = env_exports(shell, env);
+ let mut params = vec![
("OR_DIR", Param::Str(&rec.info.path)),
("OR_CWD", Param::Str(cwd)),
("OR_CMD", Param::Str(command)),
@@ -768,7 +805,10 @@ impl Engine {
("OR_LOG", Param::Str(&log_s)),
("OR_ID", Param::Str(&rec.info.id)),
];
- let exports = env_exports(shell, env);
+ // A background run on Windows doesn't inherit the environment: its script sets it.
+ if shell == Shell::Powershell {
+ params.push(("OR_ENVPS", Param::Str(&exports)));
+ }
let script = match (&rec.info.container, shell) {
(Some(container), Shell::Sh) => {
let image = rec.info.image.clone().unwrap_or_else(|| DEFAULT_IMAGE.to_string());
diff --git a/src/fleet/workspaces/scripts/exec.ps1 b/src/fleet/workspaces/scripts/exec.ps1
index 81ea759..e88ce6a 100644
--- a/src/fleet/workspaces/scripts/exec.ps1
+++ b/src/fleet/workspaces/scripts/exec.ps1
@@ -1,34 +1,54 @@
-# Runs one command in a workspace (Windows, best effort). Prepended: $OR_DIR $OR_CWD
-# $OR_CMD $OR_TIMEOUT $OR_BG $OR_LOG $OR_ID and `$env:NAME = ...` lines.
-# Timeouts are enforced by Muxen hanging up; the command isn't killed on the machine.
+# Runs one command in a workspace (Windows). Prepended: $OR_DIR $OR_CWD $OR_CMD
+# $OR_TIMEOUT $OR_BG $OR_LOG $OR_ID $OR_ENVPS and `$env:NAME = ...` lines.
+# The command runs as a script of its own in its own PowerShell, so its output
+# is text as in a terminal, its `exit` is its exit status, and a timeout can
+# end it with everything it started.
$ErrorActionPreference = 'Continue'
function Or-Fail($msg) { [Console]::Error.WriteLine("error: $msg"); [Console]::Error.WriteLine("${OR_MARK}:exit=97"); exit 0 }
try { Set-Location -LiteralPath $OR_DIR -ErrorAction Stop } catch { Or-Fail "the workspace folder is gone: $OR_DIR" }
if ($OR_CWD) { try { Set-Location -LiteralPath $OR_CWD -ErrorAction Stop } catch { Or-Fail "there's no folder $OR_CWD in the workspace" } }
+$here = (Get-Location).Path
$env:MUXEN_WORKSPACE = $OR_ID
$env:NO_COLOR = '1'
$env:GIT_TERMINAL_PROMPT = '0'
+$runs = Join-Path $OR_DIR '.muxen'
+New-Item -ItemType Directory -Force -Path (Join-Path $runs 'logs') | Out-Null
+$f = Join-Path $runs ('run-' + [guid]::NewGuid().ToString('N').Substring(0, 8) + '.ps1')
+$q = { param($s) "'" + $s.Replace("'", "''") + "'" }
+
if ($OR_BG) {
- New-Item -ItemType Directory -Force -Path (Join-Path $OR_DIR '.muxen\logs') | Out-Null
+ # Started through WMI, so it outlives this ssh session (sshd ends what a
+ # session started); WMI passes no environment, so the script sets it up.
$log = Join-Path $OR_DIR $OR_LOG
- $p = Start-Process -FilePath 'powershell' -ArgumentList @('-NoProfile', '-NonInteractive', '-Command', $OR_CMD) `
- -RedirectStandardOutput $log -RedirectStandardError "$log.err" -WindowStyle Hidden -PassThru
- Write-Output "pid=$($p.Id)"
+ $body = "[Console]::OutputEncoding = [Text.Encoding]::UTF8`n" + $OR_ENVPS +
+ "`$env:MUXEN_WORKSPACE = $(& $q $OR_ID)`n`$env:NO_COLOR = '1'`n`$env:GIT_TERMINAL_PROMPT = '0'`n" +
+ "Set-Location -LiteralPath $(& $q $here)`n" + $OR_CMD
+ Set-Content -LiteralPath $f -Value $body -Encoding UTF8
+ $line = "cmd.exe /d /c powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$f`" > `"$log`" 2>&1"
+ $r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = $line; CurrentDirectory = $here }
+ if ($r.ReturnValue -ne 0) { Or-Fail "Windows didn't start it ($($r.ReturnValue))" }
+ Write-Output "pid=$($r.ProcessId)"
[Console]::Error.WriteLine("${OR_MARK}:exit=0")
exit 0
}
-$global:LASTEXITCODE = 0
-$code = 0
-try {
- Invoke-Expression $OR_CMD
- if (-not $?) { $code = 1 }
- if ($LASTEXITCODE) { $code = $LASTEXITCODE }
-} catch {
- [Console]::Error.WriteLine($_.ToString())
- $code = 1
+Set-Content -LiteralPath $f -Value $OR_CMD -Encoding UTF8
+$out = "$f.out"; $err = "$f.err"
+$run = "[Console]::OutputEncoding = [Text.Encoding]::UTF8; & $(& $q $f); if (`$LASTEXITCODE) { exit `$LASTEXITCODE } elseif (-not `$?) { exit 1 } else { exit 0 }"
+$p = Start-Process -FilePath 'powershell' -ArgumentList @('-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', "`"$($run.Replace('"', '\"'))`"") `
+ -NoNewWindow -PassThru -RedirectStandardOutput $out -RedirectStandardError $err
+$null = $p.Handle
+$done = $p.WaitForExit([int]$OR_TIMEOUT * 1000)
+if (-not $done) {
+ taskkill /T /F /PID $p.Id 2>&1 | Out-Null
+ [Console]::Error.WriteLine("${OR_MARK}:timeout")
}
+$utf8 = New-Object Text.UTF8Encoding $false
+if (Test-Path -LiteralPath $out) { [Console]::Out.Write([IO.File]::ReadAllText($out, $utf8)) }
+if (Test-Path -LiteralPath $err) { [Console]::Error.Write([IO.File]::ReadAllText($err, $utf8)) }
+$code = if ($done) { $p.ExitCode } else { 124 }
+Remove-Item -LiteralPath $f, $out, $err -Force -ErrorAction SilentlyContinue
[Console]::Error.WriteLine("${OR_MARK}:exit=$code")
exit 0
diff --git a/src/fleet/workspaces/scripts/files.ps1 b/src/fleet/workspaces/scripts/files.ps1
index 95fe9e7..902dc24 100644
--- a/src/fleet/workspaces/scripts/files.ps1
+++ b/src/fleet/workspaces/scripts/files.ps1
@@ -11,7 +11,8 @@ switch ($OR_ACTION) {
$item = Get-Item -LiteralPath $full -Force
if ($item.PSIsContainer) { [Console]::Error.WriteLine("error: $OR_REL is a folder"); exit 3 }
Write-Output "size=$($item.Length)"
- $stream = [IO.File]::OpenRead($full)
+ # Shared, so a log a command is still writing can be read.
+ $stream = [IO.File]::Open($full, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::ReadWrite -bor [IO.FileShare]::Delete)
try {
$count = [Math]::Min([int64]$OR_MAX, $item.Length)
$buf = New-Object byte[] $count
diff --git a/src/fleet/workspaces/transport.rs b/src/fleet/workspaces/transport.rs
index 81d74ee..a7aeea5 100644
--- a/src/fleet/workspaces/transport.rs
+++ b/src/fleet/workspaces/transport.rs
@@ -23,7 +23,6 @@ use crate::probe;
/// of those shells, since ssh hands the remote command to the user's shell.
const LOGIN_WRAPPER: &str =
r#"case "$SHELL" in */bash|*/zsh|*/sh|*/ksh|*/dash) exec "$SHELL" -l -s;; *) exec sh -l -s;; esac"#;
-const PS_READ_STDIN: &str = "[Console]::In.ReadToEnd() | Invoke-Expression";
/// After the script reports its exit status, give stragglers holding the
/// output pipes (a server the command left running) this long, then hang up.
const AFTER_EXIT_GRACE: Duration = Duration::from_secs(2);
@@ -61,7 +60,9 @@ pub struct Output {
impl Output {
/// A short reason for a failure: the script's `error: ...` line, else the last stderr lines.
pub fn reason(&self) -> String {
- let lines: Vec<&str> = self.stderr.lines().chain(self.preamble.lines()).map(str::trim).filter(|l| !l.is_empty()).collect();
+ // PowerShell's errors arrive as CLIXML when stderr isn't a terminal: their text.
+ let stderr = clixml_text(&self.stderr);
+ let lines: Vec<&str> = stderr.lines().chain(self.preamble.lines()).map(str::trim).filter(|l| !l.is_empty() && !l.starts_with("At line:") && !l.starts_with('+')).collect();
if let Some(e) = lines.iter().find_map(|l| l.strip_prefix("error: ")) {
return e.to_string();
}
@@ -74,6 +75,20 @@ impl Output {
}
}
+/// The text of PowerShell's CLIXML error records (`<S S="Error">…</S>`), as
+/// lines; anything else as it is.
+pub fn clixml_text(stderr: &str) -> String {
+ if !stderr.contains("<S S=\"Error\">") {
+ return stderr.to_string();
+ }
+ let mut out = String::new();
+ for part in stderr.split("<S S=\"Error\">").skip(1) {
+ let text = part.split("</S>").next().unwrap_or("");
+ out.push_str(&text.replace("_x000D__x000A_", "\n").replace("&apos;", "'").replace("&quot;", "\"").replace("&lt;", "<").replace("&gt;", ">").replace("&amp;", "&"));
+ }
+ out
+}
+
pub fn new_marker() -> String {
format!("__muxen_{}__", super::random_id(12))
}
@@ -94,7 +109,7 @@ fn command(spec: &MachineSpec, windows: bool) -> Command {
if spec.is_local() {
if windows {
let mut c = Command::new("powershell");
- c.args(["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", PS_READ_STDIN]);
+ c.args(crate::ops::remote::ps_stdin_args());
c
} else {
let mut c = Command::new("/bin/sh");
@@ -105,7 +120,7 @@ fn command(spec: &MachineSpec, windows: bool) -> Command {
let mut c = Command::new("ssh");
c.args(probe::ssh_args(spec));
c.arg(if windows {
- format!("powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command \"{PS_READ_STDIN}\"")
+ format!("powershell {}", crate::ops::remote::ps_stdin_args().join(" "))
} else {
format!("sh -c '{LOGIN_WRAPPER}'")
});
@@ -153,6 +168,7 @@ pub async fn run(
let work = async {
// The script is small (or a bounded file upload); write it whole, then close stdin.
+ let script = if windows { crate::ops::remote::ps_sendable(&script) } else { script };
let writer = async {
let _ = stdin.write_all(script.as_bytes()).await;
drop(stdin);
diff --git a/src/main.rs b/src/main.rs
index 66f9caf..e4366f5 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1358,7 +1358,7 @@ fn main() -> ExitCode {
}
Some(Command::Usage(a)) => {
let req = api::UsageRequest { days: Some(a.days), machine_id: a.machine };
- run(&runtime, &a.agent, async move |e| api::usage(&e, req).await, |u| cli::usage(u))
+ run(&runtime, &a.agent, async move |e| api::usage(&e, req).await, cli::usage)
}
Some(Command::Ports(a)) => {
let req = api::PortsRequest { machine_id: a.machine_id };
@@ -1462,7 +1462,35 @@ fn main() -> ExitCode {
ExitCode::from(code)
}
+/// Windows: started from Explorer or the Start menu, the window comes with a
+/// console of its own (a terminal window). Start again without one: a
+/// console that has no window, which every ssh and PowerShell Muxen starts
+/// then shares instead of each opening a window. True when it did (this
+/// process should end).
+#[cfg(windows)]
+fn without_console_window() -> bool {
+ use std::os::windows::process::CommandExt;
+ use windows_sys::Win32::System::Console::GetConsoleProcessList;
+ const CREATE_NO_WINDOW: u32 = 0x0800_0000;
+ if std::env::var_os("MUXEN_NO_CONSOLE").is_some() {
+ return false;
+ }
+ // Someone else on this console: started from a terminal, which stays.
+ let mut ids = [0u32; 2];
+ if unsafe { GetConsoleProcessList(ids.as_mut_ptr(), ids.len() as u32) } != 1 {
+ return false;
+ }
+ let Ok(exe) = std::env::current_exe() else { return false };
+ let mut cmd = std::process::Command::new(exe);
+ cmd.args(std::env::args_os().skip(1)).env("MUXEN_NO_CONSOLE", "1").creation_flags(CREATE_NO_WINDOW);
+ cmd.spawn().is_ok()
+}
+
fn open(args: OpenArgs, runtime: &tokio::runtime::Runtime) -> u8 {
+ #[cfg(windows)]
+ if without_console_window() {
+ return 0;
+ }
// The engine runs on tokio; the window runs on GPUI's main-thread executor.
let _guard = runtime.enter();
let engine = Engine::new(args.common.paths(), args.demo);
diff --git a/src/ops/remote.rs b/src/ops/remote.rs
index 18db0c5..8ea25d6 100644
--- a/src/ops/remote.rs
+++ b/src/ops/remote.rs
@@ -13,8 +13,26 @@ use crate::config::MachineSpec;
use crate::fleet::Engine;
use crate::probe::{self, ProbeResult, Shell};
-/// `-Command -` runs stdin line by line and breaks multi-line blocks; read it whole instead.
-const PS_READ_STDIN: &str = "[Console]::In.ReadToEnd() | Invoke-Expression";
+/// PowerShell scripts go over stdin and end with this line. (`-Command -` runs
+/// stdin line by line and breaks multi-line blocks, so the script is read
+/// whole; and Windows' OpenSSH doesn't always pass on the end of stdin once
+/// a script is a few KB, so reading to the end could wait forever.)
+pub(crate) const PS_END: &str = "#muxen-end";
+const PS_READ_STDIN: &str = "$ProgressPreference = 'SilentlyContinue'; $b = New-Object Text.StringBuilder; while ((($l = [Console]::In.ReadLine()) -ne $null) -and ($l -ne '#muxen-end')) { [void]$b.AppendLine($l) }; $b.ToString() | Invoke-Expression";
+
+/// PowerShell's arguments to run a script sent on stdin (see `ps_sendable`),
+/// encoded so no shell on the way changes them.
+pub(crate) fn ps_stdin_args() -> Vec<String> {
+ use base64::Engine as _;
+ let utf16: Vec<u8> = PS_READ_STDIN.encode_utf16().flat_map(u16::to_le_bytes).collect();
+ let encoded = base64::engine::general_purpose::STANDARD.encode(utf16);
+ ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", &encoded].map(String::from).to_vec()
+}
+
+/// A PowerShell script as it's sent: with its end line.
+pub(crate) fn ps_sendable(script: &str) -> String {
+ format!("{}\n{PS_END}\n", script.trim_end_matches(['\r', '\n']))
+}
const STDERR_TAIL: usize = 4;
/// The shell a machine speaks: pinned in config.toml, else what the last check used, else by OS.
@@ -88,6 +106,7 @@ pub async fn run(
let work = async {
// Ignore write errors (e.g. ssh exiting early); stderr says why.
+ let script = if shell == Shell::Powershell { ps_sendable(&script) } else { script };
let _ = stdin.write_all(script.as_bytes()).await;
drop(stdin);
@@ -149,7 +168,7 @@ fn command(spec: &MachineSpec, shell: Shell) -> Command {
}
Shell::Powershell => {
let mut c = Command::new("powershell");
- c.args(["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", PS_READ_STDIN]);
+ c.args(ps_stdin_args());
c
}
}
@@ -158,9 +177,7 @@ fn command(spec: &MachineSpec, shell: Shell) -> Command {
c.args(probe::ssh_args(spec));
c.arg(match shell {
Shell::Sh => "sh -s".to_string(),
- Shell::Powershell => {
- format!("powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command \"{PS_READ_STDIN}\"")
- }
+ Shell::Powershell => format!("powershell {}", ps_stdin_args().join(" ")),
});
c
}
diff --git a/src/probe/mod.rs b/src/probe/mod.rs
index d0a691b..8d35eae 100644
--- a/src/probe/mod.rs
+++ b/src/probe/mod.rs
@@ -16,7 +16,6 @@ const PROBE_SH: &str = include_str!("scripts/probe.sh");
const PROBE_PS1: &str = include_str!("scripts/probe.ps1");
const TIMEOUT: Duration = Duration::from_secs(45);
/// `-Command -` runs stdin line by line and breaks multi-line blocks; read it whole instead.
-const PS_READ_STDIN: &str = "[Console]::In.ReadToEnd() | Invoke-Expression";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
@@ -254,7 +253,7 @@ async fn run(spec: &MachineSpec, shell: Shell) -> Result<String, RunError> {
}
Shell::Powershell => {
let mut c = Command::new("powershell");
- c.args(["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", PS_READ_STDIN]);
+ c.args(crate::ops::remote::ps_stdin_args());
c
}
}
@@ -263,9 +262,7 @@ async fn run(spec: &MachineSpec, shell: Shell) -> Result<String, RunError> {
c.args(ssh_args(spec));
c.arg(match shell {
Shell::Sh => "sh -s".to_string(),
- Shell::Powershell => {
- format!("powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command \"{PS_READ_STDIN}\"")
- }
+ Shell::Powershell => format!("powershell {}", crate::ops::remote::ps_stdin_args().join(" ")),
});
c
};
@@ -277,6 +274,7 @@ async fn run(spec: &MachineSpec, shell: Shell) -> Result<String, RunError> {
let mut stdin = child.stdin.take().expect("piped stdin");
let output = async move {
// The script is small; ignore write errors (e.g. ssh exiting early) and read why from stderr.
+ let script = if shell == Shell::Powershell { crate::ops::remote::ps_sendable(&script) } else { script };
let _ = stdin.write_all(script.as_bytes()).await;
drop(stdin);
child.wait_with_output().await
diff --git a/src/probe/scripts/probe.ps1 b/src/probe/scripts/probe.ps1
index 24db056..d980ccb 100644
--- a/src/probe/scripts/probe.ps1
+++ b/src/probe/scripts/probe.ps1
@@ -67,3 +67,45 @@ foreach ($d in ($dirs | Sort-Object -Unique)) {
}
$i++
}
+
+# --- The machine --------------------------------------------------------------
+# Someone signed in to the desktop (Explorer runs in their session): there's a screen to show.
+if (Get-Process explorer -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -ne 0 }) { kv 'desktop' 'yes' } else { kv 'desktop' 'no' }
+# A battery means a laptop (PCSystemType 2 is "mobile").
+$cs = Get-CimInstance Win32_ComputerSystem
+if ($cs) { kv 'form_factor' ($(if ($cs.PCSystemType -eq 2) { 'laptop' } else { 'desktop' })) }
+# An administrator's ssh session is elevated: like passwordless sudo.
+$me = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
+if ($me.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { kv 'sudo' 'passwordless' } else { kv 'sudo' 'password' }
+
+# --- Docker -------------------------------------------------------------------
+if (Get-Command docker -ErrorAction SilentlyContinue) {
+ $dv = (& docker version --format '{{.Server.Version}}' 2>$null | Select-Object -First 1)
+ if ($dv) { kv 'docker' $dv }
+ else { kv 'docker_error' ((& docker version 2>&1 | Out-String) -split "`n" | Where-Object { $_ -match 'error|cannot|denied' } | Select-Object -First 1) }
+}
+
+# --- The network card it's reached by (to wake it later), and what wants a look -
+$route = Get-NetRoute -DestinationPrefix '0.0.0.0/0' | Sort-Object { $_.RouteMetric + $_.InterfaceMetric } | Select-Object -First 1
+if ($route) {
+ $nic = Get-NetAdapter -InterfaceIndex $route.ifIndex
+ if ($nic -and $nic.MacAddress) { kv 'mac' ($nic.MacAddress.Replace('-', ':').ToLower()) }
+ $ip = Get-NetIPAddress -InterfaceIndex $route.ifIndex -AddressFamily IPv4 | Where-Object { $_.PrefixOrigin -ne 'WellKnown' } | Select-Object -First 1
+ if ($ip) {
+ $bytes = ([Net.IPAddress]$ip.IPAddress).GetAddressBytes()
+ $bits = [int]$ip.PrefixLength
+ $brd = for ($k = 0; $k -lt 4; $k++) {
+ $keep = [Math]::Max(0, [Math]::Min(8, $bits - 8 * $k))
+ $bytes[$k] -bor (255 -shr $keep)
+ }
+ kv 'lan' ("{0}/{1} {2}" -f $ip.IPAddress, $bits, ($brd -join '.'))
+ }
+}
+# Updates waiting for a restart.
+$pending = (Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired') -or
+ (Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending')
+if ($pending) { kv 'reboot_required' 'yes' }
+# Services that should run (automatic, not delayed) but stopped with an error.
+$failed = @(Get-CimInstance Win32_Service -Filter "StartMode='Auto' AND State='Stopped'" |
+ Where-Object { $_.ExitCode -ne 0 -and $_.ExitCode -ne 1077 -and -not $_.DelayedAutoStart } | Select-Object -ExpandProperty Name)
+if ($failed.Count -gt 0) { kv 'failed_units' ($failed -join ' ') }
diff --git a/src/ui/detail.rs b/src/ui/detail.rs
index 21c1ac5..3669a8d 100644
--- a/src/ui/detail.rs
+++ b/src/ui/detail.rs
@@ -82,7 +82,7 @@ impl Root {
),
)
.child({
- let windows = m.platform.starts_with("windows");
+
let mut buttons: Vec<AnyElement> = Vec::new();
// Disconnected on purpose: connecting is what there is to do.
if disconnected {
@@ -109,7 +109,7 @@ impl Root {
.into_any_element(),
);
}
- if !windows {
+ {
let mid = m.id.clone();
buttons.push(
Button::new("m-logs", "Logs")
@@ -135,7 +135,7 @@ impl Root {
.on_click(cx.listener(move |this, _, window, cx| this.show_install_dialog(&mid, window, cx)))
.into_any_element(),
);
- if !windows {
+ {
let mid = m.id.clone();
buttons.push(
Button::new("m-copy", "Copy files")
@@ -244,11 +244,11 @@ impl Root {
if !m.host.is_empty() {
body = body.child(self.machine_sessions(&theme, &s, &m, cx));
// Its servers, to open here (not for this computer, or one we can't reach).
- if !m.platform.starts_with("windows") && !m.local && !offline {
+ if !m.local && !offline {
body = body.child(self.machine_servers(&theme, &m, cx));
}
// Connection and git are about a machine we can reach.
- if !m.platform.starts_with("windows") && !offline {
+ if !offline {
if m.host != "local" {
body = body.child(self.machine_connection(&theme, &m, cx));
}
diff --git a/src/ui/files.rs b/src/ui/files.rs
index 9a5c191..69305ba 100644
--- a/src/ui/files.rs
+++ b/src/ui/files.rs
@@ -72,7 +72,7 @@ impl CopyDialog {
let mut machines: Vec<(String, String, bool)> = snap
.machines
.iter()
- .filter(|m| !m.host.is_empty() && !m.platform.starts_with("windows"))
+ .filter(|m| !m.host.is_empty())
.map(|m| (m.id.clone(), m.name.clone(), !m.is_down()))
.collect();
// This computer first.
diff --git a/src/ui/format.rs b/src/ui/format.rs
index 1db69fa..8773b68 100644
--- a/src/ui/format.rs
+++ b/src/ui/format.rs
@@ -51,7 +51,7 @@ pub fn disk_low(m: &Machine) -> bool {
/// Whether Muxen can show the machine's desktop (Linux with X11, macOS).
pub fn has_desktop(m: &Machine) -> bool {
// A Linux machine needs an X server; one checked before checks said is given the benefit of the doubt.
- m.platform.starts_with("darwin") || (m.platform.starts_with("linux") && m.probe.as_ref().and_then(|p| p.desktop) != Some(false))
+ m.platform.starts_with("darwin") || ((m.platform.starts_with("linux") || m.platform.starts_with("windows")) && m.probe.as_ref().and_then(|p| p.desktop) != Some(false))
}
/// Gradient for a machine's icon tile, by OS.
diff --git a/src/ui/github.rs b/src/ui/github.rs
index e588a74..75c2b8f 100644
--- a/src/ui/github.rs
+++ b/src/ui/github.rs
@@ -136,7 +136,7 @@ impl Root {
// Look for checkouts on the machines once per visit.
if !self.gh.scanned {
self.gh.scanned = true;
- for m in self.snapshot.machines.iter().filter(|m| m.status == "online" && !m.platform.starts_with("windows")) {
+ for m in self.snapshot.machines.iter().filter(|m| m.status == "online") {
let engine = self.engine.clone();
let id = m.id.clone();
engine.runtime().clone().spawn(async move {
diff --git a/src/ui/menu.rs b/src/ui/menu.rs
index 148db42..2e1da56 100644
--- a/src/ui/menu.rs
+++ b/src/ui/menu.rs
@@ -163,16 +163,12 @@ impl Root {
if super::format::has_desktop(m) && !m.local {
items.push(needs_up(act("Show desktop", "monitor", Action::ShowDesktop(id.clone()))));
}
- if super::format::has_desktop(m) && !s.demo {
+ if super::format::has_desktop(m) && !s.demo && !m.platform.starts_with("windows") {
items.push(needs_up(act("Add virtual monitor…", "monitor", Action::AddDisplay(id.clone()))));
}
- if !m.platform.starts_with("windows") {
- items.push(needs_up(act("Logs", "scroll-text", Action::ShowLogs(id.clone()))));
- items.push(needs_up(act("Services", "layers", Action::ShowServices(id.clone()))));
- }
- if !m.platform.starts_with("windows") {
- items.push(needs_up(act("Copy files…", "folder", Action::CopyFiles(id.clone()))));
- }
+ items.push(needs_up(act("Logs", "scroll-text", Action::ShowLogs(id.clone()))));
+ items.push(needs_up(act("Services", "layers", Action::ShowServices(id.clone()))));
+ items.push(needs_up(act("Copy files…", "folder", Action::CopyFiles(id.clone()))));
items.push(needs_up(act("Run a command…", "zap", Action::RunOn(id.clone()))));
items.push(Item::Separator);
if !m.is_disconnected() {
diff --git a/src/ui/mod.rs b/src/ui/mod.rs
index 51f6002..d076854 100644
--- a/src/ui/mod.rs
+++ b/src/ui/mod.rs
@@ -66,6 +66,13 @@ pub fn run(engine: Arc<Engine>, initial_view: Option<String>) {
// (test runs stay off the main monitor); otherwise the primary display.
let wants_builtin = initial_view.as_deref().is_some_and(|v| v.split(',').any(|p| p.trim() == "display:builtin"));
let display = wants_builtin.then(|| builtin_display(cx)).flatten();
+ // No bigger than the screen it opens on (a laptop's, a VM's 1280×800).
+ let screen = display.and_then(|id| cx.find_display(id)).or_else(|| cx.primary_display()).map(|d| d.bounds().size);
+ let (w, h) = match screen {
+ // (Room for Windows' taskbar, the Dock, a panel.)
+ Some(s) => (w.min(f32::from(s.width) * 0.94).max(640.), h.min(f32::from(s.height) * 0.86).max(480.)),
+ None => (w, h),
+ };
let bounds = Bounds::centered(display, size(px(w), px(h)), cx);
let titlebar = if cfg!(target_os = "macos") {
TitlebarOptions { title: Some("Muxen".into()), appears_transparent: true, traffic_light_position: Some(point(px(16.), px(19.))) }
diff --git a/src/ui/ports.rs b/src/ui/ports.rs
index d26a534..ecbf82a 100644
--- a/src/ui/ports.rs
+++ b/src/ui/ports.rs
@@ -265,7 +265,7 @@ impl Root {
for id in machines {
// Only machines we can reach (an offline one says nothing about its servers).
let Some(m) = self.snapshot.machines.iter().find(|m| m.id == id) else { continue };
- if m.is_down() || m.local || m.status != "online" || m.platform.starts_with("windows") {
+ if m.is_down() || m.local || m.status != "online" {
continue;
}
let name = m.name.clone();
diff --git a/src/ui/root.rs b/src/ui/root.rs
index 96e4154..475856b 100644
--- a/src/ui/root.rs
+++ b/src/ui/root.rs
@@ -1114,7 +1114,7 @@ impl Root {
/// A machine's GPUs, for its page (none: no GPU card).
pub(super) fn load_machine_gpus(&mut self, machine_id: &str, cx: &mut Context<Self>) {
let Some(m) = self.snapshot.machines.iter().find(|m| m.id == machine_id) else { return };
- if m.is_down() || m.host.is_empty() || m.platform.starts_with("windows") {
+ if m.is_down() || m.host.is_empty() {
return;
}
let (engine, id) = (self.engine.clone(), machine_id.to_string());
@@ -1978,7 +1978,7 @@ impl Root {
.id(SharedString::from(format!("side-m-{}", m.id)))
.group("machine-row")
// Files from the Finder dropped here are copied to the machine.
- .when(!m.host.is_empty() && !m.platform.starts_with("windows"), |d| {
+ .when(!m.host.is_empty(), |d| {
let (mid, accent) = (m.id.clone(), theme.accent);
d.drag_over::<gpui::ExternalPaths>(move |st, _, _, _| st.bg(accent.opacity(0.18)))
.on_drop(cx.listener(move |this, paths: &gpui::ExternalPaths, window, cx| this.copy_dropped(&mid, paths.paths(), window, cx)))
diff --git a/src/ui/sessions.rs b/src/ui/sessions.rs
index 6b48a3b..16581e9 100644
--- a/src/ui/sessions.rs
+++ b/src/ui/sessions.rs
@@ -900,12 +900,11 @@ impl Root {
let content = if sessions.is_empty() {
- let text = match (runs_in_app(m), m.platform.starts_with("windows")) {
+ let text = match runs_in_app(m) {
_ if m.is_disconnected() => format!("Connect to {} to start Claude Code, Codex or a shell there.", m.name),
_ if m.is_down() => format!("Start Claude Code, Codex or a shell here once {} is back.", m.name),
- (true, true) => "Run Claude Code, Codex or a shell here. On Windows, sessions run while Muxen is open.".to_string(),
- (true, false) => format!("Run Claude Code, Codex or a shell here. {} so sessions run while Muxen is open.", m.sessions_error.clone().unwrap_or_default().trim_end_matches('.')),
- _ => "Run Claude Code, Codex, OpenCode or a shell here. Sessions keep working on the machine after you close Muxen.".to_string(),
+ true => format!("Run Claude Code, Codex or a shell here. {} so sessions run while Muxen is open.", m.sessions_error.clone().unwrap_or_default().trim_end_matches('.')),
+ false => "Run Claude Code, Codex, OpenCode or a shell here. Sessions keep working on the machine after you close Muxen.".to_string(),
};
card(theme)
.p(px(16.))
@@ -1006,10 +1005,10 @@ impl Root {
}
}
-/// Sessions here can't live in Muxen's agent (Windows, or a platform it
-/// has no build for), so they run in this window and end with it.
+/// Sessions here can't live in Muxen's agent (a platform it has no build
+/// for), so they run in this window and end with it.
pub(super) fn runs_in_app(m: &FleetMachine) -> bool {
- m.platform.starts_with("windows") || (m.agent_version.is_none() && m.sessions_error.as_deref().is_some_and(|e| e.contains("no agent")))
+ m.agent_version.is_none() && m.sessions_error.as_deref().is_some_and(|e| e.contains("no agent"))
}
/// The unread marker: amber when the agent rang for you, the accent when it
diff --git a/src/util.rs b/src/util.rs
index 0434367..e9e78e1 100644
--- a/src/util.rs
+++ b/src/util.rs
@@ -101,8 +101,9 @@ pub fn open_url(url: &str) {
let mut cmd = if cfg!(target_os = "macos") {
std::process::Command::new("open")
} else if cfg!(windows) {
- let mut c = std::process::Command::new("cmd");
- c.args(["/C", "start", ""]);
+ // Not `cmd /C start`: cmd splits a URL at its `&`s.
+ let mut c = std::process::Command::new("rundll32.exe");
+ c.arg("url.dll,FileProtocolHandler");
c
} else {
std::process::Command::new("xdg-open")