leejunyoung5819wayland-android-remote

공개

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

기기 데몬 1단계: TLS 1.3 서버, PC 인증, 제어 채널

- 자체 서명 ECDSA P-256 기기 인증서 생성·저장, TLS 1.3 서버(Conscrypt)
- Ed25519 PC 인증(BouncyCastle, Android 15 플랫폼에 Ed25519 없음), 허용 목록, 세션 토큰, 영상 채널 연결 수락
- SYSTEM_ACTION(뒤로·홈·최근 앱 등) 키 입력 주입, 영상 설정 응답(인코더 전)
- 개발용 데몬 실행 스크립트(scripts/dev-daemon.sh)와 연결 점검 도구(examples/probe.rs)
- 실제 Galaxy S21+(Android 15)에서 USB·Wi-Fi 접속과 홈/뒤로 키 동작 확인
작성자
LeeJunyoung
작성 시각
커밋
06a39d9ad69a3a13be7b417a69749702e513ad66
부모
91377fd
이 시점의 파일 보기

변경된 파일 11개

+901-9
수정README.md+16-0
@@ -51,3 +51,19 @@ cargo run --example fake_device -- --policy always --delay-ms 3000
5151```
5252
5353다른 터미널에서 `cargo run`으로 호스트를 띄우고 IP 입력창에 `127.0.0.1`을 입력합니다. 승인 정책은 `always`, `once`, `reject`, `never` 중에서 고릅니다.
54추가:
55추가: ### 실제 휴대폰으로 테스트하기 (개발용)
56추가:
57추가: 동반 앱의 무선 디버깅 자가 기동(기획서 5.4)이 생기기 전까지는 USB로 데몬을 띄웁니다. 폰에서 USB 디버깅을 허용한 뒤:
58추가:
59추가: ```bash
60추가: ./scripts/dev-daemon.sh
61추가: ```
62추가:
63추가: APK를 빌드·설치하고 데몬을 포그라운드로 실행합니다(Ctrl+C로 종료). `adb forward`도 걸어 두므로 호스트에서 `127.0.0.1`(USB) 또는 폰의 Wi-Fi IP로 접속할 수 있습니다. 승인 팝업이 아직 없어서 처음 접속하는 PC는 `APPROVE` 환경 변수(기본 `always`)대로 처리합니다.
64추가:
65추가: GUI 없이 접속만 점검하려면:
66추가:
67추가: ```bash
68추가: cargo run --example probe -- 127.0.0.1 --key home
69추가: ```
수정android/app/build.gradle.kts+5-0
@@ -31,3 +31,8 @@ android {
3131 targetCompatibility = JavaVersion.VERSION_17
3232 }
3333}
34추가:
35추가: dependencies {
36추가: // Android 플랫폼에는 Ed25519 서명 검증이 없어 PC 인증(기획서 5.3)에 BouncyCastle 경량 API를 쓴다.
37추가: implementation(libs.bouncycastle.prov)
38추가: }
추가android/app/src/main/java/com/androidremote/daemon/Auth.kt+62-0
@@ -0,0 +1,62 @@
1추가: package com.androidremote.daemon
2추가:
3추가: import java.io.File
4추가:
5추가: /**
6추가: * 호스트 PC의 Ed25519 서명 검증 (기획서 5.3). Android 15 플랫폼 암호 공급자에는 Ed25519가
7추가: * 없어서 BouncyCastle 경량 API를 직접 쓴다. 플랫폼 내장 BC는 다른 패키지명이라 충돌하지 않는다.
8추가: */
9추가: object Ed25519 {
10추가: fun verify(publicKey: ByteArray, message: ByteArray, signature: ByteArray): Boolean = try {
11추가: val verifier = org.bouncycastle.crypto.signers.Ed25519Signer()
12추가: verifier.init(false, org.bouncycastle.crypto.params.Ed25519PublicKeyParameters(publicKey, 0))
13추가: verifier.update(message, 0, message.size)
14추가: verifier.verifySignature(signature)
15추가: } catch (e: Exception) {
16추가: Log.w("Ed25519 검증 오류: $e")
17추가: false
18추가: }
19추가: }
20추가:
21추가: /**
22추가: * 허용된 PC 공개키 목록 (기획서 5.2). 동반 앱과의 동기화를 붙이기 전까지는 데몬 저장소의
23추가: * 파일(한 줄에 `공개키16진수 호스트명`)을 직접 쓴다.
24추가: */
25추가: class Whitelist(private val file: File) {
26추가: private val keys = LinkedHashMap<String, String>()
27추가:
28추가: init {
29추가: if (file.exists()) {
30추가: file.readLines().forEach { line ->
31추가: val parts = line.trim().split(" ", limit = 2)
32추가: if (parts[0].length == 64) keys[parts[0]] = parts.getOrElse(1) { "" }
33추가: }
34추가: }
35추가: }
36추가:
37추가: @Synchronized
38추가: fun contains(publicKey: ByteArray): Boolean = keys.containsKey(Hex.encode(publicKey))
39추가:
40추가: @Synchronized
41추가: fun add(publicKey: ByteArray, hostname: String) {
42추가: keys[Hex.encode(publicKey)] = hostname.replace('\n', ' ')
43추가: DeviceIdentity.writePrivate(file, keys.entries.joinToString("") { "${it.key} ${it.value}\n" }.toByteArray())
44추가: }
45추가: }
46추가:
47추가: /** 처음 접속하는 PC를 어떻게 처리할지. 동반 앱 승인 팝업이 생기기 전까지 쓰는 임시 정책. */
48추가: enum class ApprovePolicy { ALWAYS, ONCE, REJECT }
49추가:
50추가: object Hex {
51추가: fun encode(bytes: ByteArray): String = bytes.joinToString("") { "%02x".format(it) }
52추가: }
53추가:
54추가: object Log {
55추가: private val fmt = java.text.SimpleDateFormat("HH:mm:ss.SSS", java.util.Locale.US)
56추가:
57추가: @Synchronized
58추가: fun i(msg: String) = println("${fmt.format(java.util.Date())} I $msg")
59추가:
60추가: @Synchronized
61추가: fun w(msg: String) = println("${fmt.format(java.util.Date())} W $msg")
62추가: }
수정android/app/src/main/java/com/androidremote/daemon/DaemonMain.kt+41-7
@@ -1,25 +1,59 @@
11package com.androidremote.daemon
22
3추가: import android.os.Looper
4추가: import java.io.File
5추가:
36/**
47 * shell 권한 데몬 진입점 (기획서 5.4).
58 *
6삭제: * 동반 앱이 로컬 adbd에 접속해 다음처럼 실행한다.
7삭제: * `CLASSPATH=<APK 경로> app_process / com.androidremote.daemon.DaemonMain --port 27200`
9추가: * `CLASSPATH=<APK 경로> app_process / com.androidremote.daemon.DaemonMain [옵션]`
10추가: *
11추가: * 옵션:
12추가: * - `--port N` 수신 포트 (기본 27200)
13추가: * - `--data-dir 경로` 인증서·허용 목록 저장 위치 (기본 /data/local/tmp/android-remote)
14추가: * - `--approve always|once|reject` 처음 접속하는 PC 처리. 동반 앱 승인 팝업이 생기기 전까지 쓰는
15추가: * 임시 옵션이며 기본값은 reject다.
816 */
917object DaemonMain {
1018 const val DEFAULT_PORT = 27200
19추가: private const val DEFAULT_DATA_DIR = "/data/local/tmp/android-remote"
20추가:
21추가: /** 데몬 버전 = APK versionCode (기획서 5.4). BuildConfig 없이 맞추기 위해 상수로 둔다. */
22추가: private const val DAEMON_VERSION = 1
1123
1224 @JvmStatic
1325 fun main(args: Array<String>) {
1426 val port = parsePort(args)
15삭제: println("android-remote daemon: port=$port (아직 구현 전)")
27추가: val dataDir = File(option(args, "--data-dir") ?: DEFAULT_DATA_DIR)
28추가: val policy = when (option(args, "--approve") ?: "reject") {
29추가: "always" -> ApprovePolicy.ALWAYS
30추가: "once" -> ApprovePolicy.ONCE
31추가: "reject" -> ApprovePolicy.REJECT
32추가: else -> throw IllegalArgumentException("--approve 값은 always|once|reject 중 하나입니다")
33추가: }
34추가:
35추가: // 일부 시스템 서비스 클라이언트가 Looper를 요구한다.
36추가: Looper.prepareMainLooper()
37추가:
38추가: val identity = DeviceIdentity.loadOrCreate(dataDir)
39추가: val whitelist = Whitelist(File(dataDir, "whitelist"))
40추가: Log.i("android-remote daemon v$DAEMON_VERSION uid=${android.os.Process.myUid()}")
41추가: Log.i("인증서 SHA-256: ${Hex.encode(identity.fingerprint)}")
42추가: Log.i("확인 코드: ${identity.confirmCode}, 새 PC 정책: $policy")
43추가: SystemAccess.displaySize()?.let { (w, h) -> Log.i("디스플레이: ${w}x$h") }
44추가:
45추가: Server(port, identity, whitelist, policy, DAEMON_VERSION).run()
46추가: }
47추가:
48추가: internal fun option(args: Array<String>, name: String): String? {
49추가: val i = args.indexOf(name)
50추가: return if (i >= 0) args.getOrNull(i + 1) else null
1651 }
1752
1853 internal fun parsePort(args: Array<String>): Int {
19삭제: val i = args.indexOf("--port")
20삭제: if (i < 0) return DEFAULT_PORT
21삭제: val value = args.getOrNull(i + 1)?.toIntOrNull()
22삭제: require(value != null && value in 1..65535) { "--port 값이 올바르지 않습니다: ${args.getOrNull(i + 1)}" }
54추가: val raw = option(args, "--port") ?: return DEFAULT_PORT
55추가: val value = raw.toIntOrNull()
56추가: require(value != null && value in 1..65535) { "--port 값이 올바르지 않습니다: $raw" }
2357 return value
2458 }
2559}
추가android/app/src/main/java/com/androidremote/daemon/DeviceIdentity.kt+151-0
@@ -0,0 +1,151 @@
1추가: package com.androidremote.daemon
2추가:
3추가: import android.system.Os
4추가: import java.io.ByteArrayInputStream
5추가: import java.io.ByteArrayOutputStream
6추가: import java.io.File
7추가: import java.math.BigInteger
8추가: import java.security.KeyFactory
9추가: import java.security.KeyPairGenerator
10추가: import java.security.KeyStore
11추가: import java.security.MessageDigest
12추가: import java.security.PrivateKey
13추가: import java.security.SecureRandom
14추가: import java.security.Signature
15추가: import java.security.cert.CertificateFactory
16추가: import java.security.cert.X509Certificate
17추가: import java.security.spec.ECGenParameterSpec
18추가: import java.security.spec.PKCS8EncodedKeySpec
19추가: import java.text.SimpleDateFormat
20추가: import java.util.Date
21추가: import java.util.Locale
22추가: import java.util.TimeZone
23추가: import javax.net.ssl.KeyManagerFactory
24추가: import javax.net.ssl.SSLContext
25추가:
26추가: /**
27추가: * 기기 TLS 신원 (기획서 5.5). 최초 실행 시 ECDSA P-256 키와 자체 서명 인증서를 만들어
28추가: * shell 사용자만 읽을 수 있는 디렉터리에 저장하고, 이후에는 그대로 다시 쓴다.
29추가: */
30추가: class DeviceIdentity private constructor(
31추가: private val privateKey: PrivateKey,
32추가: val certificate: X509Certificate,
33추가: ) {
34추가: /** 인증서 DER의 SHA-256. 호스트가 고정하는 값과 같다. */
35추가: val fingerprint: ByteArray = MessageDigest.getInstance("SHA-256").digest(certificate.encoded)
36추가:
37추가: /** 지문 앞 8바이트(Big-Endian u64) % 1,000,000. 호스트 `protocol::confirm_code`와 같은 계산. */
38추가: val confirmCode: String
39추가: get() {
40추가: var v = 0L
41추가: for (i in 0 until 8) v = (v shl 8) or (fingerprint[i].toLong() and 0xFF)
42추가: return "%06d".format(java.lang.Long.remainderUnsigned(v, 1_000_000))
43추가: }
44추가:
45추가: fun sslContext(): SSLContext {
46추가: val ks = KeyStore.getInstance("PKCS12")
47추가: ks.load(null, null)
48추가: ks.setKeyEntry("device", privateKey, CharArray(0), arrayOf(certificate))
49추가: val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
50추가: kmf.init(ks, CharArray(0))
51추가: val ctx = SSLContext.getInstance("TLSv1.3")
52추가: ctx.init(kmf.keyManagers, null, SecureRandom())
53추가: return ctx
54추가: }
55추가:
56추가: companion object {
57추가: private const val KEY_FILE = "device_key.pk8"
58추가: private const val CERT_FILE = "device_cert.der"
59추가:
60추가: fun loadOrCreate(dir: File): DeviceIdentity {
61추가: ensurePrivateDir(dir)
62추가: val keyFile = File(dir, KEY_FILE)
63추가: val certFile = File(dir, CERT_FILE)
64추가: if (keyFile.exists() && certFile.exists()) {
65추가: val key = KeyFactory.getInstance("EC")
66추가: .generatePrivate(PKCS8EncodedKeySpec(keyFile.readBytes()))
67추가: val cert = CertificateFactory.getInstance("X.509")
68추가: .generateCertificate(ByteArrayInputStream(certFile.readBytes())) as X509Certificate
69추가: return DeviceIdentity(key, cert)
70추가: }
71추가:
72추가: val gen = KeyPairGenerator.getInstance("EC")
73추가: gen.initialize(ECGenParameterSpec("secp256r1"), SecureRandom())
74추가: val pair = gen.generateKeyPair()
75추가: val der = SelfSignedCert.build(pair.private, pair.public.encoded, "android-remote-device")
76추가: val cert = CertificateFactory.getInstance("X.509")
77추가: .generateCertificate(ByteArrayInputStream(der)) as X509Certificate
78추가:
79추가: writePrivate(keyFile, pair.private.encoded)
80추가: writePrivate(certFile, der)
81추가: return DeviceIdentity(pair.private, cert)
82추가: }
83추가:
84추가: fun ensurePrivateDir(dir: File) {
85추가: if (!dir.exists() && !dir.mkdirs()) throw IllegalStateException("디렉터리 생성 실패: $dir")
86추가: Os.chmod(dir.path, "700".toInt(8))
87추가: }
88추가:
89추가: fun writePrivate(file: File, bytes: ByteArray) {
90추가: file.writeBytes(bytes)
91추가: Os.chmod(file.path, "600".toInt(8))
92추가: }
93추가: }
94추가: }
95추가:
96추가: /**
97추가: * 외부 라이브러리 없이 자체 서명 X.509 v3 인증서를 DER로 만든다.
98추가: * 호스트는 CA 검증 없이 지문만 비교하므로 확장 필드는 넣지 않는다.
99추가: */
100추가: object SelfSignedCert {
101추가: private val OID_ECDSA_SHA256 = byteArrayOf(0x06, 0x08, 0x2A, 0x86.toByte(), 0x48, 0xCE.toByte(), 0x3D, 0x04, 0x03, 0x02)
102추가: private val OID_COMMON_NAME = byteArrayOf(0x06, 0x03, 0x55, 0x04, 0x03)
103추가:
104추가: fun build(key: PrivateKey, spki: ByteArray, commonName: String): ByteArray {
105추가: val serialBytes = ByteArray(16).also { SecureRandom().nextBytes(it) }
106추가: serialBytes[0] = (serialBytes[0].toInt() and 0x7F).toByte() // 양수
107추가: val serial = der(0x02, BigInteger(serialBytes).toByteArray())
108추가: val sigAlg = seq(OID_ECDSA_SHA256)
109추가: val name = seq(set(seq(OID_COMMON_NAME, der(0x0C, commonName.toByteArray(Charsets.UTF_8)))))
110추가: val now = Date()
111추가: val validity = seq(utcTime(Date(now.time - 24L * 3600 * 1000)), utcTime(parseUtc("491231235959Z")))
112추가: val version = der(0xA0, der(0x02, byteArrayOf(0x02)))
113추가: val tbs = seq(version, serial, sigAlg, name, validity, name, spki)
114추가:
115추가: val signer = Signature.getInstance("SHA256withECDSA")
116추가: signer.initSign(key)
117추가: signer.update(tbs)
118추가: val signature = signer.sign()
119추가: return seq(tbs, sigAlg, der(0x03, byteArrayOf(0x00) + signature))
120추가: }
121추가:
122추가: private fun parseUtc(s: String): Date = utcFormat().parse(s)!!
123추가:
124추가: private fun utcTime(d: Date): ByteArray = der(0x17, utcFormat().format(d).toByteArray(Charsets.US_ASCII))
125추가:
126추가: private fun utcFormat() = SimpleDateFormat("yyMMddHHmmss'Z'", Locale.US).apply {
127추가: timeZone = TimeZone.getTimeZone("UTC")
128추가: }
129추가:
130추가: private fun seq(vararg parts: ByteArray) = der(0x30, concat(parts))
131추가: private fun set(vararg parts: ByteArray) = der(0x31, concat(parts))
132추가:
133추가: private fun concat(parts: Array<out ByteArray>): ByteArray {
134추가: val out = ByteArrayOutputStream()
135추가: parts.forEach { out.write(it) }
136추가: return out.toByteArray()
137추가: }
138추가:
139추가: private fun der(tag: Int, content: ByteArray): ByteArray {
140추가: val out = ByteArrayOutputStream()
141추가: out.write(tag)
142추가: val len = content.size
143추가: when {
144추가: len < 0x80 -> out.write(len)
145추가: len < 0x100 -> { out.write(0x81); out.write(len) }
146추가: else -> { out.write(0x82); out.write(len shr 8); out.write(len and 0xFF) }
147추가: }
148추가: out.write(content)
149추가: return out.toByteArray()
150추가: }
151추가: }
수정android/app/src/main/java/com/androidremote/daemon/Protocol.kt+203-2
@@ -1,14 +1,21 @@
11package com.androidremote.daemon
22
3추가: import java.io.DataInputStream
4추가: import java.io.EOFException
5추가: import java.io.IOException
6추가: import java.io.OutputStream
7추가: import java.nio.ByteBuffer
8추가:
39/**
4삭제: * 제어 채널 프레이밍 상수 (기획서 7.1, 7.2). 호스트의 Rust `protocol` 모듈과 값이 같아야 한다.
5삭제: * JVM ByteBuffer/DataInputStream 기본 바이트 순서가 Big-Endian이라 별도 변환 없이 읽는다.
10추가: * 제어 채널 프레이밍과 메시지 페이로드 (기획서 7.1 ~ 7.3). 호스트의 Rust `protocol` 모듈과
11추가: * 바이트 배치가 같아야 한다. JVM ByteBuffer 기본 바이트 순서가 Big-Endian이라 그대로 쓴다.
612 */
713object Protocol {
814 const val MAGIC: Int = 0x4152
915 const val VERSION: Int = 0x01
1016 const val HEADER_LEN: Int = 12
1117 const val MAX_PAYLOAD_LEN: Int = 4 * 1024 * 1024
18추가: const val VIDEO_HEADER_LEN: Int = 16
1219
1320 object MsgType {
1421 const val PING = 0x01
@@ -29,5 +36,199 @@ object Protocol {
2936 const val VIDEO_REQUEST_KEYFRAME = 0x42
3037 const val ACK = 0xF0
3138 const val ERROR = 0xFF
39추가:
40추가: /** AUTH_RESULT(OK) 전에도 처리할 수 있는 메시지 (기획서 7.3 6항). */
41추가: fun allowedBeforeAuth(type: Int): Boolean =
42추가: type == PING || type == PONG || type in AUTH_HELLO..AUTH_RESULT || type == ERROR
43추가: }
44추가:
45추가: object AuthStatus {
46추가: const val APPROVED = 0x00
47추가: const val PENDING_USER = 0x01
48추가: const val REJECTED = 0x02
49추가: }
50추가:
51추가: object AuthResultCode {
52추가: const val OK = 0x00
53추가: const val REJECTED = 0x01
54추가: const val TIMEOUT = 0x02
55추가: const val SIGNATURE_INVALID = 0x03
56추가: const val REVOKED = 0x04
57추가: }
58추가:
59추가: object Grant {
60추가: const val NONE = 0x00
61추가: const val ALWAYS = 0x01
62추가: const val ONCE = 0x02
63추가: }
64추가:
65추가: object Codec {
66추가: const val H264 = 0x01
67추가: const val H265 = 0x02
68추가: const val AV1 = 0x04
69추가: }
70추가:
71추가: object ErrorCode {
72추가: const val PAYLOAD_TOO_LARGE = 0x0001
73추가: const val BAD_FRAME = 0x0002
74추가: const val UNAUTHENTICATED = 0x0003
75추가: const val PERMISSION_DENIED = 0x0004
76추가: const val INTERNAL = 0x0005
77추가: }
78추가:
79추가: object SystemAction {
80추가: const val COPY = 0x01
81추가: const val PASTE = 0x02
82추가: const val CUT = 0x03
83추가: const val SELECT_ALL = 0x04
84추가: const val HOME = 0x10
85추가: const val BACK = 0x11
86추가: const val RECENTS = 0x12
87추가: }
88추가: }
89추가:
90추가: /** 프레임 경계가 깨졌거나 규격에 맞지 않는 데이터. 받으면 연결을 끊는다. */
91추가: class ProtocolException(message: String) : IOException(message)
92추가:
93추가: class Frame(val type: Int, val flags: Int, val seq: Int, val payload: ByteArray)
94추가:
95추가: /** TLS 스트림 위에서 12바이트 헤더 + 페이로드 프레임을 읽고 쓴다. */
96추가: class FrameIO(private val input: DataInputStream, private val output: OutputStream) {
97추가: private var nextSeq = 0
98추가: private val writeLock = Any()
99추가:
100추가: /** 프레임 하나를 끝까지 읽는다. 상대가 정상 종료했으면 null. */
101추가: fun read(): Frame? {
102추가: val header = ByteArray(Protocol.HEADER_LEN)
103추가: try {
104추가: input.readFully(header)
105추가: } catch (e: EOFException) {
106추가: return null
107추가: }
108추가: val b = ByteBuffer.wrap(header)
109추가: val magic = b.short.toInt() and 0xFFFF
110추가: val version = b.get().toInt() and 0xFF
111추가: val type = b.get().toInt() and 0xFF
112추가: val flags = b.short.toInt() and 0xFFFF
113추가: val seq = b.short.toInt() and 0xFFFF
114추가: val len = b.int.toLong() and 0xFFFFFFFFL
115추가: if (magic != Protocol.MAGIC) throw ProtocolException("잘못된 magic: 0x%04x".format(magic))
116추가: if (version != Protocol.VERSION) throw ProtocolException("지원하지 않는 버전: $version")
117추가: if (len > Protocol.MAX_PAYLOAD_LEN) throw ProtocolException("payload_len 초과: $len")
118추가: val payload = ByteArray(len.toInt())
119추가: input.readFully(payload)
120추가: return Frame(type, flags, seq, payload)
121추가: }
122추가:
123추가: /** 다음 순환 seq_id로 보낸다. */
124추가: fun send(type: Int, payload: ByteArray = ByteArray(0)): Int = synchronized(writeLock) {
125추가: val seq = nextSeq
126추가: nextSeq = (nextSeq + 1) and 0xFFFF
127추가: sendWithSeq(type, seq, payload)
128추가: seq
129추가: }
130추가:
131추가: /** PONG처럼 요청의 seq_id를 되돌려줄 때 쓴다. */
132추가: fun sendWithSeq(type: Int, seq: Int, payload: ByteArray = ByteArray(0)) = synchronized(writeLock) {
133추가: val buf = ByteBuffer.allocate(Protocol.HEADER_LEN + payload.size)
134추가: buf.putShort(Protocol.MAGIC.toShort())
135추가: buf.put(Protocol.VERSION.toByte())
136추가: buf.put(type.toByte())
137추가: buf.putShort(0)
138추가: buf.putShort(seq.toShort())
139추가: buf.putInt(payload.size)
140추가: buf.put(payload)
141추가: output.write(buf.array())
142추가: output.flush()
143추가: }
144추가:
145추가: fun sendError(code: Int, reason: String) {
146추가: val text = reason.toByteArray(Charsets.UTF_8)
147추가: val p = ByteBuffer.allocate(2 + text.size).putShort(code.toShort()).put(text).array()
148추가: send(Protocol.MsgType.ERROR, p)
149추가: }
150추가: }
151추가:
152추가: /** 메시지별 페이로드 인코딩/디코딩. 길이가 맞지 않으면 [ProtocolException]. */
153추가: object Messages {
154추가: class AuthHello(val publicKey: ByteArray, val hostname: String)
155추가:
156추가: fun decodeAuthHello(p: ByteArray): AuthHello {
157추가: if (p.size < 33 || p.size > 32 + 255) throw ProtocolException("AUTH_HELLO 길이 오류: ${p.size}")
158추가: val host = Utf8.decodeStrict(p.copyOfRange(32, p.size))
159추가: ?: throw ProtocolException("AUTH_HELLO 호스트명 UTF-8 오류")
160추가: return AuthHello(p.copyOfRange(0, 32), host)
161추가: }
162추가:
163추가: fun encodeAuthChallenge(status: Int, nonce: ByteArray): ByteArray =
164추가: ByteBuffer.allocate(36).put(status.toByte()).put(ByteArray(3)).put(nonce).array()
165추가:
166추가: fun decodeAuthResponse(p: ByteArray): ByteArray {
167추가: if (p.size != 64) throw ProtocolException("AUTH_RESPONSE 길이 오류: ${p.size}")
168추가: return p
169추가: }
170추가:
171추가: fun encodeAuthResult(result: Int, grant: Int, token: ByteArray, daemonVersion: Int): ByteArray =
172추가: ByteBuffer.allocate(40)
173추가: .put(result.toByte()).put(grant.toByte()).putShort(0)
174추가: .put(token).putInt(daemonVersion)
175추가: .array()
176추가:
177추가: class ChannelAttach(val kind: Int, val token: ByteArray)
178추가:
179추가: fun decodeChannelAttach(p: ByteArray): ChannelAttach {
180추가: if (p.size != 36) throw ProtocolException("CHANNEL_ATTACH 길이 오류: ${p.size}")
181추가: return ChannelAttach(p[0].toInt() and 0xFF, p.copyOfRange(4, 36))
182추가: }
183추가:
184추가: fun decodeSystemAction(p: ByteArray): Int {
185추가: if (p.size != 4) throw ProtocolException("SYSTEM_ACTION 길이 오류: ${p.size}")
186추가: return p[0].toInt() and 0xFF
187추가: }
188추가:
189추가: class VideoConfigRequest(val maxSize: Int, val maxFps: Int, val codecMask: Int, val bitrate: Long)
190추가:
191추가: fun decodeVideoConfigRequest(p: ByteArray): VideoConfigRequest {
192추가: if (p.size != 8) throw ProtocolException("VIDEO_CONFIG_REQUEST 길이 오류: ${p.size}")
193추가: val b = ByteBuffer.wrap(p)
194추가: return VideoConfigRequest(
195추가: maxSize = b.short.toInt() and 0xFFFF,
196추가: maxFps = b.get().toInt() and 0xFF,
197추가: codecMask = b.get().toInt() and 0xFF,
198추가: bitrate = b.int.toLong() and 0xFFFFFFFFL,
199추가: )
200추가: }
201추가:
202추가: class VideoConfig(
203추가: val codec: Int,
204추가: val configGen: Int,
205추가: val width: Int,
206추가: val height: Int,
207추가: val fps: Int,
208추가: val bitrate: Long,
209추가: val displayWidth: Int,
210추가: val displayHeight: Int,
211추가: )
212추가:
213추가: fun encodeVideoConfig(c: VideoConfig): ByteArray =
214추가: ByteBuffer.allocate(16)
215추가: .put(c.codec.toByte()).put(c.configGen.toByte())
216추가: .putShort(c.width.toShort()).putShort(c.height.toShort())
217추가: .put(c.fps.toByte()).put(0)
218추가: .putInt(c.bitrate.toInt())
219추가: .putShort(c.displayWidth.toShort()).putShort(c.displayHeight.toShort())
220추가: .array()
221추가: }
222추가:
223추가: object Utf8 {
224추가: /** 잘못된 UTF-8이면 null. */
225추가: fun decodeStrict(bytes: ByteArray): String? = try {
226추가: Charsets.UTF_8.newDecoder()
227추가: .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
228추가: .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT)
229추가: .decode(ByteBuffer.wrap(bytes))
230추가: .toString()
231추가: } catch (e: java.nio.charset.CharacterCodingException) {
232추가: null
32233 }
33234}
추가android/app/src/main/java/com/androidremote/daemon/Server.kt+233-0
@@ -0,0 +1,233 @@
1추가: package com.androidremote.daemon
2추가:
3추가: import android.view.KeyEvent
4추가: import java.io.BufferedInputStream
5추가: import java.io.BufferedOutputStream
6추가: import java.io.Closeable
7추가: import java.io.DataInputStream
8추가: import java.io.IOException
9추가: import java.net.InetAddress
10추가: import java.net.SocketException
11추가: import java.security.MessageDigest
12추가: import java.security.SecureRandom
13추가: import java.util.concurrent.ConcurrentHashMap
14추가: import java.util.concurrent.atomic.AtomicBoolean
15추가: import javax.net.ssl.SSLServerSocket
16추가: import javax.net.ssl.SSLSocket
17추가:
18추가: /**
19추가: * 제어·영상 연결을 받는 TLS 1.3 서버 (기획서 5.5, 7.6). 연결마다 스레드 하나를 쓴다.
20추가: * 첫 프레임이 AUTH_HELLO면 제어 연결, CHANNEL_ATTACH면 영상 연결이다.
21추가: */
22추가: class Server(
23추가: private val port: Int,
24추가: private val identity: DeviceIdentity,
25추가: private val whitelist: Whitelist,
26추가: private val policy: ApprovePolicy,
27추가: private val daemonVersion: Int,
28추가: ) {
29추가: private val random = SecureRandom()
30추가: /** 세션 토큰(16진수) -> 세션. 제어 연결이 살아 있는 동안만 들어 있다. */
31추가: private val sessions = ConcurrentHashMap<String, Session>()
32추가:
33추가: private class Session(val token: ByteArray) {
34추가: val videoAttached = AtomicBoolean(false)
35추가: val closeables = mutableListOf<Closeable>()
36추가:
37추가: @Synchronized
38추가: fun track(c: Closeable) = closeables.add(c)
39추가:
40추가: @Synchronized
41추가: fun closeAll() = closeables.forEach { runCatching { it.close() } }
42추가: }
43추가:
44추가: fun run() {
45추가: val ctx = identity.sslContext()
46추가: val ss = ctx.serverSocketFactory
47추가: .createServerSocket(port, 16, InetAddress.getByName("0.0.0.0")) as SSLServerSocket
48추가: ss.enabledProtocols = arrayOf("TLSv1.3")
49추가: ss.needClientAuth = false
50추가: Log.i("수신 대기: 0.0.0.0:$port (TLS 1.3)")
51추가: while (true) {
52추가: val socket = ss.accept() as SSLSocket
53추가: Thread({ handle(socket) }, "conn-${socket.inetAddress.hostAddress}").start()
54추가: }
55추가: }
56추가:
57추가: private fun handle(socket: SSLSocket) {
58추가: val peer = "${socket.inetAddress.hostAddress}:${socket.port}"
59추가: try {
60추가: socket.tcpNoDelay = true
61추가: socket.startHandshake()
62추가: val io = FrameIO(
63추가: DataInputStream(BufferedInputStream(socket.inputStream)),
64추가: BufferedOutputStream(socket.outputStream),
65추가: )
66추가: val first = io.read() ?: return
67추가: when (first.type) {
68추가: Protocol.MsgType.AUTH_HELLO -> handleControl(socket, io, first, peer)
69추가: Protocol.MsgType.CHANNEL_ATTACH -> handleVideo(socket, first, peer)
70추가: else -> {
71추가: Log.w("$peer: 인증 전 메시지 0x%02x".format(first.type))
72추가: io.sendError(Protocol.ErrorCode.UNAUTHENTICATED, "AUTH_HELLO가 먼저 와야 합니다")
73추가: }
74추가: }
75추가: } catch (e: SocketException) {
76추가: Log.i("$peer: 연결 종료 (${e.message})")
77추가: } catch (e: IOException) {
78추가: Log.w("$peer: $e")
79추가: } catch (e: Exception) {
80추가: Log.w("$peer: 처리 중 오류 $e")
81추가: } finally {
82추가: runCatching { socket.close() }
83추가: }
84추가: }
85추가:
86추가: private fun handleControl(socket: SSLSocket, io: FrameIO, helloFrame: Frame, peer: String) {
87추가: val hello = Messages.decodeAuthHello(helloFrame.payload)
88추가: val keyHex = Hex.encode(hello.publicKey)
89추가: val known = whitelist.contains(hello.publicKey)
90추가: Log.i("$peer: AUTH_HELLO host=${hello.hostname} key=${keyHex.take(16)}… 허용목록=${known}")
91추가:
92추가: val nonce = ByteArray(32).also { random.nextBytes(it) }
93추가: val status = if (known) Protocol.AuthStatus.APPROVED else Protocol.AuthStatus.PENDING_USER
94추가: io.send(Protocol.MsgType.AUTH_CHALLENGE, Messages.encodeAuthChallenge(status, nonce))
95추가:
96추가: val resp = readExpect(io, Protocol.MsgType.AUTH_RESPONSE) ?: return
97추가: val signature = Messages.decodeAuthResponse(resp.payload)
98추가: if (!Ed25519.verify(hello.publicKey, nonce + identity.fingerprint, signature)) {
99추가: Log.w("$peer: 서명 검증 실패")
100추가: io.send(Protocol.MsgType.AUTH_RESULT, Messages.encodeAuthResult(
101추가: Protocol.AuthResultCode.SIGNATURE_INVALID, Protocol.Grant.NONE, ByteArray(32), daemonVersion))
102추가: return
103추가: }
104추가:
105추가: val grant = if (known) {
106추가: Protocol.Grant.ALWAYS
107추가: } else {
108추가: Log.i("$peer: 새 PC 승인 요청 host=${hello.hostname} 확인 코드=${identity.confirmCode} 정책=$policy")
109추가: when (policy) {
110추가: ApprovePolicy.ALWAYS -> {
111추가: whitelist.add(hello.publicKey, hello.hostname)
112추가: Protocol.Grant.ALWAYS
113추가: }
114추가: ApprovePolicy.ONCE -> Protocol.Grant.ONCE
115추가: ApprovePolicy.REJECT -> {
116추가: io.send(Protocol.MsgType.AUTH_RESULT, Messages.encodeAuthResult(
117추가: Protocol.AuthResultCode.REJECTED, Protocol.Grant.NONE, ByteArray(32), daemonVersion))
118추가: return
119추가: }
120추가: }
121추가: }
122추가:
123추가: val token = ByteArray(32).also { random.nextBytes(it) }
124추가: val session = Session(token)
125추가: session.track(socket)
126추가: sessions[Hex.encode(token)] = session
127추가: try {
128추가: io.send(Protocol.MsgType.AUTH_RESULT, Messages.encodeAuthResult(
129추가: Protocol.AuthResultCode.OK, grant, token, daemonVersion))
130추가: Log.i("$peer: 인증 완료 grant=${if (grant == Protocol.Grant.ALWAYS) "ALWAYS" else "ONCE"}")
131추가: serveControl(io, peer)
132추가: } finally {
133추가: sessions.remove(Hex.encode(token))
134추가: session.closeAll()
135추가: Log.i("$peer: 세션 종료")
136추가: }
137추가: }
138추가:
139추가: /** 인증 중에는 PING만 응답하고 기다리던 메시지를 돌려준다. */
140추가: private fun readExpect(io: FrameIO, type: Int): Frame? {
141추가: while (true) {
142추가: val f = io.read() ?: return null
143추가: when {
144추가: f.type == type -> return f
145추가: f.type == Protocol.MsgType.PING -> io.sendWithSeq(Protocol.MsgType.PONG, f.seq)
146추가: !Protocol.MsgType.allowedBeforeAuth(f.type) -> {
147추가: io.sendError(Protocol.ErrorCode.UNAUTHENTICATED, "인증 전입니다")
148추가: return null
149추가: }
150추가: }
151추가: }
152추가: }
153추가:
154추가: private var configGen = 0
155추가:
156추가: private fun serveControl(io: FrameIO, peer: String) {
157추가: while (true) {
158추가: val f = io.read() ?: return
159추가: try {
160추가: when (f.type) {
161추가: Protocol.MsgType.PING -> io.sendWithSeq(Protocol.MsgType.PONG, f.seq)
162추가: Protocol.MsgType.PONG -> Unit
163추가: Protocol.MsgType.SYSTEM_ACTION -> handleSystemAction(Messages.decodeSystemAction(f.payload), peer)
164추가: Protocol.MsgType.VIDEO_CONFIG_REQUEST -> {
165추가: val req = Messages.decodeVideoConfigRequest(f.payload)
166추가: val cfg = videoConfigFor(req)
167추가: if (cfg == null) {
168추가: io.sendError(Protocol.ErrorCode.INTERNAL, "지원하는 코덱이 없습니다")
169추가: } else {
170추가: io.send(Protocol.MsgType.VIDEO_CONFIG, Messages.encodeVideoConfig(cfg))
171추가: Log.i("$peer: VIDEO_CONFIG ${cfg.width}x${cfg.height} ${cfg.fps}fps codec=${cfg.codec}")
172추가: }
173추가: }
174추가: else -> Log.i("$peer: 아직 처리하지 않는 메시지 0x%02x".format(f.type))
175추가: }
176추가: } catch (e: ProtocolException) {
177추가: Log.w("$peer: 잘못된 페이로드 $e")
178추가: io.sendError(Protocol.ErrorCode.BAD_FRAME, e.message ?: "")
179추가: }
180추가: }
181추가: }
182추가:
183추가: private fun handleSystemAction(code: Int, peer: String) {
184추가: val keycode = when (code) {
185추가: Protocol.SystemAction.BACK -> KeyEvent.KEYCODE_BACK
186추가: Protocol.SystemAction.HOME -> KeyEvent.KEYCODE_HOME
187추가: Protocol.SystemAction.RECENTS -> KeyEvent.KEYCODE_APP_SWITCH
188추가: Protocol.SystemAction.COPY -> KeyEvent.KEYCODE_COPY
189추가: Protocol.SystemAction.PASTE -> KeyEvent.KEYCODE_PASTE
190추가: Protocol.SystemAction.CUT -> KeyEvent.KEYCODE_CUT
191추가: else -> {
192추가: Log.w("$peer: 처리하지 않는 SYSTEM_ACTION 0x%02x".format(code))
193추가: return
194추가: }
195추가: }
196추가: SystemAccess.pressKey(keycode)
197추가: Log.i("$peer: SYSTEM_ACTION 0x%02x -> keycode $keycode".format(code))
198추가: }
199추가:
200추가: /** 1단계: 인코더 없이 기기 화면 크기로 영상 설정만 계산한다. 인코딩은 2단계에서 붙인다. */
201추가: @Synchronized
202추가: private fun videoConfigFor(req: Messages.VideoConfigRequest): Messages.VideoConfig? {
203추가: val codec = when {
204추가: req.codecMask and Protocol.Codec.H264 != 0 -> Protocol.Codec.H264
205추가: req.codecMask and Protocol.Codec.H265 != 0 -> Protocol.Codec.H265
206추가: else -> return null
207추가: }
208추가: val (dw, dh) = SystemAccess.displaySize() ?: (1080 to 2400)
209추가: val long = maxOf(dw, dh)
210추가: val scale = if (req.maxSize == 0 || req.maxSize >= long) 1.0 else req.maxSize.toDouble() / long
211추가: val w = ((dw * scale).toInt()) and 1.inv()
212추가: val h = ((dh * scale).toInt()) and 1.inv()
213추가: configGen = (configGen % 255) + 1
214추가: val fps = if (req.maxFps == 0) 60 else minOf(req.maxFps, 120)
215추가: return Messages.VideoConfig(codec, configGen, w, h, fps, req.bitrate, dw, dh)
216추가: }
217추가:
218추가: private fun handleVideo(socket: SSLSocket, first: Frame, peer: String) {
219추가: val attach = Messages.decodeChannelAttach(first.payload)
220추가: val session = sessions.values.firstOrNull {
221추가: MessageDigest.isEqual(it.token, attach.token)
222추가: }
223추가: if (attach.kind != 0x01 || session == null || !session.videoAttached.compareAndSet(false, true)) {
224추가: Log.w("$peer: CHANNEL_ATTACH 거부 (토큰 없음, 재사용 또는 종류 오류)")
225추가: return
226추가: }
227추가: session.track(socket)
228추가: Log.i("$peer: 영상 채널 연결 (인코더는 2단계에서 구현)")
229추가: // 호스트는 영상 채널로 아무것도 보내지 않는다. 연결이 닫힐 때까지 기다린다.
230추가: val buf = ByteArray(256)
231추가: while (socket.inputStream.read(buf) >= 0) Unit
232추가: }
233추가: }
추가android/app/src/main/java/com/androidremote/daemon/SystemAccess.kt+56-0
@@ -0,0 +1,56 @@
1추가: package com.androidremote.daemon
2추가:
3추가: import android.os.SystemClock
4추가: import android.view.InputDevice
5추가: import android.view.InputEvent
6추가: import android.view.KeyCharacterMap
7추가: import android.view.KeyEvent
8추가: import java.lang.reflect.Method
9추가:
10추가: /**
11추가: * shell 권한으로만 쓸 수 있는 숨은 시스템 API 접근. 리플렉션으로 호출한다.
12추가: * minSdk 35이므로 API 34+ 클래스(InputManagerGlobal)를 바로 쓴다.
13추가: */
14추가: object SystemAccess {
15추가: private const val INJECT_MODE_ASYNC = 0
16추가:
17추가: private val injector: Pair<Any, Method> by lazy {
18추가: val cls = Class.forName("android.hardware.input.InputManagerGlobal")
19추가: val instance = cls.getMethod("getInstance").invoke(null)!!
20추가: val method = cls.getMethod("injectInputEvent", InputEvent::class.java, Int::class.javaPrimitiveType)
21추가: instance to method
22추가: }
23추가:
24추가: fun injectEvent(event: InputEvent): Boolean = try {
25추가: val (instance, method) = injector
26추가: method.invoke(instance, event, INJECT_MODE_ASYNC) as Boolean
27추가: } catch (e: Exception) {
28추가: Log.w("입력 주입 실패: $e")
29추가: false
30추가: }
31추가:
32추가: /** 키를 눌렀다 뗀다. 뒤로·홈·최근 앱 버튼에 쓴다. */
33추가: fun pressKey(keycode: Int) {
34추가: val now = SystemClock.uptimeMillis()
35추가: for (action in intArrayOf(KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP)) {
36추가: val e = KeyEvent(
37추가: now, now, action, keycode, 0, 0,
38추가: KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, InputDevice.SOURCE_KEYBOARD,
39추가: )
40추가: injectEvent(e)
41추가: }
42추가: }
43추가:
44추가: /** 기본 디스플레이의 논리 해상도 (현재 회전 기준). 실패하면 null. */
45추가: fun displaySize(): Pair<Int, Int>? = try {
46추가: val cls = Class.forName("android.hardware.display.DisplayManagerGlobal")
47추가: val global = cls.getMethod("getInstance").invoke(null)!!
48추가: val info = cls.getMethod("getDisplayInfo", Int::class.javaPrimitiveType).invoke(global, 0)!!
49추가: val w = info.javaClass.getField("logicalWidth").getInt(info)
50추가: val h = info.javaClass.getField("logicalHeight").getInt(info)
51추가: w to h
52추가: } catch (e: Exception) {
53추가: Log.w("디스플레이 정보 조회 실패: $e")
54추가: null
55추가: }
56추가: }
수정android/gradle/libs.versions.toml+4-0
@@ -1,5 +1,9 @@
11[versions]
22agp = "9.5.2"
3추가: bouncycastle = "1.87"
4추가:
5추가: [libraries]
6추가: bouncycastle-prov = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bouncycastle" }
37
48[plugins]
59android-application = { id = "com.android.application", version.ref = "agp" }
추가examples/probe.rs+104-0
@@ -0,0 +1,104 @@
1추가: //! 기기 연결 점검 도구. GUI 없이 접속, 인증, PING 왕복, 영상 설정, 시스템 버튼을 확인한다.
2추가: //!
3추가: //! `cargo run --example probe -- 127.0.0.1:27200 [--key back|home|recents]`
4추가: //!
5추가: //! GUI와 같은 PC 키(`~/.config/android-remote/device_key`)와 기기 지문 목록을 쓰므로,
6추가: //! 여기서 허용된 PC는 GUI에서도 승인 없이 연결된다.
7추가:
8추가: use std::time::{Duration, Instant};
9추가:
10추가: use wayland_android_remote::net::{
11추가: ConnectOptions, FramedError, HostIdentity, KnownDevices, connect,
12추가: };
13추가: use wayland_android_remote::protocol::{
14추가: AuthGrant, CodecMask, Message, SystemAction, VideoConfigRequest, fingerprint_hex,
15추가: };
16추가:
17추가: #[tokio::main]
18추가: async fn main() -> Result<(), Box<dyn std::error::Error>> {
19추가: let args: Vec<String> = std::env::args().skip(1).collect();
20추가: let target = args
21추가: .first()
22추가: .ok_or("사용법: probe <IP:포트> [--key back|home|recents]")?;
23추가: let target = wayland_android_remote_target(target)?;
24추가: let key = args
25추가: .iter()
26추가: .position(|a| a == "--key")
27추가: .and_then(|i| args.get(i + 1))
28추가: .map(|k| match k.as_str() {
29추가: "back" => Ok(SystemAction::Back),
30추가: "home" => Ok(SystemAction::Home),
31추가: "recents" => Ok(SystemAction::Recents),
32추가: other => Err(format!("알 수 없는 키: {other}")),
33추가: })
34추가: .transpose()?;
35추가:
36추가: let path = HostIdentity::default_path().ok_or("설정 디렉터리를 찾지 못했습니다")?;
37추가: let identity = HostIdentity::load_or_create(&path)?;
38추가: let mut known = KnownDevices::load_default();
39추가: let pinned = known.get(target.ip());
40추가: println!("접속: {target} (저장된 지문: {})", pinned.is_some());
41추가:
42추가: let started = Instant::now();
43추가: let mut session = connect(target, &identity, pinned, ConnectOptions::default(), |e| {
44추가: println!(" {e:?}")
45추가: })
46추가: .await?;
47추가: println!(
48추가: "인증 완료 {:?}: grant={:?} daemon_version={} 지문={}",
49추가: started.elapsed(),
50추가: session.grant,
51추가: session.daemon_version,
52추가: fingerprint_hex(&session.fingerprint)
53추가: );
54추가: if session.grant == AuthGrant::Always {
55추가: known.insert(target.ip(), session.fingerprint)?;
56추가: }
57추가:
58추가: let control = session.control();
59추가: for _ in 0..5 {
60추가: let t = Instant::now();
61추가: let seq = control.send(&Message::Ping).await?;
62추가: loop {
63추가: let (s, msg) = control.read_message().await?;
64추가: if s == seq && msg == Message::Pong {
65추가: break;
66추가: }
67추가: }
68추가: println!("PING 왕복 {:?}", t.elapsed());
69추가: }
70추가:
71추가: control
72추가: .send(&Message::VideoConfigRequest(VideoConfigRequest {
73추가: max_size: 1920,
74추가: max_fps: 60,
75추가: codecs: CodecMask::H264 | CodecMask::H265,
76추가: bitrate: 8_000_000,
77추가: }))
78추가: .await?;
79추가: let reply = tokio::time::timeout(Duration::from_secs(3), control.read_message()).await??;
80추가: println!("영상 설정 응답: {:?}", reply.1);
81추가:
82추가: if let Some(action) = key {
83추가: control.send(&Message::SystemAction(action)).await?;
84추가: println!("SYSTEM_ACTION {action:?} 전송");
85추가: }
86추가:
87추가: let mut video = session.open_video(Duration::from_secs(5)).await?;
88추가: match tokio::time::timeout(Duration::from_millis(500), video.read_packet()).await {
89추가: Err(_) => println!("영상 채널 연결됨 (아직 영상 없음)"),
90추가: Ok(Ok((h, data))) => println!("영상 패킷 수신: {h:?} {}바이트", data.len()),
91추가: Ok(Err(FramedError::Closed)) => println!("영상 채널이 바로 닫혔습니다"),
92추가: Ok(Err(e)) => println!("영상 채널 오류: {e}"),
93추가: }
94추가: Ok(())
95추가: }
96추가:
97추가: fn wayland_android_remote_target(s: &str) -> Result<std::net::SocketAddr, String> {
98추가: if let Ok(a) = s.parse() {
99추가: return Ok(a);
100추가: }
101추가: s.parse::<std::net::IpAddr>()
102추가: .map(|ip| std::net::SocketAddr::new(ip, 27200))
103추가: .map_err(|_| format!("주소 형식 오류: {s}"))
104추가: }
추가scripts/dev-daemon.sh+26-0
@@ -0,0 +1,26 @@
1추가: #!/usr/bin/env bash
2추가: # 개발용: APK를 빌드·설치하고 USB로 연결한 폰에서 데몬을 포그라운드로 실행한다.
3추가: # Ctrl+C로 멈추면 데몬도 함께 종료된다.
4추가: #
5추가: # APPROVE=always|once|reject 처음 접속하는 PC 처리 (기본 always, 동반 앱 승인 팝업 전까지 임시)
6추가: # PORT=27200 데몬 포트. 같은 번호로 adb forward도 건다.
7추가: # SKIP_BUILD=1 빌드와 설치를 건너뛴다.
8추가: set -euo pipefail
9추가: cd "$(dirname "$0")/.."
10추가:
11추가: APPROVE="${APPROVE:-always}"
12추가: PORT="${PORT:-27200}"
13추가: export ANDROID_HOME="${ANDROID_HOME:-$HOME/Android/Sdk}"
14추가: export PATH="$ANDROID_HOME/platform-tools:$PATH"
15추가:
16추가: if [[ -z "${SKIP_BUILD:-}" ]]; then
17추가: (cd android && ./gradlew -q assembleDebug)
18추가: adb install -r android/app/build/outputs/apk/debug/app-debug.apk >/dev/null
19추가: fi
20추가:
21추가: adb shell "pkill -f com.androidremote.daemon.DaemonMain" >/dev/null 2>&1 || true
22추가: adb forward "tcp:$PORT" "tcp:$PORT" >/dev/null
23추가: APK="$(adb shell pm path com.androidremote | tr -d '\r' | cut -d: -f2)"
24추가:
25추가: echo "데몬 시작: USB는 127.0.0.1:$PORT, Wi-Fi는 폰 IP:$PORT 로 접속"
26추가: exec adb shell -t "CLASSPATH=$APK exec app_process / com.androidremote.daemon.DaemonMain --port $PORT --approve $APPROVE"