mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 19:14:26 +00:00
* craft-ipc: local-socket server, client and discovery for Craft apps Adds craft-ipc, the transport for a Craft app that talks to other Craft apps on one machine. It is native only: interprocess has no wasm32 build. - server and client: one JSON object per line, push events, a bulk connection for frames, token auth on every connection, connection and time limits. - discovery: one record per running app in a per-user runtime directory, with a lock file that shows whether the owner is alive. - launch, trust, cache: find an app binary, start it only after an executable check, keep caches in a private per-user directory. - activate: focus hand-off between apps. - moniker, record, payload, asset, refresh, fetch, watch: asset names, stored link records, open payloads, linked-file polling and a frame cache. - PROTOCOL.md describes the wire protocol. The record schemas and fixtures are in the crate. - The crate compiles and passes clippy -D warnings on x86_64-pc-windows-gnu and aarch64-apple-darwin. This is a compile and lint fix only. No one ran the Windows or macOS code paths, so this does not claim they work there. Part of #414. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: app.activate no longer claims a request it cannot make ActivationBackend gains can_apply_token (default false). On Linux a token only counts when the backend can apply it to a live window. Stock winit cannot, so the answer is false plus a request for user attention. Wire values are unchanged. PROTOCOL.md says what each value means. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: keep a partial reply line across client read timeouts pull_line dropped the bytes it had read when a read timed out, so next_event returned Ok(None) and the next read saw only the tail of the line. The client now keeps the partial line and resumes it on the next read. A test splits an event line across a timeout. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: scope the macOS fallback runtime directory to the user With TMPDIR unset or relative, the fallback was the shared path /tmp/craft. The first user to create it owned it, and every other user then failed the owner check. The fallback is now /tmp/craft-<euid>, as on Linux. The path choice is a pure function with a test. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: fetch rejects non-finite time, bounds its queue, keeps waited-for asks Three changes to FrameFetcher::fetch. A non-finite time_s was queued and failed in request_reply before any socket I/O. The worker read that as a dead connection and exited, so enough bad asks took every worker down. fetch now returns Fetched::Failed and queues nothing. The queue had no length limit, so stalled workers let it grow with the request rate. It now holds at most QUEUE_MAX asks (256, a new public constant). A miss past the cap drops the oldest queued ask and counts it in stats.skipped. next_job dropped any job older than max_age, even when the caller had waited longer than max_age and was still there. The caller then re-queued at the tail. Each job now records the latest deadline of its waiting callers and is skipped for age only when no caller is left. Tests cover each case. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: reject file:// media URLs that do not percent-decode local_path returned None for a file:// URL with a bad percent escape, and missing_media then skipped it, so the server accepted a local target without the media probe. Such a URL now gets payload_invalid. URLs that name no local file (remote host, other scheme, relative path) are still left to the app. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: open watched files without waiting on a FIFO Tracker::poll, Tracker::new and fingerprint opened the path with File::open before stat checked the file type. A FIFO with no writer made that open wait, and poll_entry held the entry lock for the whole call, so one such path stalled every link on the watcher and the watcher drop. The open now sets O_NONBLOCK (new crate fsopen), and stat rejects the FIFO on the open handle with LinkError::Invalid. A check before the open would not close the window between check and open. craft-ipc gains a unix-only dependency on libc for the open flags. libc 0.2.190 is already in Cargo.lock. The lock file gains one dependency line for craft-ipc. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: read_private checks and reads one open handle read_private checked the path with symlink_metadata and then read it with fs::read, so the entry could change between the two calls. On Unix it now opens once with O_NOFOLLOW and O_NONBLOCK, checks type, owner and mode on that handle, and reads from the same handle. A symlink is still Refused (found by looking at the path after a failed open, because the errno differs between Unix systems), a FIFO is Refused and cannot stall the open, and a missing file is still an I/O error. Other platforms keep the old checks. Tests cover the symlink and FIFO cases. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: Tracker reports an epoch it cannot raise instead of a false bump apply saturated the epoch at u64::MAX while poll and relink still returned bumped: true, so Change::bumped (documented as one added to the epoch) was false and a cached frame kept passing for changed content. poll and relink now return LinkError::Invalid and leave the tracker as it was when the bump would pass u64::MAX. A test covers both calls. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: document write_atomic errors that follow the rename The directory flush and the fingerprint run after the rename. An error from either can be returned while the path already holds the new bytes. The doc comment now says so. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: say that check_executable accepts group-writable paths The module and function docs described the check as protection from other local users. A group-writable file or directory passes, and the other members of its group can replace it. The docs now state that and keep the private-group reason. Behavior is unchanged. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: refuse an auth line that completes after the deadline authenticate returned a completed line before it looked at the deadline, so a line that finished after auth_deadline still authenticated. The overshoot was up to one 250 ms read poll. The deadline is now checked first, with the same auth failure reply as the other expiry paths. A test sends the line between the deadline and the next poll. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: do not append an error record after a partial frame write send_frame wrote an error record whenever write_frame failed. When the failure came from the stream (for example a send timeout in the middle of a record), the first record was cut short, and a peer that drained the buffer then read the error record as the rest of it. send_frame now checks that the record can be built before it writes. A record that cannot be built gets the error record as before. A write failure is returned alone and the bulk loop closes the connection. wire gains check_cfrm, the pre-write part of write_cfrm. write_cfrm behaves as before. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: LineReader applies the line limit to a last line without a newline At end of stream LineReader::read returned a buffered line with no length check, so a peer that sent one byte over the limit and closed its write side got that line dispatched, while the same bytes with a newline were refused. The end of stream path now returns TooLarge for a line over the limit. A test covers both paths. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: answer a control reply over the line limit with payload_too_large write_value passed every reply to write_line, which has no size check. A sink result larger than MAX_LINE went out as one line that the client refuses, and the rest of the line stayed unread on the connection. Replies now go through wire::write_reply_line. A reply over the limit is replaced by a payload_too_large error that keeps the request id. When that does not fit either, or the value has no id, nothing is written and the request loop ends. Event lines are unchanged. wire gains write_reply_line. write_line behaves as before. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: accept a shallow or deep poll in the native ticker test The test expected the first notice to come from a shallow poll. With a 50 ms deep interval the poll that first sees the edit can be a deep one, so the assertion failed on a slow or loaded machine. It now takes the deep flag from the notice and checks every other field. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: refuse a frame stride that cannot hold one row FrameLayout::check only tested len == stride * h, so w = 4, stride = 1, h = 3, len = 3 was a valid rgba8 layout. A reader that splits the payload by stride cannot decode it. frames.open, a rendered frame and the client reply parser now require stride >= w * bytes per pixel (4 for rgba8_premul, 8 for rgba16f_premul). open checks before it mints a ticket, so a refused layout leaves no ticket. The bulk test source used stride 16 for rgba16f with w = 4, which needs 32. It now uses a stride that fits the format. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: reject calendar days that do not exist in a record's created field valid_rfc3339 checked the day only against 1 to 31, so 2026-02-31T09:30:00Z passed LinkRecord::validate while the schema's date-time format refused it. The year, month and day now go through chrono::NaiveDate::from_ymd_opt, as the workspace rules require for calendar logic. The accepted syntax is unchanged. The schema agreement table gets rows for impossible days and for leap days. craft-ipc gains the workspace chrono dependency. chrono is already in Cargo.lock; the lock file gains one dependency line for craft-ipc. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: make the link record moniker pattern match Moniker::parse The asset.moniker pattern accepted any id without / ? #, so a record the schema passed could fail LinkRecord::validate (bad or truncated escape, raw space, escape that decodes to invalid UTF-8, id over 512 bytes). The pattern is now two patterns under allOf. One checks the shape: unreserved characters and two-digit escapes only, 1 to 512 of them, which is 1 to 512 decoded bytes. The other checks that the decoded bytes are valid UTF-8, written as the well-formed UTF-8 byte sequences. Neither uses lookahead, so any ECMA 262 engine can run them. The schema agreement test gets rows for each case in the list above and for the length limits, and a sweep of lead, second and tail bytes that compares the schema verdict with the Rust verdict. This tightens the published schema: documents it accepted that Rust refused are now refused. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: document that Assets methods must return in bounded time Server::shutdown and drop join every connection thread, and an Assets call runs on one with no deadline and no view of the stop flag. The trait docs now say so and ask implementations to bound their own I/O. Behavior is unchanged. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: name the writer type in the listener tests Clippy's type_complexity lint failed on the test helper's return type. Behavior is unchanged. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: run Assets and Activate calls on detached helper threads with a deadline Server::shutdown and drop join every connection thread, and an Assets or Activate call ran on one with no deadline and no view of the stop flag, so a provider that never returned made shutdown hang. These calls now run on a helper thread (server/provider.rs). The connection thread waits for the answer in 100 ms slices, for at most Limits::provider_deadline (default REPLY_DEADLINE_SECS) and not past the stop flag. On timeout the caller gets a timeout reply and the helper is detached, so shutdown does not join it. At most 32 helper threads are alive at once, stuck ones included, and a call past that gets a busy error without starting a thread. A panic in a provider becomes an io_error reply. Frames stays on the connection thread because it is one call per frame. Its trait docs now say that the stop flag is checked before each request and that a running call is waited for. The module docs describe the shutdown guarantee for each provider kind. Public API: new Limits::provider_deadline field. Tests use a provider that blocks until released, for Assets and for Activate. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: give a caller whose queued ask was dropped a Failed outcome When the fetch queue was full, the oldest ask was dropped but its waiting callers got no answer. They woke, found the key neither cached nor in flight, and queued it again, which dropped another ask and repeated the cycle. A dropped ask now records a failure for its key before the waiters are woken, so each waiter returns Fetched::Failed and does not queue the key again. The drop-oldest policy and stats.skipped are unchanged. Failure records are shared with the worker path and kept to a fixed number, oldest first. No type or variant changes. The Fetched::Failed doc now covers this case. A test overflows the queue while a caller waits on the oldest key, and checks that the caller returns at once and that no further asks are dropped. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: require two hex digits in a file URL percent escape percent_decode used u8::from_str_radix, which accepts a leading plus, so file:///tmp/a%+fb decoded to the byte 0x0f and went on to the media probe instead of getting payload_invalid. The two bytes after a percent sign must now both be ASCII hex digits. The decode test gets a plus, a minus, a space and a short escape. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: make the euid probe create only its own file, and gate the macOS path test On Unix systems other than Linux, current_euid read the owner of a file named .craft-uid-<pid> in the temp directory, made with create and truncate. A file or symlink planted at that name was opened and truncated. The probe now lives in probe_euid: random name, create_new (which refuses an existing path), mode 0600, and removal before it returns. The std library has no safe euid call and this crate forbids unsafe code, so the probe stays. A test plants a file and a symlink at the old and a similar name and checks that both are untouched and that the probe file is gone. macos_fallback_is_per_user compares Unix paths, so it and the macos_runtime_path helper it needs are now compiled for tests on Unix only. That removes the unused function warning in Windows test builds. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * craft-ipc: an event larger than one line becomes an events.overflow marker Server::emit wrote the serialized event unchecked. A line over MAX_LINE made Client::next_event return TooLarge and left the stream out of sync. enqueue now checks the serialized size and queues the existing overflow marker instead. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NFCDiYoKS325v2rtv2F7D8 * ipc: validate executable path ancestry * ipc: preserve queued replies after macOS peer shutdown * ipc: validate native transports and use portable platform fixtures * Make IPC integration fixtures portable and collision-free * Use native paths and unique directories across IPC fixtures * Bound Windows pipe I/O and stabilize IPC tests * Retry empty nonblocking Windows pipes * #433: Serialize hub tests sharing a Windows pipe * #433: Use native endpoint in schema capability tests * ipc: report a non-regular watch target as Invalid on every platform * ipc: format the new error classification --------- Co-authored-by: User <bigwolfeman@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
778 lines
29 KiB
Rust
778 lines
29 KiB
Rust
//! Find and start a Craft app.
|
|
//!
|
|
//! `resolve` reads the process environment. The decision itself is
|
|
//! `resolve_with`, which takes an owned env map, a home directory, and the
|
|
//! candidate directories. Tests call that function and do not change the
|
|
//! process environment.
|
|
|
|
use std::collections::BTreeMap;
|
|
use std::ffi::OsString;
|
|
use std::path::{Path, PathBuf};
|
|
use std::process::Command;
|
|
use std::time::{Duration, Instant};
|
|
|
|
use serde_json::Value;
|
|
|
|
use crate::client::{Client, HelloClient};
|
|
use crate::error::LinkError;
|
|
use crate::trust;
|
|
use crate::{Discovery, InstanceRecord, RuntimeDir};
|
|
|
|
const RECORD_WAIT: Duration = Duration::from_secs(15);
|
|
const RECORD_POLL: Duration = Duration::from_millis(50);
|
|
|
|
/// Progress reported by [`launch_at`].
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum Phase {
|
|
Spawned,
|
|
RecordSeen,
|
|
HelloOk,
|
|
}
|
|
|
|
/// Find the binary for `app` from the process environment.
|
|
pub fn resolve(app: &str) -> Result<PathBuf, LinkError> {
|
|
let env = std::env::vars().collect::<BTreeMap<_, _>>();
|
|
let home = std::env::var_os("HOME").map(PathBuf::from);
|
|
let exe_dir = std::env::current_exe().ok().and_then(|path| path.parent().map(Path::to_path_buf));
|
|
let search = default_search_dirs(home.as_deref());
|
|
resolve_with(app, &env, home.as_deref(), exe_dir.as_deref(), &search)
|
|
}
|
|
|
|
/// [`resolve`] then [`launch_at`] with no args and the real runtime directory.
|
|
pub fn launch(app: &str, extra_env: &[(&str, &str)]) -> Result<InstanceRecord, LinkError> {
|
|
let bin = resolve(app)?;
|
|
launch_at(app, &bin, &[], extra_env, None, &mut |_| {})
|
|
}
|
|
|
|
/// Spawn `bin` and wait until its discovery record answers `link.hello`.
|
|
///
|
|
/// `extra_env` is applied with [`Command::env`]. This function does not mint
|
|
/// an activation token. `XDG_ACTIVATION_TOKEN` and `DESKTOP_STARTUP_ID` are
|
|
/// passed through when the caller puts them in `extra_env`.
|
|
///
|
|
/// `runtime` `None` scans [`RuntimeDir::resolve`]. The returned record is one
|
|
/// this function observed for the spawned pid.
|
|
pub fn launch_at(
|
|
app: &str,
|
|
bin: &Path,
|
|
args: &[OsString],
|
|
extra_env: &[(&str, &str)],
|
|
runtime: Option<&RuntimeDir>,
|
|
on_phase: &mut dyn FnMut(Phase),
|
|
) -> Result<InstanceRecord, LinkError> {
|
|
// `resolve` already checked `bin`. The caller may pass any path, and time has passed.
|
|
trust::check_executable(bin)?;
|
|
let mut cmd = Command::new(bin);
|
|
cmd.args(args);
|
|
for (key, value) in extra_env {
|
|
cmd.env(key, value);
|
|
}
|
|
// A new process group. The child is not in this process's group.
|
|
// The waiter thread reaps it. kill_on_drop stays off.
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::process::CommandExt;
|
|
cmd.process_group(0);
|
|
}
|
|
let mut child = cmd.spawn().map_err(LinkError::io)?;
|
|
let pid = child.id();
|
|
std::thread::Builder::new()
|
|
.name("craft-ipc-wait".into())
|
|
.spawn(move || {
|
|
let _ = child.wait();
|
|
})
|
|
.map_err(LinkError::io)?;
|
|
on_phase(Phase::Spawned);
|
|
if let Some(dir) = runtime {
|
|
finish_launch(app, pid, dir, on_phase)
|
|
} else {
|
|
let owned = RuntimeDir::resolve()?;
|
|
finish_launch(app, pid, &owned, on_phase)
|
|
}
|
|
}
|
|
|
|
fn finish_launch(app: &str, pid: u32, dir: &RuntimeDir, on_phase: &mut dyn FnMut(Phase)) -> Result<InstanceRecord, LinkError> {
|
|
let record = wait_for_record(dir, app, pid)?;
|
|
on_phase(Phase::RecordSeen);
|
|
greet(&record, app)?;
|
|
on_phase(Phase::HelloOk);
|
|
Ok(record)
|
|
}
|
|
|
|
fn wait_for_record(dir: &RuntimeDir, app: &str, pid: u32) -> Result<InstanceRecord, LinkError> {
|
|
let deadline = Instant::now() + RECORD_WAIT;
|
|
loop {
|
|
let records = Discovery::scan(dir)?;
|
|
if let Some(record) = records.into_iter().find(|record| record.app == app && record.pid == pid) {
|
|
return Ok(record);
|
|
}
|
|
let now = Instant::now();
|
|
if now >= deadline {
|
|
return Err(LinkError::Timeout);
|
|
}
|
|
std::thread::sleep(RECORD_POLL.min(deadline.saturating_duration_since(now)));
|
|
}
|
|
}
|
|
|
|
fn greet(record: &InstanceRecord, app: &str) -> Result<(), LinkError> {
|
|
let mut client = Client::connect(record).map_err(as_not_ready)?;
|
|
let identity = HelloClient {
|
|
app: app.to_string(),
|
|
app_version: "launch".into(),
|
|
pid: std::process::id(),
|
|
instance: crate::random_uuid().map_err(as_not_ready)?,
|
|
protocol_min: crate::wire::PROTOCOL_MIN,
|
|
protocol_max: crate::wire::PROTOCOL_MAX,
|
|
};
|
|
client.hello(&identity).map_err(as_not_ready)?;
|
|
Ok(())
|
|
}
|
|
|
|
fn as_not_ready(err: LinkError) -> LinkError {
|
|
match err {
|
|
LinkError::Timeout => LinkError::Timeout,
|
|
LinkError::NotReady(_) => err,
|
|
other => LinkError::NotReady(other.to_string()),
|
|
}
|
|
}
|
|
|
|
fn resolve_with(
|
|
app: &str,
|
|
env: &BTreeMap<String, String>,
|
|
home: Option<&Path>,
|
|
exe_dir: Option<&Path>,
|
|
search_dirs: &[PathBuf],
|
|
) -> Result<PathBuf, LinkError> {
|
|
if let Some(found) = env_override(app, env) {
|
|
return found;
|
|
}
|
|
if let Some(manifest) = manifest_path(env, home, exe_dir)
|
|
&& let Some(bin) = from_manifest(app, &manifest)
|
|
{
|
|
return Ok(bin);
|
|
}
|
|
if let Some(bin) = from_path_env(app, env) {
|
|
return Ok(bin);
|
|
}
|
|
for dir in search_dirs {
|
|
if let Some(bin) = search_dir(app, dir) {
|
|
return Ok(bin);
|
|
}
|
|
}
|
|
if let Some(bin) = platform_bundle(app, home) {
|
|
return Ok(bin);
|
|
}
|
|
Err(LinkError::NotInstalled { app: app.to_string() })
|
|
}
|
|
|
|
/// `CRAFT_<APP>_BIN`. Set means authoritative, including a missing file.
|
|
fn env_override(app: &str, env: &BTreeMap<String, String>) -> Option<Result<PathBuf, LinkError>> {
|
|
let value = env.get(&bin_env_key(app))?;
|
|
let path = PathBuf::from(value);
|
|
if !path.is_file() {
|
|
return Some(Err(LinkError::NotInstalled { app: app.to_string() }));
|
|
}
|
|
Some(trust::check_executable(&path).map(|()| path))
|
|
}
|
|
|
|
fn bin_env_key(app: &str) -> String {
|
|
let mut key = String::from("CRAFT_");
|
|
for byte in app.bytes() {
|
|
if byte.is_ascii_alphanumeric() {
|
|
key.push(byte.to_ascii_uppercase() as char);
|
|
} else {
|
|
key.push('_');
|
|
}
|
|
}
|
|
key.push_str("_BIN");
|
|
key
|
|
}
|
|
|
|
fn manifest_path(env: &BTreeMap<String, String>, home: Option<&Path>, exe_dir: Option<&Path>) -> Option<PathBuf> {
|
|
if let Some(dir) = exe_dir
|
|
&& dir.join("portable.txt").is_file()
|
|
{
|
|
return Some(dir.join("ArtCraftLauncherData").join("data").join("installed.json"));
|
|
}
|
|
Some(data_dir(env, home)?.join(launcher_dir_name()).join("installed.json"))
|
|
}
|
|
|
|
fn launcher_dir_name() -> &'static str {
|
|
if cfg!(any(target_os = "macos", windows)) { "ArtCraft Launcher" } else { "artcraft-launcher" }
|
|
}
|
|
|
|
fn data_dir(env: &BTreeMap<String, String>, home: Option<&Path>) -> Option<PathBuf> {
|
|
#[cfg(target_os = "linux")]
|
|
{
|
|
linux_data_dir(env, home)
|
|
}
|
|
#[cfg(target_os = "macos")]
|
|
{
|
|
let _ = env;
|
|
home.map(|dir| dir.join("Library").join("Application Support"))
|
|
}
|
|
#[cfg(windows)]
|
|
{
|
|
let _ = home;
|
|
env.get("LOCALAPPDATA").map(PathBuf::from).filter(|path| path.is_absolute())
|
|
}
|
|
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
|
|
{
|
|
let _ = (env, home);
|
|
None
|
|
}
|
|
}
|
|
|
|
#[cfg(target_os = "linux")]
|
|
fn linux_data_dir(env: &BTreeMap<String, String>, home: Option<&Path>) -> Option<PathBuf> {
|
|
if let Some(xdg) = env.get("XDG_DATA_HOME") {
|
|
let path = PathBuf::from(xdg);
|
|
if path.is_absolute() {
|
|
return Some(path);
|
|
}
|
|
}
|
|
home.map(|dir| dir.join(".local").join("share"))
|
|
}
|
|
|
|
/// Only `path` is required. An unknown `kind` is ignored. A path that is not a file is skipped.
|
|
fn from_manifest(app: &str, path: &Path) -> Option<PathBuf> {
|
|
let bytes = std::fs::read(path).ok()?;
|
|
let value: Value = serde_json::from_slice(&bytes).ok()?;
|
|
let text = value.get("apps")?.get(app)?.get("path")?.as_str()?;
|
|
let bin = PathBuf::from(text);
|
|
trust::check_executable(&bin).is_ok().then_some(bin)
|
|
}
|
|
|
|
/// A `PATH` entry that is empty or relative names the current directory, so it is skipped.
|
|
fn from_path_env(app: &str, env: &BTreeMap<String, String>) -> Option<PathBuf> {
|
|
let path = env.get("PATH")?;
|
|
for dir in std::env::split_paths(path) {
|
|
if !dir.is_absolute() {
|
|
continue;
|
|
}
|
|
let candidate = dir.join(app);
|
|
if trust::check_executable(&candidate).is_ok() {
|
|
return Some(candidate);
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
fn default_search_dirs(home: Option<&Path>) -> Vec<PathBuf> {
|
|
#[cfg(target_os = "linux")]
|
|
{
|
|
let mut dirs = Vec::new();
|
|
if let Some(home) = home {
|
|
dirs.push(home.join("Applications"));
|
|
dirs.push(home.join("AppImages"));
|
|
dirs.push(home.join(".local").join("bin"));
|
|
}
|
|
dirs.push(PathBuf::from("/usr/bin"));
|
|
dirs.push(PathBuf::from("/usr/local/bin"));
|
|
dirs
|
|
}
|
|
#[cfg(not(target_os = "linux"))]
|
|
{
|
|
let _ = home;
|
|
Vec::new()
|
|
}
|
|
}
|
|
|
|
fn search_dir(app: &str, dir: &Path) -> Option<PathBuf> {
|
|
let exact = dir.join(app);
|
|
if trust::check_executable(&exact).is_ok() {
|
|
return Some(exact);
|
|
}
|
|
let entries = std::fs::read_dir(dir).ok()?;
|
|
let mut names = Vec::new();
|
|
for entry in entries {
|
|
let Ok(entry) = entry else { continue };
|
|
let Ok(name) = entry.file_name().into_string() else { continue };
|
|
if is_appimage(app, &name) {
|
|
names.push(name);
|
|
}
|
|
}
|
|
names.sort();
|
|
for name in names {
|
|
let path = dir.join(name);
|
|
if trust::check_executable(&path).is_ok() {
|
|
return Some(path);
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
/// `{app}.appimage` in any ASCII case, or a name that starts with `{app}-` and ends with `.AppImage`.
|
|
fn is_appimage(app: &str, name: &str) -> bool {
|
|
const EXT: &str = ".appimage";
|
|
let Some(split) = name.len().checked_sub(EXT.len()) else {
|
|
return false;
|
|
};
|
|
let Some(ext) = name.get(split..) else {
|
|
return false;
|
|
};
|
|
let Some(base) = name.get(..split) else {
|
|
return false;
|
|
};
|
|
if !ext.eq_ignore_ascii_case(EXT) {
|
|
return false;
|
|
}
|
|
if base.eq_ignore_ascii_case(app) {
|
|
return true;
|
|
}
|
|
let mut prefix = String::with_capacity(app.len() + 1);
|
|
prefix.push_str(app);
|
|
prefix.push('-');
|
|
name.starts_with(&prefix)
|
|
}
|
|
|
|
/// An id that ends with `craft` becomes `PrefixCraft` (`filmcraft` to `FilmCraft`).
|
|
/// Used by the macOS bundle search. Linux resolves AppImages without this name.
|
|
#[cfg_attr(not(any(test, target_os = "macos")), allow(dead_code))]
|
|
fn display_name(app: &str) -> String {
|
|
if let Some(prefix) = app.strip_suffix("craft") {
|
|
let mut name = String::new();
|
|
let mut chars = prefix.chars();
|
|
if let Some(first) = chars.next() {
|
|
name.push(first.to_ascii_uppercase());
|
|
name.push_str(chars.as_str());
|
|
}
|
|
name.push_str("Craft");
|
|
return name;
|
|
}
|
|
let mut chars = app.chars();
|
|
let Some(first) = chars.next() else {
|
|
return String::new();
|
|
};
|
|
let mut name = String::new();
|
|
name.push(first.to_ascii_uppercase());
|
|
name.push_str(chars.as_str());
|
|
name
|
|
}
|
|
|
|
/// macOS bundles. Windows uninstall-registry lookup is not implemented (no winreg).
|
|
/// PATH, `CRAFT_<APP>_BIN`, and `installed.json` still apply on Windows.
|
|
#[cfg(target_os = "macos")]
|
|
fn platform_bundle(app: &str, home: Option<&Path>) -> Option<PathBuf> {
|
|
let bundle = format!("{}.app", display_name(app));
|
|
let mut candidates = vec![PathBuf::from("/Applications").join(&bundle)];
|
|
if let Some(home) = home {
|
|
candidates.push(home.join("Applications").join(&bundle));
|
|
}
|
|
for bundle_path in candidates {
|
|
if !bundle_path.is_dir() {
|
|
continue;
|
|
}
|
|
let exe = bundle_path.join("Contents").join("MacOS").join(app);
|
|
if trust::check_executable(&exe).is_ok() {
|
|
return Some(exe);
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
#[cfg(not(target_os = "macos"))]
|
|
fn platform_bundle(_app: &str, _home: Option<&Path>) -> Option<PathBuf> {
|
|
None
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
|
mod tests {
|
|
use std::collections::BTreeMap;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use super::*;
|
|
|
|
struct Tmp {
|
|
path: PathBuf,
|
|
}
|
|
|
|
impl Tmp {
|
|
fn new(label: &str) -> Self {
|
|
let mut bytes = [0u8; 4];
|
|
getrandom::getrandom(&mut bytes).unwrap();
|
|
let path = std::env::temp_dir().join(format!("cl-{label}-{}", crate::auth::encode_hex(&bytes)));
|
|
let _ = std::fs::remove_dir_all(&path);
|
|
std::fs::create_dir_all(&path).unwrap();
|
|
Self { path }
|
|
}
|
|
|
|
fn path(&self) -> &Path {
|
|
&self.path
|
|
}
|
|
}
|
|
|
|
impl Drop for Tmp {
|
|
fn drop(&mut self) {
|
|
let _ = std::fs::remove_dir_all(&self.path);
|
|
}
|
|
}
|
|
|
|
fn touch(path: &Path) {
|
|
if let Some(parent) = path.parent() {
|
|
std::fs::create_dir_all(parent).unwrap();
|
|
}
|
|
std::fs::write(path, b"bin").unwrap();
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::fs::PermissionsExt;
|
|
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
|
}
|
|
}
|
|
|
|
/// Mode of the directory that holds `path`, for the trust tests.
|
|
#[cfg(unix)]
|
|
fn chmod(path: &Path, mode: u32) {
|
|
use std::os::unix::fs::PermissionsExt;
|
|
std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap();
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[test]
|
|
fn relative_and_empty_path_entries_are_skipped() {
|
|
let root = Tmp::new("relpath");
|
|
let cwd = std::env::current_dir().unwrap();
|
|
// A program in the current directory must not be found through "" or ".".
|
|
let here = cwd.join(format!("effectcraft-relpath-{}", std::process::id()));
|
|
touch(&here);
|
|
let name = here.file_name().unwrap().to_str().unwrap().to_string();
|
|
let good_dir = root.path().join("bin");
|
|
for path in ["", ".", "./", "bin:", ":bin"] {
|
|
let env = env_map(&[("PATH", path)]);
|
|
let err = super::resolve_with(&name, &env, None, None, &[]);
|
|
assert!(err.is_err(), "PATH={path:?} found {err:?}");
|
|
}
|
|
// An absolute entry later in the list still works.
|
|
touch(&good_dir.join(&name));
|
|
let path = format!(":.:{}", good_dir.display());
|
|
let env = env_map(&[("PATH", path.as_str())]);
|
|
assert_eq!(super::resolve_with(&name, &env, None, None, &[]).unwrap(), good_dir.join(&name));
|
|
std::fs::remove_file(&here).unwrap();
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[test]
|
|
fn loose_programs_and_directories_are_not_run() {
|
|
let root = Tmp::new("loose");
|
|
let bin_dir = root.path().join("bin");
|
|
let bin = bin_dir.join("effectcraft");
|
|
touch(&bin);
|
|
let env = env_map(&[("PATH", bin_dir.to_str().unwrap())]);
|
|
assert!(super::resolve_with("effectcraft", &env, None, None, &[]).is_ok());
|
|
chmod(&bin_dir, 0o777);
|
|
assert!(super::resolve_with("effectcraft", &env, None, None, &[]).is_err(), "world-writable directory");
|
|
// The same holds for the override, the manifest and the fixed search directories.
|
|
let by_env = env_map(&[("CRAFT_EFFECTCRAFT_BIN", bin.to_str().unwrap())]);
|
|
assert!(matches!(super::resolve_with("effectcraft", &by_env, None, None, &[]), Err(LinkError::Refused { .. })));
|
|
assert!(super::resolve_with("effectcraft", &env_map(&[]), None, None, std::slice::from_ref(&bin_dir)).is_err());
|
|
let data = root.path().join("xdg");
|
|
let home = root.path().join("home");
|
|
write_manifest(&installed_manifest(&home, Some(&data)), "effectcraft", &bin);
|
|
let by_manifest = data_env(&data);
|
|
chmod(&bin_dir, 0o755);
|
|
assert_eq!(super::resolve_with("effectcraft", &by_manifest, Some(&home), None, &[]).unwrap(), bin);
|
|
chmod(&bin_dir, 0o777);
|
|
assert!(super::resolve_with("effectcraft", &by_manifest, Some(&home), None, &[]).is_err());
|
|
chmod(&bin_dir, 0o755);
|
|
chmod(&bin, 0o666);
|
|
assert!(super::resolve_with("effectcraft", &env, None, None, &[]).is_err(), "not executable and world-writable");
|
|
chmod(&bin, 0o644);
|
|
assert!(super::resolve_with("effectcraft", &env, None, None, &[]).is_err(), "not executable");
|
|
// A relative override is refused, not run from the current directory.
|
|
let relative = env_map(&[("CRAFT_EFFECTCRAFT_BIN", "Cargo.toml")]);
|
|
assert!(super::resolve_with("effectcraft", &relative, None, None, &[]).is_err());
|
|
// launch_at checks the path too.
|
|
let err = launch_at("effectcraft", &bin, &[], &[], None, &mut |_| {}).unwrap_err();
|
|
assert!(matches!(err, LinkError::Refused { .. }), "{err:?}");
|
|
}
|
|
|
|
fn env_map(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
|
|
pairs.iter().map(|(key, value)| ((*key).to_string(), (*value).to_string())).collect()
|
|
}
|
|
|
|
// Independent fixture paths for the launcher's documented native install record.
|
|
fn installed_manifest(home: &Path, xdg: Option<&Path>) -> PathBuf {
|
|
if cfg!(target_os = "macos") {
|
|
home.join("Library/Application Support/ArtCraft Launcher/installed.json")
|
|
} else if cfg!(windows) {
|
|
xdg.unwrap_or(home).join("ArtCraft Launcher/installed.json")
|
|
} else {
|
|
xdg.map_or_else(|| home.join(".local/share"), Path::to_path_buf).join("artcraft-launcher/installed.json")
|
|
}
|
|
}
|
|
|
|
fn data_env(data: &Path) -> BTreeMap<String, String> {
|
|
let key = if cfg!(windows) { "LOCALAPPDATA" } else { "XDG_DATA_HOME" };
|
|
env_map(&[(key, data.to_str().unwrap())])
|
|
}
|
|
|
|
fn write_manifest(path: &Path, app: &str, bin: &Path) {
|
|
if let Some(parent) = path.parent() {
|
|
std::fs::create_dir_all(parent).unwrap();
|
|
}
|
|
let body = serde_json::json!({
|
|
"apps": {
|
|
app: {"kind": "mystery", "path": bin}
|
|
}
|
|
});
|
|
std::fs::write(path, serde_json::to_vec(&body).unwrap()).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn bin_env_key_uppercases_and_replaces_other_bytes() {
|
|
assert_eq!(super::bin_env_key("effectcraft"), "CRAFT_EFFECTCRAFT_BIN");
|
|
assert_eq!(super::bin_env_key("film-craft"), "CRAFT_FILM_CRAFT_BIN");
|
|
}
|
|
|
|
#[test]
|
|
fn display_name_for_craft_apps() {
|
|
assert_eq!(super::display_name("filmcraft"), "FilmCraft");
|
|
assert_eq!(super::display_name("effectcraft"), "EffectCraft");
|
|
assert_eq!(super::display_name("pdfcraft"), "PdfCraft");
|
|
}
|
|
|
|
#[test]
|
|
fn appimage_names() {
|
|
assert!(super::is_appimage("effectcraft", "effectcraft.AppImage"));
|
|
assert!(super::is_appimage("effectcraft", "EffectCraft.appimage"));
|
|
assert!(super::is_appimage("effectcraft", "effectcraft-0.8.3-linux-x86_64.AppImage"));
|
|
assert!(!super::is_appimage("effectcraft", "effectcraft-0.8.3.deb"));
|
|
assert!(!super::is_appimage("effectcraft", "not-effectcraft.AppImage"));
|
|
assert!(!super::is_appimage("effectcraft", "effectcraft.AppImage.zsync"));
|
|
}
|
|
|
|
#[test]
|
|
fn env_override_missing_file_does_not_fall_through() {
|
|
let root = Tmp::new("miss");
|
|
let missing = root.path().join("nope");
|
|
let real_dir = root.path().join("bin");
|
|
let real = real_dir.join("effectcraft");
|
|
touch(&real);
|
|
let env = env_map(&[("CRAFT_EFFECTCRAFT_BIN", missing.to_str().unwrap()), ("PATH", real_dir.to_str().unwrap())]);
|
|
let err = super::resolve_with("effectcraft", &env, None, None, &[real_dir]).unwrap_err();
|
|
match err {
|
|
LinkError::NotInstalled { app } => assert_eq!(app, "effectcraft"),
|
|
other => panic!("expected NotInstalled, got {other}"),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn env_override_existing_file_is_that_path() {
|
|
let root = Tmp::new("envok");
|
|
let bin = root.path().join("custom");
|
|
touch(&bin);
|
|
let env = env_map(&[("CRAFT_EFFECTCRAFT_BIN", bin.to_str().unwrap())]);
|
|
let got = super::resolve_with("effectcraft", &env, None, None, &[]).unwrap();
|
|
assert_eq!(got, bin);
|
|
}
|
|
|
|
#[test]
|
|
fn installed_json_supplies_the_path() {
|
|
let root = Tmp::new("man");
|
|
let data = root.path().join("xdg");
|
|
let bin = root.path().join("from-manifest");
|
|
touch(&bin);
|
|
let home = root.path().join("home");
|
|
let manifest = installed_manifest(&home, Some(&data));
|
|
write_manifest(&manifest, "effectcraft", &bin);
|
|
let env = data_env(&data);
|
|
let got = super::resolve_with("effectcraft", &env, Some(&home), None, &[]).unwrap();
|
|
assert_eq!(got, bin);
|
|
}
|
|
|
|
#[cfg(target_os = "linux")]
|
|
#[test]
|
|
fn relative_xdg_data_home_uses_home() {
|
|
let root = Tmp::new("rel");
|
|
let home = root.path().join("home");
|
|
let bin = root.path().join("home-bin");
|
|
touch(&bin);
|
|
let manifest = installed_manifest(&home, None);
|
|
write_manifest(&manifest, "effectcraft", &bin);
|
|
let env = env_map(&[("XDG_DATA_HOME", "relative/data")]);
|
|
let got = super::resolve_with("effectcraft", &env, Some(&home), None, &[]).unwrap();
|
|
assert_eq!(got, bin);
|
|
}
|
|
|
|
#[cfg(windows)]
|
|
#[test]
|
|
fn relative_localappdata_is_not_used() {
|
|
let env = env_map(&[("LOCALAPPDATA", "relative/data")]);
|
|
assert!(matches!(super::resolve_with("effectcraft", &env, None, None, &[]), Err(LinkError::NotInstalled { .. })));
|
|
}
|
|
|
|
#[test]
|
|
fn portable_manifest_wins_over_native_data_directory() {
|
|
let root = Tmp::new("port");
|
|
let exe = root.path().join("exe-dir");
|
|
std::fs::create_dir_all(&exe).unwrap();
|
|
std::fs::write(exe.join("portable.txt"), b"1").unwrap();
|
|
let bin = root.path().join("portable-bin");
|
|
touch(&bin);
|
|
write_manifest(&exe.join("ArtCraftLauncherData").join("data").join("installed.json"), "effectcraft", &bin);
|
|
let xdg = root.path().join("xdg");
|
|
let decoy = root.path().join("decoy-bin");
|
|
touch(&decoy);
|
|
let home = root.path().join("home");
|
|
write_manifest(&installed_manifest(&home, Some(&xdg)), "effectcraft", &decoy);
|
|
let env = data_env(&xdg);
|
|
let got = super::resolve_with("effectcraft", &env, Some(&home), Some(&exe), &[]).unwrap();
|
|
assert_eq!(got, bin);
|
|
}
|
|
|
|
#[test]
|
|
fn manifest_directory_is_skipped_for_path() {
|
|
let root = Tmp::new("skip");
|
|
let data = root.path().join("xdg");
|
|
let folder = root.path().join("not-a-file");
|
|
std::fs::create_dir_all(&folder).unwrap();
|
|
let home = root.path().join("home");
|
|
write_manifest(&installed_manifest(&home, Some(&data)), "effectcraft", &folder);
|
|
let bin_dir = root.path().join("bin");
|
|
let bin = bin_dir.join("effectcraft");
|
|
touch(&bin);
|
|
let mut env = data_env(&data);
|
|
env.insert("PATH".into(), bin_dir.to_str().unwrap().into());
|
|
let got = super::resolve_with("effectcraft", &env, Some(&home), None, &[]).unwrap();
|
|
assert_eq!(got, bin);
|
|
}
|
|
|
|
#[test]
|
|
fn path_supplies_the_path() {
|
|
let root = Tmp::new("path");
|
|
let bin_dir = root.path().join("bin");
|
|
let bin = bin_dir.join("effectcraft");
|
|
touch(&bin);
|
|
let env = env_map(&[("PATH", bin_dir.to_str().unwrap())]);
|
|
let got = super::resolve_with("effectcraft", &env, None, None, &[]).unwrap();
|
|
assert_eq!(got, bin);
|
|
}
|
|
|
|
#[test]
|
|
fn linux_location_supplies_the_path() {
|
|
let root = Tmp::new("fs");
|
|
let apps = root.path().join("Applications");
|
|
let image = apps.join("effectcraft-1.0.0.AppImage");
|
|
touch(&image);
|
|
std::fs::write(apps.join("not-effectcraft.AppImage"), b"no").unwrap();
|
|
let later = root.path().join("usr-bin");
|
|
let exact = later.join("effectcraft");
|
|
touch(&exact);
|
|
let env = env_map(&[("PATH", root.path().join("empty").to_str().unwrap())]);
|
|
let got = super::resolve_with("effectcraft", &env, None, None, &[apps.clone(), later]).unwrap();
|
|
assert_eq!(got, image);
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[test]
|
|
fn launch_at_reaches_hello() {
|
|
// The child branch returns at once when CRAFT_LAUNCH_DIR is unset.
|
|
// A normal cargo test takes the parent path and does not park.
|
|
if let Ok(dir) = std::env::var("CRAFT_LAUNCH_DIR") {
|
|
child_launch(&dir);
|
|
}
|
|
parent_launch();
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
fn child_launch(dir: &str) -> ! {
|
|
use std::io::BufReader;
|
|
use std::os::unix::net::UnixListener;
|
|
|
|
let runtime = RuntimeDir::at(dir).unwrap();
|
|
let app = "effectcraft";
|
|
let pid = std::process::id();
|
|
std::fs::write(runtime.path().join("child.pid"), pid.to_string()).unwrap();
|
|
let sock = runtime.socket_file(app, pid);
|
|
let _ = std::fs::remove_file(&sock);
|
|
let listener = UnixListener::bind(&sock).unwrap();
|
|
crate::discovery::enforce_mode(&sock, 0o600).unwrap();
|
|
let endpoint = runtime.unix_endpoint(app, pid).unwrap();
|
|
let record = InstanceRecord::new(app, "0.8.3", pid, endpoint).unwrap();
|
|
let published = Discovery::publish(&runtime, record.clone()).unwrap();
|
|
std::fs::write(runtime.path().join("ready"), pid.to_string()).unwrap();
|
|
let (stream, _) = listener.accept().unwrap();
|
|
stream.set_read_timeout(Some(Duration::from_secs(20))).unwrap();
|
|
stream.set_write_timeout(Some(Duration::from_secs(20))).unwrap();
|
|
let mut reader = BufReader::new(stream);
|
|
let auth = crate::wire::read_line(&mut reader, crate::wire::MAX_LINE).unwrap().unwrap();
|
|
let auth_value: Value = serde_json::from_slice(&auth).unwrap();
|
|
assert_eq!(auth_value["method"], "auth");
|
|
assert_eq!(auth_value["params"]["token"], record.token);
|
|
crate::wire::write_line(reader.get_mut(), &crate::wire::auth_success(&serde_json::json!(0))).unwrap();
|
|
let hello = crate::wire::read_line(&mut reader, crate::wire::MAX_LINE).unwrap().unwrap();
|
|
let hello_value: Value = serde_json::from_slice(&hello).unwrap();
|
|
assert_eq!(hello_value["method"], "link.hello");
|
|
let id = hello_value.get("id").cloned().unwrap_or(serde_json::json!(1));
|
|
let result = serde_json::json!({
|
|
"app": app,
|
|
"app_version": record.app_version,
|
|
"pid": record.pid,
|
|
"instance": record.instance,
|
|
"protocol": 1,
|
|
});
|
|
crate::wire::write_line(reader.get_mut(), &crate::wire::reply_ok(&id, result)).unwrap();
|
|
let _keep = (published, listener, reader);
|
|
// park can wake without an unpark. Loop so Drop does not run until SIGKILL.
|
|
loop {
|
|
std::thread::park();
|
|
}
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
fn parent_launch() {
|
|
let _spawning = crate::SPAWN_GUARD.write().unwrap_or_else(std::sync::PoisonError::into_inner);
|
|
let mut bytes = [0u8; 4];
|
|
getrandom::getrandom(&mut bytes).unwrap();
|
|
let path = std::env::temp_dir().join(format!("cl-launch-{}", crate::auth::encode_hex(&bytes)));
|
|
let _ = std::fs::remove_dir_all(&path);
|
|
let runtime = RuntimeDir::at(&path).unwrap();
|
|
let _cleanup = LaunchCleanup { dir: path.clone() };
|
|
let exe = std::env::current_exe().unwrap();
|
|
let args = vec![OsString::from("--exact"), OsString::from("launch::tests::launch_at_reaches_hello"), OsString::from("--test-threads=1")];
|
|
let dir_text = path.to_str().unwrap();
|
|
let mut phases = Vec::new();
|
|
// The test binary can sit on a file system that marks every file 0777, and `launch_at`
|
|
// refuses such a program. A private launcher script that execs it keeps the pid.
|
|
let script = path.join("launcher");
|
|
std::fs::write(&script, format!("#!/bin/sh\nexec '{}' \"$@\"\n", exe.display())).unwrap();
|
|
chmod(&script, 0o755);
|
|
let result = launch_at("effectcraft", &script, &args, &[("CRAFT_LAUNCH_DIR", dir_text)], Some(&runtime), &mut |phase| phases.push(phase));
|
|
let record = result.unwrap_or_else(|err| panic!("launch_at failed: {err}; phases={phases:?}"));
|
|
assert_eq!(phases, vec![Phase::Spawned, Phase::RecordSeen, Phase::HelloOk]);
|
|
let ready = std::fs::read_to_string(path.join("ready")).unwrap();
|
|
let child_pid: u32 = ready.trim().parse().unwrap();
|
|
assert_eq!(record.pid, child_pid);
|
|
assert_eq!(record.app, "effectcraft");
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
struct LaunchCleanup {
|
|
dir: PathBuf,
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
impl Drop for LaunchCleanup {
|
|
fn drop(&mut self) {
|
|
kill_recorded(&self.dir);
|
|
let _ = std::fs::remove_dir_all(&self.dir);
|
|
}
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
fn kill_recorded(dir: &Path) {
|
|
for name in ["child.pid", "ready"] {
|
|
let Ok(text) = std::fs::read_to_string(dir.join(name)) else { continue };
|
|
let Ok(pid) = text.trim().parse::<u32>() else { continue };
|
|
let _ = Command::new("kill").args(["-KILL", &pid.to_string()]).status();
|
|
let proc = PathBuf::from(format!("/proc/{pid}"));
|
|
let deadline = Instant::now() + Duration::from_secs(2);
|
|
while proc.exists() && Instant::now() < deadline {
|
|
std::thread::sleep(Duration::from_millis(20));
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
}
|