leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | package com.androidremote.companion |
| 2 | |
| 3 | import android.Manifest |
| 4 | import android.content.Context |
| 5 | import android.content.pm.PackageManager |
| 6 | import android.provider.Settings |
| 7 | import android.util.Log |
| 8 | import io.github.muntashirakon.adb.android.AdbMdns |
| 9 | import java.io.ByteArrayOutputStream |
| 10 | import java.io.IOException |
| 11 | |
| 12 | /** |
| 13 | * 무선 디버깅으로 shell 권한 데몬을 띄우는 자가 기동 (기획서 5.4). |
| 14 | * |
| 15 | * 1. 최초 1회: 사용자가 무선 디버깅의 페어링 코드를 알림에 입력하면 [pair]로 앱 전용 키를 등록한다. |
| 16 | * 2. 기동: [launchDaemon]이 기기 자신의 adbd에 TLS로 접속해 데몬을 setsid로 분리 실행한다. |
| 17 | * 데몬이 동반 앱에 WRITE_SECURE_SETTINGS를 부여하므로, 그 뒤로는 무선 디버깅을 앱이 직접 |
| 18 | * 켰다가 기동 후 원래대로 끌 수 있다(재부팅 후 무인 재기동). |
| 19 | */ |
| 20 | object Bootstrap { |
| 21 | private const val TAG = "AndroidRemote" |
| 22 | private const val PREFS = "bootstrap" |
| 23 | private const val ADB_WIFI = "adb_wifi_enabled" |
| 24 | const val DAEMON_PORT = 27200 |
| 25 | |
| 26 | fun isPaired(context: Context) = prefs(context).getBoolean("paired", false) |
| 27 | |
| 28 | fun canToggleWirelessDebugging(context: Context) = |
| 29 | context.checkSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS) == PackageManager.PERMISSION_GRANTED |
| 30 | |
| 31 | fun isWirelessDebuggingOn(context: Context) = |
| 32 | Settings.Global.getInt(context.contentResolver, ADB_WIFI, 0) == 1 |
| 33 | |
| 34 | /** 무선 디버깅 화면의 "페어링 코드로 기기 페어링"이 열려 있는 동안 호출한다. 작업자 스레드 전용. */ |
| 35 | fun pair(context: Context, code: String): Result<Unit> = runCatching { |
| 36 | val (host, port) = SelfAdb.discover(context, AdbMdns.SERVICE_TYPE_TLS_PAIRING, 15_000) |
| 37 | ?: throw IOException("페어링 포트를 찾지 못했습니다. 무선 디버깅의 '페어링 코드로 기기 페어링' 창을 열어 두세요") |
| 38 | val adb = SelfAdb.get(context) |
| 39 | val target = host?.hostAddress ?: "127.0.0.1" |
| 40 | Log.i(TAG, "페어링 시도 $target:$port") |
| 41 | adb.pair(target, port, code.trim()) |
| 42 | prefs(context).edit().putBoolean("paired", true).apply() |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * 데몬을 (다시) 띄운다. 작업자 스레드 전용. |
| 47 | * 무선 디버깅이 꺼져 있으면 WRITE_SECURE_SETTINGS가 있을 때만 잠깐 켰다가 끝나면 되돌린다. |
| 48 | */ |
| 49 | fun launchDaemon(context: Context): Result<String> = runCatching { |
| 50 | if (!isPaired(context)) throw IllegalStateException("먼저 무선 디버깅 페어링을 해야 합니다") |
| 51 | val wasOn = isWirelessDebuggingOn(context) |
| 52 | val toggled = !wasOn && canToggleWirelessDebugging(context) |
| 53 | if (!wasOn && !toggled) throw IllegalStateException("개발자 옵션에서 무선 디버깅을 켜 주세요") |
| 54 | if (toggled) Settings.Global.putInt(context.contentResolver, ADB_WIFI, 1) |
| 55 | try { |
| 56 | val (host, port) = SelfAdb.discover(context, AdbMdns.SERVICE_TYPE_TLS_CONNECT, 15_000) |
| 57 | ?: throw IOException("무선 디버깅 포트를 찾지 못했습니다. Wi-Fi에 연결되어 있는지 확인하세요") |
| 58 | val adb = SelfAdb.get(context) |
| 59 | val target = host?.hostAddress ?: "127.0.0.1" |
| 60 | Log.i(TAG, "adbd 접속 $target:$port") |
| 61 | if (!adb.isConnected) adb.connect(target, port) |
| 62 | try { |
| 63 | runShell(adb, startCommand(context.packageName)) |
| 64 | } finally { |
| 65 | runCatching { adb.disconnect() } |
| 66 | } |
| 67 | } finally { |
| 68 | if (toggled) Settings.Global.putInt(context.contentResolver, ADB_WIFI, 0) |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | /** |
| 73 | * 이전 감시 셸·데몬을 끝내고, setsid로 분리한 감시 셸이 데몬을 실행하게 한다. 데몬이 어떤 |
| 74 | * 이유로든 끝나면 감시 셸이 3초 뒤 다시 띄운다(기획서 5.4 "데몬 비정상 종료 시 재기동"). |
| 75 | * ADB 연결이 끊기거나 무선 디버깅이 꺼져도 계속 돈다. 로그는 데몬 저장소의 daemon.log에 남긴다. |
| 76 | * |
| 77 | * 명령 줄 자체에 찾을 이름이 그대로 들어가면 pkill/pgrep -f가 이 셸까지 죽이거나 찾으므로, |
| 78 | * 이름은 변수로 만들고 검색 패턴은 [c]om…, [a]ndroid… 형태로 써서 자기 자신과 맞지 않게 한다. |
| 79 | */ |
| 80 | private fun startCommand(pkg: String): String { |
| 81 | val dir = "/data/local/tmp/android-remote" |
| 82 | val daemon = "'[c]om.androidremote.daemon.DaemonMain'" |
| 83 | val supervisor = "'[a]ndroid-remote-supervisor'" |
| 84 | val loop = "while :; do " + |
| 85 | "APK=\$(pm path $pkg | head -n1 | cut -d: -f2); " + |
| 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" |
| 93 | } |
| 94 | |
| 95 | private fun runShell(adb: SelfAdb, command: String): String { |
| 96 | val stream = adb.openStream("shell:$command") |
| 97 | val out = ByteArrayOutputStream() |
| 98 | try { |
| 99 | val input = stream.openInputStream() |
| 100 | val buf = ByteArray(4096) |
| 101 | while (true) { |
| 102 | val n = input.read(buf, 0, buf.size) |
| 103 | if (n < 0) break |
| 104 | out.write(buf, 0, n) |
| 105 | } |
| 106 | } catch (e: IOException) { |
| 107 | // 라이브러리는 스트림이 닫히면 -1 대신 "Stream closed." IOException을 낸다. |
| 108 | } finally { |
| 109 | runCatching { stream.close() } |
| 110 | } |
| 111 | val text = out.toString(Charsets.UTF_8).trim() |
| 112 | Log.i(TAG, "데몬 기동 결과: $text") |
| 113 | if (!text.contains("started")) throw IOException("데몬을 시작하지 못했습니다: $text") |
| 114 | return text |
| 115 | } |
| 116 | |
| 117 | private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) |
| 118 | } |