leejunyoung5819wayland-android-remote

공개

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

동반 앱: 무선 디버깅 자가 기동과 자동 재기동

- libadb-android(Apache-2.0)와 Conscrypt로 기기 자신의 무선 디버깅에 페어링·접속 (앱 전용 RSA-2048 키, 자체 서명 인증서)
- 페어링 코드는 알림 답장(RemoteInput)으로 입력, mDNS로 페어링·접속 포트 탐색
- 데몬을 setsid로 분리 실행(명령 줄이 pkill/pgrep 패턴과 맞지 않게 처리), 무선 디버깅을 꺼도 유지
- 데몬이 동반 앱에 WRITE_SECURE_SETTINGS를 부여해 재부팅·앱 업데이트 후 앱이 무선 디버깅을 잠깐 켜서 데몬을 띄우고 원래대로 끔 (포그라운드 서비스, 실패 시 재시도)
- 메인 화면에 'USB 없이 시작' 안내와 버튼, Conscrypt 네이티브 라이브러리 ABI 제한
- 실제 Galaxy S21+에서 페어링, 앱에서 데몬 시작, 무선 디버깅 끈 뒤 PC 연결, 앱 업데이트 후 무인 재기동 확인
작성자
LeeJunyoung
작성 시각
커밋
d09a636daa87d58ffb4a441f02fb253a4293edab
부모
278a3d7
이 시점의 파일 보기

변경된 파일 12개

