feat: add optional Windows virtual USB ADB device
This commit is contained in:
1 parent
2abfb63da9
commit
08d60de364
23 files changed
+802
-26
No files matched your search
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "ads-usb"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
clap.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
@@ -0,0 +1,15 @@
|
||||
# ads-usb:可选虚拟 ADB USB 设备
|
||||
|
||||
源码在 `src/`(Rust);`main.rs` 管理回环监听和会话,`descriptors.rs` 提供 ADB/WinUSB 描述符,`protocol.rs` 实现 USB/IP 1.1.1、控制请求、批量传输、URB 取消与 ADB 帧适配。依赖 USBip 虚拟控制器的 Windows 后端已验证,程序本身不包含内核驱动。
|
||||
|
||||
```powershell
|
||||
cargo build -p ads-usb --release --locked
|
||||
# 先运行 ads-client --no-auto-connect,取得远端设备租约
|
||||
.\bin\ads-usb.exe --listen 127.0.0.1:3240 --upstream 127.0.0.1:15555 --serial ADS-home-phone
|
||||
& 'C:\Program Files\USBip\usbip.exe' --tcp-port 3240 attach -r 127.0.0.1 -b 1-1 --terse --once
|
||||
adb -s ADS-home-phone shell getprop ro.product.model
|
||||
```
|
||||
|
||||
USB/IP 只监听回环,不能向公网发布。进程只允许一个导入者,上游直接使用本机 ads-client 的 adbd 字节流,不是 ADB server 5037。无需远程手机实际 USB 插线;远端可以仍通过 LAN adbd 接入。关闭本次 ads-usb 进程会断开本次虚拟设备。
|
||||
|
||||
仅提供 ADB 接口;不提供 MTP、fastboot 或整台手机 USB 透传。Windows 安装、使用和验证见 [windows-usb.md](../docs/windows-usb.md)。
|
||||
@@ -0,0 +1,122 @@
|
||||
//! One high-speed vendor-specific ADB interface, no MTP or other USB functions.
|
||||
pub const BUS_ID: &str = "1-1";
|
||||
pub const GUID: &str = "{F72FE0D4-CBCB-407D-8814-9ED673D0DD6B}";
|
||||
pub const DEVICE: &[u8] = &[
|
||||
18, 1, 0, 2, 0, 0, 0, 64, 0xd1, 0x18, 0xe7, 0x4e, 0, 1, 1, 2, 3, 1,
|
||||
];
|
||||
pub const CONFIG: &[u8] = &[
|
||||
9, 2, 32, 0, 1, 1, 0, 0x80, 50, 9, 4, 0, 0, 2, 0xff, 0x42, 1, 0, 7, 5, 0x81, 2, 0, 2, 0, 7, 5,
|
||||
0x02, 2, 0, 2, 0,
|
||||
];
|
||||
pub fn string(value: &str) -> Vec<u8> {
|
||||
let body: Vec<u8> = value.encode_utf16().flat_map(u16::to_le_bytes).collect();
|
||||
let mut out = vec![(body.len() + 2) as u8, 3];
|
||||
out.extend(body);
|
||||
out
|
||||
}
|
||||
pub fn compat_id() -> Vec<u8> {
|
||||
let mut out = vec![0; 40];
|
||||
out[..4].copy_from_slice(&40u32.to_le_bytes());
|
||||
out[4..6].copy_from_slice(&0x100u16.to_le_bytes());
|
||||
out[6..8].copy_from_slice(&4u16.to_le_bytes());
|
||||
out[8] = 1;
|
||||
out[17] = 1;
|
||||
out[18..24].copy_from_slice(b"WINUSB");
|
||||
out
|
||||
}
|
||||
pub fn properties() -> Vec<u8> {
|
||||
let name: Vec<u8> = "DeviceInterfaceGUIDs\0"
|
||||
.encode_utf16()
|
||||
.flat_map(u16::to_le_bytes)
|
||||
.collect();
|
||||
let data: Vec<u8> = format!("{GUID}\0\0")
|
||||
.encode_utf16()
|
||||
.flat_map(u16::to_le_bytes)
|
||||
.collect();
|
||||
let section = 14 + name.len() + data.len();
|
||||
let mut out = Vec::new();
|
||||
out.extend(((10 + section) as u32).to_le_bytes());
|
||||
out.extend(0x100u16.to_le_bytes());
|
||||
out.extend(5u16.to_le_bytes());
|
||||
out.extend(1u16.to_le_bytes());
|
||||
out.extend((section as u32).to_le_bytes());
|
||||
out.extend(7u32.to_le_bytes());
|
||||
out.extend((name.len() as u16).to_le_bytes());
|
||||
out.extend(name);
|
||||
out.extend((data.len() as u32).to_le_bytes());
|
||||
out.extend(data);
|
||||
out
|
||||
}
|
||||
pub fn control(setup: [u8; 8], serial: &str, configured: &mut u8) -> Result<Vec<u8>, i32> {
|
||||
let [kind, request, vl, vh, il, ih, ll, lh] = setup;
|
||||
let value = u16::from_le_bytes([vl, vh]);
|
||||
let index = u16::from_le_bytes([il, ih]);
|
||||
let length = u16::from_le_bytes([ll, lh]) as usize;
|
||||
let mut data = match (kind, request) {
|
||||
(0x80, 6) => match (vh, vl) {
|
||||
(1, 0) => DEVICE.to_vec(),
|
||||
(2, 0) => CONFIG.to_vec(),
|
||||
(3, 0) => vec![4, 3, 9, 4],
|
||||
(3, 1) => string("TTSTD"),
|
||||
(3, 2) => string("ADS Virtual ADB"),
|
||||
(3, 3) => string(serial),
|
||||
(3, 0xee) => {
|
||||
let mut v = string("MSFT100");
|
||||
v.extend([0x20, 0]);
|
||||
v[0] = 18;
|
||||
v
|
||||
}
|
||||
(6, 0) => vec![10, 6, 0, 2, 0, 0, 0, 64, 1, 0],
|
||||
_ => return Err(-32),
|
||||
},
|
||||
(0xc0, 0x20) if index == 4 => compat_id(),
|
||||
(0xc0 | 0xc1, 0x20) if index == 5 => properties(),
|
||||
(0x80 | 0x81 | 0x82, 0) => vec![0, 0],
|
||||
(0, 5) if value <= 127 => vec![],
|
||||
(0, 9) if value <= 1 => {
|
||||
*configured = value as u8;
|
||||
vec![]
|
||||
}
|
||||
(0x80, 8) => vec![*configured],
|
||||
(0x81, 10) if index == 0 => vec![0],
|
||||
(1, 11) if value == 0 && index == 0 => vec![],
|
||||
(2, 1) if value == 0 && (index == 0x81 || index == 2) => vec![],
|
||||
_ => return Err(-32),
|
||||
};
|
||||
data.truncate(length);
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn descriptors_are_consistent() {
|
||||
assert_eq!(CONFIG.len(), 32);
|
||||
assert_eq!(CONFIG[20], 0x81);
|
||||
assert_eq!(CONFIG[27], 2);
|
||||
assert_eq!(DEVICE.len(), 18);
|
||||
assert_eq!(compat_id().len(), 40);
|
||||
let p = properties();
|
||||
assert_eq!(
|
||||
u32::from_le_bytes(p[..4].try_into().unwrap()) as usize,
|
||||
p.len()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn control_bounds_and_stalls() {
|
||||
let mut c = 0;
|
||||
assert_eq!(
|
||||
control([0x80, 6, 0, 1, 0, 0, 8, 0], "ADS-test", &mut c)
|
||||
.unwrap()
|
||||
.len(),
|
||||
8
|
||||
);
|
||||
assert!(control([0x80, 6, 0, 15, 0, 0, 255, 0], "ADS-test", &mut c).is_err());
|
||||
assert_eq!(
|
||||
control([0, 9, 1, 0, 0, 0, 0, 0], "ADS-test", &mut c).unwrap(),
|
||||
Vec::<u8>::new()
|
||||
);
|
||||
assert_eq!(c, 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
mod descriptors;
|
||||
mod protocol;
|
||||
use anyhow::{bail, Context, Result};
|
||||
use clap::Parser;
|
||||
use std::{
|
||||
net::SocketAddr,
|
||||
sync::{atomic::AtomicBool, Arc},
|
||||
};
|
||||
use tokio::{net::TcpListener, task::JoinSet};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
version,
|
||||
about = "Local virtual ADB USB device exported to the Windows USB/IP controller"
|
||||
)]
|
||||
struct Args {
|
||||
#[arg(long, default_value = "127.0.0.1:3240")]
|
||||
listen: SocketAddr,
|
||||
/// Existing ads-client raw adbd endpoint; must be loopback
|
||||
#[arg(long)]
|
||||
upstream: SocketAddr,
|
||||
#[arg(long, default_value = "ADS-home-phone")]
|
||||
serial: String,
|
||||
}
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter("ads_usb=info")
|
||||
.init();
|
||||
let args = Args::parse();
|
||||
if !args.listen.ip().is_loopback()
|
||||
|| !args.upstream.ip().is_loopback()
|
||||
|| args.listen.port() == 0
|
||||
|| args.upstream.port() == 0
|
||||
|| args.listen == args.upstream
|
||||
{
|
||||
bail!("USB/IP and upstream must be distinct loopback endpoints")
|
||||
}
|
||||
if args.serial.is_empty()
|
||||
|| args.serial.len() > 120
|
||||
|| !args
|
||||
.serial
|
||||
.bytes()
|
||||
.all(|v| v.is_ascii_alphanumeric() || b"-_.".contains(&v))
|
||||
{
|
||||
bail!("serial must use ASCII letters, digits, -, _ or . (1-120 bytes)")
|
||||
}
|
||||
let listener = TcpListener::bind(args.listen)
|
||||
.await
|
||||
.context("cannot bind private USB/IP endpoint")?;
|
||||
let occupied = Arc::new(AtomicBool::new(false));
|
||||
let mut tasks = JoinSet::new();
|
||||
tracing::info!(endpoint=%args.listen,serial=%args.serial,"virtual ADB USB device ready");
|
||||
loop {
|
||||
tokio::select! {
|
||||
incoming=listener.accept()=>{
|
||||
let (socket,_)=incoming?;if tasks.len()>=16{drop(socket);continue}
|
||||
let serial=args.serial.clone();let occupied=occupied.clone();let target=args.upstream;
|
||||
tasks.spawn(async move{if let Err(error)=protocol::serve(socket,target,serial,occupied).await{tracing::warn!(%error,"USB session ended");}});
|
||||
},
|
||||
_=tasks.join_next(),if !tasks.is_empty()=>{},
|
||||
_=tokio::signal::ctrl_c()=>return Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
use crate::descriptors;
|
||||
use anyhow::{bail, Context, Result};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
net::SocketAddr,
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::{
|
||||
tcp::{OwnedReadHalf, OwnedWriteHalf},
|
||||
TcpStream,
|
||||
},
|
||||
sync::mpsc,
|
||||
task::JoinSet,
|
||||
time::timeout,
|
||||
};
|
||||
const MAX: usize = 1024 * 1024;
|
||||
const IO: Duration = Duration::from_secs(30);
|
||||
const DEV: u32 = 0x10001;
|
||||
fn be(data: &[u8], offset: usize) -> u32 {
|
||||
u32::from_be_bytes(data[offset..offset + 4].try_into().unwrap())
|
||||
}
|
||||
fn device() -> Vec<u8> {
|
||||
let mut v = vec![0; 312];
|
||||
let path = b"/ads/virtual/1-1";
|
||||
v[..path.len()].copy_from_slice(path);
|
||||
v[256..259].copy_from_slice(descriptors::BUS_ID.as_bytes());
|
||||
for (offset, value) in [(288, 1u32), (292, 1), (296, 3)] {
|
||||
v[offset..offset + 4].copy_from_slice(&value.to_be_bytes());
|
||||
}
|
||||
v[300..302].copy_from_slice(&0x18d1u16.to_be_bytes());
|
||||
v[302..304].copy_from_slice(&0x4ee7u16.to_be_bytes());
|
||||
v[304..306].copy_from_slice(&0x100u16.to_be_bytes());
|
||||
v[309..312].copy_from_slice(&[1, 1, 1]);
|
||||
v
|
||||
}
|
||||
async fn op(socket: &mut TcpStream, code: u16, status: u32) -> Result<()> {
|
||||
let mut header = vec![];
|
||||
header.extend(0x111u16.to_be_bytes());
|
||||
header.extend(code.to_be_bytes());
|
||||
header.extend(status.to_be_bytes());
|
||||
timeout(IO, socket.write_all(&header)).await??;
|
||||
Ok(())
|
||||
}
|
||||
struct Occupied(Arc<AtomicBool>);
|
||||
impl Drop for Occupied {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(false, Ordering::Release);
|
||||
}
|
||||
}
|
||||
pub async fn serve(
|
||||
mut socket: TcpStream,
|
||||
target: SocketAddr,
|
||||
serial: String,
|
||||
occupied: Arc<AtomicBool>,
|
||||
) -> Result<()> {
|
||||
socket.set_nodelay(true)?;
|
||||
let mut header = [0; 8];
|
||||
timeout(Duration::from_secs(5), socket.read_exact(&mut header)).await??;
|
||||
if header[..2] != [1, 0x11] || be(&header, 4) != 0 {
|
||||
bail!("invalid USB/IP handshake")
|
||||
}
|
||||
match u16::from_be_bytes([header[2], header[3]]) {
|
||||
0x8005 => {
|
||||
op(&mut socket, 5, 0).await?;
|
||||
socket.write_all(&1u32.to_be_bytes()).await?;
|
||||
socket.write_all(&device()).await?;
|
||||
socket.write_all(&[0xff, 0x42, 1, 0]).await?;
|
||||
Ok(())
|
||||
}
|
||||
0x8003 => {
|
||||
let mut bus = [0; 32];
|
||||
timeout(Duration::from_secs(5), socket.read_exact(&mut bus)).await??;
|
||||
let mut expected = [0; 32];
|
||||
expected[..3].copy_from_slice(descriptors::BUS_ID.as_bytes());
|
||||
if bus != expected {
|
||||
op(&mut socket, 3, 1).await?;
|
||||
bail!("unknown USB bus ID")
|
||||
}
|
||||
if occupied
|
||||
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
|
||||
.is_err()
|
||||
{
|
||||
op(&mut socket, 3, 2).await?;
|
||||
bail!("virtual USB device already imported")
|
||||
}
|
||||
let _guard = Occupied(occupied);
|
||||
op(&mut socket, 3, 0).await?;
|
||||
socket.write_all(&device()).await?;
|
||||
imported(socket, target, &serial).await
|
||||
}
|
||||
_ => bail!("unsupported USB/IP operation"),
|
||||
}
|
||||
}
|
||||
struct Request {
|
||||
header: [u8; 48],
|
||||
data: Vec<u8>,
|
||||
}
|
||||
async fn read_requests(mut read: OwnedReadHalf, tx: mpsc::Sender<Request>) -> Result<()> {
|
||||
loop {
|
||||
let mut header = [0; 48];
|
||||
read.read_exact(&mut header).await?;
|
||||
let command = be(&header, 0);
|
||||
if command != 1 && command != 2 {
|
||||
bail!("invalid USB/IP command")
|
||||
}
|
||||
let direction = be(&header, 12);
|
||||
let size = be(&header, 24) as usize;
|
||||
if command == 1 && (size > MAX || direction > 1 || !matches!(be(&header, 32), 0 | u32::MAX))
|
||||
{
|
||||
bail!("invalid or oversized URB")
|
||||
}
|
||||
let mut data = vec![
|
||||
0;
|
||||
if command == 1 && direction == 0 {
|
||||
size
|
||||
} else {
|
||||
0
|
||||
}
|
||||
];
|
||||
if !data.is_empty() {
|
||||
timeout(IO, read.read_exact(&mut data)).await??;
|
||||
}
|
||||
tx.send(Request { header, data })
|
||||
.await
|
||||
.context("USB request queue closed")?;
|
||||
}
|
||||
}
|
||||
// Preserve ADB USB transfer boundaries independently of TCP segmentation.
|
||||
async fn read_adb(mut read: OwnedReadHalf, tx: mpsc::Sender<Vec<u8>>) -> Result<()> {
|
||||
loop {
|
||||
let mut header = vec![0; 24];
|
||||
read.read_exact(&mut header).await?;
|
||||
let word = |n| u32::from_le_bytes(header[n..n + 4].try_into().unwrap());
|
||||
if word(0) ^ word(20) != u32::MAX {
|
||||
bail!("invalid ADB frame magic")
|
||||
}
|
||||
let size = word(12) as usize;
|
||||
if size > MAX {
|
||||
bail!("ADB payload exceeds 1 MiB")
|
||||
}
|
||||
tx.send(header).await.context("ADB receive queue closed")?;
|
||||
if size > 0 {
|
||||
let mut payload = vec![0; size];
|
||||
timeout(IO, read.read_exact(&mut payload)).await??;
|
||||
tx.send(payload).await.context("ADB receive queue closed")?;
|
||||
if size % 512 == 0 {
|
||||
tx.send(vec![]).await.context("ADB receive queue closed")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
async fn reply(
|
||||
write: &mut OwnedWriteHalf,
|
||||
request: &Request,
|
||||
status: i32,
|
||||
data: &[u8],
|
||||
actual: usize,
|
||||
) -> Result<()> {
|
||||
let mut header = [0; 48];
|
||||
header[..4].copy_from_slice(&3u32.to_be_bytes());
|
||||
header[4..8].copy_from_slice(&request.header[4..8]);
|
||||
header[20..24].copy_from_slice(&status.to_be_bytes());
|
||||
header[24..28].copy_from_slice(&(actual as u32).to_be_bytes());
|
||||
timeout(IO, async {
|
||||
write.write_all(&header).await?;
|
||||
write.write_all(data).await
|
||||
})
|
||||
.await??;
|
||||
Ok(())
|
||||
}
|
||||
async fn unlink(write: &mut OwnedWriteHalf, request: &Request, status: i32) -> Result<()> {
|
||||
let mut header = [0; 48];
|
||||
header[..4].copy_from_slice(&4u32.to_be_bytes());
|
||||
header[4..8].copy_from_slice(&request.header[4..8]);
|
||||
header[20..24].copy_from_slice(&status.to_be_bytes());
|
||||
timeout(IO, write.write_all(&header)).await??;
|
||||
Ok(())
|
||||
}
|
||||
async fn imported(socket: TcpStream, target: SocketAddr, serial: &str) -> Result<()> {
|
||||
let (read, mut write) = socket.into_split();
|
||||
let (tx, mut requests) = mpsc::channel(32);
|
||||
let mut tasks = JoinSet::new();
|
||||
tasks.spawn(read_requests(read, tx));
|
||||
let (data_tx, mut data_rx) = mpsc::channel(16);
|
||||
let mut backend: Option<OwnedWriteHalf> = None;
|
||||
let mut pending: VecDeque<Request> = VecDeque::new();
|
||||
let mut bytes: VecDeque<Vec<u8>> = VecDeque::new();
|
||||
let mut offset = 0;
|
||||
let mut configured = 0;
|
||||
loop {
|
||||
while !pending.is_empty() && !bytes.is_empty() {
|
||||
let request = pending.pop_front().unwrap();
|
||||
let front = bytes.front().unwrap();
|
||||
let size = (be(&request.header, 24) as usize).min(front.len() - offset);
|
||||
reply(&mut write, &request, 0, &front[offset..offset + size], size).await?;
|
||||
offset += size;
|
||||
if offset == front.len() {
|
||||
bytes.pop_front();
|
||||
offset = 0;
|
||||
}
|
||||
}
|
||||
tokio::select! {
|
||||
request=requests.recv()=>{
|
||||
let request=request.context("USB/IP disconnected")?;let h=&request.header;
|
||||
if be(h,0)==2{
|
||||
let seq=be(h,20);let found=pending.iter().position(|r|be(&r.header,4)==seq);
|
||||
if let Some(index)=found{pending.remove(index);}
|
||||
unlink(&mut write,&request,if found.is_some(){-104}else{0}).await?;continue
|
||||
}
|
||||
if be(h,8)!=DEV{bail!("incorrect device ID")}
|
||||
if pending.iter().any(|r|be(&r.header,4)==be(h,4)){bail!("duplicate pending sequence")}
|
||||
let direction=be(h,12);let ep=be(h,16);let size=be(h,24) as usize;
|
||||
if ep==0{
|
||||
let result=descriptors::control(h[40..48].try_into().unwrap(),serial,&mut configured);
|
||||
match result{Ok(data)=>{let data=&data[..data.len().min(size)];reply(&mut write,&request,0,if direction==1{data}else{&[]},if direction==1{data.len()}else{request.data.len()}).await?;},Err(status)=>reply(&mut write,&request,status,&[],0).await?}
|
||||
}else if (ep==1&&direction==1)||(ep==2&&direction==0){
|
||||
if size==0{reply(&mut write,&request,0,&[],0).await?;continue}
|
||||
if backend.is_none(){
|
||||
let socket=timeout(Duration::from_secs(10),TcpStream::connect(target)).await??;socket.set_nodelay(true)?;
|
||||
let(read,write)=socket.into_split();backend=Some(write);
|
||||
tasks.spawn(read_adb(read,data_tx.clone()));
|
||||
}
|
||||
if direction==0{
|
||||
timeout(IO,backend.as_mut().unwrap().write_all(&request.data)).await??;
|
||||
reply(&mut write,&request,0,&[],request.data.len()).await?;
|
||||
}else{
|
||||
if pending.len()>=64{bail!("too many pending bulk reads")}
|
||||
pending.push_back(request);
|
||||
}
|
||||
}else{reply(&mut write,&request,-32,&[],0).await?;}
|
||||
},
|
||||
data=data_rx.recv(),if bytes.len()<16=>{bytes.push_back(data.context("ADB disconnected")?);},
|
||||
result=tasks.join_next()=>{return result.context("USB worker missing")?.context("USB worker failed")?;},
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user