mirror of
https://github.com/VallierDev/uu-remote-linux.git
synced 2026-11-17 01:00:41 +01:00
Remote assistance (experimental) and unified host window
Like the official client: share a device ID + verification code; the other person connects from 开始协助. Guest identity before sign-in, account identity after (same share ID). One GTK window: 本设备 (allow switch, ID/code with copy, verification modes incl. custom code, rotation schedule, copy & share) and 账号 (QR before sign-in, masked account + sign out after). Logged-in hosts keep the window hidden; `uuremote-server show` / the desktop launcher opens it. App icon and .desktop entry in contrib/desktop. Protocol from the official Windows lite host; guest flow, wrong-code rejection, rotation, switching off, sign-in/sign-out verified with the official Mac viewer. Signed-in assistance from another account is not yet verified. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
03f611811c
commit
94039c092a
15 files changed
+1606
-399
No files matched your search
+530
@@ -0,0 +1,530 @@
|
||||
//! Opt-in guest assistance. Protocol sources: docs/validation/remote-assist-evidence.md.
|
||||
//! Secret values never implement Display/Debug or enter diagnostics.
|
||||
use crate::auth::{Credentials, RoomData, UUAuthClient};
|
||||
use serde_json::{json, Value};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::io::{Read, Write};
|
||||
use std::os::unix::{fs::OpenOptionsExt, io::AsRawFd};
|
||||
|
||||
const CREATE: &str = "/api/v1/guest/create";
|
||||
const INFO: &str = "/api/v1/guest/share/info";
|
||||
const CANCEL: &str = "/api/v1/guest/share/cancel";
|
||||
const ROOM: &str = "/api/v1/guest/room/create";
|
||||
const SIGN: &str = "/api/v1/guest/room/share/upload/sign";
|
||||
const CONTROL_MODE: &str = "/api/v1/guest/room/share/upload_control_mode";
|
||||
// Logged-in host: the same flow on the account identity (official Windows host NrdDevice/NrdBusinessEntry).
|
||||
const ACCOUNT_INFO: &str = "/api/v1/device/share/info";
|
||||
const ACCOUNT_CANCEL: &str = "/api/v1/device/share/cancel";
|
||||
const ACCOUNT_SIGN: &str = "/api/v2/room/share/upload_sign";
|
||||
const ACCOUNT_CONTROL_MODE: &str = "/api/v2/room/share/upload_control_mode";
|
||||
const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||
|
||||
/// Guest mode uses its own device/config identity and never consumes an account token.
|
||||
pub fn configure() -> Result<(), String> {
|
||||
if ["UU_USER_ID", "UU_TOKEN", "UU_CSRF"].iter().any(|k| std::env::var_os(k).is_some_and(|v| !v.is_empty())) {
|
||||
return Err("assist mode cannot use account credential environment variables".into());
|
||||
}
|
||||
if std::env::var_os("UU_CONFIG").is_none() {
|
||||
if crate::config::read_fresh()?.as_ref().is_some_and(|v| ["token", "user_id"].iter()
|
||||
.any(|k| v.get(k).and_then(Value::as_str).is_some_and(|s| !s.is_empty()))) {
|
||||
return Err("account identity already configured; guest assist needs an explicit separate UU_CONFIG".into());
|
||||
}
|
||||
let path = crate::config::path().with_file_name("assist").join("config.json");
|
||||
std::env::set_var("UU_CONFIG", path);
|
||||
}
|
||||
if crate::config::read_fresh()?.as_ref().is_some_and(|v| ["token", "user_id", "csrf"].iter()
|
||||
.any(|k| v.get(k).and_then(Value::as_str).is_some_and(|s| !s.is_empty()))) {
|
||||
return Err("assist requires a separate config without account credentials".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Official RecipientConfigModel.verificationType: temporary only, custom only, or both.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum Verify { Temporary = 0, Custom = 1, Both = 2 }
|
||||
impl Verify {
|
||||
fn parse(v: &str) -> Option<Self> { match v { "temporary" => Some(Self::Temporary), "custom" => Some(Self::Custom), "both" => Some(Self::Both), _ => None } }
|
||||
fn name(self) -> &'static str { match self { Self::Temporary => "temporary", Self::Custom => "custom", Self::Both => "both" } }
|
||||
fn from_index(i: i64) -> Option<Self> { match i { 0 => Some(Self::Temporary), 1 => Some(Self::Custom), 2 => Some(Self::Both), _ => None } }
|
||||
}
|
||||
/// Official RecipientCodeRefreshType: after each session (closeConnect), hourly, 12 h, 24 h, never.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum Refresh { Session = 0, Hour = 1, Hour12 = 2, Hour24 = 3, Never = 4 }
|
||||
impl Refresh {
|
||||
fn parse(v: &str) -> Option<Self> { match v { "session" => Some(Self::Session), "1h" => Some(Self::Hour), "12h" => Some(Self::Hour12), "24h" => Some(Self::Hour24), "never" => Some(Self::Never), _ => None } }
|
||||
fn name(self) -> &'static str { match self { Self::Session => "session", Self::Hour => "1h", Self::Hour12 => "12h", Self::Hour24 => "24h", Self::Never => "never" } }
|
||||
fn from_index(i: i64) -> Option<Self> { [Self::Session, Self::Hour, Self::Hour12, Self::Hour24, Self::Never].get(usize::try_from(i).ok()?).copied() }
|
||||
fn period(self) -> Option<std::time::Duration> {
|
||||
match self { Self::Hour => Some(3600), Self::Hour12 => Some(12 * 3600), Self::Hour24 => Some(24 * 3600), _ => None }.map(std::time::Duration::from_secs)
|
||||
}
|
||||
}
|
||||
/// Mainland mobile numbers are shown like the official client: 186******08.
|
||||
pub fn display_account(name: &str) -> String {
|
||||
if name.len() == 11 && name.bytes().all(|b| b.is_ascii_digit()) { format!("{}******{}", &name[..3], &name[9..]) } else { name.to_owned() }
|
||||
}
|
||||
/// 8-16 ASCII letters/digits including both (official RecipientCustomCodeView rules).
|
||||
fn valid_custom(code: &str) -> bool {
|
||||
(8..=16).contains(&code.len()) && code.bytes().all(|b| b.is_ascii_alphanumeric())
|
||||
&& code.bytes().any(|b| b.is_ascii_alphabetic()) && code.bytes().any(|b| b.is_ascii_digit())
|
||||
}
|
||||
|
||||
pub enum Command { Allow, Deny, Reset, Stop, Verify(Verify), Refresh(Refresh), Custom(String), Logout }
|
||||
|
||||
#[cfg(uu_gtk)]
|
||||
extern "C" {
|
||||
fn uu_assist_ui_start(hidden: libc::c_int, hide_on_close: libc::c_int) -> libc::c_int;
|
||||
fn uu_assist_ui_present();
|
||||
fn uu_ui_set_user(name: *const libc::c_char);
|
||||
fn uu_assist_ui_set(id: *const libc::c_char, code: *const libc::c_char, allowed: libc::c_int, verify: libc::c_int, refresh: libc::c_int, has_custom: libc::c_int);
|
||||
fn uu_assist_ui_take_command(arg: *mut libc::c_char, len: libc::size_t) -> libc::c_int;
|
||||
fn uu_assist_ui_close();
|
||||
}
|
||||
|
||||
/// "243829726" -> "243 829 726", as the official client shows device IDs.
|
||||
fn display_id(id: &str) -> String {
|
||||
if id.is_empty() || !id.bytes().all(|b| b.is_ascii_digit()) { return id.to_owned(); }
|
||||
id.as_bytes().chunks(3).map(|c| String::from_utf8_lossy(c).into_owned()).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// Where the ID/code are shown and commands come from: a local GTK window (c_engine/assist_window.c)
|
||||
/// when a display is available, otherwise /dev/tty, which bypasses stdout/stderr, journals,
|
||||
/// redirected output and the logger. Without either, refuse startup rather than disclose the code.
|
||||
pub enum LocalUi { Tty(tokio::io::unix::AsyncFd<std::fs::File>), #[cfg(uu_gtk)] Window }
|
||||
impl LocalUi {
|
||||
/// Standalone `assist`: visible window (closing it stops assistance), else /dev/tty.
|
||||
pub fn open() -> Result<Self, String> { Self::open_visible(false) }
|
||||
/// `hide_on_close`: the not-logged-in host service (window stays reachable with `uuremote-server show`).
|
||||
pub fn open_visible(hide_on_close: bool) -> Result<Self, String> {
|
||||
#[cfg(not(uu_gtk))] let _ = hide_on_close;
|
||||
#[cfg(uu_gtk)]
|
||||
if std::env::var("UU_ASSIST_UI").ok().as_deref() != Some("tty") && Self::display() && unsafe { uu_assist_ui_start(0, i32::from(hide_on_close)) } == 0 {
|
||||
return Ok(Self::Window);
|
||||
}
|
||||
let tty = std::fs::OpenOptions::new().read(true).write(true)
|
||||
.custom_flags(libc::O_NONBLOCK | libc::O_NOCTTY).open("/dev/tty")
|
||||
.map_err(|_| "assist requires a desktop window or a local controlling terminal; no code was printed")?;
|
||||
if unsafe { libc::isatty(tty.as_raw_fd()) } != 1 { return Err("assist output is not a terminal".into()); }
|
||||
Ok(Self::Tty(tokio::io::unix::AsyncFd::new(tty).map_err(|_| "assist terminal registration failed")?))
|
||||
}
|
||||
fn display() -> bool { std::env::var_os("DISPLAY").is_some() || std::env::var_os("WAYLAND_DISPLAY").is_some() }
|
||||
/// Host service: a hidden window opened on demand (`uuremote-server show`); closing only hides it.
|
||||
/// No terminal fallback: a background service has nowhere safe to print the code.
|
||||
pub fn open_service() -> Result<Self, String> {
|
||||
#[cfg(uu_gtk)]
|
||||
if Self::display() && unsafe { uu_assist_ui_start(1, 1) } == 0 { return Ok(Self::Window); }
|
||||
Err("remote assistance needs a desktop window for the host service".into())
|
||||
}
|
||||
/// Account card: signed-in user (name already masked for display).
|
||||
pub fn set_user(&self, name: &str) {
|
||||
#[cfg(uu_gtk)]
|
||||
if matches!(self, Self::Window) { let name = std::ffi::CString::new(name).unwrap_or_default(); unsafe { uu_ui_set_user(name.as_ptr()) } }
|
||||
#[cfg(not(uu_gtk))] let _ = name;
|
||||
}
|
||||
pub fn present(&self) {
|
||||
#[cfg(uu_gtk)]
|
||||
if matches!(self, Self::Window) { unsafe { uu_assist_ui_present() } }
|
||||
}
|
||||
fn show(&self, id: &str, code: &str, allowed: bool, verify: Verify, refresh: Refresh, has_custom: bool) -> Result<(), String> {
|
||||
#[cfg(not(uu_gtk))] let _ = has_custom;
|
||||
match self {
|
||||
Self::Tty(tty) => {
|
||||
// Bound/control-character-validated server identifier; no terminal escape injection.
|
||||
let mut tty = tty.get_ref();
|
||||
write!(tty, "\n远程协助 / Remote assistance\n设备 ID: {}\n临时验证码: {code}\n允许他人远程协助: {allowed}\n验证方式: {} 自动刷新: {}\n仅向可信的人提供验证码。allow=允许,deny=不允许,reset=换码,mode temporary|custom|both,refresh session|1h|12h|24h|never,off=关闭并撤销\n", display_id(id), verify.name(), refresh.name())
|
||||
.map_err(|_| "assist terminal display failed".into())
|
||||
}
|
||||
#[cfg(uu_gtk)]
|
||||
Self::Window => {
|
||||
let (id, code) = (std::ffi::CString::new(display_id(id)).unwrap_or_default(), std::ffi::CString::new(code).unwrap_or_default());
|
||||
unsafe { uu_assist_ui_set(id.as_ptr(), code.as_ptr(), i32::from(allowed), verify as i32, refresh as i32, i32::from(has_custom)) };
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
pub async fn command(&self) -> Command {
|
||||
match self {
|
||||
Self::Tty(tty) => Self::tty_command(tty).await,
|
||||
#[cfg(uu_gtk)]
|
||||
Self::Window => loop {
|
||||
let mut arg = [0 as libc::c_char; 40];
|
||||
let cmd = unsafe { uu_assist_ui_take_command(arg.as_mut_ptr(), arg.len()) };
|
||||
let text = unsafe { std::ffi::CStr::from_ptr(arg.as_ptr()) }.to_string_lossy().into_owned();
|
||||
let index = text.parse::<i64>().unwrap_or(-1);
|
||||
match cmd {
|
||||
1 => return Command::Allow, 2 => return Command::Deny, 3 => return Command::Reset, 4 => return Command::Stop,
|
||||
5 => if let Some(v) = Verify::from_index(index) { return Command::Verify(v) },
|
||||
6 => if let Some(r) = Refresh::from_index(index) { return Command::Refresh(r) },
|
||||
7 => return Command::Custom(text),
|
||||
8 => return Command::Logout,
|
||||
_ => tokio::time::sleep(std::time::Duration::from_millis(150)).await,
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
async fn tty_command(tty: &tokio::io::unix::AsyncFd<std::fs::File>) -> Command {
|
||||
let mut line = Vec::new();
|
||||
loop {
|
||||
let mut ready = match tty.readable().await { Ok(v) => v, Err(_) => return Command::Stop };
|
||||
let result = ready.try_io(|fd| { let mut byte = [0u8]; let mut tty = fd.get_ref(); tty.read(&mut byte).map(|n| (n, byte[0])) });
|
||||
match result {
|
||||
Ok(Ok((0, _))) | Ok(Err(_)) => return Command::Stop,
|
||||
Ok(Ok((_, byte))) if byte == b'\n' => {
|
||||
let text = String::from_utf8_lossy(&line).trim().to_owned();
|
||||
let cmd = match text.split_once(' ') {
|
||||
Some(("mode", v)) => Verify::parse(v).map(Command::Verify),
|
||||
Some(("refresh", v)) => Refresh::parse(v).map(Command::Refresh),
|
||||
_ => match text.as_str() { "allow" => Some(Command::Allow), "deny" => Some(Command::Deny), "reset" => Some(Command::Reset), "off" | "q" => Some(Command::Stop), _ => None },
|
||||
};
|
||||
line.clear(); if let Some(cmd) = cmd { return cmd; }
|
||||
}
|
||||
Ok(Ok((_, byte))) => { if line.len() < 64 { line.push(byte); } },
|
||||
Err(_) => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for LocalUi {
|
||||
fn drop(&mut self) {
|
||||
#[cfg(uu_gtk)]
|
||||
if matches!(self, Self::Window) { unsafe { uu_assist_ui_close() } }
|
||||
}
|
||||
}
|
||||
|
||||
fn response(status: u16, value: &Value) -> Result<&Value, String> {
|
||||
let code = value.get("code").and_then(Value::as_i64).unwrap_or(-1);
|
||||
if status == 200 && code == 0 { return Ok(value.get("data").unwrap_or(&Value::Null)); }
|
||||
// No server message, validation payload, headers, URLs, token or code in errors. UU_ASSIST_DEBUG=1 adds
|
||||
// the server's short human-readable message (bounded) for diagnosing rejected guest calls.
|
||||
let message = (std::env::var("UU_ASSIST_DEBUG").ok().as_deref() == Some("1"))
|
||||
.then(|| value.get("message").or_else(|| value.get("msg")).and_then(Value::as_str)
|
||||
.map(|m| m.chars().filter(|c| !c.is_control()).take(120).collect::<String>()))
|
||||
.flatten().map(|m| format!(" message={m:?}")).unwrap_or_default();
|
||||
Err(format!("assist API rejected request: http={status} code={code}{message}"))
|
||||
}
|
||||
fn text(value: &Value, key: &str) -> Result<String, String> {
|
||||
value.get(key).and_then(Value::as_str).filter(|s| !s.is_empty() && s.len() <= 16384)
|
||||
.map(str::to_owned).ok_or_else(|| "assist response missing required string".into())
|
||||
}
|
||||
fn share_id(value: &Value) -> Result<String, String> {
|
||||
let id = text(value, "connect_id")?;
|
||||
if id.len() > 128 || !id.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-') {
|
||||
return Err("assist response invalid device identifier".into());
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
fn generate_code() -> Result<String, String> {
|
||||
let mut random = std::fs::File::open("/dev/urandom").map_err(|_| "assist random source unavailable")?;
|
||||
let mut code = String::new();
|
||||
// Rejection sampling avoids modulo bias (alphabet has 32 entries).
|
||||
let limit = 256 / ALPHABET.len() * ALPHABET.len();
|
||||
while code.len() < 8 {
|
||||
let mut byte = [0u8]; random.read_exact(&mut byte).map_err(|_| "assist random source failed")?;
|
||||
if (byte[0] as usize) < limit { code.push(ALPHABET[byte[0] as usize % ALPHABET.len()] as char); }
|
||||
}
|
||||
Ok(code)
|
||||
}
|
||||
fn digest(salt: &str, code: &str) -> String {
|
||||
let mut hash = Sha256::new(); hash.update(salt.as_bytes()); hash.update(code.as_bytes()); hex::encode(hash.finalize())
|
||||
}
|
||||
/// Official: temporary-only signs the temporary code with an empty backup; both adds the custom code
|
||||
/// as `backup_sign`; custom-only puts the custom code in the primary `sign`.
|
||||
fn sign_body(control_id: &str, salt: &str, temporary: &str, custom: Option<&str>, verify: Verify, allow: bool) -> Value {
|
||||
let (primary, backup) = match (verify, custom) {
|
||||
(Verify::Custom, Some(c)) => (c, None),
|
||||
(Verify::Both, Some(c)) => (temporary, Some(c)),
|
||||
_ => (temporary, None),
|
||||
};
|
||||
json!({"can_remote_control": allow, "control_id": control_id,
|
||||
"sign": digest(salt, primary), "backup_sign": backup.map(|c| digest(salt, c)).unwrap_or_default()})
|
||||
}
|
||||
fn challenge(value: &Value) -> Option<(&str, &str)> {
|
||||
let id = value.get("control_id")?.as_str()?; let salt = value.get("salt")?.as_str()?;
|
||||
(!id.is_empty() && id.len() <= 256 && !salt.is_empty() && salt.len() <= 4096).then_some((id, salt))
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct RetryBackoff(u64);
|
||||
impl RetryBackoff {
|
||||
fn next(&mut self) -> std::time::Duration { self.0 = (self.0 + 15).min(99); std::time::Duration::from_secs(self.0) }
|
||||
}
|
||||
|
||||
pub struct Assist {
|
||||
_lock: std::fs::File,
|
||||
pub renewed: bool,
|
||||
device: Credentials,
|
||||
pub client: std::sync::Arc<UUAuthClient>,
|
||||
ui: std::sync::Arc<LocalUi>,
|
||||
code: String,
|
||||
custom: Option<String>,
|
||||
id: String,
|
||||
pub allowed: bool,
|
||||
verify: Verify,
|
||||
refresh: Refresh,
|
||||
code_at: std::time::Instant,
|
||||
/// Logged-in host: account endpoints and the host's own room (no guest identity).
|
||||
account: bool,
|
||||
}
|
||||
impl Assist {
|
||||
pub async fn start(shutdown: &mut tokio::sync::watch::Receiver<bool>, service: bool) -> Result<Self, String> {
|
||||
let ui = std::sync::Arc::new(LocalUi::open_visible(service)?);
|
||||
let lock = Self::lock()?;
|
||||
// guest/create rejects an unregistered device (HTTP 422 code 1001, verified live): register the
|
||||
// Windows device identity first, exactly as account login does (no account involved).
|
||||
let (config, device) = crate::login::prepare_device().await.map_err(|_| "assist device registration failed")?;
|
||||
let (custom, verify, refresh, allowed) = Self::settings(&config)?;
|
||||
let mut retry = RetryBackoff::default();
|
||||
let client = loop {
|
||||
if *shutdown.borrow() { return Err("assist stopped".into()); }
|
||||
let result = tokio::select! {
|
||||
result = Self::authenticate(&device) => result,
|
||||
_ = shutdown.changed() => return Err("assist stopped".into()),
|
||||
_ = ui.command() => return Err("assist stopped before guest identity was available".into()),
|
||||
};
|
||||
match result { Ok(client) => break client, Err(error) => {
|
||||
let delay = retry.next();
|
||||
// `error` carries only HTTP status / API code numbers or a fixed transport label.
|
||||
log::warn!("Guest identity request failed: {error}; retry_s={}", delay.as_secs());
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(delay) => {},
|
||||
_ = shutdown.changed() => return Err("assist stopped".into()),
|
||||
_ = ui.command() => return Err("assist stopped before guest identity was available".into()),
|
||||
}
|
||||
}}
|
||||
};
|
||||
let this = Self { _lock: lock, renewed: false, device, client: std::sync::Arc::new(client), ui, code: generate_code()?, custom, id: String::new(),
|
||||
allowed, verify, refresh, code_at: std::time::Instant::now(), account: false };
|
||||
// guest/share/info answers 400/2004 until a guest room exists (verified live), so the ID/code
|
||||
// are published right after the first room(), which serve() requests before signaling.
|
||||
Ok(this)
|
||||
}
|
||||
fn settings(config: &Value) -> Result<(Option<String>, Verify, Refresh, bool), String> {
|
||||
let custom = config.get("assist_custom_code").and_then(Value::as_str).map(str::to_owned);
|
||||
if custom.as_deref().is_some_and(|c| !valid_custom(c)) {
|
||||
return Err("assist_custom_code requires 8-16 ASCII letters/digits, including both".into());
|
||||
}
|
||||
let setting = |key: &str| config.get(key).and_then(Value::as_str).map(str::to_owned);
|
||||
let verify = setting("assist_verify").as_deref().and_then(Verify::parse).filter(|v| *v == Verify::Temporary || custom.is_some()).unwrap_or(Verify::Temporary);
|
||||
let refresh = setting("assist_refresh").as_deref().and_then(Refresh::parse).unwrap_or(Refresh::Session);
|
||||
// Official default is "not allowed"; the switch state persists like isAllowRecipient.
|
||||
let allowed = std::env::var("UU_ASSIST_ALLOW").ok().as_deref() == Some("1")
|
||||
|| config.get("assist_allow").and_then(Value::as_bool) == Some(true);
|
||||
Ok((custom, verify, refresh, allowed))
|
||||
}
|
||||
fn lock() -> Result<std::fs::File, String> {
|
||||
let lock_path = crate::config::path().with_file_name("assist.lock");
|
||||
if let Some(dir) = lock_path.parent() { std::fs::create_dir_all(dir).map_err(|_| "assist config directory unavailable")?; }
|
||||
let lock = std::fs::OpenOptions::new().create(true).write(true).mode(0o600).custom_flags(libc::O_NOFOLLOW).open(lock_path)
|
||||
.map_err(|_| "assist lock unavailable")?;
|
||||
if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 { return Err("another assist host uses this config".into()); }
|
||||
Ok(lock)
|
||||
}
|
||||
/// Remote assistance on a logged-in host, shown in the service's hidden window.
|
||||
pub fn start_account(client: std::sync::Arc<UUAuthClient>, device: Credentials) -> Result<Self, String> {
|
||||
let lock = Self::lock()?;
|
||||
let ui = std::sync::Arc::new(LocalUi::open_service()?);
|
||||
let config = crate::config::read_fresh()?.unwrap_or_else(|| json!({}));
|
||||
let (custom, verify, refresh, allowed) = Self::settings(&config)?;
|
||||
let this = Self { _lock: lock, renewed: false, device, client, ui, code: generate_code()?, custom, id: String::new(),
|
||||
allowed, verify, refresh, code_at: std::time::Instant::now(), account: true };
|
||||
this.show()?;
|
||||
Ok(this)
|
||||
}
|
||||
pub fn is_account(&self) -> bool { self.account }
|
||||
/// Logged-in host: account name for the account card (saved at login, else /api/v1/user/info).
|
||||
pub async fn load_account_name(&self) {
|
||||
let saved = crate::config::read_fresh().ok().flatten()
|
||||
.and_then(|c| c.get("account_name").and_then(Value::as_str).map(str::to_owned)).filter(|n| !n.is_empty());
|
||||
let name = match saved {
|
||||
Some(name) => name,
|
||||
None => match self.client.assist_get("/api/v1/user/info").await {
|
||||
Ok((200, v)) => v.get("data").and_then(|d| ["nickname", "mobile", "phone"].iter()
|
||||
.find_map(|k| d.get(*k).and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_owned)))
|
||||
.unwrap_or_else(|| self.device.user_id.clone()),
|
||||
_ => self.device.user_id.clone(),
|
||||
},
|
||||
};
|
||||
self.ui.set_user(&display_account(&name));
|
||||
}
|
||||
/// Sign out: official /api/v1/user/logout (best effort), withdraw the share, drop local credentials.
|
||||
pub async fn logout(&mut self) {
|
||||
let _ = self.client.assist_post("/api/v1/user/logout", None).await;
|
||||
let _ = self.cancel().await;
|
||||
self.save_many(&[("token", Value::Null), ("csrf", Value::Null), ("user_id", Value::Null), ("account_name", Value::Null)]);
|
||||
log::info!("Signed out; restarting without an account");
|
||||
}
|
||||
pub fn ui(&self) -> std::sync::Arc<LocalUi> { self.ui.clone() }
|
||||
fn path(&self, guest: &'static str) -> &'static str {
|
||||
if !self.account { return guest; }
|
||||
match guest { INFO => ACCOUNT_INFO, CANCEL => ACCOUNT_CANCEL, SIGN => ACCOUNT_SIGN, CONTROL_MODE => ACCOUNT_CONTROL_MODE, other => other }
|
||||
}
|
||||
/// Logged-in host: publish the share ID/code once its own room exists (same ordering as guests).
|
||||
pub async fn ensure_published(&mut self) -> Result<(), String> {
|
||||
if self.id.is_empty() { self.publish().await } else { Ok(()) }
|
||||
}
|
||||
async fn authenticate(device: &Credentials) -> Result<UUAuthClient, String> {
|
||||
let client = UUAuthClient::new(device.clone());
|
||||
let (status, value) = client.assist_post(CREATE, None).await?;
|
||||
let data = response(status, &value)?;
|
||||
Ok(UUAuthClient::new_guest(device.clone(), text(data, "guest_id")?, text(data, "token")?))
|
||||
}
|
||||
async fn post(&mut self, path: &'static str, body: Option<&Value>) -> Result<Value, String> {
|
||||
let path = self.path(path);
|
||||
let (mut status, mut value) = if path == ACCOUNT_INFO { self.client.assist_get(path).await? } else { self.client.assist_post(path, body).await? };
|
||||
if self.account { return response(status, &value).map(Clone::clone); }
|
||||
// Official wrapper refreshes on 1120 and retries once, rather than on a guessed TTL.
|
||||
if value.get("code").and_then(Value::as_i64) == Some(crate::auth::TOKEN_INVALID) {
|
||||
self.client = std::sync::Arc::new(Self::authenticate(&self.device).await?);
|
||||
self.renewed = true;
|
||||
(status, value) = self.client.assist_post(path, body).await?;
|
||||
}
|
||||
response(status, &value).map(Clone::clone)
|
||||
}
|
||||
async fn publish(&mut self) -> Result<(), String> {
|
||||
self.id = share_id(&self.post(INFO, None).await?)?;
|
||||
self.show()
|
||||
}
|
||||
pub async fn room(&mut self) -> Result<RoomData, String> {
|
||||
let value = self.post(ROOM, None).await?;
|
||||
if self.renewed || self.id.is_empty() {
|
||||
if let Err(error) = self.publish().await { let _ = self.cancel().await; return Err(error); }
|
||||
self.renewed = false;
|
||||
}
|
||||
serde_json::from_value(value).map_err(|_| "assist room response malformed".into())
|
||||
}
|
||||
pub async fn challenge(&mut self, value: &Value) -> Result<(), String> {
|
||||
let (control, salt) = challenge(value).ok_or("assist challenge malformed")?;
|
||||
self.post(SIGN, Some(&sign_body(control, salt, &self.code, self.custom.as_deref(), self.verify, self.allowed))).await?;
|
||||
Ok(())
|
||||
}
|
||||
/// Answer the cloud's `get_control_mode` push (data {control_id}). Official Windows host
|
||||
/// (GameViewerServer RemoteAssistCode::respRemoteGetControlMode -> NrdBusinessEntry::uploadControlMode)
|
||||
/// posts {control_id, allow_control, control_mode: by_password|by_confirmation|password_confirmation}.
|
||||
/// Only the temporary/custom code mode is implemented, so this host reports `by_password`.
|
||||
pub async fn control_mode(&mut self, value: &Value) -> Result<(), String> {
|
||||
let control = value.get("control_id").and_then(Value::as_str).filter(|s| !s.is_empty() && s.len() <= 256)
|
||||
.ok_or("assist control mode request malformed")?;
|
||||
self.post(CONTROL_MODE, Some(&json!({"control_id": control, "allow_control": self.allowed, "control_mode": "by_password"}))).await.map(|_| ())
|
||||
}
|
||||
/// The code the controller types: the custom code in custom-only mode, else the temporary one.
|
||||
fn show(&self) -> Result<(), String> {
|
||||
let code = match (self.verify, &self.custom) { (Verify::Custom, Some(c)) => c.as_str(), _ => self.code.as_str() };
|
||||
self.ui.show(&self.id, code, self.allowed, self.verify, self.refresh, self.custom.is_some())
|
||||
}
|
||||
/// Saves one assist setting into the owner's 0600 config (custom code included, never logged).
|
||||
fn save_many(&self, entries: &[(&str, Value)]) {
|
||||
let mut cfg = std::fs::read(crate::config::path()).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok())
|
||||
.filter(Value::is_object).unwrap_or_else(|| json!({}));
|
||||
if let Some(map) = cfg.as_object_mut() { for (k, v) in entries { if v.is_null() { map.remove(*k); } else { map.insert((*k).to_owned(), v.clone()); } } }
|
||||
if crate::login::write_config(&cfg).is_err() { log::warn!("Account settings could not be saved"); }
|
||||
}
|
||||
fn save(&self, key: &str, value: Value) {
|
||||
// Re-read the file: config::file() is a startup snapshot that predates device registration,
|
||||
// so writing it back would drop device_id (and earlier saves) and change the device ID.
|
||||
let mut cfg = std::fs::read(crate::config::path()).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok())
|
||||
.filter(Value::is_object).unwrap_or_else(|| json!({}));
|
||||
cfg[key] = value;
|
||||
if crate::login::write_config(&cfg).is_err() { log::warn!("Assist setting could not be saved: key={key}"); }
|
||||
}
|
||||
pub fn reset(&mut self) -> Result<(), String> { self.code = generate_code()?; self.code_at = std::time::Instant::now(); self.show() }
|
||||
pub fn allow(&mut self) -> Result<(), String> { self.allowed = true; self.save("assist_allow", json!(true)); self.show() }
|
||||
pub fn deny(&mut self) -> Result<(), String> { self.allowed = false; self.save("assist_allow", json!(false)); self.show() }
|
||||
pub fn set_verify(&mut self, verify: Verify) -> Result<(), String> {
|
||||
if verify != Verify::Temporary && self.custom.is_none() { return self.show(); } // UI asks for a code first
|
||||
self.verify = verify; self.save("assist_verify", json!(verify.name())); self.show()
|
||||
}
|
||||
pub fn set_refresh(&mut self, refresh: Refresh) -> Result<(), String> {
|
||||
self.refresh = refresh; self.code_at = std::time::Instant::now(); self.save("assist_refresh", json!(refresh.name())); self.show()
|
||||
}
|
||||
pub fn set_custom(&mut self, code: String) -> Result<(), String> {
|
||||
if !valid_custom(&code) { return self.show(); }
|
||||
self.custom = Some(code.clone()); self.save("assist_custom_code", json!(code));
|
||||
if self.verify == Verify::Temporary { self.verify = Verify::Custom; self.save("assist_verify", json!(self.verify.name())); }
|
||||
self.show()
|
||||
}
|
||||
/// After the last desktop session: rotate only in "每次远控结束" mode.
|
||||
pub fn session_ended(&mut self) -> Result<(), String> { if self.refresh == Refresh::Session { self.reset() } else { Ok(()) } }
|
||||
/// Periodic rotation for the hourly/12 h/24 h settings.
|
||||
pub fn tick(&mut self) -> Result<(), String> {
|
||||
match self.refresh.period() { Some(p) if self.code_at.elapsed() >= p => self.reset(), _ => Ok(()) }
|
||||
}
|
||||
pub fn commands(&self, shutdown: tokio::sync::watch::Sender<bool>) -> (tokio::sync::mpsc::Receiver<Command>, tokio::task::JoinHandle<()>) {
|
||||
let (tx, rx) = tokio::sync::mpsc::channel(4);
|
||||
let ui = self.ui.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
loop {
|
||||
let command = tokio::select! { command = ui.command() => command, _ = tx.closed() => return };
|
||||
if matches!(command, Command::Stop) { let _ = shutdown.send(true); return; }
|
||||
match tx.try_send(command) {
|
||||
Ok(()) | Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => {},
|
||||
Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => return,
|
||||
}
|
||||
}
|
||||
});
|
||||
(rx, task)
|
||||
}
|
||||
pub async fn cancel(&mut self) -> Result<(), String> { self.post(CANCEL, None).await.map(|_| ()) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[tokio::test]
|
||||
async fn local_terminal_display_and_explicit_commands() {
|
||||
// Private PTY pair only, never the user's actual terminal; all values synthetic.
|
||||
let pair = nix::pty::openpty(None, None).unwrap();
|
||||
let slave = std::fs::File::from(pair.slave);
|
||||
unsafe { libc::fcntl(slave.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK); }
|
||||
let ui = LocalUi::Tty(tokio::io::unix::AsyncFd::new(slave).unwrap());
|
||||
let mut master = std::fs::File::from(pair.master);
|
||||
ui.show("fixture-123", "FIXTURE8", false, Verify::Temporary, Refresh::Session, false).unwrap();
|
||||
let mut bytes = [0u8; 1024];
|
||||
let n = master.read(&mut bytes).unwrap();
|
||||
let text = std::str::from_utf8(&bytes[..n]).unwrap();
|
||||
assert!(text.contains("fixture-123") && text.contains("FIXTURE8") && text.contains("false"));
|
||||
for (input, expected) in [(b"unknown\nallow\n".as_slice(), 0), (b"reset\n".as_slice(), 1), (b"off\n".as_slice(), 2)] {
|
||||
master.write_all(input).unwrap();
|
||||
let command = tokio::time::timeout(std::time::Duration::from_secs(2), ui.command()).await.unwrap();
|
||||
assert!(matches!((command, expected), (Command::Allow, 0) | (Command::Reset, 1) | (Command::Stop, 2)));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn official_challenge_sign_and_shape() {
|
||||
// Synthetic fixture, independently calculated SHA256("saltABC234XY").
|
||||
let body = sign_body("fixture-control", "salt", "ABC234XY", None, Verify::Temporary, false);
|
||||
assert_eq!(body.as_object().unwrap().len(), 4);
|
||||
assert_eq!(body["can_remote_control"], false);
|
||||
assert_eq!(body["control_id"], "fixture-control");
|
||||
assert_eq!(body["sign"], "dc747ee8adb0e591f5ff4ab6cabcaf3a0ec312851580f225d4ca140766229c94");
|
||||
assert_eq!(body["backup_sign"], "");
|
||||
let both = sign_body("fixture", "salt", "ABC234XY", Some("test1234"), Verify::Both, true);
|
||||
assert_ne!(both["sign"], both["backup_sign"]);
|
||||
assert_eq!(both["can_remote_control"], true);
|
||||
}
|
||||
#[test]
|
||||
fn rejects_missing_or_unbounded_challenges_and_terminal_injection() {
|
||||
for value in [json!({}), json!({"control_id":"x", "salt":""}), json!({"control_id":12,"salt":"s"}), json!({"control_id":"x","salt":"s".repeat(4097)})] {
|
||||
assert!(challenge(&value).is_none());
|
||||
}
|
||||
assert!(challenge(&json!({"control_id":"fixture", "salt":"fixture"})).is_some());
|
||||
assert!(share_id(&json!({"connect_id":"fixture-123"})).is_ok());
|
||||
for id in ["", "\u{1b}[2J", "a\nb", "x\u{7}"] { assert!(share_id(&json!({"connect_id":id})).is_err()); }
|
||||
}
|
||||
#[test]
|
||||
fn responses_do_not_disclose_untrusted_server_errors() {
|
||||
let error = response(422, &json!({"code":1120,"msg":"synthetic-secret","data":{"token":"synthetic-secret"}})).unwrap_err();
|
||||
assert!(!error.contains("synthetic-secret"));
|
||||
assert!(response(200, &json!({"code":0})).unwrap().is_null());
|
||||
assert!(text(&Value::Null, "token").is_err());
|
||||
assert_eq!(text(&json!({"guest_id":"fixture-guest"}), "guest_id").unwrap(), "fixture-guest");
|
||||
}
|
||||
#[test]
|
||||
fn official_guest_failure_retry_schedule() {
|
||||
let mut retry = RetryBackoff::default();
|
||||
let actual: Vec<_> = (0..9).map(|_| retry.next().as_secs()).collect();
|
||||
assert_eq!(actual, [15,30,45,60,75,90,99,99,99]);
|
||||
}
|
||||
#[test]
|
||||
fn secure_temporary_code_format() {
|
||||
for _ in 0..64 { let code = generate_code().unwrap(); assert_eq!(code.len(),8); assert!(code.bytes().all(|b| ALPHABET.contains(&b))); }
|
||||
}
|
||||
}
|
||||
+85
-5
@@ -73,7 +73,7 @@ pub struct ApiResponse<T> {
|
||||
pub data: Option<T>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[derive(Clone, Deserialize)]
|
||||
pub struct RoomData {
|
||||
pub signaling_server: String,
|
||||
pub token: String,
|
||||
@@ -81,9 +81,14 @@ pub struct RoomData {
|
||||
pub ws_connect_timeout_ms: Option<u64>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RoomData {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("RoomData { .. }") }
|
||||
}
|
||||
|
||||
pub struct UUAuthClient {
|
||||
pub creds: Credentials,
|
||||
http: reqwest::Client,
|
||||
guest_id: Option<String>,
|
||||
}
|
||||
|
||||
impl UUAuthClient {
|
||||
@@ -92,7 +97,16 @@ impl UUAuthClient {
|
||||
.timeout(std::time::Duration::from_secs(12))
|
||||
.build()
|
||||
.unwrap();
|
||||
Self { creds, http }
|
||||
Self { creds, http, guest_id: None }
|
||||
}
|
||||
|
||||
/// Explicit guest identity: never inherits account Authorization/cookies.
|
||||
/// Official ApiDefaultHeaders 0x1003853ac/0x1003853f8 (see assist evidence).
|
||||
pub fn new_guest(mut device: Credentials, guest_id: String, token: String) -> Self {
|
||||
device.user_id.clear(); device.csrf.clear(); device.token = token;
|
||||
let mut client = Self::new(device);
|
||||
client.guest_id = Some(guest_id);
|
||||
client
|
||||
}
|
||||
|
||||
/// 计算网易 NRD HMAC-SHA256 签名
|
||||
@@ -147,6 +161,7 @@ impl UUAuthClient {
|
||||
("x-param-system-id", &self.creds.system_id), ("x-param-user-id", &self.creds.user_id)] {
|
||||
if !value.is_empty() { param_map.insert(key.into(), value.clone()); }
|
||||
}
|
||||
if let Some(id) = &self.guest_id { param_map.insert("x-param-guest-id".into(), id.clone()); }
|
||||
param_map.insert("x-param-ts".into(), ts);
|
||||
|
||||
let sign = self.sign_request(method, path, ¶m_map, body_str);
|
||||
@@ -160,10 +175,12 @@ impl UUAuthClient {
|
||||
);
|
||||
if !self.creds.token.is_empty() {
|
||||
if let Ok(v) = HeaderValue::from_str(&format!("Bearer {}", self.creds.token)) { headers.insert("Authorization", v); }
|
||||
if let Ok(v) = HeaderValue::from_str(&format!("nrd_access_token={}; nrd_csrf_access_token={}", self.creds.token, self.creds.csrf)) {
|
||||
headers.insert("Cookie", v);
|
||||
if self.guest_id.is_none() {
|
||||
if let Ok(v) = HeaderValue::from_str(&format!("nrd_access_token={}; nrd_csrf_access_token={}", self.creds.token, self.creds.csrf)) {
|
||||
headers.insert("Cookie", v);
|
||||
}
|
||||
if let Ok(v) = HeaderValue::from_str(&self.creds.csrf) { headers.insert("X-CSRF-TOKEN", v); }
|
||||
}
|
||||
if let Ok(v) = HeaderValue::from_str(&self.creds.csrf) { headers.insert("X-CSRF-TOKEN", v); }
|
||||
}
|
||||
|
||||
for (k, v) in param_map {
|
||||
@@ -189,6 +206,34 @@ impl UUAuthClient {
|
||||
Ok((status, value))
|
||||
}
|
||||
|
||||
/// Guest APIs use requestPlain for empty requests; sign the actual empty body.
|
||||
/// Errors intentionally exclude response text and URL (both can contain secrets).
|
||||
pub async fn assist_post(&self, path: &str, body: Option<&serde_json::Value>) -> Result<(u16, serde_json::Value), String> {
|
||||
self.assist_send(self.assist_request(path, body)?).await
|
||||
}
|
||||
/// Account share info is a GET (POST answers 405, verified live).
|
||||
pub async fn assist_get(&self, path: &str) -> Result<(u16, serde_json::Value), String> {
|
||||
let request = self.http.get(format!("{BASE_URL}{path}")).headers(self.build_headers("GET", path, "")).build()
|
||||
.map_err(|_| "assist request construction failed")?;
|
||||
self.assist_send(request).await
|
||||
}
|
||||
async fn assist_send(&self, request: reqwest::Request) -> Result<(u16, serde_json::Value), String> {
|
||||
let response = self.http.execute(request)
|
||||
.await.map_err(|_| "assist request transport failed")?;
|
||||
let status = response.status().as_u16();
|
||||
let bytes = response.bytes().await.map_err(|_| "assist response read failed")?;
|
||||
if bytes.len() > 65536 { return Err("assist response too large".into()); }
|
||||
let value = serde_json::from_slice(&bytes).map_err(|_| "assist response malformed")?;
|
||||
Ok((status, value))
|
||||
}
|
||||
|
||||
fn assist_request(&self, path: &str, body: Option<&serde_json::Value>) -> Result<reqwest::Request, String> {
|
||||
let body = body.map(serde_json::to_string).transpose().map_err(|_| "assist request encoding failed")?.unwrap_or_default();
|
||||
self.http.post(format!("{BASE_URL}{path}"))
|
||||
.headers(self.build_headers("POST", path, &body)).body(body).build()
|
||||
.map_err(|_| "assist request construction failed".into())
|
||||
}
|
||||
|
||||
/// 向网易服务器请求创建房间,获取最新的信令服务器与鉴权 Token
|
||||
pub async fn create_room(&self) -> Result<RoomData, RoomError> {
|
||||
let (status, body) = self.post_json("/api/v1/room/create", &serde_json::json!({})).await.map_err(RoomError::Other)?;
|
||||
@@ -231,3 +276,38 @@ mod room_lifetime_tests {
|
||||
assert_eq!(room_token_lifetime("h.invalid.s",1000),None);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod guest_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn official_request_plain_body_and_sanitized_room_debug() {
|
||||
let client = UUAuthClient::new_guest(Credentials { sign_key: "fixture-key".into(), ..Default::default() },
|
||||
"fixture-guest".into(), "fixture-token".into());
|
||||
let request = client.assist_request("/api/v1/guest/create", None).unwrap();
|
||||
assert_eq!(request.method(), reqwest::Method::POST);
|
||||
assert_eq!(request.body().unwrap().as_bytes(), Some(&b""[..]));
|
||||
let other = client.assist_request("/api/v1/guest/create", Some(&serde_json::json!({}))).unwrap();
|
||||
assert_eq!(other.body().unwrap().as_bytes(), Some(&b"{}"[..]));
|
||||
assert_ne!(request.headers()["x-param-sign"], other.headers()["x-param-sign"]);
|
||||
let room: RoomData = serde_json::from_value(serde_json::json!({"signaling_server":"wss://fixture.invalid", "token":"synthetic-room-secret"})).unwrap();
|
||||
assert!(!format!("{room:?}").contains("synthetic-room-secret"));
|
||||
assert!(serde_json::from_value::<RoomData>(serde_json::json!({"token":42})).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn guest_signs_guest_id_and_never_inherits_account_identity() {
|
||||
let account = Credentials { user_id: "fixture-account".into(), token: "fixture-account-token".into(),
|
||||
csrf: "fixture-account-csrf".into(), client_id: "fixture-client".into(),
|
||||
device_id: "fixture-device".into(), sign_key: "fixture-sign-key".into(), ..Default::default() };
|
||||
let client = UUAuthClient::new_guest(account, "fixture-guest".into(), "fixture-guest-token".into());
|
||||
let headers = client.build_headers("POST", "/api/v1/guest/room/create", "");
|
||||
assert_eq!(headers["authorization"], "Bearer fixture-guest-token");
|
||||
assert_eq!(headers["x-param-guest-id"], "fixture-guest");
|
||||
for key in ["x-param-user-id", "cookie", "x-csrf-token"] { assert!(!headers.contains_key(key)); }
|
||||
let params: BTreeMap<String,String> = headers.iter().filter_map(|(key, value)|
|
||||
key.as_str().starts_with("x-param-").then(|| (key.to_string(), value.to_str().unwrap().to_owned()))).collect();
|
||||
assert_eq!(headers["x-param-sign"], client.sign_request("POST", "/api/v1/guest/room/create", ¶ms, ""));
|
||||
let mut without_guest = params; without_guest.remove("x-param-guest-id");
|
||||
assert_ne!(headers["x-param-sign"], client.sign_request("POST", "/api/v1/guest/room/create", &without_guest, ""));
|
||||
}
|
||||
}
|
||||
+26
-7
@@ -143,7 +143,7 @@ fn qr_rgba(content: &str, scale: usize, quiet: usize) -> Result<(Vec<u8>, usize)
|
||||
Ok((rgba, edge))
|
||||
}
|
||||
|
||||
fn write_config(cfg: &Value) -> Result<std::path::PathBuf, String> {
|
||||
pub(crate) fn write_config(cfg: &Value) -> Result<std::path::PathBuf, String> {
|
||||
use std::io::Write;
|
||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||
let path = crate::config::path();
|
||||
@@ -227,8 +227,8 @@ pub async fn run(gui: bool) -> Result<(), String> {
|
||||
result.map(|_| ())
|
||||
}
|
||||
|
||||
/// Returns the account nickname (or user id) on success.
|
||||
async fn flow(ui: &LoginUi) -> Result<String, String> {
|
||||
/// Local installation identifiers only; guest creation does not require device/init.
|
||||
pub fn prepare_identity() -> Result<(Value, Credentials), String> {
|
||||
let mut cfg = crate::config::file()?.cloned().unwrap_or_else(|| json!({}));
|
||||
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();
|
||||
@@ -237,8 +237,16 @@ async fn flow(ui: &LoginUi) -> Result<String, String> {
|
||||
for (key, make) in [("client_id", random_uuid as fn() -> String), ("system_id", || random_uuid().to_uppercase()), ("machine_guid", machine_guid)] {
|
||||
if get(&cfg, key).is_empty() { cfg[key] = json!(make()); }
|
||||
}
|
||||
let mut creds = Credentials { client_id: get(&cfg, "client_id"), system_id: get(&cfg, "system_id"), sign_key, ..Default::default() };
|
||||
let creds = Credentials { client_id: get(&cfg, "client_id"), system_id: get(&cfg, "system_id"), device_id: get(&cfg, "device_id"), sign_key, ..Default::default() };
|
||||
|
||||
write_config(&cfg)?;
|
||||
Ok((cfg, creds))
|
||||
}
|
||||
|
||||
pub async fn prepare_device() -> Result<(Value, Credentials), String> {
|
||||
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();
|
||||
if get(&cfg, "device_id").is_empty() {
|
||||
let body = json!({
|
||||
"name": hostname(), "client_id": creds.client_id, "system_id": creds.system_id, "machine_guid": get(&cfg, "machine_guid"),
|
||||
@@ -248,11 +256,17 @@ async fn flow(ui: &LoginUi) -> Result<String, String> {
|
||||
let (status, resp) = UUAuthClient::new(creds.clone()).post_json("/api/v1/device/windows/init", &body).await?;
|
||||
let d = data("device init", status, &resp)?;
|
||||
let id = d.get("device_id").and_then(|v| v.as_str()).ok_or("device init returned no device_id")?;
|
||||
println!("Registered device: name={} id={}", d.get("alias").and_then(|v| v.as_str()).unwrap_or(""), id);
|
||||
log::info!("Registered local device identity");
|
||||
cfg["device_id"] = json!(id);
|
||||
write_config(&cfg)?; // keep the device even if the QR step is abandoned
|
||||
}
|
||||
creds.device_id = get(&cfg, "device_id");
|
||||
Ok((cfg, creds))
|
||||
}
|
||||
|
||||
/// Returns the account nickname (or user id) on success.
|
||||
pub(crate) async fn flow(ui: &LoginUi) -> Result<String, String> {
|
||||
let (mut cfg, creds) = prepare_device().await?;
|
||||
let client = UUAuthClient::new(creds.clone());
|
||||
|
||||
loop {
|
||||
@@ -274,7 +288,7 @@ async fn flow(ui: &LoginUi) -> Result<String, String> {
|
||||
let mut file=std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(path).map_err(|e|e.to_string())?;
|
||||
file.write_all(&crate::cursor::encode_png(edge as u32,edge as u32,&rgba)).map_err(|e|e.to_string())?;
|
||||
}
|
||||
println!("\nScan with the UU Remote mobile app (网易UU远程 App 扫码登录):\n{}", render_qr(&url)?);
|
||||
if !ui.quiet() { println!("\nScan with the UU Remote mobile app (网易UU远程 App 扫码登录):\n{}", render_qr(&url)?); }
|
||||
// Status is a long poll: send the state already shown (server enum 1..4; observed:
|
||||
// 1 waiting, 2 scanned, 4 after the phone confirmed); the server answers when it changes.
|
||||
let mut login_status = 1i64;
|
||||
@@ -315,8 +329,13 @@ async fn flow(ui: &LoginUi) -> Result<String, String> {
|
||||
cfg["token"] = json!(token);
|
||||
cfg["user_id"] = json!(user);
|
||||
cfg["csrf"] = json!(csrf_from_token(token).ok_or("token carries no csrf claim")?);
|
||||
let path = write_config(&cfg)?;
|
||||
let nickname = d.get("nickname").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if !nickname.is_empty() { cfg["account_name"] = json!(nickname); }
|
||||
// Keep settings saved meanwhile (e.g. from the assist card): merge into the fresh file.
|
||||
if let Ok(Some(Value::Object(fresh))) = crate::config::read_fresh() {
|
||||
for (k, v) in fresh { if cfg.get(&k).is_none() { cfg[k] = v; } }
|
||||
}
|
||||
let path = write_config(&cfg)?;
|
||||
println!("Logged in as {} ({}); saved to {}", nickname, user, path.display());
|
||||
return Ok(if nickname.is_empty() { user.to_string() } else { nickname.to_string() });
|
||||
}
|
||||
|
||||
+14
-4
@@ -15,13 +15,13 @@ extern "C" {
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum Tone { Info = 0, Ok = 1, Error = 2 }
|
||||
|
||||
pub struct LoginUi { shown: bool }
|
||||
pub struct LoginUi { shown: bool, attached: bool }
|
||||
|
||||
#[cfg(uu_gtk)]
|
||||
fn cstr(s: &str) -> std::ffi::CString { std::ffi::CString::new(s.replace('\0', "")).unwrap_or_default() }
|
||||
|
||||
impl LoginUi {
|
||||
pub fn none() -> Self { LoginUi { shown: false } }
|
||||
pub fn none() -> Self { LoginUi { shown: false, attached: false } }
|
||||
|
||||
/// Opens the window when built with GTK and a display is present; falls back silently otherwise.
|
||||
#[allow(unused_variables)]
|
||||
@@ -30,13 +30,23 @@ impl LoginUi {
|
||||
if std::env::var_os("DISPLAY").is_some() || std::env::var_os("WAYLAND_DISPLAY").is_some() {
|
||||
let (n, o, c, g) = (cstr(name), cstr(os), cstr(cpu), cstr(gpu));
|
||||
if unsafe { uu_login_ui_start(n.as_ptr(), o.as_ptr(), c.as_ptr(), g.as_ptr()) } == 0 {
|
||||
return LoginUi { shown: true };
|
||||
return LoginUi { shown: true, attached: false };
|
||||
}
|
||||
eprintln!("Login window unavailable; using the terminal QR code");
|
||||
}
|
||||
LoginUi::none()
|
||||
}
|
||||
|
||||
/// Account card of the host's own main window (already open): the QR stays in the window only
|
||||
/// (a service's stdout is the journal and the QR URL is a login ticket), and dropping this
|
||||
/// handle never closes the shared window.
|
||||
pub fn attached() -> Self {
|
||||
#[cfg(uu_gtk)]
|
||||
{ unsafe { uu_login_ui_start(std::ptr::null(), std::ptr::null(), std::ptr::null(), std::ptr::null()) }; LoginUi { shown: true, attached: true } }
|
||||
#[cfg(not(uu_gtk))]
|
||||
LoginUi { shown: false, attached: true }
|
||||
}
|
||||
pub fn quiet(&self) -> bool { self.attached }
|
||||
pub fn shown(&self) -> bool { self.shown }
|
||||
|
||||
#[allow(unused_variables)]
|
||||
@@ -73,6 +83,6 @@ impl LoginUi {
|
||||
impl Drop for LoginUi {
|
||||
fn drop(&mut self) {
|
||||
#[cfg(uu_gtk)]
|
||||
if self.shown { unsafe { uu_login_ui_close() } }
|
||||
if self.shown && !self.attached { unsafe { uu_login_ui_close() } }
|
||||
}
|
||||
}
|
||||
+263
-53
@@ -7,6 +7,7 @@ mod network_diagnostics;
|
||||
mod session_ice;
|
||||
mod wayland;
|
||||
mod auth;
|
||||
mod assist;
|
||||
mod config;
|
||||
mod login;
|
||||
mod login_ui;
|
||||
@@ -53,18 +54,80 @@ use std::sync::Arc;
|
||||
use tokio::sync::{mpsc, Mutex};
|
||||
use webrtc::WebRtcSession;
|
||||
|
||||
/// Set before a normal return when the host must come back in the other mode (signed in / out).
|
||||
static RESTART: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
/// Re-executes this host; the new instance opens its window so the user sees the result.
|
||||
fn restart_host() -> ! {
|
||||
use std::os::unix::process::CommandExt;
|
||||
let error = std::process::Command::new("/proc/self/exe").args(std::env::args_os().skip(1)).env("UU_SHOW_WINDOW", "1").exec();
|
||||
eprintln!("restart failed: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
fn display_present() -> bool { std::env::var_os("DISPLAY").is_some() || std::env::var_os("WAYLAND_DISPLAY").is_some() }
|
||||
/// SIGUSR1 (`uuremote-server show`) opens the host window.
|
||||
fn present_on_usr1(ui: std::sync::Arc<assist::LocalUi>) {
|
||||
write_host_pid();
|
||||
tokio::spawn(async move {
|
||||
let Ok(mut usr1) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::user_defined1()) else { return };
|
||||
while usr1.recv().await.is_some() { ui.present(); }
|
||||
});
|
||||
}
|
||||
|
||||
fn host_pid_path() -> std::path::PathBuf { config::path().with_file_name("host.pid") }
|
||||
/// Lets `uuremote-server show` find this host service to open its window (SIGUSR1).
|
||||
fn write_host_pid() {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
use std::io::Write;
|
||||
if let Ok(mut f) = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(host_pid_path()) {
|
||||
let _ = write!(f, "{}", std::process::id());
|
||||
}
|
||||
}
|
||||
/// `uuremote-server show` (desktop launcher): open the running host's window, or start the host in the
|
||||
/// foreground with its window when none runs (e.g. no systemd unit installed yet).
|
||||
fn show_running_host() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let running = std::fs::read_to_string(host_pid_path()).ok().and_then(|s| s.trim().parse::<i32>().ok()).filter(|p| *p > 1)
|
||||
.filter(|pid| {
|
||||
let exe = std::fs::read_link(format!("/proc/{pid}/exe")).ok();
|
||||
let own = std::env::current_exe().ok();
|
||||
exe.is_some() && exe.as_ref().and_then(|p| p.file_name()) == own.as_ref().and_then(|p| p.file_name())
|
||||
});
|
||||
if let Some(pid) = running {
|
||||
if unsafe { libc::kill(pid, libc::SIGUSR1) } == 0 { return Ok(()); }
|
||||
}
|
||||
use std::os::unix::process::CommandExt;
|
||||
Err(Box::new(std::process::Command::new("/proc/self/exe").env("UU_SHOW_WINDOW", "1").exec()))
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
|
||||
// Not signed in, with a desktop: one window offers remote assistance (guest identity) and the QR
|
||||
// login together; signing in restarts the host in account mode (assistance continues there).
|
||||
let unified = std::env::args().nth(1).is_none() && display_present()
|
||||
&& std::env::var("UU_REMOTE_ASSIST").ok().as_deref() != Some("0") && std::env::var("UU_LOGIN_WINDOW").ok().as_deref() != Some("0")
|
||||
&& config::read_fresh().ok().flatten().and_then(|c| c.get("token").and_then(|t| t.as_str()).map(|t| !t.is_empty())) != Some(true)
|
||||
&& ["UU_USER_ID", "UU_TOKEN", "UU_CSRF"].iter().all(|k| std::env::var_os(k).map_or(true, |v| v.is_empty()));
|
||||
let assist_enabled = unified || std::env::args().nth(1).as_deref() == Some("assist")
|
||||
|| (std::env::args().nth(1).is_none() && std::env::var("UU_REMOTE_ASSIST").ok().as_deref() == Some("1"));
|
||||
if assist_enabled {
|
||||
// HTTP/WS dependency trace logging can expose Authorization or room headers.
|
||||
env_logger::Builder::new().filter_level(log::LevelFilter::Off)
|
||||
.filter_module("uuremote_server", log::LevelFilter::Info).init();
|
||||
} else { env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); }
|
||||
// An unknown argument must never fall through to starting a second full host server.
|
||||
const SUBCOMMANDS: [&str; 11] = ["desktop-input-probe", "virtual-audio-probe", "login", "unlock-check", "desktop-probe", "desktop-video-probe", "desktop-audio-probe", "wayland-capture",
|
||||
const SUBCOMMANDS: [&str; 13] = ["show", "assist", "desktop-input-probe", "virtual-audio-probe", "login", "unlock-check", "desktop-probe", "desktop-video-probe", "desktop-audio-probe", "wayland-capture",
|
||||
"wayland-input-probe", "clipboard-acceptance", "portal-acceptance"];
|
||||
if let Some(arg) = std::env::args().nth(1).filter(|a| !SUBCOMMANDS.contains(&a.as_str())) {
|
||||
let usage = format!("usage: uuremote-server [{}]\n (no argument: run the host)", SUBCOMMANDS.join(" | "));
|
||||
if matches!(arg.as_str(), "help" | "-h" | "--help") { println!("{usage}"); return Ok(()); }
|
||||
eprintln!("unknown argument: {arg}\n{usage}");
|
||||
eprintln!("unknown argument\n{usage}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
|
||||
if std::env::args().nth(1).as_deref() == Some("show") { return show_running_host(); }
|
||||
if assist_enabled && !unified {
|
||||
if std::env::args().len() > 2 { return Err("assist accepts no additional arguments; configure it with a private UU_CONFIG".into()); }
|
||||
assist::configure()?;
|
||||
}
|
||||
if std::env::args().nth(1).as_deref() == Some("clipboard-acceptance") {
|
||||
return tokio::task::spawn_blocking(clipboard_probe::run).await?.map_err(Into::into);
|
||||
}
|
||||
@@ -261,7 +324,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let _audio_cleanup=virtual_audio::Cleanup;
|
||||
log::info!("Starting uu-remote-linux host v{}...", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
let mut capture = Arc::new((if desktop_backend::headless() {
|
||||
let capture = Arc::new((if desktop_backend::headless() {
|
||||
Err("headless mode (UU_DESKTOP_BACKEND=none)".to_owned())
|
||||
} else if desktop_backend::detect()?==desktop_backend::DesktopBackend::Portal
|
||||
&& std::env::var("UU_PORTAL_PREAUTHORIZE").ok().as_deref()!=Some("1") {
|
||||
@@ -274,34 +337,120 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
input.bind_portal(capture.portal.clone());
|
||||
input.release_held(); // recover stale input before accepting any peer
|
||||
let _pointer_worker = input.start_pointer_worker();
|
||||
#[cfg(target_os="linux")]
|
||||
{
|
||||
let shutdown_input=input.clone();
|
||||
let (shutdown_tx, mut shutdown) = tokio::sync::watch::channel(false);
|
||||
let shutdown_input = input.clone();
|
||||
let signal_tx = shutdown_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
#[cfg(target_os="linux")]
|
||||
{
|
||||
let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).expect("SIGTERM handler");
|
||||
tokio::select! { _ = term.recv() => {}, _ = tokio::signal::ctrl_c() => {} }
|
||||
}
|
||||
#[cfg(not(target_os="linux"))]
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
if !assist_enabled { shutdown_input.shutdown(); virtual_audio::disable(); terminal::shutdown_all(); std::process::exit(0); }
|
||||
let _ = signal_tx.send(true);
|
||||
});
|
||||
let mut assist = if assist_enabled { Some(assist::Assist::start(&mut shutdown, unified).await?) } else { None };
|
||||
if let Some(session) = assist.as_ref().filter(|_| unified) {
|
||||
present_on_usr1(session.ui());
|
||||
let login_done = shutdown_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Ok(mut term)=tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
|
||||
tokio::select! { _=term.recv()=>{}, _=tokio::signal::ctrl_c()=>{} }
|
||||
shutdown_input.shutdown(); virtual_audio::disable(); terminal::shutdown_all(); std::process::exit(0);
|
||||
let ui = login_ui::LoginUi::attached();
|
||||
loop {
|
||||
match login::flow(&ui).await {
|
||||
Ok(_) => { RESTART.store(true, std::sync::atomic::Ordering::SeqCst); let _ = login_done.send(true); return; }
|
||||
Err(error) => { log::warn!("QR login failed: {error}; retrying"); tokio::time::sleep(std::time::Duration::from_secs(5)).await; }
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let creds = match config::file().and_then(Credentials::load) {
|
||||
Ok(creds) => creds,
|
||||
Err(e) => {
|
||||
log::warn!("Not logged in: {e} ({} or UU_* environment variables)", config::path().display());
|
||||
login::wait_for_credentials(None).await
|
||||
let webrtc_sessions: Arc<Mutex<HashMap<String, WebRtcSession>>> = Arc::new(Mutex::new(HashMap::new()));
|
||||
let (mut commands, command_task) = match assist.as_ref() {
|
||||
Some(s) => { let (rx, task) = s.commands(shutdown_tx); (rx, Some(task)) },
|
||||
None => (tokio::sync::mpsc::channel(1).1, None),
|
||||
};
|
||||
let mut immediate_shutdown = shutdown.clone();
|
||||
let result = tokio::select! {
|
||||
result = serve(capture, input.clone(), &mut shutdown, &mut assist, &mut commands, webrtc_sessions.clone()) => result,
|
||||
_ = immediate_shutdown.changed() => Ok(()),
|
||||
};
|
||||
if let Some(task) = command_task { task.abort(); }
|
||||
// One exit path for commands, signals, transport failures and UI failures.
|
||||
if let Some(session) = assist.as_mut() { session.allowed = false; }
|
||||
for (_, old) in webrtc_sessions.lock().await.drain() { let _ = old.pc.close().await; }
|
||||
virtual_audio::disable(); input.shutdown(); terminal::shutdown_all();
|
||||
// Switching identity (signed in / out) restarts at once and the new identity republishes the same
|
||||
// device share: logout already withdrew it, and after a QR login the cloud moved it to the account
|
||||
// (a guest cancel then fails). Only a real stop withdraws here.
|
||||
let switching = RESTART.load(std::sync::atomic::Ordering::SeqCst);
|
||||
let revoke = match assist.as_mut() { Some(s) if !switching => s.cancel().await, _ => Ok(()) };
|
||||
if revoke.is_err() { log::error!("Cloud assistance revocation failed; host is closed locally"); }
|
||||
result?;
|
||||
if RESTART.load(std::sync::atomic::Ordering::SeqCst) { restart_host(); }
|
||||
revoke.map_err(|_| "assist disabled locally, but cloud cancel failed; cloud revocation is unverified")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn serve(mut capture: Arc<ScreenCapture>, input: Arc<InputInjector>, shutdown: &mut tokio::sync::watch::Receiver<bool>,
|
||||
assist: &mut Option<assist::Assist>, commands: &mut mpsc::Receiver<assist::Command>, webrtc_sessions: Arc<Mutex<HashMap<String, WebRtcSession>>>) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut auth = if let Some(session) = assist.as_ref() { session.client.clone() } else {
|
||||
let creds = match config::file().and_then(Credentials::load) {
|
||||
Ok(creds) => creds,
|
||||
Err(e) => {
|
||||
log::warn!("Not logged in: {e} ({} or UU_* environment variables)", config::path().display());
|
||||
login::wait_for_credentials(None).await
|
||||
}
|
||||
};
|
||||
let client = Arc::new(UUAuthClient::new(creds.clone()));
|
||||
// Logged-in host: remote assistance (ID + code) alongside the device list, like the official
|
||||
// client. Shown in a hidden window opened with `uuremote-server show`; UU_REMOTE_ASSIST=0 disables.
|
||||
if std::env::var("UU_REMOTE_ASSIST").ok().as_deref() != Some("0") {
|
||||
match assist::Assist::start_account(client.clone(), creds) {
|
||||
Ok(session) => {
|
||||
let (rx, _task) = session.commands(tokio::sync::watch::channel(false).0);
|
||||
*commands = rx;
|
||||
session.load_account_name().await;
|
||||
present_on_usr1(session.ui());
|
||||
if std::env::var("UU_SHOW_WINDOW").ok().as_deref() == Some("1") { session.ui().present(); }
|
||||
std::env::remove_var("UU_SHOW_WINDOW");
|
||||
log::info!("Remote assistance ready on the logged-in host (window: uuremote-server show)");
|
||||
*assist = Some(session);
|
||||
}
|
||||
Err(error) => log::info!("Remote assistance unavailable on this host: {error}"),
|
||||
}
|
||||
}
|
||||
client
|
||||
};
|
||||
let mut auth = Arc::new(UUAuthClient::new(creds));
|
||||
|
||||
// One peer per viewer connection (desktop, file transfer, terminal...), keyed by ice_id.
|
||||
let webrtc_sessions: Arc<Mutex<HashMap<String, WebRtcSession>>> = Arc::new(Mutex::new(HashMap::new()));
|
||||
let mut next_capture_type: Option<(u64,crate::session_ice::SessionIce)> = None;
|
||||
let mut capture_types: HashMap<String, (u64,crate::session_ice::SessionIce)> = HashMap::new();
|
||||
|
||||
loop {
|
||||
if *shutdown.borrow() {
|
||||
return Ok(());
|
||||
}
|
||||
log::info!("Requesting fresh room credentials from NetEase cloud...");
|
||||
let room_data = match auth.create_room().await {
|
||||
Ok(data) => data,
|
||||
let room_result = tokio::select! {
|
||||
result = async {
|
||||
match assist.as_mut() {
|
||||
Some(session) if !session.is_account() => {
|
||||
let result = session.room().await.map_err(auth::RoomError::Other);
|
||||
auth = session.client.clone(); result
|
||||
}
|
||||
_ => auth.create_room().await,
|
||||
}
|
||||
} => result,
|
||||
_ = shutdown.changed() => return Ok(()),
|
||||
};
|
||||
let room_data = match room_result {
|
||||
Ok(data) => {
|
||||
if let Some(session) = assist.as_mut().filter(|s| s.is_account()) {
|
||||
if let Err(error) = session.ensure_published().await { log::warn!("Remote assistance share info failed: {error}"); }
|
||||
}
|
||||
data
|
||||
}
|
||||
Err(auth::RoomError::LoginExpired) => {
|
||||
// Like the official client: an expired token needs a new QR login, not retries.
|
||||
log::error!("UU login is invalid or expired; a new QR login is required");
|
||||
@@ -316,20 +465,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
};
|
||||
|
||||
log::info!(
|
||||
"Acquired room signaling target: {}",
|
||||
room_data.signaling_server
|
||||
);
|
||||
log::info!("Acquired room signaling credentials");
|
||||
|
||||
let (tx_event, mut rx_event) = mpsc::channel::<SignalingEvent>(64);
|
||||
let tx_timer = tx_event.clone();
|
||||
let signaling_client = match SignalingClient::connect(
|
||||
&room_data.signaling_server,
|
||||
&room_data.token,
|
||||
tx_event,
|
||||
)
|
||||
.await
|
||||
{
|
||||
let connected = tokio::select! {
|
||||
result = SignalingClient::connect(&room_data.signaling_server, &room_data.token, tx_event) => result,
|
||||
_ = shutdown.changed() => return Ok(()),
|
||||
};
|
||||
let signaling_client = match connected {
|
||||
Ok(cli) => {
|
||||
let renewal_peers=webrtc_sessions.clone();
|
||||
tokio::spawn(async move {
|
||||
@@ -351,27 +495,80 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
Arc::new(cli)
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Failed to connect signaling: {}. Retrying in 5s...", e);
|
||||
let _ = e;
|
||||
log::error!("Failed to connect signaling; retrying in 5s (details omitted)");
|
||||
tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// 事件处理主循环
|
||||
while let Some(evt) = rx_event.recv().await {
|
||||
// Guest display/control commands never use stdout, stderr or logs.
|
||||
let mut assist_tick = tokio::time::interval(std::time::Duration::from_secs(1));
|
||||
loop {
|
||||
let event = tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.changed() => Some(SignalingEvent::Stop),
|
||||
command = commands.recv(), if assist.is_some() => Some(SignalingEvent::AssistCommand(command.unwrap_or(assist::Command::Stop))),
|
||||
_ = assist_tick.tick(), if assist.is_some() => Some(SignalingEvent::AssistTick),
|
||||
event = rx_event.recv() => event,
|
||||
};
|
||||
let Some(evt) = event else { break; };
|
||||
match evt {
|
||||
SignalingEvent::Stop | SignalingEvent::AssistCommand(assist::Command::Stop) => {
|
||||
return Ok(());
|
||||
}
|
||||
SignalingEvent::AssistCommand(assist::Command::Allow) => { if let Some(s) = assist.as_mut() { s.allow()?; } }
|
||||
SignalingEvent::AssistCommand(assist::Command::Deny) => { if let Some(s) = assist.as_mut() { s.deny()?; } }
|
||||
SignalingEvent::AssistCommand(assist::Command::Verify(v)) => { if let Some(s) = assist.as_mut() { s.set_verify(v)?; } }
|
||||
SignalingEvent::AssistCommand(assist::Command::Refresh(r)) => { if let Some(s) = assist.as_mut() { s.set_refresh(r)?; } }
|
||||
SignalingEvent::AssistCommand(assist::Command::Custom(c)) => { if let Some(s) = assist.as_mut() { s.set_custom(c)?; } }
|
||||
SignalingEvent::AssistCommand(assist::Command::Logout) => {
|
||||
if let Some(s) = assist.as_mut().filter(|s| s.is_account()) {
|
||||
s.logout().await;
|
||||
RESTART.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
SignalingEvent::AssistCommand(assist::Command::Reset) => { if let Some(s) = assist.as_mut() { s.reset()?; } }
|
||||
SignalingEvent::AssistTick => {
|
||||
let mut sessions = webrtc_sessions.lock().await;
|
||||
let ended: Vec<_> = sessions.iter().filter(|(_, s)| matches!(s.pc.connection_state(),
|
||||
::webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState::Closed |
|
||||
::webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState::Failed)).map(|(id, _)| id.clone()).collect();
|
||||
let mut desktop_ended = false;
|
||||
for id in ended { if let Some(s) = sessions.remove(&id) { desktop_ended |= s.desktop; let _ = s.pc.close().await; } }
|
||||
if desktop_ended && !sessions.values().any(|s| s.desktop) { if let Some(s) = assist.as_mut() { s.session_ended()?; } }
|
||||
if let Some(s) = assist.as_mut() { s.tick()?; }
|
||||
}
|
||||
SignalingEvent::Connected => {
|
||||
log::info!("Signaling handshake established.");
|
||||
}
|
||||
SignalingEvent::RoomInfoAck(val) => {
|
||||
log::info!(
|
||||
"RoomInfo acknowledged by NetEase server: room_id={}",
|
||||
val.get("room_id")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("unknown")
|
||||
);
|
||||
}
|
||||
SignalingEvent::RoomInfoAck(_) => { log::info!("RoomInfo acknowledged by NetEase server"); }
|
||||
SignalingEvent::DeviceInfoChanged(val) => {
|
||||
if assist.is_some() {
|
||||
// Shape only (type value + key names), never field values: guest challenges carry salts/ids.
|
||||
let keys = |v: Option<&serde_json::Value>| v.and_then(|v| v.as_object()).map(|o| o.keys().cloned().collect::<Vec<_>>()).unwrap_or_default();
|
||||
log::debug!("Assist bmsg_push shape: type={:?} keys={:?} data_keys={:?}",
|
||||
val.get("type").and_then(serde_json::Value::as_str), keys(Some(&val)), keys(val.get("data")));
|
||||
}
|
||||
if val.get("type").and_then(serde_json::Value::as_str) == Some("get_control_mode") {
|
||||
if let Some(s) = assist.as_mut() {
|
||||
match s.control_mode(val.get("data").unwrap_or(&serde_json::Value::Null)).await {
|
||||
Ok(()) => log::info!("Assist control mode reported"),
|
||||
Err(error) => log::warn!("Assist control mode report failed: {error}"),
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if val.get("type").and_then(serde_json::Value::as_str) == Some("remote_control") {
|
||||
if let Some(s) = assist.as_mut() {
|
||||
if let Err(error) = s.challenge(val.get("data").unwrap_or(&serde_json::Value::Null)).await {
|
||||
log::warn!("Assist challenge failed: {error}");
|
||||
}
|
||||
if s.renewed { break; }
|
||||
}
|
||||
continue;
|
||||
}
|
||||
log::info!(
|
||||
"Device status synchronized: status={:?}, availability={:?}",
|
||||
val.get("data")
|
||||
@@ -394,18 +591,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
|
||||
SignalingEvent::Soac(soac) => {
|
||||
log::info!(
|
||||
"SOAC signaling received: type={}, ice_id={:?}",
|
||||
soac.msg_type,
|
||||
soac.ice_id
|
||||
);
|
||||
log::info!("SOAC signaling received: offer={} candidate={}", soac.msg_type == "offer", soac.msg_type == "candidate");
|
||||
// Guest host: every peer is an assist peer. A logged-in host must keep serving its owner;
|
||||
// assist peers there are already gated by the cloud (allow_control / code check).
|
||||
if assist.as_ref().is_some_and(|s| !s.is_account() && !s.allowed) { continue; }
|
||||
let ice = soac.ice_id.as_ref().map(|v| v.as_str().map(str::to_owned).unwrap_or_else(|| v.to_string())).unwrap_or_default();
|
||||
let mut sessions = webrtc_sessions.lock().await;
|
||||
// Drop peers that already ended.
|
||||
let ended: Vec<String> = sessions.iter().filter(|(_, s)| matches!(s.pc.connection_state(),
|
||||
::webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState::Closed |
|
||||
::webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState::Failed)).map(|(k, _)| k.clone()).collect();
|
||||
for k in ended { if let Some(old) = sessions.remove(&k) { let _ = old.pc.close().await; } }
|
||||
let mut desktop_ended = false;
|
||||
for k in ended { if let Some(old) = sessions.remove(&k) { desktop_ended |= old.desktop; let _ = old.pc.close().await; } }
|
||||
if desktop_ended && !sessions.values().any(|s| s.desktop) { if let Some(s) = assist.as_mut() { s.session_ended()?; } }
|
||||
if let Some(s) = assist.as_mut() { s.tick()?; }
|
||||
|
||||
if soac.msg_type == "offer" {
|
||||
let (capture_type,transport) = capture_types.remove(&ice).or_else(|| next_capture_type.take()).unwrap_or((1,crate::session_ice::SessionIce::default()));
|
||||
@@ -439,7 +638,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// current desktop's authorized Portal input session.
|
||||
if desktop { input.bind_portal(session_capture.portal.clone()); }
|
||||
match WebRtcSession::new(session_capture, input.clone(), signaling_client.clone(), desktop, transport).await {
|
||||
Ok(sess) => match sess.handle_offer(&soac).await {
|
||||
Ok(sess) => {
|
||||
// Register before awaiting SDP: shutdown can always close
|
||||
// a peer whose answer may already be queued to the viewer.
|
||||
sessions.insert(ice.clone(), sess);
|
||||
let offer = sessions.get(&ice).expect("registered peer").handle_offer(&soac).await;
|
||||
match offer {
|
||||
Ok(answer_sdp) => {
|
||||
log::info!("Local SDP Answer generated, emitting soac response...");
|
||||
let resp = SoacMessage {
|
||||
@@ -454,15 +658,17 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
app_control_id: soac.app_control_id.clone(),
|
||||
};
|
||||
if let Err(e) = signaling_client.emit_soac(resp).await { log::error!("Answer signaling send failed: {}", e); }
|
||||
sessions.insert(ice, sess);
|
||||
}
|
||||
Err(e) => { log::error!("Failed to handle offer: {}", e); let _ = sess.pc.close().await; }
|
||||
},
|
||||
Err(e) => log::error!("Create peer failed: {}", e),
|
||||
Err(_) => {
|
||||
log::error!("Failed to handle offer (details omitted)");
|
||||
if let Some(session) = sessions.remove(&ice) { let _ = session.pc.close().await; }
|
||||
}
|
||||
}},
|
||||
Err(_) => log::error!("Create peer failed (details omitted)"),
|
||||
}
|
||||
} else if soac.msg_type == "candidate" {
|
||||
if let Some(sess) = sessions.get(&ice) {
|
||||
if let Err(e) = sess.add_candidate(&soac).await { log::error!("Remote ICE candidate failed: {}", e); }
|
||||
if let Err(e) = sess.add_candidate(&soac).await { let _ = e; log::error!("Remote ICE candidate failed (details omitted)"); }
|
||||
} else {
|
||||
log::warn!("Remote ICE candidate for unknown connection");
|
||||
}
|
||||
@@ -478,11 +684,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
_ => sessions.keys().cloned().collect(),
|
||||
};
|
||||
log::info!("Remote controller disconnected: keys={:?} ice_matched={} closing={}", keys, ice.as_ref().is_some_and(|i| sessions.contains_key(i)), targets.len());
|
||||
let mut desktop_ended = false;
|
||||
for k in targets {
|
||||
if let Some(old) = sessions.remove(&k) {
|
||||
desktop_ended |= old.desktop;
|
||||
if let Err(e) = old.pc.close().await { log::warn!("Close released peer failed: {}", e); }
|
||||
}
|
||||
}
|
||||
if desktop_ended && !sessions.values().any(|s| s.desktop) { if let Some(s) = assist.as_mut() { s.session_ended()?; } }
|
||||
if let Some(s) = assist.as_mut() { s.tick()?; }
|
||||
}
|
||||
SignalingEvent::Disconnected => {
|
||||
capture_types.clear();
|
||||
|
||||
+8
-3
@@ -32,6 +32,9 @@ pub struct SoacMessage {
|
||||
}
|
||||
|
||||
pub enum SignalingEvent {
|
||||
Stop,
|
||||
AssistCommand(crate::assist::Command),
|
||||
AssistTick,
|
||||
Connected,
|
||||
RoomInfoAck(Value),
|
||||
DeviceInfoChanged(Value),
|
||||
@@ -119,7 +122,7 @@ impl SignalingClient {
|
||||
.await
|
||||
.map_err(|e| format!("WS connect failed: {}", e))?;
|
||||
|
||||
log::info!("Connected to Engine.IO / Socket.IO at {}", ws_url);
|
||||
log::info!("Connected to Engine.IO / Socket.IO");
|
||||
let (mut write, mut read) = ws_stream.split();
|
||||
let (tx_outgoing, mut rx_outgoing) = mpsc::channel::<String>(32);
|
||||
|
||||
@@ -127,7 +130,8 @@ impl SignalingClient {
|
||||
let writer=tokio::spawn(async move {
|
||||
while let Some(msg) = rx_outgoing.recv().await {
|
||||
if let Err(e) = write.send(Message::Text(msg)).await {
|
||||
log::warn!("WS send error: {}", e);
|
||||
let _ = e;
|
||||
log::warn!("WS send failed (details omitted)");
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -267,7 +271,8 @@ impl SignalingClient {
|
||||
.await;
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Failed to deserialize SoacMessage: error={}, raw={}", e, data);
|
||||
let _ = e;
|
||||
log::error!("Failed to deserialize SoacMessage (payload omitted)");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -839,7 +839,7 @@ impl WebRtcSession {
|
||||
ctx.client_id = soac.client_id.clone();
|
||||
ctx.ice_id = soac.ice_id.clone();
|
||||
ctx.app_control_id = soac.app_control_id.clone();
|
||||
log::info!("Updated WebRTC session context: client_id={:?}, ice_id={:?}", ctx.client_id, ctx.ice_id);
|
||||
log::info!("Updated WebRTC session context: client_id_present={} ice_id_present={}", ctx.client_id.is_some(), ctx.ice_id.is_some());
|
||||
}
|
||||
let mut sdp_str = soac.sdp.clone().unwrap_or_default();
|
||||
if sdp_str.is_empty() {
|
||||
|
||||
Reference in new issue
Block a user