use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::path::PathBuf;
#[cfg(not(windows))]
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use anyhow::{bail, Context, Result};
use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::wslc_common::container_steps::OutStream;
use crate::wslc_common::daemon_protocol::{
encode_frame, CancelExecConfig, DaemonApiFailure, DaemonRequest, DaemonResponse,
DeprovisionConfig, DeprovisionSessionConfig, ErrKind, ExecConfig, ExecStdinConfig,
ExecTerminal, ProvisionConfig, ProvisionSessionConfig, StartConfig, StopConfig, StreamFrame,
MAX_FRAME_SIZE, MAX_STDIN_CHUNK_BYTES, PROTOCOL_VERSION,
};
use crate::wslc_common::daemon_record::{live_daemon, DaemonRecord, TransitionLock};
const READY_TIMEOUT: Duration = Duration::from_secs(60);
const SPAWN_LOCK_TIMEOUT: Duration = Duration::from_secs(75);
const CALL_TIMEOUT: Duration = Duration::from_secs(600);
const READY_TIMEOUT_ENV: &str = "MXC_WSLC_DAEMON_READY_TIMEOUT_SECS";
const SPAWN_LOCK_TIMEOUT_ENV: &str = "MXC_WSLC_DAEMON_SPAWN_LOCK_TIMEOUT_SECS";
pub const CALL_TIMEOUT_ENV: &str = "MXC_WSLC_DAEMON_CALL_TIMEOUT_SECS";
const READER_CANCEL_GRACE: Duration = Duration::from_secs(5);
const READER_RECOVERY_GRACE: Duration = Duration::from_millis(250);
fn duration_from_env(var: &str, default: Duration) -> Duration {
resolve_duration(std::env::var(var).ok().as_deref(), default)
}
fn resolve_duration(raw: Option<&str>, default: Duration) -> Duration {
raw.and_then(|s| s.trim().parse::<u64>().ok())
.filter(|&secs| secs > 0)
.map(Duration::from_secs)
.unwrap_or(default)
}
fn ready_timeout() -> Duration {
duration_from_env(READY_TIMEOUT_ENV, READY_TIMEOUT)
}
fn spawn_lock_timeout() -> Duration {
duration_from_env(SPAWN_LOCK_TIMEOUT_ENV, SPAWN_LOCK_TIMEOUT)
}
pub fn call_timeout() -> Duration {
duration_from_env(CALL_TIMEOUT_ENV, CALL_TIMEOUT)
}
const READY_POLL: Duration = Duration::from_millis(100);
const OPEN_TIMEOUT: Duration = Duration::from_secs(10);
const OPEN_RETRY: Duration = Duration::from_millis(20);
const ERROR_FILE_NOT_FOUND: i32 = 2;
const ERROR_PIPE_BUSY: i32 = 231;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ExecResult {
pub exit_code: i32,
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
}
pub type DaemonExecOutcome = ExecTerminal;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DaemonExecCompletion {
pub outcome: DaemonExecOutcome,
pub truncated: bool,
}
#[derive(Debug)]
pub(crate) struct AdmittedExec {
pipe: File,
}
impl AdmittedExec {
pub(crate) fn read_to_completion(
mut self,
mut on_output: impl FnMut(OutStream, &[u8]),
) -> DaemonResult<DaemonExecCompletion> {
let mut truncated = false;
loop {
let outcome = match read_frame::<StreamFrame>(&mut self.pipe)? {
StreamFrame::Stdout { data } => {
on_output(OutStream::Stdout, &data);
continue;
}
StreamFrame::Stderr { data } => {
on_output(OutStream::Stderr, &data);
continue;
}
StreamFrame::Truncated => {
truncated = true;
continue;
}
StreamFrame::Exit { code } => DaemonExecOutcome::Exited(code),
StreamFrame::TimedOut => DaemonExecOutcome::TimedOut,
StreamFrame::Cancelled => DaemonExecOutcome::Cancelled,
StreamFrame::Error {
message,
api_failure,
} => {
return Err(DaemonError::Daemon {
kind: ErrKind::Backend,
message: format!("exec failed: {message}{}", truncation_suffix(truncated)),
api_failure,
})
}
StreamFrame::Stdin { .. } => {
return Err(DaemonError::transport(
"protocol error: daemon sent a Stdin frame to the client",
))
}
};
return Ok(DaemonExecCompletion { outcome, truncated });
}
}
}
pub(crate) fn truncation_suffix(truncated: bool) -> &'static str {
if truncated {
" (live output was truncated: it was not drained fast enough and a bounded output queue \
overflowed)"
} else {
""
}
}
#[derive(Debug)]
pub enum DaemonError {
Daemon {
kind: ErrKind,
message: String,
api_failure: Option<DaemonApiFailure>,
},
Transport(anyhow::Error),
}
impl DaemonError {
fn transport(message: impl Into<String>) -> Self {
Self::Transport(anyhow::anyhow!(message.into()))
}
}
impl std::fmt::Display for DaemonError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Daemon { kind, message, .. } => {
write!(f, "daemon error [{kind:?}]: {message}")
}
Self::Transport(e) => write!(f, "{e}"),
}
}
}
impl std::error::Error for DaemonError {}
impl From<anyhow::Error> for DaemonError {
fn from(e: anyhow::Error) -> Self {
Self::Transport(e)
}
}
pub type DaemonResult<T> = std::result::Result<T, DaemonError>;
#[derive(Clone)]
pub struct DaemonClient {
pipe_name: String,
#[cfg_attr(not(windows), allow(dead_code))]
server_pid: u32,
#[cfg_attr(not(windows), allow(dead_code))]
server_pid_creation_time: u64,
}
impl DaemonClient {
pub fn connect() -> Result<Self> {
if let Some(record) = ready_daemon()? {
return Ok(Self::from_record(&record));
}
let _lock = TransitionLock::acquire(spawn_lock_timeout())
.context("acquire daemon spawn transition lock")?;
let ready_timeout = ready_timeout();
let deadline = Instant::now() + ready_timeout;
let mut spawned = false;
loop {
match live_daemon()? {
Some(record) if !record.protocol_compatible() => {
bail!(
"a running wslc daemon speaks control protocol v{} but this build speaks \
v{}; refusing to drive it (stop the stale daemon and retry)",
record.protocol_version,
PROTOCOL_VERSION
);
}
Some(record) if record.ready => return Ok(Self::from_record(&record)),
Some(_) => {}
None => {
if !spawned {
spawn_daemon()?;
spawned = true;
}
}
}
if Instant::now() >= deadline {
bail!(
"timed out after {ready_timeout:?} waiting for the wslc daemon to become ready"
);
}
std::thread::sleep(READY_POLL);
}
}
fn from_record(record: &DaemonRecord) -> Self {
Self {
pipe_name: record.pipe_name.clone(),
server_pid: record.pid,
server_pid_creation_time: record.pid_creation_time,
}
}
pub fn ping(&self) -> DaemonResult<()> {
match self.call(&DaemonRequest::Ping)? {
DaemonResponse::Pong => Ok(()),
other => Err(reply_error("unexpected reply to ping", other)),
}
}
pub fn provision_session(&self, config: ProvisionSessionConfig) -> DaemonResult<String> {
match self.call(&DaemonRequest::ProvisionSession(config))? {
DaemonResponse::SessionProvisioned { session_ref } => Ok(session_ref),
other => Err(reply_error("unexpected reply to provision_session", other)),
}
}
pub fn deprovision_session(&self, config: DeprovisionSessionConfig) -> DaemonResult<()> {
expect_ok(self.call(&DaemonRequest::DeprovisionSession(config))?)
}
pub fn provision(&self, config: ProvisionConfig) -> DaemonResult<String> {
match self.call(&DaemonRequest::Provision(config))? {
DaemonResponse::Provisioned { sandbox_id } => Ok(sandbox_id),
other => Err(reply_error("unexpected reply to provision", other)),
}
}
pub fn start(&self, config: StartConfig) -> DaemonResult<()> {
expect_ok(self.call(&DaemonRequest::Start(config))?)
}
pub fn stop(&self, config: StopConfig) -> DaemonResult<()> {
expect_ok(self.call(&DaemonRequest::Stop(config))?)
}
pub fn deprovision(&self, config: DeprovisionConfig) -> DaemonResult<()> {
expect_ok(self.call(&DaemonRequest::Deprovision(config))?)
}
pub fn exec(&self, config: ExecConfig) -> DaemonResult<ExecResult> {
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let completion = self.exec_streaming(config, |stream, data| match stream {
OutStream::Stdout => stdout.extend_from_slice(data),
OutStream::Stderr => stderr.extend_from_slice(data),
})?;
let exit_code = match completion.outcome {
DaemonExecOutcome::Exited(code) => code,
DaemonExecOutcome::TimedOut => {
return Err(DaemonError::transport(format!(
"exec timed out{}",
truncation_suffix(completion.truncated)
)))
}
DaemonExecOutcome::Cancelled => {
return Err(DaemonError::transport(format!(
"exec was cancelled{}",
truncation_suffix(completion.truncated)
)))
}
};
if completion.truncated {
return Err(DaemonError::transport(format!(
"exec output was truncated before it could be captured (the process exited \
{exit_code})"
)));
}
Ok(ExecResult {
exit_code,
stdout,
stderr,
})
}
pub fn exec_streaming(
&self,
config: ExecConfig,
on_output: impl FnMut(OutStream, &[u8]),
) -> DaemonResult<DaemonExecCompletion> {
self.admit_exec(config)?.read_to_completion(on_output)
}
pub(crate) fn admit_exec(&self, config: ExecConfig) -> DaemonResult<AdmittedExec> {
let mut pipe = self.open_pipe()?;
write_frame(&mut pipe, &DaemonRequest::Exec(config))?;
let timeout = call_timeout();
let (pipe, response) = read_frame_with_deadline(
move || {
let response = read_frame::<DaemonResponse>(&mut pipe)?;
Ok((pipe, response))
},
timeout,
)?;
match response {
DaemonResponse::Ok => {}
other => return Err(reply_error("unexpected exec admission reply", other)),
}
Ok(AdmittedExec { pipe })
}
pub fn cancel_exec(&self, exec_id: String, run_token: String) -> DaemonResult<()> {
expect_ok(self.call(&DaemonRequest::CancelExec(CancelExecConfig {
exec_id,
run_token,
}))?)
}
pub(crate) fn forward_stdin(
&self,
exec_id: String,
run_token: String,
input: impl Read,
) -> DaemonResult<()> {
copy_stdin(input, || self.attach_stdin(exec_id, run_token))
}
fn attach_stdin(&self, exec_id: String, run_token: String) -> DaemonResult<Option<File>> {
let mut pipe = self.open_pipe()?;
write_frame(
&mut pipe,
&DaemonRequest::ExecStdin(ExecStdinConfig { exec_id, run_token }),
)?;
let (pipe, response) = read_frame_with_deadline(
move || {
let response = read_frame::<DaemonResponse>(&mut pipe)?;
Ok((pipe, response))
},
call_timeout(),
)?;
match response {
DaemonResponse::Err {
kind: ErrKind::Rejected,
..
} => Ok(None),
response => expect_ok(response).map(|()| Some(pipe)),
}
}
fn call(&self, request: &DaemonRequest) -> DaemonResult<DaemonResponse> {
let mut pipe = self.open_pipe()?;
write_frame(&mut pipe, request)?;
let timeout = call_timeout();
read_frame_with_deadline::<DaemonResponse, _>(move || read_frame(&mut pipe), timeout)
}
fn open_pipe(&self) -> Result<File> {
let deadline = Instant::now() + OPEN_TIMEOUT;
let file = loop {
match open_pipe_handle(&self.pipe_name) {
Ok(file) => break file,
Err(e) => {
let retryable = matches!(
e.raw_os_error(),
Some(ERROR_PIPE_BUSY) | Some(ERROR_FILE_NOT_FOUND)
);
if retryable && Instant::now() < deadline {
std::thread::sleep(OPEN_RETRY);
continue;
}
return Err(e).with_context(|| format!("open daemon pipe {}", self.pipe_name));
}
}
};
self.verify_server_identity(&file)?;
Ok(file)
}
#[cfg(windows)]
fn verify_server_identity(&self, pipe: &File) -> Result<()> {
use std::os::windows::io::AsRawHandle;
use windows::Win32::Foundation::HANDLE;
use windows::Win32::System::Pipes::GetNamedPipeServerProcessId;
let handle = HANDLE(pipe.as_raw_handle());
let mut server_pid: u32 = 0;
unsafe { GetNamedPipeServerProcessId(handle, &mut server_pid) }
.map_err(|e| anyhow::anyhow!("GetNamedPipeServerProcessId failed: {e}"))?;
if server_pid != self.server_pid {
bail!(
"refusing to talk to daemon pipe {}: connected server pid {} does not match the \
trusted discovery record pid {} (possible pipe-squatting attempt)",
self.pipe_name,
server_pid,
self.server_pid
);
}
match crate::wslc_common::daemon_record::process_creation_time(server_pid) {
Some(ct) if ct == self.server_pid_creation_time => Ok(()),
Some(ct) => bail!(
"refusing to talk to daemon pipe {}: server pid {} creation time {} does not \
match the trusted record {} (pid reuse or spoofed server)",
self.pipe_name,
server_pid,
ct,
self.server_pid_creation_time
),
None => bail!(
"refusing to talk to daemon pipe {}: could not read the creation time of server \
pid {} to authenticate it",
self.pipe_name,
server_pid
),
}
}
#[cfg(not(windows))]
fn verify_server_identity(&self, _pipe: &File) -> Result<()> {
Ok(())
}
}
fn open_pipe_handle(pipe_name: &str) -> std::io::Result<File> {
let mut opts = OpenOptions::new();
opts.read(true).write(true);
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
const SECURITY_SQOS_PRESENT: u32 = 0x0010_0000;
const SECURITY_IDENTIFICATION: u32 = 0x0001_0000;
opts.custom_flags(SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION);
}
opts.open(pipe_name)
}
fn ready_daemon() -> Result<Option<DaemonRecord>> {
match live_daemon()? {
Some(record) if record.ready && record.protocol_compatible() => Ok(Some(record)),
_ => Ok(None),
}
}
#[cfg(windows)]
fn spawn_daemon() -> Result<()> {
use std::os::windows::ffi::OsStrExt;
use windows::core::{PCWSTR, PWSTR};
use windows::Win32::Foundation::CloseHandle;
use windows::Win32::System::Threading::{
CreateProcessW, CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP, PROCESS_INFORMATION,
STARTF_USESHOWWINDOW, STARTUPINFOW,
};
let exe = daemon_exe_path()?;
let mut command_line: Vec<u16> = std::iter::once(u16::from(b'"'))
.chain(exe.as_os_str().encode_wide())
.chain([u16::from(b'"'), 0])
.collect();
let startup = STARTUPINFOW {
cb: std::mem::size_of::<STARTUPINFOW>() as u32,
dwFlags: STARTF_USESHOWWINDOW,
wShowWindow: 0,
..Default::default()
};
let mut info = PROCESS_INFORMATION::default();
unsafe {
CreateProcessW(
PCWSTR::null(),
Some(PWSTR(command_line.as_mut_ptr())),
None,
None,
false,
CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP,
None,
PCWSTR::null(),
&startup,
&mut info,
)
.with_context(|| format!("spawn wslc daemon {}", exe.display()))?;
let _ = CloseHandle(info.hProcess);
let _ = CloseHandle(info.hThread);
}
Ok(())
}
#[cfg(not(windows))]
fn spawn_daemon() -> Result<()> {
let exe = daemon_exe_path()?;
Command::new(&exe)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.with_context(|| format!("spawn wslc daemon {}", exe.display()))?;
Ok(())
}
fn daemon_exe_path() -> Result<PathBuf> {
let module =
crate::mxc_common::process_util::module_path_for_address(daemon_exe_path as *const ())
.map_err(anyhow::Error::msg)?;
let dir = module
.parent()
.context("MXC native module has no parent directory")?;
let name = if cfg!(windows) {
"wxc-wslc-daemon.exe"
} else {
"wxc-wslc-daemon"
};
Ok(dir.join(name))
}
fn expect_ok(response: DaemonResponse) -> DaemonResult<()> {
match response {
DaemonResponse::Ok => Ok(()),
other => Err(reply_error("unexpected reply (expected ok)", other)),
}
}
fn reply_error(unexpected: &str, response: DaemonResponse) -> DaemonError {
match response {
DaemonResponse::Err {
kind,
message,
api_failure,
} => DaemonError::Daemon {
kind,
message,
api_failure,
},
other => DaemonError::transport(format!("{unexpected}: {other:?}")),
}
}
fn copy_stdin<W: Write>(
mut input: impl Read,
attach: impl FnOnce() -> DaemonResult<Option<W>>,
) -> DaemonResult<()> {
let mut buf = vec![0u8; MAX_STDIN_CHUNK_BYTES];
let mut read = read_stdin(&mut input, &mut buf)?;
let Some(mut pipe) = attach()? else {
return Ok(());
};
while read > 0 {
let chunk = StreamFrame::Stdin {
data: buf[..read].to_vec(),
};
write_frame(&mut pipe, &chunk).context("send stdin to the WSLc daemon")?;
read = read_stdin(&mut input, &mut buf)?;
}
write_frame(&mut pipe, &StreamFrame::Stdin { data: Vec::new() })
.context("send stdin end-of-file to the WSLc daemon")?;
Ok(())
}
fn read_stdin(input: &mut impl Read, buf: &mut [u8]) -> DaemonResult<usize> {
loop {
match input.read(buf) {
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
read => {
return read.map_err(|error| {
DaemonError::transport(format!("reading the exec's stdin failed: {error}"))
})
}
}
}
}
fn write_frame<T: Serialize>(pipe: &mut impl Write, msg: &T) -> Result<()> {
let frame = encode_frame(msg).context("encode frame")?;
pipe.write_all(&frame).context("write frame")?;
pipe.flush().context("flush frame")?;
Ok(())
}
fn read_frame<T: DeserializeOwned>(pipe: &mut impl Read) -> Result<T> {
let mut len_buf = [0u8; 4];
pipe.read_exact(&mut len_buf)
.context("read frame length prefix")?;
let len = u32::from_le_bytes(len_buf) as usize;
if len > MAX_FRAME_SIZE {
bail!("incoming frame length {len} exceeds maximum {MAX_FRAME_SIZE}");
}
let mut body = vec![0u8; len];
pipe.read_exact(&mut body).context("read frame body")?;
serde_json::from_slice(&body).context("deserialise frame body")
}
fn read_frame_with_deadline<T, F>(read: F, timeout: Duration) -> DaemonResult<T>
where
T: Send + 'static,
F: FnOnce() -> Result<T> + Send + 'static,
{
use std::sync::mpsc::{channel, RecvTimeoutError};
let (tx, rx) = channel();
let reader = std::thread::spawn(move || {
let _ = tx.send(read());
});
match rx.recv_timeout(timeout) {
Ok(result) => result.map_err(DaemonError::Transport),
Err(RecvTimeoutError::Timeout) => match recover_or_cancel_read(reader, &rx) {
Some(result) => result.map_err(DaemonError::Transport),
None => Err(DaemonError::transport(format!(
"timed out after {timeout:?} waiting for the wslc daemon to respond; it may be \
wedged on a prior operation (override with {CALL_TIMEOUT_ENV})"
))),
},
Err(RecvTimeoutError::Disconnected) => Err(DaemonError::transport(
"wslc daemon reader thread ended without a response",
)),
}
}
#[cfg(windows)]
fn recover_or_cancel_read<T>(
reader: std::thread::JoinHandle<()>,
rx: &std::sync::mpsc::Receiver<Result<T>>,
) -> Option<Result<T>> {
use std::os::windows::io::AsRawHandle;
use windows::Win32::Foundation::HANDLE;
use windows::Win32::System::IO::CancelSynchronousIo;
let cancelled = unsafe { CancelSynchronousIo(HANDLE(reader.as_raw_handle())) }.is_ok();
if !cancelled {
return rx.recv_timeout(READER_RECOVERY_GRACE).ok();
}
let _ = rx.recv_timeout(READER_CANCEL_GRACE);
None
}
#[cfg(not(windows))]
fn recover_or_cancel_read<T>(
_reader: std::thread::JoinHandle<()>,
_rx: &std::sync::mpsc::Receiver<Result<T>>,
) -> Option<Result<T>> {
None
}
#[cfg(all(test, windows))]
pub(crate) mod test_daemon {
use super::*;
use std::os::windows::io::FromRawHandle;
use std::sync::mpsc::{channel, Receiver};
use windows::core::PCWSTR;
use windows::Win32::Foundation::ERROR_PIPE_CONNECTED;
use windows::Win32::Storage::FileSystem::PIPE_ACCESS_DUPLEX;
use windows::Win32::System::Pipes::{
ConnectNamedPipe, CreateNamedPipeW, PIPE_READMODE_BYTE, PIPE_TYPE_BYTE,
PIPE_UNLIMITED_INSTANCES, PIPE_WAIT,
};
pub(crate) struct Connection {
pub(crate) request: DaemonRequest,
pipe: File,
}
impl Connection {
pub(crate) fn reply<T: Serialize>(&mut self, msg: &T) {
write_frame(&mut self.pipe, msg).expect("reply to the client");
}
pub(crate) fn read<T: DeserializeOwned>(&mut self) -> T {
read_frame(&mut self.pipe).expect("read from the client")
}
}
pub(crate) struct TestDaemon {
pub(crate) client: DaemonClient,
connections: Receiver<Connection>,
}
impl TestDaemon {
pub(crate) fn start() -> Self {
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let pipe_name = format!(
r"\\.\pipe\mxc-wslc-test-daemon-{}-{}",
std::process::id(),
NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
);
let (connected, connections) = channel();
let name = pipe_name.clone();
std::thread::spawn(move || {
let wide: Vec<u16> = name.encode_utf16().chain(std::iter::once(0)).collect();
loop {
let server = unsafe {
CreateNamedPipeW(
PCWSTR(wide.as_ptr()),
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
4096,
4096,
0,
None,
)
};
assert!(!server.is_invalid(), "create a test daemon pipe instance");
if let Err(error) = unsafe { ConnectNamedPipe(server, None) } {
assert_eq!(error.code(), ERROR_PIPE_CONNECTED.to_hresult());
}
let mut pipe = unsafe { File::from_raw_handle(server.0) };
let Ok(request) = read_frame(&mut pipe) else {
continue;
};
if connected.send(Connection { request, pipe }).is_err() {
return;
}
}
});
let pid = std::process::id();
let client = DaemonClient {
pipe_name,
server_pid: pid,
server_pid_creation_time: crate::wslc_common::daemon_record::process_creation_time(
pid,
)
.expect("read this process's creation time"),
};
Self {
client,
connections,
}
}
pub(crate) fn next(&self) -> Connection {
self.connections
.recv_timeout(Duration::from_secs(10))
.expect("the client did not connect")
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn daemon_exe_is_resolved_next_to_containing_module() {
let path = daemon_exe_path().unwrap();
let expected_dir = crate::mxc_common::process_util::module_path_for_address(
daemon_exe_is_resolved_next_to_containing_module as *const (),
)
.unwrap()
.parent()
.unwrap()
.to_path_buf();
assert_eq!(path.parent().unwrap(), expected_dir);
assert!(path
.file_name()
.unwrap()
.to_string_lossy()
.starts_with("wxc-wslc-daemon"));
}
#[test]
fn expect_ok_maps_variants() {
assert!(expect_ok(DaemonResponse::Ok).is_ok());
let err = expect_ok(DaemonResponse::Err {
kind: ErrKind::NotStarted,
message: "sandbox not started".to_string(),
api_failure: Some(DaemonApiFailure {
operation: "WslcStartContainer".to_string(),
native_code: Some("0x80072740".to_string()),
}),
})
.unwrap_err();
match &err {
DaemonError::Daemon {
kind: ErrKind::NotStarted,
api_failure: Some(api_failure),
..
} => {
assert_eq!(api_failure.operation, "WslcStartContainer");
assert_eq!(api_failure.native_code.as_deref(), Some("0x80072740"));
}
other => panic!("unexpected error: {other:?}"),
}
assert!(err.to_string().contains("NotStarted"));
assert!(err.to_string().contains("sandbox not started"));
assert_eq!(
expect_ok(DaemonResponse::Pong).unwrap_err().to_string(),
"unexpected reply (expected ok): Pong"
);
}
struct ScriptedInput<F>(F);
impl<F: FnMut(&mut [u8]) -> std::io::Result<usize>> Read for ScriptedInput<F> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
(self.0)(buf)
}
}
fn stdin_frames(mut sent: &[u8]) -> Vec<Vec<u8>> {
let mut frames = Vec::new();
while !sent.is_empty() {
match read_frame::<StreamFrame>(&mut sent).unwrap() {
StreamFrame::Stdin { data } => frames.push(data),
other => panic!("expected a stdin frame, got {other:?}"),
}
}
frames
}
#[test]
fn stdin_is_attached_only_once_there_is_input_to_send() {
let attached = std::cell::Cell::new(false);
let mut chunks = vec![b"world".to_vec(), b"hello ".to_vec()];
let input = ScriptedInput(|buf: &mut [u8]| {
if chunks.len() == 2 {
assert!(
!attached.get(),
"stdin was attached before any input arrived"
);
}
let chunk = chunks.pop().unwrap_or_default();
buf[..chunk.len()].copy_from_slice(&chunk);
Ok(chunk.len())
});
let mut sent = Vec::new();
let sink = &mut sent;
let attaching = &attached;
copy_stdin(input, move || {
attaching.set(true);
Ok(Some(sink))
})
.unwrap();
assert_eq!(
stdin_frames(&sent),
vec![b"hello ".to_vec(), b"world".to_vec(), Vec::new()]
);
}
#[test]
fn an_input_that_is_already_closed_still_sends_end_of_file() {
let mut sent = Vec::new();
let sink = &mut sent;
copy_stdin(std::io::empty(), move || Ok(Some(sink))).unwrap();
assert_eq!(stdin_frames(&sent), vec![Vec::<u8>::new()]);
}
#[test]
fn stdin_for_a_run_that_is_over_is_dropped_without_error() {
let mut reads = 0;
let input = ScriptedInput(|buf: &mut [u8]| {
reads += 1;
buf[0] = b'x';
Ok(1)
});
copy_stdin::<Vec<u8>>(input, || Ok(None)).unwrap();
assert_eq!(reads, 1, "input was read after the run was over");
}
#[test]
fn a_failed_read_of_the_input_is_an_error_without_attaching() {
let input = ScriptedInput(|_: &mut [u8]| Err(std::io::Error::other("input broke")));
let error =
copy_stdin::<Vec<u8>>(input, || panic!("attached for a failed input")).unwrap_err();
assert!(error.to_string().contains("input broke"), "{error}");
}
#[test]
fn daemon_error_display_carries_kind_and_message() {
let err = DaemonError::Daemon {
kind: ErrKind::Busy,
message: "single-flight slot held".to_string(),
api_failure: None,
};
let text = err.to_string();
assert!(text.contains("Busy"));
assert!(text.contains("single-flight slot held"));
}
#[test]
fn from_record_captures_server_identity() {
use crate::wslc_common::daemon_record::RECORD_SCHEMA_VERSION;
let record = DaemonRecord {
schema_version: RECORD_SCHEMA_VERSION,
pid: 4321,
pid_creation_time: 0xABCD,
pipe_name: r"\\.\pipe\mxc-wslc-test".to_string(),
ready: true,
protocol_version: PROTOCOL_VERSION,
};
let client = DaemonClient::from_record(&record);
assert_eq!(client.pipe_name, record.pipe_name);
assert_eq!(client.server_pid, 4321);
assert_eq!(client.server_pid_creation_time, 0xABCD);
}
#[test]
fn read_frame_with_deadline_returns_value_before_deadline() {
let v: DaemonResult<u32> = read_frame_with_deadline(|| Ok(42u32), Duration::from_secs(5));
assert_eq!(v.unwrap(), 42);
}
#[test]
fn read_frame_with_deadline_times_out_on_wedged_reader() {
let start = Instant::now();
let v: DaemonResult<u32> = read_frame_with_deadline(
|| {
std::thread::sleep(Duration::from_secs(30));
Ok(0u32)
},
Duration::from_millis(100),
);
let err = v.unwrap_err();
assert!(matches!(err, DaemonError::Transport(_)));
let text = err.to_string();
assert!(text.contains("timed out"), "unexpected message: {text}");
assert!(
text.contains(CALL_TIMEOUT_ENV),
"should name the override env"
);
assert!(start.elapsed() < Duration::from_secs(5));
}
#[cfg(windows)]
#[test]
fn a_timed_out_pipe_read_is_cancelled_so_the_server_sees_the_close() {
use std::io::Read;
use std::sync::mpsc::channel;
use windows::core::PCWSTR;
use windows::Win32::Foundation::{CloseHandle, HANDLE};
use windows::Win32::Storage::FileSystem::PIPE_ACCESS_DUPLEX;
use windows::Win32::System::Pipes::{
ConnectNamedPipe, CreateNamedPipeW, PIPE_TYPE_BYTE, PIPE_WAIT,
};
let name = format!(
r"\\.\pipe\mxc-wslc-cancel-{}-{:?}",
std::process::id(),
std::thread::current().id()
);
let wide: Vec<u16> = name.encode_utf16().chain(std::iter::once(0)).collect();
let server = unsafe {
CreateNamedPipeW(
PCWSTR(wide.as_ptr()),
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE | PIPE_WAIT,
1,
4096,
4096,
0,
None,
)
};
assert!(!server.is_invalid(), "could not create the test pipe");
let (connected_tx, connected_rx) = channel();
let (write_tx, write_rx) = channel();
let server_raw = server.0 as isize;
let server_thread = std::thread::spawn(move || {
let handle = HANDLE(server_raw as *mut _);
unsafe {
let _ = ConnectNamedPipe(handle, None);
let _ = connected_tx.send(());
std::thread::sleep(Duration::from_millis(600));
let mut written = 0u32;
let wrote = windows::Win32::Storage::FileSystem::WriteFile(
handle,
Some(b"frame"),
Some(&mut written),
None,
);
let _ = write_tx.send(wrote.is_ok());
let _ = CloseHandle(handle);
}
});
let mut client = OpenOptions::new()
.read(true)
.write(true)
.open(&name)
.expect("open the test pipe");
connected_rx
.recv_timeout(Duration::from_secs(5))
.expect("server accepted the connection");
let start = Instant::now();
let outcome: DaemonResult<usize> = read_frame_with_deadline(
move || {
let mut buf = [0u8; 8];
let n = client.read(&mut buf)?;
Ok(n)
},
Duration::from_millis(150),
);
let err = outcome.unwrap_err();
assert!(matches!(err, DaemonError::Transport(_)));
assert!(
start.elapsed() < Duration::from_secs(5),
"the deadline must return promptly, not wait out the read"
);
let server_wrote = write_rx
.recv_timeout(Duration::from_secs(10))
.expect("server reported its write");
assert!(
!server_wrote,
"the client's end must be closed, so the server's reply cannot land"
);
server_thread.join().expect("server thread");
}
#[cfg(windows)]
#[test]
fn a_read_that_beat_the_deadline_is_reported_rather_than_discarded() {
let outcome: DaemonResult<u32> = read_frame_with_deadline(
|| {
std::thread::sleep(Duration::from_millis(120));
Ok(7u32)
},
Duration::from_millis(100),
);
assert_eq!(
outcome.expect("a completed read must not be reported as a timeout"),
7
);
}
#[test]
fn read_frame_with_deadline_propagates_reader_error() {
let v: DaemonResult<u32> = read_frame_with_deadline(
|| Err(anyhow::anyhow!("framing error")),
Duration::from_secs(5),
);
let err = v.unwrap_err();
assert!(matches!(err, DaemonError::Transport(_)));
assert!(err.to_string().contains("framing error"));
}
#[test]
fn resolve_duration_falls_back_when_absent_or_invalid() {
let default = Duration::from_secs(600);
assert_eq!(resolve_duration(None, default), default);
assert_eq!(resolve_duration(Some(""), default), default);
assert_eq!(resolve_duration(Some("nope"), default), default);
assert_eq!(resolve_duration(Some("0"), default), default);
}
#[test]
fn resolve_duration_honours_positive_override() {
assert_eq!(
resolve_duration(Some(" 3 "), Duration::from_secs(600)),
Duration::from_secs(3)
);
}
}