Skip to content
Open
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
46 changes: 36 additions & 10 deletions client/src-tauri/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use airhand_link::LinkConfig;
use airhand_link::net::{MemoryTrust, Trust, TrustStore, format_fingerprint, parse_fingerprint};
use airhand_link::secure::Identity;
use airhand_proto::signal::Reclaim;
use anyhow::{Result, bail};
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use tokio::sync::watch;
use toml_edit::{DocumentMut, Item};
Expand Down Expand Up @@ -900,9 +900,14 @@ fn edit(f: impl FnOnce(&mut DocumentMut) -> Result<()>) -> Result<()> {
}

fn edit_at(path: &Path, f: impl FnOnce(&mut DocumentMut) -> Result<()>) -> Result<()> {
edit_if_writable(path, f).map(|_| ())
}

/// 检查配置写入是否已暂停,并返回是否真的写入了。
fn edit_if_writable(path: &Path, f: impl FnOnce(&mut DocumentMut) -> Result<()>) -> Result<bool> {
let mut last = last();
if FROZEN.load(std::sync::atomic::Ordering::Acquire) {
return Ok(());
return Ok(false);
}
let mut doc = match std::fs::read_to_string(path) {
// 用户写坏了的文件不覆盖:这次就不保存了
Expand All @@ -916,7 +921,7 @@ fn edit_at(path: &Path, f: impl FnOnce(&mut DocumentMut) -> Result<()>) -> Resul
let text = doc.to_string();
write(path, &text)?;
*last = Some(text);
Ok(())
Ok(true)
}

/// 先写临时文件再改名:写到一半断电也不会把配置文件弄坏。目录不存在时创建(macOS / Linux 第一次运行、
Expand Down Expand Up @@ -1367,10 +1372,15 @@ fn autostart_note() -> String {

/// 保存控制台的"我的设备":整个列表换成 `list`([`crate::devices::for_file`] 整理过的,`code` 已经加密)
pub fn save_devices(list: &[crate::devices::Device]) -> Result<()> {
edit(|doc| {
put_devices(doc, list);
Ok(())
})
let path = path().context("the configuration file path is unavailable")?;
anyhow::ensure!(
edit_if_writable(&path, |doc| {
put_devices(doc, list);
Ok(())
})?,
"configuration writes are paused"
);
Ok(())
}

fn put_devices(doc: &mut DocumentMut, list: &[crate::devices::Device]) {
Expand Down Expand Up @@ -2026,6 +2036,7 @@ mod tests {
quality: None,
mouse: None,
swap_ctrl_command: false,
auto_privacy: false,
host_key: None,
}
}
Expand Down Expand Up @@ -2315,7 +2326,7 @@ mod tests {
save_code(Some(code)).unwrap();
let mut d = device("482913");
save_devices(&crate::devices::for_file(vec![d.clone()]).unwrap()).unwrap();
assert_eq!(crate::devices::load(), vec![d.clone()]);
assert_eq!(crate::devices::load().unwrap(), vec![d.clone()]);
assert_eq!(parse(&read_text().unwrap()).unwrap().code(), Some(code));
// Windows:文件里没有明文的控制码
#[cfg(windows)]
Expand All @@ -2329,7 +2340,7 @@ mod tests {
let text = read_text().unwrap();
assert!(text.starts_with("# Airhand"));
assert_eq!(parse(&text).unwrap().code(), Some(code));
assert_eq!(crate::devices::load(), vec![d.clone()]);
assert_eq!(crate::devices::load().unwrap(), vec![d.clone()]);

// 手动给设备起了个名字,然后整个目录被删掉
let edited = text.replace(
Expand All @@ -2344,7 +2355,7 @@ mod tests {
});
std::fs::remove_dir_all(&dir).unwrap();
wait_for("the directory to be recreated", &|| file.exists());
assert_eq!(crate::devices::load(), vec![d]);
assert_eq!(crate::devices::load().unwrap(), vec![d]);
assert_eq!(parse(&read_text().unwrap()).unwrap().code(), Some(code));
#[cfg(unix)]
{
Expand All @@ -2357,6 +2368,21 @@ mod tests {
std::fs::remove_dir_all(&root).unwrap();
}

#[test]
fn devices_distinguish_empty_config_from_read_failure() {
let root = tempfile::tempdir().unwrap();
let file = root.path().join(FILE_NAME);
TEST_PATH.with(|p| *p.borrow_mut() = Some(file.clone()));
assert!(crate::devices::load().is_err());
std::fs::write(&file, "").unwrap();
assert!(crate::devices::load().unwrap().is_empty());

std::fs::write(&file, "[[").unwrap();
assert!(crate::devices::load().is_err());
assert!(save_devices(&[]).is_err());
assert_eq!(std::fs::read_to_string(file).unwrap(), "[[");
}

/// 服务器地址:host:port,端口 1~65535,IPv6 写在方括号里(和控制台的 validServer、Android 的设置一样)
#[test]
fn server_address_rules() {
Expand Down
39 changes: 25 additions & 14 deletions client/src-tauri/src/devices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
//!
//! `mouse` 是上次用的鼠标模式(控制台的"桌面" / "游戏",没有就是"自动")。
//! `swap_ctrl_command = true`:操作这台 Mac 时互换 Ctrl 和 Command;默认关闭。
//! `auto_privacy = true`:连接这台设备时请求防窥模式;默认关闭。
//!
//! `host_key` 是那台电脑的端到端加密公钥(第一次连上时记下,见 `airhand_link::controller` 的"端到端加密"):
//! 之后只认它,对不上就警告。是公钥,不用加密。
Expand All @@ -28,12 +29,11 @@

use airhand_proto::session::{Codec, QualitySettings};
use airhand_proto::signal::ResumeToken;
use anyhow::Result;
use anyhow::{Context, Result};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use serde::{Deserialize, Serialize};
use toml_edit::{Datetime, InlineTable, Item, Table, Value};
use tracing::warn;

/// 每个账户最多保存多少台(控制台也按这个数截断)
pub const MAX: usize = 50;
Expand Down Expand Up @@ -74,6 +74,8 @@ pub struct Device {
pub mouse: Option<String>,
#[serde(default)]
pub swap_ctrl_command: bool,
#[serde(default)]
pub auto_privacy: bool,
}

/// 认识的鼠标模式(自动是默认,不记)
Expand Down Expand Up @@ -119,17 +121,19 @@ fn host_key(s: &str) -> Option<String> {

// ───────────────────────────── 读 ─────────────────────────────

/// 配置文件里本账户的设备(文件不存在、没有设备时为空)
pub fn load() -> Vec<Device> {
let Some(text) = crate::config::read_text() else {
return Vec::new();
};
let Ok(doc) = text.parse::<toml_edit::DocumentMut>() else {
warn!("config.toml isn't valid TOML, can't read the saved devices");
return Vec::new();
};
/// 配置文件里本账户的设备。启动代码会先创建配置文件;读不到时由控制台提示重试。
pub fn load() -> Result<Vec<Device>> {
let doc = read_device_document()?;
let list = entries(&doc).into_iter().filter_map(open).collect();
normalize(list)
Ok(normalize(list))
}

fn read_device_document() -> Result<toml_edit::DocumentMut> {
let path = crate::config::path().context("the configuration file path is unavailable")?;
let text =
std::fs::read_to_string(&path).with_context(|| format!("can't read {}", path.display()))?;
text.parse()
.with_context(|| format!("{} isn't valid TOML", path.display()))
}

/// 文件里的所有项(`code` 还没解密)
Expand Down Expand Up @@ -177,6 +181,7 @@ fn from_table(t: &Table) -> Option<Device> {
.and_then(mouse_mode)
.map(Into::into),
swap_ctrl_command: t.get("swap_ctrl_command").and_then(Item::as_bool) == Some(true),
auto_privacy: t.get("auto_privacy").and_then(Item::as_bool) == Some(true),
host_key: t.get("host_key").and_then(Item::as_str).and_then(host_key),
})
}
Expand Down Expand Up @@ -222,9 +227,8 @@ pub fn for_file(mine: Vec<Device>) -> Result<Vec<Device>> {
}
// 别的账户保存的(本账户解不开)原样保留;本账户的以控制台发来的为准(删掉的就不要了)
#[cfg(windows)]
if let Some(doc) =
crate::config::read_text().and_then(|t| t.parse::<toml_edit::DocumentMut>().ok())
{
let doc = read_device_document()?;
out.extend(
entries(&doc)
.into_iter()
Expand Down Expand Up @@ -273,6 +277,9 @@ pub fn to_table(d: &Device) -> Option<Table> {
if d.swap_ctrl_command {
t["swap_ctrl_command"] = toml_edit::value(true);
}
if d.auto_privacy {
t["auto_privacy"] = toml_edit::value(true);
}
if let Some(r) = &d.resume {
t["resume"] = toml_edit::value(STANDARD.encode(r));
}
Expand Down Expand Up @@ -368,6 +375,7 @@ mod tests {
}),
mouse: Some("game".into()),
swap_ctrl_command: true,
auto_privacy: true,
host_key: Some("ab".repeat(32)),
}
}
Expand Down Expand Up @@ -402,14 +410,17 @@ mod tests {
quality: None,
mouse: None,
swap_ctrl_command: false,
auto_privacy: false,
last_used: 0,
host_key: None,
..d.clone()
};
let bare_table = to_table(&bare).unwrap();
assert!(!bare_table.contains_key("swap_ctrl_command"));
assert!(!bare_table.contains_key("auto_privacy"));
assert_eq!(from_table(&bare_table), Some(bare));
assert!(t.to_string().contains("mouse = \"game\""));
assert!(t.to_string().contains("auto_privacy = true"));
// 自动(默认)和不认识的鼠标模式不写进文件,读回来是自动
for m in ["auto", "warp"] {
let other = Device {
Expand Down
28 changes: 19 additions & 9 deletions client/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -620,10 +620,11 @@ fn app_info() -> AppInfo {

/// 我的设备(配置文件里本账户的)
#[tauri::command]
async fn devices_load() -> Vec<devices::Device> {
async fn devices_load() -> Result<Vec<devices::Device>, Problem> {
tauri::async_runtime::spawn_blocking(devices::load)
.await
.unwrap_or_default()
.map_err(Problem::failed)?
.map_err(|e| Problem::failed(format!("{e:#}")))
}

/// 保存我的设备(控制台传来整个列表)
Expand All @@ -640,15 +641,24 @@ async fn devices_save(
// Windows 安装版:配置文件在安装目录里,由服务里的被控端维护(托盘没有写权限),经命名管道交给它写
#[cfg(windows)]
if state.service_mode {
let connected = state.hub.borrow().service.is_some_and(|s| s.connected);
let sv = state.services.lock().unwrap();
return match &sv.host {
Some(Hosting::Service(link)) if connected => {
link.send(winsvc::ipc::ToAgent::SaveDevices { devices: list });
Ok(())
let saved = {
let connected = state.hub.borrow().service.is_some_and(|s| s.connected);
let sv = state.services.lock().unwrap();
match &sv.host {
Some(Hosting::Service(link)) if connected => {
link.save_devices(list).map_err(Problem::failed)?
}
_ => {
return Err(Problem::failed(
"the Airhand service isn't reachable from this session",
));
}
}
};
return match tokio::time::timeout(Duration::from_secs(5), saved).await {
Ok(Ok(result)) => result.map_err(Problem::failed),
_ => Err(Problem::failed(
"the Airhand service isn't reachable from this session",
"the Airhand service didn't confirm the device settings were saved",
)),
};
}
Expand Down
Loading