From e503041dac097136d1c31764254c2f88405046c9 Mon Sep 17 00:00:00 2001 From: "Its.spixy" <38753219+spixyy7@users.noreply.github.com> Date: Thu, 29 Oct 2026 04:40:52 +0800 Subject: [PATCH] =?UTF-8?q?=E7=99=BB=E5=BD=95=EF=BC=9A=E8=B7=A8=E8=BF=9B?= =?UTF-8?q?=E7=A8=8B=E4=B8=B2=E8=A1=8C=E5=8C=96=E8=AE=BE=E5=A4=87=E6=B3=A8?= =?UTF-8?q?=E5=86=8C=20(#127)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 主机扫码窗口与控制端登录可能各自调用 device/windows/init,导致账号绑定一台设备而 config.json 保存另一台(主机显示离线的幽灵设备)。现在在 config.json 旁的排他文件锁下注册设备,取锁后重读配置,第二个流程复用已注册设备。 感谢 @spixyy7 的贡献。 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- src/login.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/login.rs b/src/login.rs index 7de6d72..43f43aa 100644 --- a/src/login.rs +++ b/src/login.rs @@ -272,7 +272,26 @@ pub fn prepare_identity() -> Result<(Value, Credentials), String> { Ok((cfg, creds)) } +/// Holds an exclusive lock beside config.json while a device identity is created: the host's own QR +/// window and the viewer's sign-in can run at once, and two `device/windows/init` calls would leave the +/// account bound to one device while config.json keeps the other (the host then shows as offline). +struct IdentityLock(std::fs::File); +impl IdentityLock { + fn acquire() -> Result { + use std::os::unix::io::AsRawFd; + let path = crate::config::path().with_extension("lock"); + if let Some(dir) = path.parent() { let _ = std::fs::create_dir_all(dir); } + let file = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(&path).map_err(|_| "Cannot open the identity lock")?; + if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } != 0 { return Err("Cannot lock the device identity".into()) } + Ok(Self(file)) + } +} +impl Drop for IdentityLock { fn drop(&mut self) { use std::os::unix::io::AsRawFd; unsafe { libc::flock(self.0.as_raw_fd(), libc::LOCK_UN); } } } + pub async fn prepare_device() -> Result<(Value, Credentials), String> { + // Read the configuration only after taking the lock, so a waiting process sees the device the + // first one registered instead of creating its own. + let _lock = tokio::task::spawn_blocking(IdentityLock::acquire).await.map_err(|_| "Identity lock task failed")??; let (mut cfg, mut creds) = prepare_identity()?; let get = |cfg: &Value, k: &str| std::env::var(format!("UU_{}", k.to_uppercase())).ok().filter(|v| !v.is_empty()) .or_else(|| cfg.get(k).and_then(|v| v.as_str()).map(str::to_owned)).unwrap_or_default();