Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,14 @@ What changed in each release, one line per change. Versions follow [Semantic Ver
- The H.264 copy of the phone's own video counts a crashed ffmpeg as a failure and moves on to the next encoder, instead of restarting it for ever (#201).
- `task run --url` stops within 10 seconds of Ctrl-C even if the viewer doesn't answer, and gives up an event stream that goes silent or sends an endless event (#201).
- Only one daemon runs per socket, even when two start at once, and the socket is private from the moment it is created; a lock that can't be taken at all is reported as such instead of as another daemon (#201).
- The control page and the login page only run their own scripts (a Content-Security-Policy with their hashes) and send no referrer; a client that stops reading no longer holds a connection for good (#202).
- With HTTPS on, the viewer takes actions only from a page served the way it serves it (HTTPS, or plain HTTP from this machine) (#202).
- A viewer stopped while it made its certificate makes a new one on the next start, instead of failing to load a key that doesn't match (#202).
- A token removed with `viewer token remove` is refused at once also within the same second, and `viewer token` commands run at the same time no longer lose each other's changes (#202).
- A setting written twice in `~/.config/iphone-control/env` takes its last value, as the services read it (#202).
- Services install from a program path with spaces, and refuse one with characters systemd or the shell would read as their own; an update that paused the viewer's service starts it again without turning on its start at login; setting up the automatic update job and failing leaves none of its files behind, even when the service manager can't be reached (#202).
- An AI task from the control page works when `IPHONE_CONTROL_URL` is set in the settings file (#202).
- A read-only login no longer sends touches from the picture (each answered with an error) and shows no pointer on it (#202).
- When pressing Home finds a system alert in the way, the daemon's answer now also marks it in its structured result (`alert_reported`), as launching an app or opening a link does; programs reading the result rather than its text missed it (#200).
- A long press falls back to HID like a tap when WebDriverAgent can't be reached (#200).
- Requests that can't run (a tap count of 0, an empty tap sequence, an unknown button, a point that isn't a number) are refused at once, before waiting for the phone and without dropping the cached screen (#200).
Expand Down
8 changes: 8 additions & 0 deletions CHANGELOG.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,14 @@
- 手机原生视频转成 H.264 时,ffmpeg 崩溃算作失败,换下一个编码器,不再无休止地重启(#201)。
- `task run --url` 在控制台不应答时,按 Ctrl-C 后 10 秒内也能停下;事件流长时间没动静或发来没有结尾的事件时会放弃(#201)。
- 一个 socket 只会有一个守护进程在跑,两个同时启动也一样;socket 从创建那一刻起就只有自己能访问;根本拿不到锁时如实报错,不再说成已有守护进程(#201)。
- 控制台和登录页只运行它们自己的脚本(带脚本哈希的 Content-Security-Policy),也不再发送 Referer;客户端不读数据时不会一直占着连接(#202)。
- 开着 HTTPS 时,控制台只接受以它实际提供的方式打开的页面发来的操作(HTTPS,或本机的明文 HTTP)(#202)。
- 控制台在生成证书的中途被停掉,下次启动会重新生成,不再因为私钥和证书对不上而起不来(#202)。
- 用 `viewer token remove` 删掉的令牌,即使在同一秒内也会立刻失效;同时运行的几个 `viewer token` 命令不会再互相覆盖改动(#202)。
- `~/.config/iphone-control/env` 里同一个设置写了两次时,以最后一次为准,和后台服务的读法一致(#202)。
- 程序路径里有空格也能装服务;带有 systemd 或 shell 会特殊处理的字符时拒绝安装;升级时暂停过的控制台服务恢复时,不再把它的开机自启打开;配置自动更新任务失败时,连不上服务管理器也不会留下它的文件(#202)。
- 设置文件里写了 `IPHONE_CONTROL_URL` 时,控制台上的 AI 任务也能正常工作(#202)。
- 只读登录时,在画面上按下不再把触摸发给手机(之前每次都会弹一个错误),也不显示指针(#202)。
- 按 Home 时发现有系统弹窗挡着,守护进程的应答现在也会在结构化结果里标出(`alert_reported`),和启动 App、打开链接一样;之前只读结果字段、不看文字的程序会漏掉(#200)。
- 长按和点击一样,连不上 WebDriverAgent 时改用 HID(#200)。
- 执行不了的请求(点击次数为 0、空的点击序列、不认识的按键、坐标不是有效数字)立刻拒绝,不再先排队等手机,也不会清掉缓存的界面(#200)。
Expand Down
51 changes: 50 additions & 1 deletion apps/iphone-control/src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,16 +191,47 @@ fn sub_dir(private: &Path, name: &str) -> std::io::Result<PathBuf> {
Ok(dir)
}

/// Token files left by an earlier viewer (killed before it could remove them): its agents were stopped with it, and
/// one of them could share a name with a new file once a process number comes round again. The directory is this
/// user's, shared by every viewer they run (another port, a test): a file is only removed when the process named in it
/// (`task-<pid>-<n>.token`) is this one (nothing of its own is made yet) or gone
fn clear_stale_tokens(dir: &Path) {
let own = std::process::id();
for e in std::fs::read_dir(dir).into_iter().flatten().flatten() {
let name = e.file_name();
let Some(pid) = name
.to_str()
.and_then(|n| n.strip_prefix("task-")?.strip_suffix(".token")?.split_once('-'))
.and_then(|(pid, _)| pid.parse::<u32>().ok())
else {
continue;
};
if e.file_type().is_ok_and(|t| t.is_file()) && (pid == own || gone(pid)) {
let _ = std::fs::remove_file(e.path());
}
}
}

/// No process has this number (one of another user's still counts as there)
fn gone(pid: u32) -> bool {
let Ok(pid) = libc::pid_t::try_from(pid) else { return false };
pid > 0
&& unsafe { libc::kill(pid, 0) } == -1
&& std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH)
}

impl Agents {
pub fn new(socket: &Path) -> anyhow::Result<Arc<Self>> {
let base = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).filter(|p| p.is_absolute());
let private = private_dir(&base.unwrap_or_else(std::env::temp_dir))?;
// the agent works in `work`; the tasks' tokens are kept beside it, not in what it works on
let tokens = sub_dir(&private, "tokens")?;
clear_stale_tokens(&tokens);
Ok(Arc::new(Self {
exe: std::env::current_exe()?,
socket: socket.to_path_buf(),
workdir: sub_dir(&private, "work")?,
tokens: sub_dir(&private, "tokens")?,
tokens,
running: Default::default(),
}))
}
Expand Down Expand Up @@ -642,6 +673,24 @@ mod tests {
}
}

/// What an earlier viewer left (its process is gone, or its number is this process's now) is cleared when the next
/// one starts; what another viewer still running uses is not
#[test]
fn only_tokens_of_viewers_that_are_gone_are_cleared() {
let dir = tempfile::tempdir().unwrap();
let mut dead = std::process::Command::new("true").spawn().unwrap();
let dead_pid = dead.id();
dead.wait().unwrap();
let name = |pid: u32| format!("task-{pid}-0.token");
let files = [name(std::process::id()), name(dead_pid), name(1), "notes.token".into(), "task-x-0.token".into()];
for f in &files {
std::fs::write(dir.path().join(f), "t").unwrap();
}
clear_stale_tokens(dir.path());
let left: Vec<bool> = files.iter().map(|f| dir.path().join(f).exists()).collect();
assert_eq!(left, [false, false, true, true, true], "this process's and a gone one's go; a live one's stays");
}

#[test]
fn the_agent_works_in_a_directory_of_its_own() {
use std::os::unix::fs::{MetadataExt, PermissionsExt};
Expand Down
20 changes: 13 additions & 7 deletions apps/iphone-control/src/completions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,27 @@ pub enum Shell {
/// 根选项的值可以恰好是 `completions`,所以不能只搜索这个单词。
pub fn requested(args: impl IntoIterator<Item = OsString>) -> bool {
let mut args = args.into_iter();
match command(&mut args) {
Some(arg) if arg == "help" => args.next().is_some_and(|arg| arg == "completions"),
Some(arg) => arg == "completions",
None => false,
}
}

/// The first argument after the root options (`--data-dir`, `--socket` and their values), which names the command;
/// `args` is left at the command's own arguments. None when there is none
pub fn command(args: &mut impl Iterator<Item = OsString>) -> Option<OsString> {
while let Some(arg) = args.next() {
if arg == "--data-dir" || arg == "--socket" {
if args.next().is_none() {
return false;
}
args.next()?;
} else if arg.as_encoded_bytes().starts_with(b"--data-dir=") || arg.as_encoded_bytes().starts_with(b"--socket=")
{
continue;
} else if arg == "help" {
return args.next().is_some_and(|arg| arg == "completions");
} else {
return arg == "completions";
return Some(arg);
}
}
false
None
}

pub fn write(shell: Shell, output: &mut dyn Write) -> anyhow::Result<()> {
Expand Down
48 changes: 37 additions & 11 deletions apps/iphone-control/src/envfile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,21 @@ impl EnvFile {
if let Some(dir) = self.path.parent() {
std::fs::create_dir_all(dir)?;
}
let tmp = self.path.with_extension("tmp");
let mut f = std::fs::OpenOptions::new().create(true).write(true).truncate(true).mode(0o600).open(&tmp)?;
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
f.write_all(self.text.as_bytes())?;
f.sync_all()?;
std::fs::rename(&tmp, &self.path)?;
Ok(())
// a name of its own: two commands saving at once must not write into the same temporary file
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let tmp = self.path.with_extension(format!("{}.{n}.tmp", std::process::id()));
let written = (|| {
let mut f = std::fs::OpenOptions::new().create_new(true).write(true).mode(0o600).open(&tmp)?;
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
f.write_all(self.text.as_bytes())?;
f.sync_all()?;
std::fs::rename(&tmp, &self.path)
})();
if written.is_err() {
let _ = std::fs::remove_file(&tmp);
}
Ok(written?)
}
}

Expand Down Expand Up @@ -138,22 +146,40 @@ fn quote(v: &str) -> anyhow::Result<String> {
}

/// Puts the file's settings into this process's environment, without overriding what is already set (a variable on
/// the command line wins). Called once at start-up, before any thread is started
pub fn load_into_process() {
/// the command line wins), except the keys in `skip`. A key set twice takes its last value, as the shell and systemd
/// read the file. Called once at start-up, before any thread is started
pub fn load_into_process(skip: &[&str]) {
let Ok(text) = std::fs::read_to_string(path()) else { return };
for (k, v) in parse(&text) {
if v.is_empty() || std::env::var_os(&k).is_some() {
for (k, v) in last_values(parse(&text)) {
if v.is_empty() || skip.contains(&k.as_str()) || std::env::var_os(&k).is_some() {
continue;
}
// SAFETY: single-threaded: main() calls this before building the async runtime
unsafe { std::env::set_var(&k, &v) };
}
}

/// Each key once, with its last value (an empty last one too: it unsets the key, as in the shell)
fn last_values(pairs: Vec<(String, String)>) -> Vec<(String, String)> {
let mut out: Vec<(String, String)> = Vec::new();
for (k, v) in pairs {
out.retain(|(o, _)| *o != k);
out.push((k, v));
}
out
}

#[cfg(test)]
mod tests {
use super::*;

/// A key set twice takes its last value, as the shell and systemd read the file; a last empty one unsets it
#[test]
fn the_last_value_of_a_key_wins() {
let v = last_values(parse("A=1\nB=x\nA=2\nexport B=\nC='3'\n"));
assert_eq!(v, vec![("A".into(), "2".into()), ("B".into(), String::new()), ("C".into(), "3".into())]);
}

#[test]
fn set_replaces_in_place_and_keeps_comments() {
let dir = std::env::temp_dir().join(format!("ictl-env-{}", std::process::id()));
Expand Down
52 changes: 50 additions & 2 deletions apps/iphone-control/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,11 +272,39 @@ fn main() -> anyhow::Result<()> {
return completions::write(shell, &mut std::io::stdout().lock());
}
}
// 设置文件先读进环境(命令行上已设的优先),要在启动任何线程之前:语言、代理、通知等对所有命令都生效
envfile::load_into_process();
// 设置文件先读进环境(命令行上已设的优先),要在启动任何线程之前:语言、代理、通知等对所有命令都生效。
// 控制台给它的 agent 起的 MCP 服务(`mcp --task-token-file`)只连本机:设置文件里给自己的命令连别处用的地址不读,
// 读了会和这个参数冲突、服务起不来
let local_only = mcp_with_token_file(std::env::args_os().skip(1));
let skip: &[&str] =
if local_only { &[ictl_daemon::protocol::env::URL, ictl_daemon::protocol::env::CA] } else { &[] };
envfile::load_into_process(skip);
tokio::runtime::Runtime::new()?.block_on(run())
}

/// `mcp --task-token-file FILE` (or `=FILE`): read off the raw arguments, before clap (which caches the language,
/// known only once the settings are loaded). Not taken for an argument of another command that happens to read the
/// same (a prompt of `task run`), and arguments that aren't UTF-8 are read too
fn mcp_with_token_file(args: impl IntoIterator<Item = std::ffi::OsString>) -> bool {
let mut args = args.into_iter();
if completions::command(&mut args).is_none_or(|c| c != "mcp") {
return false;
}
while let Some(arg) = args.next() {
if arg == "--task-token-file" || arg.as_encoded_bytes().starts_with(b"--task-token-file=") {
return true;
}
if arg == "--" {
return false;
}
// an option's value isn't an option (`--ca --task-token-file` is a certificate of that name)
if arg == "--url" || arg == "--ca" {
args.next();
}
}
false
}

/// Commands that ask once, print the result and end; see [`restore_sigpipe`]
fn prints_and_exits(command: Option<&Command>) -> bool {
matches!(
Expand Down Expand Up @@ -1609,4 +1637,24 @@ mod tests {
assert!(!host_is_loopback(b"GET / HTTP/1.1\r\nHost: localhost.evil.example\r\n\r\n"));
assert!(!host_is_loopback(b"GET / HTTP/1.1\r\n\r\n"));
}

/// Only `mcp`'s own option, in either form, after any root options; not a prompt that reads the same, and an
/// argument that isn't UTF-8 doesn't stop it
#[test]
fn the_token_file_option_is_found_only_for_mcp() {
use super::mcp_with_token_file;
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
let found = |args: &[&str]| mcp_with_token_file(args.iter().map(OsString::from));
assert!(found(&["mcp", "--task-token-file", "/t"]));
assert!(found(&["mcp", "--task-token-file=/t"]));
assert!(found(&["--socket", "/s.sock", "--data-dir=/d", "mcp", "--task-token-file", "/t"]));
assert!(!found(&["mcp"]));
assert!(!found(&["task", "run", "--", "echo", "--task-token-file"]), "another command's argument");
assert!(!found(&["--socket", "mcp", "status", "--task-token-file"]), "a root option's value isn't the command");
assert!(!found(&["mcp", "--ca", "--task-token-file"]), "an option's value");
let odd =
vec![OsString::from("mcp"), OsString::from_vec(vec![0xff, 0xfe]), OsString::from("--task-token-file=/t")];
assert!(mcp_with_token_file(odd));
}
}
Loading
Loading