leejunyoung5819wayland-android-remote

공개

Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)

릴리스 APK 서명·R8, 데몬 감시 셸, USB ADB 모드 모듈, PC 설치 스크립트

- 동반 앱: 데몬을 감시 셸(setsid)로 띄워 비정상 종료 시 3초 뒤 재기동
- 릴리스 빌드: 저장소 밖 키로 디버그·릴리스 모두 서명, R8 축소·리소스 축소
- 데몬 숨은 API 반사 접근은 shell app_process 전용이라 lint 예외 처리
- src/adb.rs: 호스트 adb로 USB 기기에서 데몬을 띄우고 포워딩 (probe usb 로 실기기 확인)
- scripts/install.sh, packaging/: ~/.local 설치, 바탕화면 항목, 아이콘
작성자
LeeJunyoung
작성 시각
커밋
b5893f6451b744e955be370a166b7ada95431f27
부모
d09a636
이 시점의 파일 보기

변경된 파일 11개

+406-21
수정android/app/build.gradle.kts+31-1
@@ -1,7 +1,21 @@
1추가: import java.util.Properties
2추가:
13plugins {
24 alias(libs.plugins.android.application)
35}
46
7추가: /**
8추가: * 서명 키 정보. 저장소 밖(~/.config/android-remote-signing/keystore.properties, 또는
9추가: * ANDROID_REMOTE_SIGNING 환경 변수가 가리키는 파일)에 두고 커밋하지 않는다.
10추가: * 디버그 빌드도 같은 키로 서명해 디버그·릴리스 APK를 지우지 않고 서로 덮어 설치할 수 있게 한다.
11추가: */
12추가: val signingProps: Properties? = run {
13추가: val path = System.getenv("ANDROID_REMOTE_SIGNING")
14추가: ?: "${System.getProperty("user.home")}/.config/android-remote-signing/keystore.properties"
15추가: val f = file(path)
16추가: if (f.exists()) Properties().apply { f.inputStream().use { load(it) } } else null
17추가: }
18추가:
519android {
620 namespace = "com.androidremote"
721 compileSdk = 36
@@ -21,9 +35,25 @@ android {
2135 }
2236 }
2337
38추가: signingConfigs {
39추가: if (signingProps != null) {
40추가: create("shared") {
41추가: storeFile = file(signingProps.getProperty("storeFile"))
42추가: storePassword = signingProps.getProperty("storePassword")
43추가: keyAlias = signingProps.getProperty("keyAlias")
44추가: keyPassword = signingProps.getProperty("keyPassword")
45추가: }
46추가: }
47추가: }
48추가:
2449 buildTypes {
50추가: debug {
51추가: signingConfigs.findByName("shared")?.let { signingConfig = it }
52추가: }
2553 release {
26삭제: isMinifyEnabled = false
54추가: signingConfigs.findByName("shared")?.let { signingConfig = it }
55추가: isMinifyEnabled = true
56추가: isShrinkResources = true
2757 proguardFiles(
2858 getDefaultProguardFile("proguard-android-optimize.txt"),
2959 "proguard-rules.pro",
수정android/app/proguard-rules.pro+14-4
@@ -1,4 +1,14 @@
1삭제: # 데몬은 app_process로 직접 실행되므로 앱 코드에서 참조되지 않는다. 축소 시 지워지지 않게 유지한다.
2삭제: -keep class com.androidremote.daemon.DaemonMain {
3삭제: public static void main(java.lang.String[]);
4삭제: }
1추가: # 데몬은 app_process로 직접 실행되고 숨은 프레임워크 API를 리플렉션으로 부른다. 통째로 유지한다.
2추가: -keep class com.androidremote.daemon.** { *; }
3추가:
4추가: # 클립보드 리스너 AIDL 스텁. 실행 시에는 프레임워크의 같은 이름 클래스가 쓰인다.
5추가: -keep class android.content.IOnPrimaryClipChangedListener** { *; }
6추가:
7추가: # libadb-android는 Conscrypt를 이름으로 찾고(Class.forName), BouncyCastle과 spake2(JNI)를 쓴다.
8추가: -keep class io.github.muntashirakon.** { *; }
9추가: -keep class org.conscrypt.** { *; }
10추가: -keep class org.bouncycastle.** { *; }
11추가: -dontwarn org.conscrypt.**
12추가: -dontwarn org.bouncycastle.**
13추가: -dontwarn io.github.muntashirakon.**
14추가: -dontwarn com.android.org.conscrypt.**
수정android/app/src/main/java/com/androidremote/companion/Bootstrap.kt+16-11
@@ -70,21 +70,26 @@ object Bootstrap {
7070 }
7171
7272 /**
73삭제: * 이전 데몬을 끝내고 APK 안의 데몬을 setsid로 분리 실행한다. ADB 연결이 끊기거나 무선 디버깅이
74삭제: * 꺼져도 계속 돈다. 로그는 데몬 저장소의 daemon.log에 남긴다.
73추가: * 이전 감시 셸·데몬을 끝내고, setsid로 분리한 감시 셸이 데몬을 실행하게 한다. 데몬이 어떤
74추가: * 이유로든 끝나면 감시 셸이 3초 뒤 다시 띄운다(기획서 5.4 "데몬 비정상 종료 시 재기동").
75추가: * ADB 연결이 끊기거나 무선 디버깅이 꺼져도 계속 돈다. 로그는 데몬 저장소의 daemon.log에 남긴다.
76추가: *
77추가: * 명령 줄 자체에 찾을 이름이 그대로 들어가면 pkill/pgrep -f가 이 셸까지 죽이거나 찾으므로,
78추가: * 이름은 변수로 만들고 검색 패턴은 [c]om…, [a]ndroid… 형태로 써서 자기 자신과 맞지 않게 한다.
7579 */
7680 private fun startCommand(pkg: String): String {
7781 val dir = "/data/local/tmp/android-remote"
78삭제: // 명령 줄 자체에 클래스 이름이 그대로 들어가면 pkill/pgrep -f가 이 셸까지 죽이거나 찾으므로,
79삭제: // 실행 인자는 변수로 만들고 검색 패턴은 [c]om… 형태로 써서 자기 자신과 맞지 않게 한다.
80삭제: val pattern = "'[c]om.androidremote.daemon.DaemonMain'"
81삭제: return "pkill -f $pattern; " +
82삭제: "mkdir -p $dir; " +
83삭제: "M=com.androidremote.daemon; " +
82추가: val daemon = "'[c]om.androidremote.daemon.DaemonMain'"
83추가: val supervisor = "'[a]ndroid-remote-supervisor'"
84추가: val loop = "while :; do " +
8485 "APK=\$(pm path $pkg | head -n1 | cut -d: -f2); " +
85삭제: "CLASSPATH=\$APK setsid app_process / \$M.DaemonMain --port $DAEMON_PORT " +
86삭제: "> $dir/daemon.log 2>&1 < /dev/null & " +
87삭제: "sleep 1; pgrep -f $pattern > /dev/null && echo started || echo failed"
86추가: "CLASSPATH=\$APK app_process / \$M.DaemonMain --port $DAEMON_PORT >> $dir/daemon.log 2>&1 < /dev/null; " +
87추가: "echo \"daemon exited \$?, restarting\" >> $dir/daemon.log; sleep 3; done"
88추가: return "pkill -f $supervisor; pkill -f $daemon; " +
89추가: "mkdir -p $dir; : > $dir/daemon.log; " +
90추가: "S=android-remote; " +
91추가: "M=com.androidremote.daemon setsid sh -c '$loop' \$S-supervisor < /dev/null > /dev/null 2>&1 & " +
92추가: "sleep 1; pgrep -f $daemon > /dev/null && echo started || echo failed"
8893 }
8994
9095 private fun runShell(adb: SelfAdb, command: String): String {
수정android/app/src/main/java/com/androidremote/daemon/DeviceControl.kt+8-2
@@ -29,7 +29,14 @@ object DisplayPower {
2929 private const val POWER_MODE_OFF = 0
3030 private const val POWER_MODE_NORMAL = 2
3131
32삭제: private val tokens: List<IBinder> by lazy {
32추가: private val tokens: List<IBinder> by lazy { loadTokens() }
33추가:
34추가: /**
35추가: * 데몬은 앱이 아니라 shell 권한 app_process로 실행되므로 앱용 숨은 API 제한(targetSdk 36)이
36추가: * 적용되지 않는다. 실기기에서 동작을 확인했다.
37추가: */
38추가: @android.annotation.SuppressLint("BlockedPrivateApi", "DiscouragedPrivateApi", "PrivateApi")
39추가: private fun loadTokens(): List<IBinder> =
3340 try {
3441 val factory = Class.forName("com.android.internal.os.ClassLoaderFactory")
3542 val create = factory.getDeclaredMethod(
@@ -52,7 +59,6 @@ object DisplayPower {
5259 Log.w("물리 디스플레이 토큰 조회 실패: ${e.cause ?: e}")
5360 emptyList()
5461 }
55삭제: }
5662
5763 fun set(on: Boolean): Boolean {
5864 if (tokens.isEmpty()) return false
수정examples/probe.rs+7-2
@@ -1,6 +1,6 @@
11//! 기기 연결 점검 도구. GUI 없이 접속, 인증, PING 왕복, 영상 설정, 시스템 버튼을 확인한다.
22//!
3삭제: //! `cargo run --example probe -- 127.0.0.1:27200 [--key back|home|recents] [--record out.h264 --seconds 3]`
3추가: //! `cargo run --example probe -- <IP:포트|usb> [--key back|home|recents] [--record out.h264 --seconds 3]`
44//!
55//! `--record`를 주면 영상 채널로 받은 Annex-B 스트림을 파일로 저장한다(ffprobe/ffplay로 확인).
66//!
@@ -28,7 +28,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
2828 let target = args
2929 .first()
3030 .ok_or("사용법: probe <IP:포트> [--key back|home|recents]")?;
31삭제: let target = wayland_android_remote_target(target)?;
31추가: // "usb": 호스트 adb로 USB 기기에서 데몬을 띄우고 포워딩한 로컬 주소로 접속한다 (USB ADB 모드).
32추가: let target = if target == "usb" {
33추가: tokio::task::spawn_blocking(wayland_android_remote::adb::prepare_usb).await??
34추가: } else {
35추가: wayland_android_remote_target(target)?
36추가: };
3237 let key = args
3338 .iter()
3439 .position(|a| a == "--key")
추가packaging/android-remote.desktop+11-0
@@ -0,0 +1,11 @@
1추가: [Desktop Entry]
2추가: Type=Application
3추가: Name=Android Remote
4추가: Comment=Android 기기 화면 미러링 및 원격 제어
5추가: Exec=android-remote
6추가: Icon=android-remote
7추가: Terminal=false
8추가: Categories=Network;RemoteAccess;
9추가: Keywords=android;phone;mirror;remote;scrcpy;
10추가: StartupWMClass=android-remote
11추가: StartupNotify=true
추가packaging/android-remote.svg+8-0
@@ -0,0 +1,8 @@
1추가: <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
2추가: <rect x="8" y="8" width="112" height="112" rx="26" fill="#161616"/>
3추가: <rect x="40" y="22" width="48" height="84" rx="9" fill="none" stroke="#5cc88a" stroke-width="6"/>
4추가: <rect x="49" y="33" width="30" height="56" rx="3" fill="#5cc88a" opacity="0.25"/>
5추가: <circle cx="64" cy="97" r="3.5" fill="#5cc88a"/>
6추가: <path d="M96 40 a16 16 0 0 1 0 24" fill="none" stroke="#e8e8e8" stroke-width="5" stroke-linecap="round"/>
7추가: <path d="M104 32 a28 28 0 0 1 0 40" fill="none" stroke="#e8e8e8" stroke-width="5" stroke-linecap="round" opacity="0.6"/>
8추가: </svg>
수정scripts/dev-daemon.sh+2-1
@@ -18,7 +18,8 @@ if [[ -z "${SKIP_BUILD:-}" ]]; then
1818 adb install -r android/app/build/outputs/apk/debug/app-debug.apk >/dev/null
1919fi
2020
21삭제: adb shell "pkill -f com.androidremote.daemon.DaemonMain" >/dev/null 2>&1 || true
21추가: # 동반 앱이 띄운 감시 셸이 있으면 데몬을 다시 띄우므로 함께 끝낸다.
22추가: adb shell "pkill -f '[a]ndroid-remote-supervisor'; pkill -f '[c]om.androidremote.daemon.DaemonMain'" >/dev/null 2>&1 || true
2223adb forward "tcp:$PORT" "tcp:$PORT" >/dev/null
2324APK="$(adb shell pm path com.androidremote | tr -d '\r' | cut -d: -f2)"
2425
추가scripts/install.sh+38-0
@@ -0,0 +1,38 @@
1추가: #!/usr/bin/env bash
2추가: # PC 앱 설치: 릴리스로 빌드해 현재 사용자 경로(~/.local)에 실행 파일, 바탕화면 항목, 아이콘을 넣는다.
3추가: # root 권한은 필요 없다.
4추가: #
5추가: # ./scripts/install.sh 빌드 후 설치
6추가: # ./scripts/install.sh --uninstall 설치한 파일 제거 (설정 ~/.config/android-remote 는 남긴다)
7추가: # PREFIX=~/.local 설치 경로
8추가: set -euo pipefail
9추가: cd "$(dirname "$0")/.."
10추가:
11추가: PREFIX="${PREFIX:-$HOME/.local}"
12추가: BIN="$PREFIX/bin/android-remote"
13추가: DESKTOP="$PREFIX/share/applications/android-remote.desktop"
14추가: ICON="$PREFIX/share/icons/hicolor/scalable/apps/android-remote.svg"
15추가:
16추가: refresh() {
17추가: command -v update-desktop-database >/dev/null && update-desktop-database -q "$PREFIX/share/applications" || true
18추가: command -v gtk-update-icon-cache >/dev/null && gtk-update-icon-cache -q -t "$PREFIX/share/icons/hicolor" 2>/dev/null || true
19추가: }
20추가:
21추가: if [[ "${1:-}" == "--uninstall" ]]; then
22추가: rm -f "$BIN" "$DESKTOP" "$ICON"
23추가: refresh
24추가: echo "제거했습니다. 설정과 키는 ~/.config/android-remote 에 남아 있습니다."
25추가: exit 0
26추가: fi
27추가:
28추가: cargo build --release --locked
29추가: install -Dm755 target/release/android-remote "$BIN"
30추가: install -Dm644 packaging/android-remote.svg "$ICON"
31추가: # Exec는 절대 경로로 바꿔 PATH에 ~/.local/bin 이 없어도 실행되게 한다.
32추가: install -d "$(dirname "$DESKTOP")"
33추가: sed "s|^Exec=android-remote|Exec=$BIN|" packaging/android-remote.desktop > "$DESKTOP"
34추가: chmod 644 "$DESKTOP"
35추가: refresh
36추가:
37추가: echo "설치했습니다: $BIN"
38추가: echo "앱 목록에서 'Android Remote'로 실행하거나, 터미널에서 android-remote [휴대폰 IP] 로 실행하세요."
추가src/adb.rs+270-0
@@ -0,0 +1,270 @@
1추가: //! USB ADB 모드 (기획서 5.4 "보조 경로"). 호스트의 adb로 USB에 연결된 기기에서 데몬을 띄우고
2추가: //! `adb forward`로 데몬 포트를 로컬에 연결한다. 이후 TLS·Ed25519 절차는 내부망 연결과 같다.
3추가: //!
4추가: //! 데몬은 동반 앱이 자가 기동할 때와 같은 감시 셸로 띄우므로, USB를 뽑아도 계속 실행되고
5추가: //! 이후에는 Wi-Fi로도 접속할 수 있다.
6추가:
7추가: use std::net::{Ipv4Addr, SocketAddr};
8추가: use std::path::{Path, PathBuf};
9추가: use std::process::{Command, Output};
10추가: use std::time::Duration;
11추가:
12추가: /// 기기에서 데몬이 대기하는 포트 (기획서 5.4).
13추가: pub const DAEMON_PORT: u16 = 27200;
14추가: const PACKAGE: &str = "com.androidremote";
15추가: const DATA_DIR: &str = "/data/local/tmp/android-remote";
16추가:
17추가: #[derive(Debug)]
18추가: pub enum AdbError {
19추가: NotFound,
20추가: NoDevice,
21추가: Unauthorized,
22추가: AppMissing,
23추가: StartFailed(String),
24추가: Io(std::io::Error),
25추가: Command(String),
26추가: }
27추가:
28추가: impl std::fmt::Display for AdbError {
29추가: fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30추가: match self {
31추가: Self::NotFound => f.write_str("adb를 찾지 못했습니다. Android platform-tools를 설치해 주세요"),
32추가: Self::NoDevice => f.write_str("USB로 연결된 기기가 없습니다. USB 디버깅을 켜고 케이블을 연결해 주세요"),
33추가: Self::Unauthorized => f.write_str("휴대폰에서 이 PC의 USB 디버깅을 허용해 주세요"),
34추가: Self::AppMissing => f.write_str("휴대폰에 Android Remote 앱이 설치되어 있지 않습니다"),
35추가: Self::StartFailed(s) => write!(f, "데몬을 시작하지 못했습니다: {s}"),
36추가: Self::Io(e) => write!(f, "adb 실행 오류: {e}"),
37추가: Self::Command(s) => write!(f, "adb 오류: {s}"),
38추가: }
39추가: }
40추가: }
41추가:
42추가: impl std::error::Error for AdbError {}
43추가:
44추가: impl From<std::io::Error> for AdbError {
45추가: fn from(e: std::io::Error) -> Self {
46추가: Self::Io(e)
47추가: }
48추가: }
49추가:
50추가: /// USB 연결 상태의 기기 한 대.
51추가: #[derive(Debug, Clone, PartialEq, Eq)]
52추가: pub struct UsbDevice {
53추가: pub serial: String,
54추가: pub authorized: bool,
55추가: }
56추가:
57추가: /// adb 실행 파일 위치. `ANDROID_HOME`, `ANDROID_SDK_ROOT`, `~/Android/Sdk`, `PATH` 순으로 찾는다.
58추가: pub fn find_adb() -> Option<PathBuf> {
59추가: let mut candidates = Vec::new();
60추가: for var in ["ANDROID_HOME", "ANDROID_SDK_ROOT"] {
61추가: if let Some(root) = std::env::var_os(var) {
62추가: candidates.push(PathBuf::from(root).join("platform-tools/adb"));
63추가: }
64추가: }
65추가: if let Some(home) = std::env::var_os("HOME") {
66추가: candidates.push(PathBuf::from(home).join("Android/Sdk/platform-tools/adb"));
67추가: }
68추가: if let Some(path) = std::env::var_os("PATH") {
69추가: candidates.extend(std::env::split_paths(&path).map(|d| d.join("adb")));
70추가: }
71추가: candidates.into_iter().find(|p| is_executable(p))
72추가: }
73추가:
74추가: fn is_executable(p: &Path) -> bool {
75추가: use std::os::unix::fs::PermissionsExt;
76추가: p.metadata().map(|m| m.is_file() && m.permissions().mode() & 0o111 != 0).unwrap_or(false)
77추가: }
78추가:
79추가: /// `adb devices -l` 출력에서 USB로 연결된 기기만 고른다(무선 디버깅 기기는 제외).
80추가: pub fn parse_devices(out: &str) -> Vec<UsbDevice> {
81추가: out.lines()
82추가: .skip_while(|l| !l.starts_with("List of devices"))
83추가: .skip(1)
84추가: .filter_map(|line| {
85추가: let mut parts = line.split_whitespace();
86추가: let serial = parts.next()?;
87추가: let state = parts.next()?;
88추가: let rest: Vec<&str> = parts.collect();
89추가: if !rest.iter().any(|p| p.starts_with("usb:")) {
90추가: return None;
91추가: }
92추가: match state {
93추가: "device" => Some(UsbDevice { serial: serial.to_owned(), authorized: true }),
94추가: "unauthorized" => Some(UsbDevice { serial: serial.to_owned(), authorized: false }),
95추가: _ => None,
96추가: }
97추가: })
98추가: .collect()
99추가: }
100추가:
101추가: /// 데몬을 감시 셸로 (다시) 띄우는 셸 명령. 동반 앱 `Bootstrap.startCommand`와 같은 방식이다.
102추가: /// 이미 실행 중이면 그대로 둔다.
103추가: pub fn start_command() -> String {
104추가: let daemon = "'[c]om.androidremote.daemon.DaemonMain'";
105추가: let supervisor = "'[a]ndroid-remote-supervisor'";
106추가: let dir = DATA_DIR;
107추가: let pkg = PACKAGE;
108추가: let port = DAEMON_PORT;
109추가: let loop_ = format!(
110추가: "while :; do APK=$(pm path {pkg} | head -n1 | cut -d: -f2); \
111추가: CLASSPATH=$APK app_process / $M.DaemonMain --port {port} >> {dir}/daemon.log 2>&1 < /dev/null; \
112추가: echo \"daemon exited $?, restarting\" >> {dir}/daemon.log; sleep 3; done"
113추가: );
114추가: format!(
115추가: "if pgrep -f {daemon} > /dev/null; then echo running; exit 0; fi; \
116추가: pkill -f {supervisor}; mkdir -p {dir}; : > {dir}/daemon.log; S=android-remote; \
117추가: M=com.androidremote.daemon setsid sh -c '{loop_}' $S-supervisor < /dev/null > /dev/null 2>&1 & \
118추가: sleep 1; pgrep -f {daemon} > /dev/null && echo started || echo failed"
119추가: )
120추가: }
121추가:
122추가: pub struct Adb {
123추가: path: PathBuf,
124추가: }
125추가:
126추가: impl Adb {
127추가: pub fn locate() -> Result<Self, AdbError> {
128추가: find_adb().map(|path| Self { path }).ok_or(AdbError::NotFound)
129추가: }
130추가:
131추가: pub fn is_available() -> bool {
132추가: find_adb().is_some()
133추가: }
134추가:
135추가: fn run(&self, args: &[&str]) -> Result<Output, AdbError> {
136추가: Ok(Command::new(&self.path).args(args).output()?)
137추가: }
138추가:
139추가: fn run_ok(&self, args: &[&str]) -> Result<String, AdbError> {
140추가: let out = self.run(args)?;
141추가: let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
142추가: if !out.status.success() {
143추가: let err = String::from_utf8_lossy(&out.stderr).trim().to_owned();
144추가: return Err(AdbError::Command(if err.is_empty() { stdout.trim().to_owned() } else { err }));
145추가: }
146추가: Ok(stdout)
147추가: }
148추가:
149추가: pub fn usb_devices(&self) -> Result<Vec<UsbDevice>, AdbError> {
150추가: Ok(parse_devices(&self.run_ok(&["devices", "-l"])?))
151추가: }
152추가:
153추가: /// USB 기기 하나를 고른다. 여러 대면 첫 번째 허용된 기기를 쓴다.
154추가: pub fn pick_device(&self) -> Result<String, AdbError> {
155추가: let devices = self.usb_devices()?;
156추가: if let Some(d) = devices.iter().find(|d| d.authorized) {
157추가: return Ok(d.serial.clone());
158추가: }
159추가: if devices.is_empty() { Err(AdbError::NoDevice) } else { Err(AdbError::Unauthorized) }
160추가: }
161추가:
162추가: /// 데몬이 없으면 띄운다. 반환값은 "running"(이미 실행 중) 또는 "started".
163추가: pub fn ensure_daemon(&self, serial: &str) -> Result<String, AdbError> {
164추가: let path = self.run_ok(&["-s", serial, "shell", "pm", "path", PACKAGE])?;
165추가: if !path.contains("package:") {
166추가: return Err(AdbError::AppMissing);
167추가: }
168추가: let out = self.run_ok(&["-s", serial, "shell", &start_command()])?;
169추가: let out = out.trim();
170추가: if out.ends_with("running") || out.ends_with("started") {
171추가: Ok(out.rsplit('\n').next().unwrap_or(out).trim().to_owned())
172추가: } else {
173추가: Err(AdbError::StartFailed(out.to_owned()))
174추가: }
175추가: }
176추가:
177추가: /// 기기의 데몬 포트를 로컬에 연결한다. 이미 걸린 포워딩이 있으면 그대로 쓰고,
178추가: /// 없으면 같은 번호를 먼저 시도한 뒤 쓰고 있으면 adb가 고른 빈 포트를 쓴다.
179추가: pub fn forward(&self, serial: &str) -> Result<u16, AdbError> {
180추가: let remote = format!("tcp:{DAEMON_PORT}");
181추가: let list = self.run_ok(&["forward", "--list"])?;
182추가: for line in list.lines() {
183추가: let parts: Vec<&str> = line.split_whitespace().collect();
184추가: if let [s, local, r] = parts[..]
185추가: && s == serial
186추가: && r == remote
187추가: && let Some(port) = local.strip_prefix("tcp:").and_then(|p| p.parse().ok())
188추가: {
189추가: return Ok(port);
190추가: }
191추가: }
192추가: let preferred = format!("tcp:{DAEMON_PORT}");
193추가: if std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, DAEMON_PORT)).is_ok()
194추가: && self.run_ok(&["-s", serial, "forward", &preferred, &remote]).is_ok()
195추가: {
196추가: return Ok(DAEMON_PORT);
197추가: }
198추가: let out = self.run_ok(&["-s", serial, "forward", "tcp:0", &remote])?;
199추가: out.trim().parse().map_err(|_| AdbError::Command(format!("forward 응답 해석 실패: {out}")))
200추가: }
201추가: }
202추가:
203추가: /// USB 기기를 골라 데몬을 띄우고 포워딩한 로컬 주소를 돌려준다. 블로킹이므로 작업자 스레드에서 부른다.
204추가: pub fn prepare_usb() -> Result<SocketAddr, AdbError> {
205추가: let adb = Adb::locate()?;
206추가: let serial = adb.pick_device()?;
207추가: let state = adb.ensure_daemon(&serial)?;
208추가: let port = adb.forward(&serial)?;
209추가: if state == "started" {
210추가: // 데몬이 TLS 포트를 열 때까지 잠시 기다린다.
211추가: wait_for_port(port, Duration::from_secs(5));
212추가: }
213추가: log::info!("USB ADB: 기기 {serial}, 데몬 {state}, 127.0.0.1:{port}");
214추가: Ok(SocketAddr::from((Ipv4Addr::LOCALHOST, port)))
215추가: }
216추가:
217추가: fn wait_for_port(port: u16, timeout: Duration) {
218추가: let deadline = std::time::Instant::now() + timeout;
219추가: let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, port));
220추가: while std::time::Instant::now() < deadline {
221추가: // adb forward는 로컬 접속은 항상 받으므로, 데몬이 받지 않으면 곧바로 끊긴다.
222추가: if let Ok(s) = std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(300)) {
223추가: let _ = s.set_read_timeout(Some(Duration::from_millis(300)));
224추가: let mut buf = [0u8; 1];
225추가: use std::io::Read;
226추가: match (&s).read(&mut buf) {
227추가: Ok(0) => {}
228추가: _ => return, // 읽기 타임아웃: 데몬이 연결을 받고 ClientHello를 기다리는 중
229추가: }
230추가: }
231추가: std::thread::sleep(Duration::from_millis(250));
232추가: }
233추가: }
234추가:
235추가: #[cfg(test)]
236추가: mod tests {
237추가: use super::*;
238추가:
239추가: #[test]
240추가: fn parses_usb_devices_only() {
241추가: let out = "List of devices attached\n\
242추가: SERIAL0001AB device usb:1-9 product:t2sksx model:SM_G996N device:t2s transport_id:1\n\
243추가: 192.168.0.12:39829 device product:t2sksx model:SM_G996N device:t2s transport_id:2\n\
244추가: ABC123 unauthorized usb:1-3 transport_id:3\n\
245추가: DEF456 offline usb:1-4 transport_id:4\n\n";
246추가: assert_eq!(
247추가: parse_devices(out),
248추가: vec![
249추가: UsbDevice { serial: "SERIAL0001AB".into(), authorized: true },
250추가: UsbDevice { serial: "ABC123".into(), authorized: false },
251추가: ]
252추가: );
253추가: }
254추가:
255추가: #[test]
256추가: fn empty_device_list() {
257추가: assert!(parse_devices("List of devices attached\n\n").is_empty());
258추가: assert!(parse_devices("").is_empty());
259추가: }
260추가:
261추가: #[test]
262추가: fn start_command_matches_companion_bootstrap() {
263추가: let cmd = start_command();
264추가: assert!(cmd.contains("--port 27200"));
265추가: assert!(cmd.contains("$S-supervisor"));
266추가: // 명령 줄에 검색 대상 이름이 그대로 들어가면 pgrep이 자기 자신을 찾는다.
267추가: assert!(!cmd.contains("pgrep -f com.androidremote"));
268추가: assert!(!cmd.contains("android-remote-supervisor"));
269추가: }
270추가: }
수정src/lib.rs+1-0
@@ -2,6 +2,7 @@
22//!
33//! Ubuntu(Wayland/X11)에서 Android 기기 화면을 미러링하고 마우스·키보드로 원격 제어한다.
44
5추가: pub mod adb;
56pub mod config;
67pub mod net;
78pub mod protocol;