+476-3
수정README.md+7-0
@@ -52,6 +52,13 @@ cargo run --example fake_device -- --policy always --delay-ms 3000
5252
5353다른 터미널에서 `cargo run`으로 호스트를 띄우고 IP 입력창에 `127.0.0.1`을 입력합니다. 승인 정책은 `always`, `once`, `reject`, `never` 중에서 고릅니다.
5454
55추가: ### 휴대폰 준비 (USB 없이 사용)
56추가:
57추가: 1. 동반 앱(Android Remote)을 설치하고 엽니다.
58추가: 2. "페어링 코드 입력 (최초 1회)"을 누르면 알림이 뜨고 개발자 옵션이 열립니다. 무선 디버깅을 켜고(확인 창에서 "이 네트워크에서 항상 허용" 선택), "페어링 코드로 기기 페어링"을 연 채로 알림의 "코드 입력"에 6자리 코드를 넣습니다.
59추가: 3. 페어링이 끝나면 서비스가 자동으로 시작됩니다. 이후에는 재부팅이나 앱 업데이트 뒤에도 앱이 무선 디버깅을 잠깐 켜서 서비스를 다시 띄우고 끕니다(Wi-Fi 연결 필요).
60추가: 4. PC 앱에 동반 앱 화면의 주소(예: `192.168.0.12`)를 입력하고, 휴대폰 승인 창에서 확인 코드를 대조해 허용합니다.
61추가:
5562### 실제 휴대폰으로 테스트하기 (개발용)
5663
5764동반 앱의 무선 디버깅 자가 기동(기획서 5.4)이 생기기 전까지는 USB로 데몬을 띄웁니다. 폰에서 USB 디버깅을 허용한 뒤:
수정android/app/build.gradle.kts+13-0
@@ -14,6 +14,11 @@ android {
1414 // 데몬 버전 = APK versionCode (기획서 5.4)
1515 versionCode = 1
1616 versionName = "0.1.0"
17추가:
18추가: ndk {
19추가: // Conscrypt 네이티브 라이브러리를 64비트 ARM(실기기)과 x86_64(에뮬레이터)만 넣는다.
20추가: abiFilters += listOf("arm64-v8a", "x86_64")
21추가: }
1722 }
1823
1924 buildTypes {
@@ -40,4 +45,12 @@ android {
4045dependencies {
4146 // Android 플랫폼에는 Ed25519 서명 검증이 없어 PC 인증(기획서 5.3)에 BouncyCastle 경량 API를 쓴다.
4247 implementation(libs.bouncycastle.prov)
48추가: // 동반 앱이 기기 자신의 무선 디버깅(adbd)에 접속해 데몬을 띄운다 (기획서 5.4).
49추가: // 라이선스: GPL-3.0-or-later 또는 Apache-2.0 중 Apache-2.0으로 사용.
50추가: implementation(libs.libadb) {
51추가: // 같은 BouncyCastle 클래스를 가진 jdk18on 판을 이미 쓰므로 중복을 뺀다.
52추가: exclude(group = "org.bouncycastle", module = "bcprov-jdk15to18")
53추가: }
54추가: // 무선 디버깅 페어링(TLS 키 내보내기)에 쓰는 Conscrypt. 플랫폼 Conscrypt는 숨은 API라 쓰지 않는다.
55추가: implementation(libs.conscrypt)
4356}
수정android/app/src/main/AndroidManifest.xml+27-0
@@ -10,6 +10,9 @@
1010 <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
1111 <!-- 재부팅 후 데몬 자동 재기동 -->
1212 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
13추가: <!-- 자동 재기동용 짧은 포그라운드 서비스 -->
14추가: <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
15추가: <uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
1316 <!-- 데몬이 pm grant로 부여한다. adb_wifi_enabled 토글용 -->
1417 <uses-permission
1518 android:name="android.permission.WRITE_SECURE_SETTINGS"
@@ -43,5 +46,29 @@
4346 android:name=".companion.TokenReceiver"
4447 android:exported="true"
4548 android:permission="android.permission.DUMP" />
49추가:
50추가: <!-- 무선 디버깅 페어링 코드(알림 답장) 수신 -->
51추가: <receiver
52추가: android:name=".companion.PairingReceiver"
53추가: android:exported="false" />
54추가:
55추가: <!-- 재부팅·앱 업데이트 후 데몬 자동 재기동 -->
56추가: <receiver
57추가: android:name=".companion.BootReceiver"
58추가: android:exported="true">
59추가: <intent-filter>
60추가: <action android:name="android.intent.action.BOOT_COMPLETED" />
61추가: <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
62추가: </intent-filter>
63추가: </receiver>
64추가:
65추가: <service
66추가: android:name=".companion.StartService"
67추가: android:exported="false"
68추가: android:foregroundServiceType="specialUse">
69추가: <property
70추가: android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
71추가: android:value="무선 디버깅으로 원격 제어 데몬(shell 프로세스)을 시작한다" />
72추가: </service>
4673 </application>
4774</manifest>
추가android/app/src/main/java/com/androidremote/companion/AutoStart.kt+54-0
@@ -0,0 +1,54 @@
1추가: package com.androidremote.companion
2추가:
3추가: import android.app.Notification
4추가: import android.app.NotificationChannel
5추가: import android.app.NotificationManager
6추가: import android.app.Service
7추가: import android.content.BroadcastReceiver
8추가: import android.content.Context
9추가: import android.content.Intent
10추가: import android.content.pm.ServiceInfo
11추가: import android.os.IBinder
12추가: import android.util.Log
13추가:
14추가: /** 재부팅·앱 업데이트 뒤 데몬을 자동으로 다시 띄운다 (기획서 5.4 "재부팅 후 자동 재기동"). */
15추가: class BootReceiver : BroadcastReceiver() {
16추가: override fun onReceive(context: Context, intent: Intent) {
17추가: if (!Bootstrap.isPaired(context) || !Bootstrap.canToggleWirelessDebugging(context)) return
18추가: context.startForegroundService(Intent(context, StartService::class.java))
19추가: }
20추가: }
21추가:
22추가: /**
23추가: * 데몬 기동을 맡는 짧은 포그라운드 서비스. 무선 디버깅은 Wi-Fi가 있어야 켜지므로
24추가: * 실패하면 10초 간격으로 몇 번 다시 시도한 뒤 끝낸다.
25추가: */
26추가: class StartService : Service() {
27추가: override fun onBind(intent: Intent?): IBinder? = null
28추가:
29추가: override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
30추가: val nm = getSystemService(NotificationManager::class.java)
31추가: nm.createNotificationChannel(NotificationChannel(CHANNEL, "서비스 시작", NotificationManager.IMPORTANCE_LOW))
32추가: val n = Notification.Builder(this, CHANNEL)
33추가: .setSmallIcon(android.R.drawable.stat_sys_data_bluetooth)
34추가: .setContentTitle("Android Remote 서비스 시작 중")
35추가: .build()
36추가: startForeground(ID, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE)
37추가: Thread {
38추가: for (attempt in 1..RETRIES) {
39추가: val r = Bootstrap.launchDaemon(applicationContext)
40추가: if (r.isSuccess) break
41추가: Log.w("AndroidRemote", "자동 기동 실패($attempt/$RETRIES): ${r.exceptionOrNull()?.message}")
42추가: Thread.sleep(10_000)
43추가: }
44추가: stopSelf()
45추가: }.start()
46추가: return START_NOT_STICKY
47추가: }
48추가:
49추가: companion object {
50추가: private const val CHANNEL = "start"
51추가: private const val ID = 1002
52추가: private const val RETRIES = 6
53추가: }
54추가: }
추가android/app/src/main/java/com/androidremote/companion/Bootstrap.kt+113-0
@@ -0,0 +1,113 @@
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추가: * 이전 데몬을 끝내고 APK 안의 데몬을 setsid로 분리 실행한다. ADB 연결이 끊기거나 무선 디버깅이
74추가: * 꺼져도 계속 돈다. 로그는 데몬 저장소의 daemon.log에 남긴다.
75추가: */
76추가: private fun startCommand(pkg: String): String {
77추가: 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; " +
84추가: "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"
88추가: }
89추가:
90추가: private fun runShell(adb: SelfAdb, command: String): String {
91추가: val stream = adb.openStream("shell:$command")
92추가: val out = ByteArrayOutputStream()
93추가: try {
94추가: val input = stream.openInputStream()
95추가: val buf = ByteArray(4096)
96추가: while (true) {
97추가: val n = input.read(buf, 0, buf.size)
98추가: if (n < 0) break
99추가: out.write(buf, 0, n)
100추가: }
101추가: } catch (e: IOException) {
102추가: // 라이브러리는 스트림이 닫히면 -1 대신 "Stream closed." IOException을 낸다.
103추가: } finally {
104추가: runCatching { stream.close() }
105추가: }
106추가: val text = out.toString(Charsets.UTF_8).trim()
107추가: Log.i(TAG, "데몬 기동 결과: $text")
108추가: if (!text.contains("started")) throw IOException("데몬을 시작하지 못했습니다: $text")
109추가: return text
110추가: }
111추가:
112추가: private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
113추가: }
수정android/app/src/main/java/com/androidremote/companion/MainActivity.kt+72-0
@@ -31,6 +31,9 @@ class MainActivity : Activity() {
3131 private lateinit var codeView: TextView
3232 private lateinit var sessionsBox: LinearLayout
3333 private lateinit var whitelistBox: LinearLayout
34추가: private lateinit var startCard: LinearLayout
35추가: private lateinit var startStatus: TextView
36추가: private lateinit var startButton: Button
3437 private var port = 27200
3538
3639 override fun onCreate(savedInstanceState: Bundle?) {
@@ -51,6 +54,8 @@ class MainActivity : Activity() {
5154 }
5255
5356 private fun onConnected(connected: Boolean) {
57추가: startCard.visibility = if (connected) View.GONE else View.VISIBLE
58추가: refreshStartCard()
5459 statusView.text = if (connected) "서비스 실행 중" else "서비스 꺼짐"
5560 statusView.setTextColor(if (connected) ACCENT else WARN)
5661 if (!connected) {
@@ -93,6 +98,51 @@ class MainActivity : Activity() {
9398 }
9499 }
95100
101추가: private fun refreshStartCard() {
102추가: val paired = Bootstrap.isPaired(this)
103추가: val wifiDebug = Bootstrap.isWirelessDebuggingOn(this)
104추가: val auto = Bootstrap.canToggleWirelessDebugging(this)
105추가: startStatus.text = buildString {
106추가: append(if (paired) "페어링: 완료" else "페어링: 안 됨")
107추가: append("\n무선 디버깅: ").append(if (wifiDebug) "켜짐" else "꺼짐")
108추가: append("\n무선 디버깅 자동 켜기: ").append(if (auto) "가능 (재부팅 후 자동 시작)" else "서비스를 한 번 시작하면 가능")
109추가: if (!paired) append("\n\n처음 한 번: 개발자 옵션 > 무선 디버깅을 켜고 '페어링 코드로 기기 페어링'을 연 뒤, 알림에 6자리 코드를 입력하세요.")
110추가: }
111추가: startButton.isEnabled = paired
112추가: }
113추가:
114추가: private fun openDeveloperSettings() {
115추가: runCatching { startActivity(android.content.Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)) }
116추가: }
117추가:
118추가: private fun startPairing() {
119추가: if (checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
120추가: requestPermissions(arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), REQ_NOTIFY)
121추가: return
122추가: }
123추가: PairingNotifier.show(this)
124추가: openDeveloperSettings()
125추가: }
126추가:
127추가: override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, results: IntArray) {
128추가: super.onRequestPermissionsResult(requestCode, permissions, results)
129추가: if (requestCode == REQ_NOTIFY && results.firstOrNull() == android.content.pm.PackageManager.PERMISSION_GRANTED) {
130추가: startPairing()
131추가: }
132추가: }
133추가:
134추가: private fun startDaemon() {
135추가: startButton.isEnabled = false
136추가: startStatus.text = "서비스 시작 중…"
137추가: Thread {
138추가: val r = Bootstrap.launchDaemon(applicationContext)
139추가: runOnUiThread {
140추가: refreshStartCard()
141추가: if (r.isFailure) startStatus.text = "시작 실패: ${r.exceptionOrNull()?.message}\n\n" + startStatus.text
142추가: }
143추가: }.start()
144추가: }
145추가:
96146 private fun confirmRevoke(host: String, key: String) {
97147 AlertDialog.Builder(this)
98148 .setTitle("$host 삭제")
@@ -134,6 +184,27 @@ class MainActivity : Activity() {
134184 card.addView(codeView)
135185 root.addView(card)
136186
187추가: startCard = card().apply {
188추가: (layoutParams as? LinearLayout.LayoutParams)?.topMargin = dp(12)
189추가: }
190추가: startCard.addView(label("USB 없이 시작", 16f, bold = true))
191추가: startStatus = label("", 13f, color = Color.LTGRAY).apply { setPadding(0, dp(6), 0, dp(10)) }
192추가: startCard.addView(startStatus)
193추가: startCard.addView(Button(this).apply {
194추가: text = "무선 디버깅 설정 열기"
195추가: setOnClickListener { openDeveloperSettings() }
196추가: })
197추가: startCard.addView(Button(this).apply {
198추가: text = "페어링 코드 입력 (최초 1회)"
199추가: setOnClickListener { startPairing() }
200추가: })
201추가: startButton = Button(this).apply {
202추가: text = "서비스 시작"
203추가: setOnClickListener { startDaemon() }
204추가: }
205추가: startCard.addView(startButton)
206추가: root.addView(startCard, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply { topMargin = dp(12) })
207추가:
137208 root.addView(section("연결 중인 PC"))
138209 sessionsBox = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
139210 root.addView(sessionsBox)
@@ -200,6 +271,7 @@ class MainActivity : Activity() {
200271 private fun dp(v: Int) = (v * resources.displayMetrics.density).toInt()
201272
202273 companion object {
274추가: private const val REQ_NOTIFY = 1
203275 private val BG = Color.rgb(0x10, 0x10, 0x10)
204276 private val CARD = Color.rgb(0x1e, 0x1e, 0x1e)
205277 private val ACCENT = Color.rgb(0x5c, 0xc8, 0x8a)
추가android/app/src/main/java/com/androidremote/companion/Pairing.kt+79-0
@@ -0,0 +1,79 @@
1추가: package com.androidremote.companion
2추가:
3추가: import android.app.Notification
4추가: import android.app.NotificationChannel
5추가: import android.app.NotificationManager
6추가: import android.app.PendingIntent
7추가: import android.app.RemoteInput
8추가: import android.content.BroadcastReceiver
9추가: import android.content.Context
10추가: import android.content.Intent
11추가:
12추가: /**
13추가: * 무선 디버깅 페어링 코드 입력 알림 (기획서 5.4 "페어링 코드 입력").
14추가: * 사용자는 설정의 페어링 코드 창을 연 채로 알림의 답장 칸에 6자리 코드를 입력한다.
15추가: */
16추가: object PairingNotifier {
17추가: private const val CHANNEL = "pairing"
18추가: const val ID = 1001
19추가: const val KEY_CODE = "code"
20추가:
21추가: fun show(context: Context, text: String = "무선 디버깅 > '페어링 코드로 기기 페어링'의 6자리 코드를 입력하세요") {
22추가: val nm = context.getSystemService(NotificationManager::class.java)
23추가: nm.createNotificationChannel(
24추가: NotificationChannel(CHANNEL, "무선 디버깅 페어링", NotificationManager.IMPORTANCE_HIGH),
25추가: )
26추가: val input = RemoteInput.Builder(KEY_CODE).setLabel("페어링 코드 6자리").build()
27추가: val reply = PendingIntent.getBroadcast(
28추가: context, 0, Intent(context, PairingReceiver::class.java),
29추가: PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE,
30추가: )
31추가: val action = Notification.Action.Builder(null, "코드 입력", reply).addRemoteInput(input).build()
32추가: val n = Notification.Builder(context, CHANNEL)
33추가: .setSmallIcon(android.R.drawable.stat_sys_data_bluetooth)
34추가: .setContentTitle("Android Remote 페어링")
35추가: .setContentText(text)
36추가: .setOngoing(true)
37추가: .addAction(action)
38추가: .build()
39추가: nm.notify(ID, n)
40추가: }
41추가:
42추가: fun result(context: Context, text: String) {
43추가: val n = Notification.Builder(context, CHANNEL)
44추가: .setSmallIcon(android.R.drawable.stat_sys_data_bluetooth)
45추가: .setContentTitle("Android Remote 페어링")
46추가: .setContentText(text)
47추가: .setAutoCancel(true)
48추가: .build()
49추가: context.getSystemService(NotificationManager::class.java).notify(ID, n)
50추가: }
51추가: }
52추가:
53추가: /** 알림 답장으로 받은 코드로 페어링하고, 성공하면 바로 데몬을 띄운다. */
54추가: class PairingReceiver : BroadcastReceiver() {
55추가: override fun onReceive(context: Context, intent: Intent) {
56추가: val code = RemoteInput.getResultsFromIntent(intent)?.getCharSequence(PairingNotifier.KEY_CODE)?.toString()
57추가: if (code.isNullOrBlank()) return
58추가: PairingNotifier.result(context, "페어링 중…")
59추가: val pending = goAsync()
60추가: val app = context.applicationContext
61추가: Thread {
62추가: try {
63추가: val paired = Bootstrap.pair(app, code)
64추가: if (paired.isFailure) {
65추가: PairingNotifier.show(app, "페어링 실패: ${paired.exceptionOrNull()?.message}. 다시 입력하세요")
66추가: return@Thread
67추가: }
68추가: val started = Bootstrap.launchDaemon(app)
69추가: PairingNotifier.result(
70추가: app,
71추가: if (started.isSuccess) "페어링 완료, 서비스를 시작했습니다"
72추가: else "페어링 완료. 서비스 시작 실패: ${started.exceptionOrNull()?.message}",
73추가: )
74추가: } finally {
75추가: pending.finish()
76추가: }
77추가: }.start()
78추가: }
79추가: }
추가android/app/src/main/java/com/androidremote/companion/SelfAdb.kt+82-0
@@ -0,0 +1,82 @@
1추가: package com.androidremote.companion
2추가:
3추가: import android.content.Context
4추가: import android.os.Build
5추가: import com.androidremote.daemon.SelfSignedCert
6추가: import io.github.muntashirakon.adb.AbsAdbConnectionManager
7추가: import io.github.muntashirakon.adb.android.AdbMdns
8추가: import java.io.ByteArrayInputStream
9추가: import java.io.File
10추가: import java.net.InetAddress
11추가: import java.security.KeyFactory
12추가: import java.security.KeyPairGenerator
13추가: import java.security.PrivateKey
14추가: import java.security.SecureRandom
15추가: import java.security.cert.Certificate
16추가: import java.security.cert.CertificateFactory
17추가: import java.security.spec.PKCS8EncodedKeySpec
18추가: import java.util.concurrent.CountDownLatch
19추가: import java.util.concurrent.TimeUnit
20추가:
21추가: /**
22추가: * 동반 앱 전용 ADB 클라이언트 (기획서 5.4 "앱 전용 ADB 키 등록").
23추가: * RSA-2048 키와 자체 서명 인증서를 앱 전용 저장소에 두고, 기기 자신의 무선 디버깅(adbd)에 접속한다.
24추가: */
25추가: class SelfAdb private constructor(context: Context) : AbsAdbConnectionManager() {
26추가: private val key: PrivateKey
27추가: private val cert: Certificate
28추가:
29추가: init {
30추가: setApi(Build.VERSION.SDK_INT)
31추가: setTimeout(15, TimeUnit.SECONDS)
32추가: val dir = File(context.filesDir, "adb").apply { mkdirs() }
33추가: val keyFile = File(dir, "adbkey.pk8")
34추가: val certFile = File(dir, "adbkey.crt")
35추가: if (keyFile.exists() && certFile.exists()) {
36추가: key = KeyFactory.getInstance("RSA").generatePrivate(PKCS8EncodedKeySpec(keyFile.readBytes()))
37추가: cert = CertificateFactory.getInstance("X.509").generateCertificate(ByteArrayInputStream(certFile.readBytes()))
38추가: } else {
39추가: val gen = KeyPairGenerator.getInstance("RSA")
40추가: gen.initialize(2048, SecureRandom())
41추가: val pair = gen.generateKeyPair()
42추가: val der = SelfSignedCert.buildRsa(pair.private, pair.public.encoded, "android-remote-companion")
43추가: key = pair.private
44추가: cert = CertificateFactory.getInstance("X.509").generateCertificate(ByteArrayInputStream(der))
45추가: keyFile.writeBytes(pair.private.encoded)
46추가: certFile.writeBytes(der)
47추가: }
48추가: }
49추가:
50추가: override fun getPrivateKey(): PrivateKey = key
51추가: override fun getCertificate(): Certificate = cert
52추가: override fun getDeviceName(): String = "Android Remote"
53추가:
54추가: companion object {
55추가: @Volatile private var instance: SelfAdb? = null
56추가:
57추가: fun get(context: Context): SelfAdb =
58추가: instance ?: synchronized(this) { instance ?: SelfAdb(context.applicationContext).also { instance = it } }
59추가:
60추가: /**
61추가: * mDNS로 이 기기의 무선 디버깅 서비스 포트를 찾는다.
62추가: * `type`은 [AdbMdns.SERVICE_TYPE_TLS_PAIRING] 또는 [AdbMdns.SERVICE_TYPE_TLS_CONNECT].
63추가: */
64추가: fun discover(context: Context, type: String, timeoutMs: Long): Pair<InetAddress?, Int>? {
65추가: val latch = CountDownLatch(1)
66추가: var found: Pair<InetAddress?, Int>? = null
67추가: val mdns = AdbMdns(context, type) { host, port ->
68추가: if (port > 0 && found == null) {
69추가: found = host to port
70추가: latch.countDown()
71추가: }
72추가: }
73추가: mdns.start()
74추가: try {
75추가: latch.await(timeoutMs, TimeUnit.MILLISECONDS)
76추가: } finally {
77추가: mdns.stop()
78추가: }
79추가: return found
80추가: }
81추가: }
82추가: }
수정android/app/src/main/java/com/androidremote/daemon/DaemonMain.kt+5-0
@@ -36,6 +36,11 @@ object DaemonMain {
3636 // 일부 시스템 서비스 클라이언트가 Looper를 요구한다.
3737 Looper.prepareMainLooper()
3838
39추가: // 동반 앱이 재부팅 후 무선 디버깅을 직접 켰다 끌 수 있게 한다 (기획서 5.4 "WRITE_SECURE_SETTINGS 자가 부여").
40추가: runCatching {
41추가: Runtime.getRuntime().exec(arrayOf("pm", "grant", "com.androidremote", "android.permission.WRITE_SECURE_SETTINGS")).waitFor()
42추가: }
43추가:
3944 val identity = DeviceIdentity.loadOrCreate(dataDir)
4045 val whitelist = Whitelist(File(dataDir, "whitelist"))
4146 Log.i("android-remote daemon v$DAEMON_VERSION uid=${android.os.Process.myUid()}")
수정android/app/src/main/java/com/androidremote/daemon/DeviceIdentity.kt+14-3
@@ -99,20 +99,31 @@ class DeviceIdentity private constructor(
9999 */
100100object SelfSignedCert {
101101 private val OID_ECDSA_SHA256 = byteArrayOf(0x06, 0x08, 0x2A, 0x86.toByte(), 0x48, 0xCE.toByte(), 0x3D, 0x04, 0x03, 0x02)
102추가: /** sha256WithRSAEncryption (1.2.840.113549.1.1.11) + NULL 매개변수. */
103추가: private val ALG_RSA_SHA256 = byteArrayOf(
104추가: 0x06, 0x09, 0x2A, 0x86.toByte(), 0x48, 0x86.toByte(), 0xF7.toByte(), 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00,
105추가: )
102106 private val OID_COMMON_NAME = byteArrayOf(0x06, 0x03, 0x55, 0x04, 0x03)
103107
104삭제: fun build(key: PrivateKey, spki: ByteArray, commonName: String): ByteArray {
108추가: /** ECDSA P-256 키로 서명한 인증서 (기기 TLS 신원). */
109추가: fun build(key: PrivateKey, spki: ByteArray, commonName: String): ByteArray =
110추가: build(key, spki, commonName, seq(OID_ECDSA_SHA256), "SHA256withECDSA")
111추가:
112추가: /** RSA 키로 서명한 인증서 (동반 앱의 ADB 클라이언트 키). */
113추가: fun buildRsa(key: PrivateKey, spki: ByteArray, commonName: String): ByteArray =
114추가: build(key, spki, commonName, seq(ALG_RSA_SHA256), "SHA256withRSA")
115추가:
116추가: private fun build(key: PrivateKey, spki: ByteArray, commonName: String, sigAlg: ByteArray, sigName: String): ByteArray {
105117 val serialBytes = ByteArray(16).also { SecureRandom().nextBytes(it) }
106118 serialBytes[0] = (serialBytes[0].toInt() and 0x7F).toByte() // 양수
107119 val serial = der(0x02, BigInteger(serialBytes).toByteArray())
108삭제: val sigAlg = seq(OID_ECDSA_SHA256)
109120 val name = seq(set(seq(OID_COMMON_NAME, der(0x0C, commonName.toByteArray(Charsets.UTF_8)))))
110121 val now = Date()
111122 val validity = seq(utcTime(Date(now.time - 24L * 3600 * 1000)), utcTime(parseUtc("491231235959Z")))
112123 val version = der(0xA0, der(0x02, byteArrayOf(0x02)))
113124 val tbs = seq(version, serial, sigAlg, name, validity, name, spki)
114125
115삭제: val signer = Signature.getInstance("SHA256withECDSA")
126추가: val signer = Signature.getInstance(sigName)
116127 signer.initSign(key)
117128 signer.update(tbs)
118129 val signature = signer.sign()
수정android/gradle/libs.versions.toml+4-0
@@ -1,9 +1,13 @@
11[versions]
22agp = "9.5.2"
33bouncycastle = "1.87"
4추가: libadb = "3.1.1"
5추가: conscrypt = "2.5.3"
46
57[libraries]
68bouncycastle-prov = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bouncycastle" }
9추가: libadb = { module = "com.github.MuntashirAkon:libadb-android", version.ref = "libadb" }
10추가: conscrypt = { module = "org.conscrypt:conscrypt-android", version.ref = "conscrypt" }
711
812[plugins]
913android-application = { id = "com.android.application", version.ref = "agp" }
수정android/settings.gradle.kts+6-0
@@ -11,6 +11,12 @@ dependencyResolutionManagement {
1111 repositories {
1212 google()
1313 mavenCentral()
14추가: // libadb-android와 그 의존성(spake2-android)은 JitPack에만 있다.
15추가: maven("https://jitpack.io") {
16추가: content {
17추가: includeGroupByRegex("com\\.github\\.MuntashirAkon.*")
18추가: }
19추가: }
1420 }
1521}
1622