feat: add headless agent management to CLI and both desktop clients

This commit is contained in:
tongtong committed 2026-11-12 21:17:44 +08:00
1 parent e91fa0235c
commit 6916dd54fb
50 files changed
+4837 -148

No files matched your search

+295
View File
@@ -0,0 +1,295 @@
use crate::{read_frame, write_frame, Request, Response};
use anyhow::{bail, Context, Result};
use sha2::{Digest, Sha256};
use std::{
future::Future,
path::{Path, PathBuf},
pin::Pin,
sync::Arc,
time::Duration,
};
use tokio::{
io::{AsyncRead, AsyncWrite},
task::JoinSet,
time::timeout,
};
pub type Handler =
Arc<dyn Fn(Request) -> Pin<Box<dyn Future<Output = Response> + Send>> + Send + Sync>;
fn absolute(path: &Path) -> Result<PathBuf> {
Ok(
std::fs::canonicalize(path.parent().context("missing config parent")?)?
.join(path.file_name().context("missing config filename")?),
)
}
pub fn endpoint(config: &Path) -> Result<String> {
let path = absolute(config)?;
if cfg!(windows) {
let normalized = path.to_string_lossy().to_lowercase();
let hash = Sha256::digest(normalized.as_bytes());
Ok(format!(r"\\.\pipe\ttstd-ads-{:x}", hash))
} else {
let hash = format!(
"{:x}",
Sha256::digest(path.file_name().unwrap().as_encoded_bytes())
);
Ok(path
.parent()
.unwrap()
.join(format!("agent-{}.sock", &hash[..16]))
.to_string_lossy()
.into_owned())
}
}
async fn connection(
mut socket: impl AsyncRead + AsyncWrite + Unpin,
handler: Handler,
) -> Result<()> {
let request = timeout(Duration::from_secs(5), read_frame(&mut socket)).await??;
let response = timeout(Duration::from_secs(12), handler(request)).await?;
timeout(Duration::from_secs(5), write_frame(&mut socket, &response)).await??;
Ok(())
}
pub async fn request(config: &Path, value: &Request) -> Result<Response> {
let name = endpoint(config)?;
timeout(Duration::from_secs(15), async {
#[cfg(windows)]
let connect_deadline = std::time::Instant::now() + Duration::from_secs(3);
#[cfg(windows)]
let mut socket = loop {
match tokio::net::windows::named_pipe::ClientOptions::new().open(&name) {
Ok(socket) => break socket,
Err(error)
if matches!(error.raw_os_error(), Some(2 | 231))
&& std::time::Instant::now() < connect_deadline =>
{
tokio::time::sleep(Duration::from_millis(50)).await
}
Err(error) => return Err(error.into()),
}
};
#[cfg(unix)]
let mut socket = tokio::net::UnixStream::connect(&name)
.await
.context("agent is not running or local socket is inaccessible")?;
write_frame(&mut socket, value).await?;
read_frame(&mut socket).await
})
.await
.context("local agent management timed out")?
}
#[cfg(unix)]
pub async fn serve(
config: &Path,
handler: Handler,
ready: tokio::sync::oneshot::Sender<()>,
) -> Result<()> {
use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt};
let name = endpoint(config)?;
let path = PathBuf::from(&name);
let directory = std::fs::metadata(path.parent().unwrap())?;
if directory.mode() & 0o022 != 0 {
bail!("config directory must not be writable by other users")
}
let owner = directory.uid();
if path.exists() {
if tokio::net::UnixStream::connect(&path).await.is_ok() {
bail!("agent already running")
}
let metadata = std::fs::symlink_metadata(&path)?;
if !metadata.file_type().is_socket() || metadata.uid() != owner {
bail!("refusing to remove a foreign socket path")
}
std::fs::remove_file(&path)?;
}
let listener = tokio::net::UnixListener::bind(&path)?;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
let cpath = std::ffi::CString::new(name)?;
if unsafe { libc::geteuid() } == 0
&& unsafe { libc::chown(cpath.as_ptr(), owner, u32::MAX) } != 0
{
bail!("cannot set local socket owner")
}
struct Cleanup(PathBuf);
impl Drop for Cleanup {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
let _cleanup = Cleanup(path);
let _ = ready.send(());
let mut tasks = JoinSet::new();
loop {
tokio::select! {
accepted=listener.accept()=>{let(socket,_)=accepted?;if tasks.len()>=16{drop(socket);continue;}let handler=handler.clone();tasks.spawn(async move{let _=connection(socket,handler).await;});},
_=tasks.join_next(),if !tasks.is_empty()=>{},
}
}
}
#[cfg(windows)]
pub async fn serve(
config: &Path,
handler: Handler,
ready: tokio::sync::oneshot::Sender<()>,
) -> Result<()> {
use tokio::net::windows::named_pipe::ServerOptions;
let name = endpoint(config)?;
let security = Security::new(config.parent().context("missing config directory")?)?;
let create = |first: bool| -> Result<_> {
let mut attributes = security.attributes();
Ok(unsafe {
ServerOptions::new()
.first_pipe_instance(first)
.reject_remote_clients(true)
.create_with_security_attributes_raw(&name, &mut attributes as *mut _ as *mut _)
}?)
};
let mut server = create(true)
.context("cannot create private management pipe; agent may already be running")?;
let _ = ready.send(());
let mut tasks = JoinSet::new();
loop {
tokio::select! {
connected=server.connect()=>{connected?;let next=create(false)?;let socket=std::mem::replace(&mut server,next);if tasks.len()>=16{drop(socket);continue;}let handler=handler.clone();tasks.spawn(async move{let _=connection(socket,handler).await;});},
_=tasks.join_next(),if !tasks.is_empty()=>{},
}
}
}
#[cfg(windows)]
pub fn owner_sid(path: &Path) -> Result<String> {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::{
Foundation::LocalFree,
Security::{
Authorization::{ConvertSidToStringSidW, GetNamedSecurityInfoW, SE_FILE_OBJECT},
OWNER_SECURITY_INFORMATION,
},
};
let name: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
let mut owner = std::ptr::null_mut();
let mut descriptor = std::ptr::null_mut();
let code = unsafe {
GetNamedSecurityInfoW(
name.as_ptr(),
SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION,
&mut owner,
std::ptr::null_mut(),
std::ptr::null_mut(),
std::ptr::null_mut(),
&mut descriptor,
)
};
if code != 0 {
bail!("cannot read config directory owner: {code}")
}
let mut sid = std::ptr::null_mut();
let result = unsafe { ConvertSidToStringSidW(owner, &mut sid) };
if result == 0 {
unsafe { LocalFree(descriptor) };
bail!("cannot format config owner SID")
}
let mut length = 0;
unsafe {
while *sid.add(length) != 0 {
length += 1;
}
}
let result = String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(sid, length) });
unsafe {
LocalFree(sid as _);
LocalFree(descriptor);
}
Ok(result)
}
#[cfg(windows)]
struct Security(*mut std::ffi::c_void);
#[cfg(windows)]
unsafe impl Send for Security {}
#[cfg(windows)]
impl Security {
fn new(directory: &Path) -> Result<Self> {
use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
let owner = owner_sid(directory)?;
let sddl: Vec<u16> = format!("D:P(A;;GA;;;SY)(A;;GA;;;{owner})")
.encode_utf16()
.chain(Some(0))
.collect();
let mut descriptor = std::ptr::null_mut();
if unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
sddl.as_ptr(),
1,
&mut descriptor,
std::ptr::null_mut(),
)
} == 0
{
bail!("cannot create private pipe ACL")
};
Ok(Self(descriptor))
}
fn attributes(&self) -> windows_sys::Win32::Security::SECURITY_ATTRIBUTES {
windows_sys::Win32::Security::SECURITY_ATTRIBUTES {
nLength: std::mem::size_of::<windows_sys::Win32::Security::SECURITY_ATTRIBUTES>()
as u32,
lpSecurityDescriptor: self.0,
bInheritHandle: 0,
}
}
}
#[cfg(windows)]
impl Drop for Security {
fn drop(&mut self) {
unsafe { windows_sys::Win32::Foundation::LocalFree(self.0) };
}
}
#[cfg(windows)]
pub fn protect_file(path: &Path, parent: &Path) -> Result<()> {
let sid = owner_sid(parent)?;
use std::os::windows::process::CommandExt;
let status = std::process::Command::new("icacls.exe")
.creation_flags(0x08000000)
.arg(path)
.args([
"/inheritance:r",
"/grant:r",
&format!("*{sid}:(F)"),
"*S-1-5-18:(F)",
"/Q",
])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()?;
if !status.success() {
bail!("cannot restrict private file permissions")
};
Ok(())
}
#[cfg(unix)]
pub fn protect_file(path: &Path, parent: &Path) -> Result<()> {
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::MetadataExt;
let metadata = std::fs::metadata(parent)?;
if metadata.mode() & 0o022 != 0 {
bail!("config directory must not be writable by other users")
}
if unsafe { libc::geteuid() } == 0 {
let path = std::ffi::CString::new(path.as_os_str().as_bytes())?;
if unsafe { libc::chown(path.as_ptr(), metadata.uid(), u32::MAX) } != 0 {
bail!("cannot preserve config owner")
}
}
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn config_filenames_have_isolated_management_endpoints() {
let folder = std::env::temp_dir();
assert_ne!(
super::endpoint(&folder.join("first-agent.json")).unwrap(),
super::endpoint(&folder.join("second-agent.json")).unwrap()
);
}
}
+367
View File
@@ -0,0 +1,367 @@
pub mod ipc;
pub mod service;
use ads_core::{valid_device_id, validate_token, NetworkArgs};
use anyhow::{bail, Context, Result};
use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use std::{
collections::HashSet,
path::{Path, PathBuf},
time::{SystemTime, UNIX_EPOCH},
};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio_tungstenite::tungstenite::Message;
pub const MAX_FRAME: usize = 128 * 1024;
pub fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
fn yes() -> bool {
true
}
fn adb_port() -> u16 {
5555
}
fn adb_server() -> String {
"127.0.0.1:5037".into()
}
fn version() -> u32 {
1
}
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug)]
#[serde(deny_unknown_fields)]
pub struct DeviceConfig {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub adb_serial: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub adb_server: Option<String>,
#[serde(default = "adb_port")]
pub device_port: u16,
#[serde(default = "yes")]
pub enabled: bool,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct AgentConfig {
#[serde(default = "version")]
pub version: u32,
pub id: String,
pub name: String,
pub server: String,
#[serde(default)]
pub connect_address: Option<String>,
#[serde(default)]
pub allow_insecure: bool,
#[serde(default = "adb_server")]
pub adb_server: String,
#[serde(default)]
pub devices: Vec<DeviceConfig>,
}
impl AgentConfig {
pub fn network(&self) -> NetworkArgs {
NetworkArgs {
server: self.server.clone(),
connect_address: self.connect_address.clone(),
allow_insecure: self.allow_insecure,
}
}
pub fn validate(&self) -> Result<()> {
if self.version != 1
|| !valid_device_id(&self.id)
|| self.name.is_empty()
|| self.name.len() > 128
|| self.name.chars().any(char::is_control)
{
bail!("invalid agent version, ID or name")
}
if serde_json::to_vec_pretty(self)?.len() > 64 * 1024 {
bail!("agent config exceeds 64 KiB")
}
self.network().url("/v3/agents/register", &[])?;
validate_address(&self.adb_server)?;
if let Some(address) = &self.connect_address {
validate_address(address)?;
}
if self.devices.len() > 128 {
bail!("at most 128 devices per agent")
}
let mut ids = HashSet::new();
for device in &self.devices {
if !valid_device_id(&device.id) || !ids.insert(&device.id) || device.device_port == 0 {
bail!("invalid or duplicate device ID/port")
}
if device.target.is_some() == device.adb_serial.is_some() {
bail!("each device requires exactly one of target or adb_serial")
}
if let Some(target) = &device.target {
validate_address(target)?;
}
if let Some(server) = &device.adb_server {
validate_address(server)?;
}
if let Some(serial) = &device.adb_serial {
if serial.is_empty() || serial.len() > 256 || serial.chars().any(char::is_control) {
bail!("invalid adb_serial")
}
}
}
Ok(())
}
pub fn load(path: &Path) -> Result<Self> {
let data = std::fs::read(path).context("cannot read agent config")?;
if data.len() > 64 * 1024 {
bail!("agent config exceeds 64 KiB")
};
let config: Self = serde_json::from_slice(&data).context("invalid agent config JSON")?;
config.validate()?;
Ok(config)
}
}
fn validate_address(value: &str) -> Result<()> {
if value.is_empty()
|| value.len() > 256
|| value.chars().any(|c| c.is_whitespace() || c.is_control())
{
bail!("invalid host:port address")
}
let (host, port) = value
.rsplit_once(':')
.context("address requires host:port")?;
if host.is_empty() || port.parse::<u16>().unwrap_or(0) == 0 {
bail!("invalid host:port address")
};
Ok(())
}
#[derive(Clone, Serialize, Deserialize, Debug)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
pub enum Request {
Status,
DevicesList,
DeviceAdd {
device: DeviceConfig,
},
DeviceRemove {
id: String,
},
DeviceEnable {
id: String,
enabled: bool,
},
ConfigGet,
ConfigSet {
config: AgentConfig,
},
Logs {
#[serde(default)]
after: u64,
#[serde(default)]
limit: u32,
},
Restart,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Response {
pub ok: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub data: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
impl Response {
pub fn success(value: impl Serialize) -> Self {
Self {
ok: true,
data: Some(serde_json::to_value(value).unwrap_or_default()),
error: None,
}
}
pub fn failure(error: impl ToString) -> Self {
Self {
ok: false,
data: None,
error: Some(error.to_string()),
}
}
pub fn value(self) -> Result<serde_json::Value> {
if !self.ok {
bail!(
"{}",
self.error
.unwrap_or_else(|| "management request failed".into())
)
};
Ok(self.data.unwrap_or_default())
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct DeviceStatus {
#[serde(flatten)]
pub config: DeviceConfig,
pub connected: bool,
pub last_error: Option<String>,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct AgentStatus {
pub id: String,
pub name: String,
pub hostname: String,
pub os: String,
pub arch: String,
pub version: String,
pub pid: u32,
pub uptime_seconds: u64,
pub supervised: bool,
pub revision: u64,
pub instance: String,
pub devices: Vec<DeviceStatus>,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct LogEntry {
pub seq: u64,
pub time: u64,
pub level: String,
pub message: String,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct LogPage {
pub instance: String,
pub next: u64,
pub entries: Vec<LogEntry>,
}
pub fn default_config() -> PathBuf {
if cfg!(windows) {
PathBuf::from(std::env::var_os("LOCALAPPDATA").unwrap_or_else(|| ".".into()))
.join("AndroidDeviceStreaming/agent/agent.json")
} else {
PathBuf::from(
std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| {
PathBuf::from(std::env::var_os("HOME").unwrap_or_else(|| ".".into()))
.join(".config")
}),
)
.join("ads/agent.json")
}
}
pub fn credential(path: &Path, key: &str) -> Result<String> {
if let Ok(value) = std::env::var(key) {
validate_token(&value)?;
return Ok(value);
}
let data = std::fs::read_to_string(path).context(
"credential file not found; set the role token in env or provide its private env file",
)?;
for line in data.lines() {
if let Some(value) = line.strip_prefix(&format!("{key}=")) {
validate_token(value)?;
return Ok(value.into());
}
}
bail!("missing {key}")
}
pub fn save_private(path: &Path, data: &[u8]) -> Result<()> {
let parent = path
.parent()
.context("configuration requires a parent directory")?;
std::fs::create_dir_all(parent)?;
let temporary = parent.join(format!(
".ads-{}-{}.tmp",
std::process::id(),
SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos()
));
use std::io::Write;
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let result = (|| -> Result<()> {
let mut file = options.open(&temporary)?;
ipc::protect_file(&temporary, parent)?;
file.write_all(data)?;
file.sync_all()?;
drop(file);
std::fs::rename(&temporary, path)?;
Ok(())
})();
if result.is_err() {
let _ = std::fs::remove_file(&temporary);
}
result
}
pub async fn read_frame<T: for<'de> Deserialize<'de>>(
stream: &mut (impl AsyncRead + Unpin),
) -> Result<T> {
let size = stream.read_u32_le().await? as usize;
if size == 0 || size > MAX_FRAME {
bail!("invalid management frame length")
};
let mut data = vec![0; size];
stream.read_exact(&mut data).await?;
Ok(serde_json::from_slice(&data)?)
}
pub async fn write_frame(
stream: &mut (impl AsyncWrite + Unpin),
value: &impl Serialize,
) -> Result<()> {
let data = serde_json::to_vec(value)?;
if data.len() > MAX_FRAME {
bail!("management response too large")
};
stream.write_u32_le(data.len() as u32).await?;
stream.write_all(&data).await?;
stream.flush().await?;
Ok(())
}
pub async fn read_ws<T: for<'de> Deserialize<'de>>(ws: &mut ads_core::Ws) -> Result<T> {
loop {
match ws.next().await.context("management connection closed")?? {
Message::Text(data) => return Ok(serde_json::from_str(&data)?),
Message::Ping(data) => ws.send(Message::Pong(data)).await?,
Message::Pong(_) => {}
_ => bail!("management connection closed or invalid message"),
}
}
}
pub async fn write_ws(ws: &mut ads_core::Ws, value: &impl Serialize) -> Result<()> {
let data = serde_json::to_string(value)?;
if data.len() > MAX_FRAME {
bail!("management response too large")
};
ws.send(Message::Text(data.into())).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepted_config_fits_the_restart_loader_limit() {
let mut cfg: AgentConfig = serde_json::from_value(serde_json::json!({
"id":"host", "name":"Host", "server":"wss://example.com/ads", "devices":[]
}))
.unwrap();
cfg.validate().unwrap();
let host = format!("{}:5555", "a".repeat(240));
for index in 0..128 {
cfg.devices.push(DeviceConfig {
id: format!("phone-{index}"),
target: Some(host.clone()),
adb_serial: None,
adb_server: Some(host.clone()),
device_port: 5555,
enabled: true,
});
}
assert!(serde_json::to_vec_pretty(&cfg).unwrap().len() > 64 * 1024);
assert!(cfg.validate().unwrap_err().to_string().contains("64 KiB"));
}
}
+170
View File
@@ -0,0 +1,170 @@
#[cfg(unix)]
use crate::save_private;
use crate::AgentConfig;
use anyhow::{bail, Context, Result};
use std::path::Path;
#[cfg(unix)]
use std::path::PathBuf;
#[derive(Clone, Copy)]
pub enum Action {
Install,
Start,
Stop,
Restart,
Status,
Uninstall,
}
fn safe_path(path: &Path) -> Result<String> {
let text = path.to_str().context("service paths must be valid UTF-8")?;
#[cfg(windows)]
let text = text.strip_prefix(r"\\?\").unwrap_or(text);
if text.chars().any(char::is_control) {
bail!("service path contains control characters")
};
Ok(text.into())
}
#[cfg(windows)]
fn ps(value: &str) -> String {
format!("'{}'", value.replace(char::from(39), "''"))
}
#[cfg(windows)]
pub fn run(action: Action, config: &Path, _system: bool, start_now: bool) -> Result<()> {
let cfg = AgentConfig::load(config)?;
let config = std::fs::canonicalize(config)?;
let executable = std::env::current_exe()?.with_file_name("ads-agent.exe");
let executable =
std::fs::canonicalize(executable).context("place ads-agent.exe next to adsctl.exe")?;
let name = format!("ADS-Agent-{}", cfg.id);
let executable = safe_path(&executable)?;
let path = safe_path(&config)?;
let arguments = format!("--quiet --supervise --config \"{path}\"");
let guard=format!("$task=Get-ScheduledTask -TaskName {} -ErrorAction SilentlyContinue; if($task -and -not (@($task.Actions | Where-Object {{ $_.Execute -eq {} -and $_.Arguments -eq {} }}).Count)) {{ throw 'A foreign task owns this name' }};",ps(&name),ps(&executable),ps(&arguments));
let body=match action{
Action::Install=>format!("$action=New-ScheduledTaskAction -Execute {} -Argument {}; $trigger=New-ScheduledTaskTrigger -AtStartup; $settings=New-ScheduledTaskSettingsSet -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero) -StartWhenAvailable -MultipleInstances IgnoreNew; Register-ScheduledTask -TaskName {} -Action $action -Trigger $trigger -Settings $settings -User SYSTEM -RunLevel Highest -Force | Out-Null; {}",ps(&executable),ps(&arguments),ps(&name),if start_now {format!("Start-ScheduledTask -TaskName {};",ps(&name))} else {String::new()}),
Action::Start=>format!("Start-ScheduledTask -TaskName {};",ps(&name)),
Action::Stop=>format!("Stop-ScheduledTask -TaskName {};",ps(&name)),
Action::Restart=>format!("Stop-ScheduledTask -TaskName {}; Start-Sleep -Seconds 1; Start-ScheduledTask -TaskName {};",ps(&name),ps(&name)),
Action::Status=>format!("Get-ScheduledTask -TaskName {} | Select-Object TaskName,State; Get-ScheduledTaskInfo -TaskName {};",ps(&name),ps(&name)),
Action::Uninstall=>format!("Stop-ScheduledTask -TaskName {} -ErrorAction SilentlyContinue; Unregister-ScheduledTask -TaskName {} -Confirm:$false;",ps(&name),ps(&name)),
};
use std::os::windows::process::CommandExt;
let output = std::process::Command::new("powershell.exe")
.creation_flags(0x08000000)
.args([
"-NoProfile",
"-NonInteractive",
"-Command",
&format!("$ErrorActionPreference='Stop';{guard}{body}"),
])
.output()?;
eprint!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
if !output.status.success() {
bail!("Windows service operation failed; install/uninstall require an elevated administrator terminal")
};
Ok(())
}
#[cfg(unix)]
pub fn run(action: Action, config: &Path, system: bool, start_now: bool) -> Result<()> {
if !cfg!(target_os = "linux") {
bail!("native service install currently supports Linux systemd and Windows Task Scheduler; run ads-agent --supervise manually on this platform")
}
let cfg = AgentConfig::load(config)?;
let config = std::fs::canonicalize(config)?;
let executable = std::fs::canonicalize(std::env::current_exe()?.with_file_name("ads-agent"))
.context("place ads-agent next to adsctl")?;
let unit = format!("ads-agent-{}.service", cfg.id);
let folder = if system {
PathBuf::from("/etc/systemd/system")
} else {
PathBuf::from(std::env::var_os("HOME").context("HOME is missing")?)
.join(".config/systemd/user")
};
let path = folder.join(&unit);
let marker = format!(
"# Managed by ADSCTL {}\n# Config: {}\n# Executable: {}\n",
cfg.id,
safe_path(&config)?,
safe_path(&executable)?
);
let systemctl = |args: &[&str]| -> Result<()> {
let mut command = std::process::Command::new("systemctl");
if !system {
command.arg("--user");
}
let output = command.args(args).output()?;
eprint!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
if !output.status.success() {
bail!("systemctl failed; check service privileges and availability")
};
Ok(())
};
let guard = || -> Result<()> {
if path.exists() && !std::fs::read_to_string(&path)?.starts_with(&marker) {
bail!("a foreign systemd unit owns this name")
};
Ok(())
};
guard()?;
match action {
Action::Install => {
let mut user = String::new();
if system {
use std::os::unix::fs::MetadataExt;
let owner = std::fs::metadata(config.parent().unwrap())?.uid();
let output = std::process::Command::new("id")
.args(["-un", &owner.to_string()])
.output()?;
if !output.status.success() {
bail!("cannot resolve service config owner")
};
let name = String::from_utf8(output.stdout)?.trim().to_string();
if name.is_empty()
|| !name
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"_-.".contains(&c))
{
bail!("unsupported service account name")
};
user = format!("User={name}\n");
}
fn quote(path: &Path) -> Result<String> {
Ok(format!(
"\"{}\"",
safe_path(path)?
.replace('%', "%%")
.replace('\\', "\\\\")
.replace('\"', "\\\"")
))
}
let body=format!("{marker}[Unit]\nDescription=ADS managed agent {}\nAfter=network-online.target\nWants=network-online.target\n[Service]\nType=simple\n{user}ExecStart={} --quiet --supervise --config {}\nRestart=on-failure\nRestartSec=3\nNoNewPrivileges=true\nPrivateTmp=true\n[Install]\nWantedBy={}\n",cfg.id,quote(&executable)?,quote(&config)?,if system{"multi-user.target"}else{"default.target"});
save_private(&path, body.as_bytes())?;
systemctl(&["daemon-reload"])?;
if start_now {
systemctl(&["enable", "--now", &unit])?;
} else {
systemctl(&["enable", &unit])?;
}
}
Action::Start => systemctl(&["start", &unit])?,
Action::Stop => systemctl(&["stop", &unit])?,
Action::Restart => systemctl(&["restart", &unit])?,
Action::Status => systemctl(&["status", "--no-pager", &unit])?,
Action::Uninstall => {
guard()?;
systemctl(&["disable", "--now", &unit])?;
if path.exists() {
std::fs::remove_file(path)?;
}
systemctl(&["daemon-reload"])?;
}
}
Ok(())
}