릴리스 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| @@ -1,7 +1,21 @@ | ||
| 1 | 추가: import java.util.Properties | |
| 2 | 추가: | |
| 1 | 3 | plugins { |
| 2 | 4 | alias(libs.plugins.android.application) |
| 3 | 5 | } |
| 4 | 6 | |
| 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 | 추가: | |
| 5 | 19 | android { |
| 6 | 20 | namespace = "com.androidremote" |
| 7 | 21 | compileSdk = 36 |
| @@ -21,9 +35,25 @@ android { | ||
| 21 | 35 | } |
| 22 | 36 | } |
| 23 | 37 | |
| 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 | 추가: | |
| 24 | 49 | buildTypes { |
| 50 | 추가: debug { | |
| 51 | 추가: signingConfigs.findByName("shared")?.let { signingConfig = it } | |
| 52 | 추가: } | |
| 25 | 53 | release { |
| 26 | 삭제: isMinifyEnabled = false | |
| 54 | 추가: signingConfigs.findByName("shared")?.let { signingConfig = it } | |
| 55 | 추가: isMinifyEnabled = true | |
| 56 | 추가: isShrinkResources = true | |
| 27 | 57 | proguardFiles( |
| 28 | 58 | getDefaultProguardFile("proguard-android-optimize.txt"), |
| 29 | 59 | "proguard-rules.pro", |
| @@ -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.** |
| @@ -70,21 +70,26 @@ object Bootstrap { | ||
| 70 | 70 | } |
| 71 | 71 | |
| 72 | 72 | /** |
| 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… 형태로 써서 자기 자신과 맞지 않게 한다. | |
| 75 | 79 | */ |
| 76 | 80 | private fun startCommand(pkg: String): String { |
| 77 | 81 | 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 " + | |
| 84 | 85 | "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" | |
| 88 | 93 | } |
| 89 | 94 | |
| 90 | 95 | private fun runShell(adb: SelfAdb, command: String): String { |
| @@ -29,7 +29,14 @@ object DisplayPower { | ||
| 29 | 29 | private const val POWER_MODE_OFF = 0 |
| 30 | 30 | private const val POWER_MODE_NORMAL = 2 |
| 31 | 31 | |
| 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> = | |
| 33 | 40 | try { |
| 34 | 41 | val factory = Class.forName("com.android.internal.os.ClassLoaderFactory") |
| 35 | 42 | val create = factory.getDeclaredMethod( |
| @@ -52,7 +59,6 @@ object DisplayPower { | ||
| 52 | 59 | Log.w("물리 디스플레이 토큰 조회 실패: ${e.cause ?: e}") |
| 53 | 60 | emptyList() |
| 54 | 61 | } |
| 55 | 삭제: } | |
| 56 | 62 | |
| 57 | 63 | fun set(on: Boolean): Boolean { |
| 58 | 64 | if (tokens.isEmpty()) return false |
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | //! 기기 연결 점검 도구. GUI 없이 접속, 인증, PING 왕복, 영상 설정, 시스템 버튼을 확인한다. |
| 2 | 2 | //! |
| 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]` | |
| 4 | 4 | //! |
| 5 | 5 | //! `--record`를 주면 영상 채널로 받은 Annex-B 스트림을 파일로 저장한다(ffprobe/ffplay로 확인). |
| 6 | 6 | //! |
| @@ -28,7 +28,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> { | ||
| 28 | 28 | let target = args |
| 29 | 29 | .first() |
| 30 | 30 | .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 | 추가: }; | |
| 32 | 37 | let key = args |
| 33 | 38 | .iter() |
| 34 | 39 | .position(|a| a == "--key") |
| @@ -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 |
| @@ -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> |
| @@ -18,7 +18,8 @@ if [[ -z "${SKIP_BUILD:-}" ]]; then | ||
| 18 | 18 | adb install -r android/app/build/outputs/apk/debug/app-debug.apk >/dev/null |
| 19 | 19 | fi |
| 20 | 20 | |
| 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 | |
| 22 | 23 | adb forward "tcp:$PORT" "tcp:$PORT" >/dev/null |
| 23 | 24 | APK="$(adb shell pm path com.androidremote | tr -d '\r' | cut -d: -f2)" |
| 24 | 25 |
| @@ -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] 로 실행하세요." |
| @@ -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 | 추가: } |
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | //! |
| 3 | 3 | //! Ubuntu(Wayland/X11)에서 Android 기기 화면을 미러링하고 마우스·키보드로 원격 제어한다. |
| 4 | 4 | |
| 5 | 추가: pub mod adb; | |
| 5 | 6 | pub mod config; |
| 6 | 7 | pub mod net; |
| 7 | 8 | pub mod protocol; |