use std::{
collections::HashMap,
path::PathBuf,
sync::{
atomic::{AtomicU64, Ordering},
Mutex, MutexGuard,
},
};
#[cfg(any(windows, target_os = "linux"))]
use std::path::Path;
use semver::Version;
use crate::{
control::ControlHandler,
operator_apps::{AppOpenPlatform, OperatorAppPolicy},
router::{RouteCtx, RouterError},
Frame,
};
pub(crate) struct LaunchEntry {
incarnation: u64,
pid: u32,
start_time: Option<u64>,
process: subc_os::Process,
child: Option<std::process::Child>,
}
impl LaunchEntry {
fn is_live(&self) -> bool {
self.process
.observe()
.is_some_and(|observed| Some(observed.start_time) == self.start_time)
}
fn reap(self) {
if let Some(mut child) = self.child {
let _ = child.try_wait();
}
#[cfg(target_os = "linux")]
{
let _ = rustix::process::waitpid(
rustix::process::Pid::from_raw(self.pid as i32),
rustix::process::WaitOptions::NOHANG,
);
}
}
#[cfg(windows)]
fn stop_rejected(mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
while matches!(child.try_wait(), Ok(None)) {
std::thread::yield_now();
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct LiveLaunch {
pub incarnation: u64,
pub pid: u32,
}
pub(crate) struct LaunchTable {
inner: Mutex<HashMap<String, LaunchEntry>>,
next_incarnation: AtomicU64,
}
#[allow(dead_code)]
impl LaunchTable {
pub fn new() -> Self {
Self {
inner: Mutex::new(HashMap::new()),
next_incarnation: AtomicU64::new(1),
}
}
fn lock(&self) -> MutexGuard<'_, HashMap<String, LaunchEntry>> {
self.inner
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn retire_locked(inner: &mut HashMap<String, LaunchEntry>, app: &str) {
if let Some(entry) = inner.remove(app) {
entry.reap();
}
}
pub fn live_entry(&self, app: &str) -> Option<LiveLaunch> {
let mut inner = self.lock();
let entry = inner.get(app)?;
if !entry.is_live() {
Self::retire_locked(&mut inner, app);
return None;
}
Some(LiveLaunch {
incarnation: entry.incarnation,
pid: entry.pid,
})
}
pub fn match_live_pid(&self, app: &str, pid: u32) -> Option<u64> {
let live = self.live_entry(app)?;
(live.pid == pid).then_some(live.incarnation)
}
pub fn is_live_incarnation(&self, app: &str, incarnation: u64) -> bool {
self.live_entry(app)
.is_some_and(|live| live.incarnation == incarnation)
}
pub fn publish(
&self,
app: &str,
pid: u32,
process: subc_os::Process,
child: Option<std::process::Child>,
) -> u64 {
let incarnation = self.next_incarnation.fetch_add(1, Ordering::Relaxed);
let start_time = process.observe().map(|observed| observed.start_time);
let mut inner = self.lock();
Self::retire_locked(&mut inner, app);
inner.insert(
app.to_owned(),
LaunchEntry {
incarnation,
pid,
start_time,
process,
child,
},
);
incarnation
}
pub fn retire(&self, app: &str) {
Self::retire_locked(&mut self.lock(), app);
}
#[cfg(windows)]
pub fn take(&self, app: &str) -> Option<LaunchEntry> {
self.lock().remove(app)
}
}
#[derive(Debug)]
pub(crate) struct AppOpenRefusal {
pub code: &'static str,
pub message: String,
}
impl AppOpenRefusal {
fn not_used(message: impl Into<String>) -> Self {
Self {
code: subc_control::APP_OPEN_NOT_USED,
message: message.into(),
}
}
fn disabled(message: impl Into<String>) -> Self {
Self {
code: subc_control::APP_OPEN_DISABLED,
message: message.into(),
}
}
fn unknown(message: impl Into<String>) -> Self {
Self {
code: subc_control::APP_UNKNOWN,
message: message.into(),
}
}
pub fn not_installed(message: impl Into<String>) -> Self {
Self {
code: subc_control::APP_NOT_INSTALLED,
message: message.into(),
}
}
#[cfg(windows)]
pub fn verification_failed(message: impl Into<String>) -> Self {
Self {
code: subc_control::APP_VERIFICATION_FAILED,
message: message.into(),
}
}
}
pub(crate) enum AppOpenDecision {
Refuse(AppOpenRefusal),
AlreadyRunning { pid: u32 },
Launch { path: PathBuf },
}
pub(crate) fn decide_app_open(
policy: &OperatorAppPolicy,
table: &LaunchTable,
platform: AppOpenPlatform,
app: &str,
) -> AppOpenDecision {
if matches!(platform, AppOpenPlatform::MacOS | AppOpenPlatform::Other) {
return AppOpenDecision::Refuse(AppOpenRefusal::not_used(
"this platform never launches apps through the daemon",
));
}
if !policy.switch_enabled(platform) {
return AppOpenDecision::Refuse(AppOpenRefusal::disabled(
"app.open is switched off on this platform",
));
}
if policy.app_id().is_none_or(|id| id != app) {
return AppOpenDecision::Refuse(AppOpenRefusal::unknown(format!(
"no compiled app named {app:?} on this platform"
)));
}
if let Some(live) = table.live_entry(app) {
return AppOpenDecision::AlreadyRunning { pid: live.pid };
}
let Some(path) = policy.installed_path(platform) else {
return AppOpenDecision::Refuse(AppOpenRefusal::not_installed(format!(
"no install location is compiled in for {app:?}"
)));
};
if !path.exists() {
return AppOpenDecision::Refuse(AppOpenRefusal::not_installed(format!(
"{} is not installed at {}",
app,
path.display()
)));
}
AppOpenDecision::Launch { path }
}
impl ControlHandler {
pub(crate) async fn handle_app_open(
&self,
_ctx: &RouteCtx,
frame: Frame,
) -> Result<Vec<Frame>, RouterError> {
let _launch_guard = self.app_open_launch_lock.lock().await;
let request = match serde_json::from_slice::<subc_control::AppOpenRequest>(&frame.body) {
Ok(request) => request,
Err(_) => {
return Ok(vec![crate::control::control_error_frame(
&frame,
"invalid_control_body",
"malformed app.open body",
)?]);
}
};
let app = request.app.clone();
match decide_app_open(
&self.operator_app_policy,
&self.launch_table,
AppOpenPlatform::current(),
&app,
) {
AppOpenDecision::Refuse(refusal) => Ok(vec![crate::control::control_error_frame(
&frame,
refusal.code,
refusal.message,
)?]),
AppOpenDecision::AlreadyRunning { pid } => {
#[cfg(windows)]
self.flash_running_app(pid);
Ok(vec![crate::control::control_response_body_frame(
&frame,
&subc_control::AppOpenReply::already_running(pid),
"app.open",
)?])
}
AppOpenDecision::Launch { path } => {
#[cfg(windows)]
let outcome = self.windows_launch_app(&app, &path).await;
#[cfg(target_os = "linux")]
let outcome = self.linux_launch_app(&app, &path).await;
#[cfg(not(any(windows, target_os = "linux")))]
let outcome: Result<u32, AppOpenRefusal> = {
let _ = path;
Err(AppOpenRefusal::not_used(
"this platform has no app launcher",
))
};
match outcome {
Ok(pid) => Ok(vec![crate::control::control_response_body_frame(
&frame,
&subc_control::AppOpenReply::launched(pid),
"app.open",
)?]),
Err(refusal) => Ok(vec![crate::control::control_error_frame(
&frame,
refusal.code,
refusal.message,
)?]),
}
}
}
}
}
#[cfg(target_os = "linux")]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum LinuxLaunchStyle {
Scope,
Direct,
}
#[cfg(target_os = "linux")]
pub(crate) fn select_linux_launch_style(
systemd_run_present: bool,
user_bus_present: bool,
) -> LinuxLaunchStyle {
if systemd_run_present && user_bus_present {
LinuxLaunchStyle::Scope
} else {
LinuxLaunchStyle::Direct
}
}
#[cfg(target_os = "linux")]
fn user_bus_present() -> bool {
use std::os::unix::fs::FileTypeExt as _;
let uid = rustix::process::getuid().as_raw();
[
std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from),
Some(PathBuf::from(format!("/run/user/{uid}"))),
]
.into_iter()
.flatten()
.any(|dir| {
std::fs::symlink_metadata(dir.join("bus"))
.is_ok_and(|metadata| metadata.file_type().is_socket())
})
}
#[cfg(target_os = "linux")]
fn find_on_path(name: &str) -> bool {
use std::os::unix::fs::PermissionsExt as _;
let Some(path) = std::env::var_os("PATH") else {
return false;
};
std::env::split_paths(&path).any(|dir| {
let candidate = dir.join(name);
candidate.is_file()
&& candidate
.metadata()
.is_ok_and(|metadata| metadata.permissions().mode() & 0o111 != 0)
})
}
#[cfg(target_os = "linux")]
pub(crate) fn systemd_run_command(path: &Path) -> tokio::process::Command {
let mut command = tokio::process::Command::new("systemd-run");
command.args([
"--user",
"--scope",
"--",
"/bin/sh",
"-c",
"echo $$; exec \"$0\" \"$@\"",
&path.display().to_string(),
]);
command
}
#[cfg(target_os = "linux")]
fn scrub_app_environment(command: &mut std::process::Command) {
for key in ["LD_PRELOAD", "LD_LIBRARY_PATH", "LD_AUDIT"] {
command.env_remove(key);
}
}
#[cfg(target_os = "linux")]
impl ControlHandler {
async fn linux_launch_app(&self, app: &str, path: &Path) -> Result<u32, AppOpenRefusal> {
let style = if self.operator_app_policy.linux_force_direct {
LinuxLaunchStyle::Direct
} else {
select_linux_launch_style(find_on_path("systemd-run"), user_bus_present())
};
match style {
LinuxLaunchStyle::Direct => self.linux_launch_direct(app, path, &[]),
LinuxLaunchStyle::Scope => self.linux_launch_scoped(app, path).await,
}
}
fn linux_launch_direct(
&self,
app: &str,
path: &Path,
extra_env: &[(&str, &str)],
) -> Result<u32, AppOpenRefusal> {
use std::os::unix::process::CommandExt as _;
let mut command = std::process::Command::new(path);
for (key, value) in extra_env {
command.env(key, value);
}
command.process_group(0);
scrub_app_environment(&mut command);
command
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
let mut child = command.spawn().map_err(|error| {
AppOpenRefusal::not_installed(format!(
"installed file {} could not be started: {error}",
path.display()
))
})?;
let pid = child.id();
let process = subc_os::Process::open(pid).map_err(|error| {
AppOpenRefusal::not_installed(format!(
"launched process {pid} cannot be tracked: {error}"
))
})?;
let Some(process) = process else {
let _ = child.kill();
while matches!(child.try_wait(), Ok(None)) {
std::thread::yield_now();
}
return Err(AppOpenRefusal::not_installed(format!(
"installed file {} exited before it could be tracked",
path.display()
)));
};
self.launch_table.publish(app, pid, process, Some(child));
Ok(pid)
}
async fn linux_launch_scoped(&self, app: &str, path: &Path) -> Result<u32, AppOpenRefusal> {
use tokio::io::AsyncBufReadExt as _;
let mut command = systemd_run_command(path);
scrub_app_environment_std(&mut command);
command
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.kill_on_drop(true);
let mut child = command.spawn().map_err(|error| {
AppOpenRefusal::not_installed(format!("transient scope could not start: {error}"))
})?;
let stdout = child.stdout.take().ok_or_else(|| {
AppOpenRefusal::not_installed("transient scope reported no pid".to_string())
})?;
let mut lines = tokio::io::BufReader::new(stdout).lines();
let pid_line = tokio::time::timeout(std::time::Duration::from_secs(10), lines.next_line())
.await
.map_err(|_| {
AppOpenRefusal::not_installed(
"transient scope did not report its pid in time".to_string(),
)
})?
.map_err(|error| {
AppOpenRefusal::not_installed(format!(
"transient scope pid could not be read: {error}"
))
})?
.ok_or_else(|| {
AppOpenRefusal::not_installed(
"transient scope exited without reporting its pid".to_string(),
)
})?;
let pid: u32 = pid_line.trim().parse().map_err(|_| {
AppOpenRefusal::not_installed(format!(
"transient scope reported an unparsable pid: {pid_line:?}"
))
})?;
let status = tokio::time::timeout(std::time::Duration::from_secs(10), child.wait())
.await
.map_err(|_| {
AppOpenRefusal::not_installed(
"transient scope starter did not exit in time".to_string(),
)
})?
.map_err(|error| {
AppOpenRefusal::not_installed(format!(
"transient scope starter could not be reaped: {error}"
))
})?;
if !status.success() {
return Err(AppOpenRefusal::not_installed(format!(
"transient scope starter exited with {status}"
)));
}
let process = subc_os::Process::open(pid).map_err(|error| {
AppOpenRefusal::not_installed(format!(
"scoped process {pid} cannot be tracked: {error}"
))
})?;
let Some(process) = process else {
return Err(AppOpenRefusal::not_installed(format!(
"scoped process {pid} exited before it could be tracked"
)));
};
self.launch_table.publish(app, pid, process, None);
Ok(pid)
}
}
#[cfg(target_os = "linux")]
fn scrub_app_environment_std(command: &mut tokio::process::Command) {
for key in ["LD_PRELOAD", "LD_LIBRARY_PATH", "LD_AUDIT"] {
command.env_remove(key);
}
}
#[allow(dead_code)]
#[derive(Clone, Debug)]
pub struct WindowsVerifyRequest {
pub app: String,
pub publisher: Option<String>,
pub floor: Version,
pub path: PathBuf,
}
#[allow(dead_code)]
#[cfg(windows)]
pub type WindowsVerifyFn = std::sync::Arc<
dyn Fn(&subc_os::ExecutableCapture, &WindowsVerifyRequest) -> Result<String, String>
+ Send
+ Sync,
>;
#[allow(dead_code)]
#[cfg(windows)]
pub type WindowsTrackFn =
std::sync::Arc<dyn Fn(u32) -> std::io::Result<Option<subc_os::Process>> + Send + Sync>;
#[allow(dead_code)]
#[cfg(windows)]
pub type WindowsFlashFn = std::sync::Arc<dyn Fn(u32) + Send + Sync>;
#[cfg(windows)]
const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000;
#[cfg(windows)]
pub(crate) fn windows_creation_flags(breakaway: bool) -> u32 {
let mut flags = subc_jobobject::CONTAINMENT_CREATION_FLAGS;
if breakaway {
flags |= CREATE_BREAKAWAY_FROM_JOB;
}
flags
}
#[cfg(windows)]
impl ControlHandler {
fn flash_running_app(&self, pid: u32) {
#[cfg(windows)]
if let Some(flash) = self.windows_flash.as_ref() {
flash(pid);
return;
}
tracing::debug!(
pid,
"app already running; no window-flash primitive in this build"
);
}
fn verify_windows_image(
&self,
capture: &subc_os::ExecutableCapture,
request: WindowsVerifyRequest,
) -> Result<String, AppOpenRefusal> {
#[cfg(windows)]
if let Some(verify) = self.windows_verify.as_ref() {
let version = verify(capture, &request).map_err(AppOpenRefusal::verification_failed)?;
if !crate::operator_apps::meets_release_floor(Some(&version), &request.floor) {
return Err(AppOpenRefusal::verification_failed(format!(
"verified version {version} is below the release floor"
)));
}
return Ok(version);
}
Err(AppOpenRefusal::verification_failed(format!(
"this build carries no Authenticode verifier for {}",
request.app
)))
}
fn track_launched_process(&self, pid: u32) -> std::io::Result<Option<subc_os::Process>> {
#[cfg(windows)]
if let Some(track) = self.windows_track.as_ref() {
return track(pid);
}
subc_os::Process::open(pid)
}
async fn windows_launch_app(&self, app: &str, path: &Path) -> Result<u32, AppOpenRefusal> {
use std::os::windows::process::CommandExt as _;
let capture = subc_os::ExecutableCapture::open(path).map_err(|error| {
AppOpenRefusal::not_installed(format!(
"installed file {} cannot be opened: {error}",
path.display()
))
})?;
let request = WindowsVerifyRequest {
app: app.to_owned(),
publisher: self
.operator_app_policy
.windows_publisher()
.map(str::to_owned),
floor: self.operator_app_policy.release_floor().clone(),
path: path.to_path_buf(),
};
let _verified_version = self.verify_windows_image(&capture, request)?;
let mut command = std::process::Command::new(capture.path());
command
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
command.creation_flags(windows_creation_flags(
self.operator_app_policy.windows_breakaway,
));
#[cfg(test)]
self.windows_spawn_attempts.fetch_add(1, Ordering::Relaxed);
let mut child = command.spawn().map_err(|error| {
AppOpenRefusal::verification_failed(format!(
"installed file {} could not be started: {error}",
path.display()
))
})?;
let pid = child.id();
let image = match capture.bind(&child) {
Ok(image) => image,
Err(error) => {
stop_rejected_child(&mut child);
return Err(AppOpenRefusal::verification_failed(format!(
"launched process {pid} could not be bound to its image: {error}"
)));
}
};
if !matches!(
image.agreement(image.start_time()),
subc_os::ImageAgreement::Match(_)
) {
stop_rejected_child(&mut child);
return Err(AppOpenRefusal::verification_failed(format!(
"launched process {pid} does not match its verified image"
)));
}
let process = match self.track_launched_process(pid) {
Ok(Some(process)) => process,
Ok(None) => {
stop_rejected_child(&mut child);
return Err(AppOpenRefusal::verification_failed(format!(
"launched process {pid} exited before it could be tracked"
)));
}
Err(error) => {
stop_rejected_child(&mut child);
return Err(AppOpenRefusal::verification_failed(format!(
"launched process {pid} cannot be tracked: {error}"
)));
}
};
self.launch_table.publish(app, pid, process, Some(child));
if let Err(error) = subc_jobobject::resume_main_thread(pid) {
if let Some(entry) = self.launch_table.take(app) {
entry.stop_rejected();
}
return Err(AppOpenRefusal::verification_failed(format!(
"launched process {pid} could not be resumed and was stopped: {error}"
)));
}
Ok(pid)
}
pub(crate) fn stamp_windows_launch(
&self,
peer: &subc_os::local_peer::CapturedPeer,
) -> Option<crate::operator_apps::OperatorAppStamp> {
use subc_os::local_peer::ObservedPeer as OsPeer;
if !self.operator_app_policy.windows_enabled {
return None;
}
let app = self.operator_app_policy.app_id()?;
let OsPeer::Observed(observation) = peer.observation() else {
return None;
};
let incarnation = self.launch_table.match_live_pid(app, observation.pid)?;
Some(crate::operator_apps::OperatorAppStamp::launch_stamp(
subc_protocol::peer::OperatorApp::new(app, observation.pid),
peer.clone(),
incarnation,
))
}
}
#[cfg(windows)]
fn stop_rejected_child(child: &mut std::process::Child) {
let _ = child.kill();
while matches!(child.try_wait(), Ok(None)) {
std::thread::yield_now();
}
}
#[cfg(test)]
mod tests;