208 lines
7.2 KiB
Rust
208 lines
7.2 KiB
Rust
use ads_core::{
|
|
dial, init_logging, next_control, relay, valid_device_id, validate_token, NetworkArgs,
|
|
};
|
|
use anyhow::{bail, Context, Result};
|
|
use clap::Parser;
|
|
use std::{net::SocketAddr, path::PathBuf, sync::Arc, time::Duration};
|
|
use tokio::{
|
|
net::TcpListener,
|
|
process::Command,
|
|
sync::watch,
|
|
task::JoinSet,
|
|
time::{sleep, timeout},
|
|
};
|
|
use tracing::{info, warn};
|
|
|
|
#[derive(Parser)]
|
|
#[command(
|
|
version,
|
|
about = "Local ADS daemon: expose a remote phone as a local adb connect endpoint"
|
|
)]
|
|
struct Args {
|
|
#[command(flatten)]
|
|
network: NetworkArgs,
|
|
#[arg(long, env = "ADS_CLIENT_TOKEN", hide_env_values = true)]
|
|
token: String,
|
|
#[arg(long)]
|
|
device: String,
|
|
/// Local endpoint; loopback addresses only
|
|
#[arg(long, default_value = "127.0.0.1:15555")]
|
|
listen: SocketAddr,
|
|
#[arg(long, default_value = "adb")]
|
|
adb: PathBuf,
|
|
/// Do not periodically invoke local adb connect (useful for manual control/tests)
|
|
#[arg(long)]
|
|
no_auto_connect: bool,
|
|
/// Prefer direct WebRTC or force WSS relay nodes
|
|
#[arg(long, default_value = "auto", value_parser = ["auto", "relay"])]
|
|
transport: String,
|
|
/// Exclude LAN/VPN host candidates (diagnostic WAN test)
|
|
#[arg(long)]
|
|
p2p_public_only: bool,
|
|
/// Machine-readable active transport state for desktop clients
|
|
#[arg(long)]
|
|
status_file: Option<PathBuf>,
|
|
/// Optional lease readiness file for virtual USB consumers (no secret tickets)
|
|
#[arg(long)]
|
|
lease_status_file: Option<PathBuf>,
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
struct LeaseState {
|
|
id: String,
|
|
protocol: u8,
|
|
}
|
|
|
|
fn publish_lease(args: &Args, ready: bool) {
|
|
if let Some(file) = &args.lease_status_file {
|
|
let temp = file.with_extension("tmp");
|
|
if std::fs::write(&temp, if ready { "true" } else { "false" }).is_ok() {
|
|
let _ = std::fs::rename(temp, file);
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn lease_once(args: &Args, state: &watch::Sender<Option<LeaseState>>) -> Result<()> {
|
|
let mut ws = dial(
|
|
args.network
|
|
.url("/v1/lease", &[("device", &args.device), ("v", "2")])?,
|
|
&args.token,
|
|
args.network.connect_address.as_deref(),
|
|
)
|
|
.await?;
|
|
let response = next_control(&mut ws).await?;
|
|
if response.kind != "leased" {
|
|
bail!("expected leased response");
|
|
}
|
|
let id = response.lease.context("missing lease ticket")?;
|
|
publish_lease(args, true);
|
|
state.send_replace(Some(LeaseState {
|
|
id,
|
|
protocol: response.protocol,
|
|
}));
|
|
info!(device = %args.device, endpoint = %args.listen, "device leased; local tunnel ready");
|
|
loop {
|
|
next_control(&mut ws).await?;
|
|
}
|
|
}
|
|
|
|
async fn maintain_lease(args: Arc<Args>, state: watch::Sender<Option<LeaseState>>) {
|
|
let mut delay = 1;
|
|
loop {
|
|
let started = std::time::Instant::now();
|
|
if let Err(error) = lease_once(&args, &state).await {
|
|
warn!(%error, "lease unavailable; reconnecting");
|
|
}
|
|
publish_lease(&args, false);
|
|
state.send_replace(None);
|
|
if started.elapsed() > Duration::from_secs(30) {
|
|
delay = 1;
|
|
}
|
|
sleep(Duration::from_secs(delay)).await;
|
|
delay = (delay * 2).min(30);
|
|
}
|
|
}
|
|
|
|
async fn adb_command(args: &Args, action: &str) -> Result<()> {
|
|
let output = timeout(
|
|
Duration::from_secs(8),
|
|
Command::new(&args.adb)
|
|
.env_remove("ADB_SERVER_SOCKET")
|
|
.env_remove("ANDROID_ADB_SERVER_ADDRESS")
|
|
.env_remove("ANDROID_ADB_SERVER_PORT")
|
|
.arg(action)
|
|
.arg(args.listen.to_string())
|
|
.kill_on_drop(true)
|
|
.output(),
|
|
)
|
|
.await
|
|
.context("adb command timed out")??;
|
|
if !output.status.success() {
|
|
bail!(
|
|
"adb command failed: {}",
|
|
String::from_utf8_lossy(&output.stderr).trim()
|
|
);
|
|
}
|
|
// adb can report a connection failure with exit code 0; retain its text.
|
|
let message = String::from_utf8_lossy(&output.stdout);
|
|
info!(output = %message.trim(), "local adb");
|
|
Ok(())
|
|
}
|
|
|
|
async fn maintain_adb(args: Arc<Args>, state: watch::Receiver<Option<LeaseState>>) {
|
|
loop {
|
|
if state.borrow().is_some() {
|
|
if let Err(error) = adb_command(&args, "connect").await {
|
|
warn!(%error, "local adb connect failed");
|
|
}
|
|
}
|
|
sleep(Duration::from_secs(5)).await;
|
|
}
|
|
}
|
|
|
|
async fn accept_connections(
|
|
args: Arc<Args>,
|
|
listener: TcpListener,
|
|
state: watch::Receiver<Option<LeaseState>>,
|
|
) -> Result<()> {
|
|
let status = ads_core::transport::TransportStatus::new(args.status_file.clone());
|
|
let mut tasks = JoinSet::new();
|
|
loop {
|
|
tokio::select! {
|
|
accepted = listener.accept() => {
|
|
let (tcp, _) = accepted?;
|
|
let lease = state.borrow().clone();
|
|
let Some(lease) = lease else { drop(tcp); continue; };
|
|
if tasks.len() >= 32 { drop(tcp); warn!("local stream limit reached"); continue; }
|
|
let args = args.clone();
|
|
let status = status.stream();
|
|
tasks.spawn(async move {
|
|
let result = async {
|
|
let path = if lease.protocol >= 2 { "/v2/connect" } else { "/v1/connect" };
|
|
let public_only = if args.p2p_public_only { "1" } else { "0" };
|
|
let url = args.network.url(path, &[("device", &args.device), ("lease", &lease.id), ("public_only", public_only)])?;
|
|
let ws = dial(url, &args.token, args.network.connect_address.as_deref()).await?;
|
|
if lease.protocol >= 2 {
|
|
ads_core::transport::client_session(tcp, ws, &args.network, &args.transport, &status).await
|
|
} else { status.set("compat", "controller-v1"); relay(tcp, ws).await }
|
|
}.await;
|
|
if let Err(error) = result { warn!(%error, "local device stream ended"); }
|
|
});
|
|
},
|
|
_ = tasks.join_next(), if !tasks.is_empty() => {},
|
|
}
|
|
}
|
|
}
|
|
|
|
#[tokio::main]
|
|
async fn main() -> Result<()> {
|
|
init_logging();
|
|
let args = Arc::new(Args::parse());
|
|
publish_lease(&args, false);
|
|
validate_token(&args.token)?;
|
|
if !valid_device_id(&args.device) {
|
|
bail!("invalid device ID");
|
|
}
|
|
if !args.listen.ip().is_loopback() || args.listen.port() == 0 {
|
|
bail!("--listen must use a loopback address and a nonzero port");
|
|
}
|
|
args.network.url("/v1/lease", &[])?;
|
|
let listener = TcpListener::bind(args.listen)
|
|
.await
|
|
.context("cannot bind local ADB endpoint")?;
|
|
let (sender, receiver) = watch::channel(None);
|
|
info!(endpoint = %args.listen, "listening; local adb will show this address after connection");
|
|
// Dropping these futures on shutdown closes control and data connections.
|
|
tokio::select! {
|
|
_ = maintain_lease(args.clone(), sender) => {},
|
|
_ = maintain_adb(args.clone(), receiver.clone()), if !args.no_auto_connect => {},
|
|
result = accept_connections(args.clone(), listener, receiver) => { result?; },
|
|
result = tokio::signal::ctrl_c() => { result?; },
|
|
}
|
|
if !args.no_auto_connect {
|
|
let _ = adb_command(&args, "disconnect").await;
|
|
}
|
|
info!("client stopping");
|
|
Ok(())
|
|
}
|