기기 데몬 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| @@ -51,3 +51,19 @@ cargo run --example fake_device -- --policy always --delay-ms 3000 | ||
| 51 | 51 | ``` |
| 52 | 52 | |
| 53 | 53 | 다른 터미널에서 `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 | 추가: ``` |
| @@ -31,3 +31,8 @@ android { | ||
| 31 | 31 | targetCompatibility = JavaVersion.VERSION_17 |
| 32 | 32 | } |
| 33 | 33 | } |
| 34 | 추가: | |
| 35 | 추가: dependencies { | |
| 36 | 추가: // Android 플랫폼에는 Ed25519 서명 검증이 없어 PC 인증(기획서 5.3)에 BouncyCastle 경량 API를 쓴다. | |
| 37 | 추가: implementation(libs.bouncycastle.prov) | |
| 38 | 추가: } |
| @@ -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 | 추가: } |
| @@ -1,25 +1,59 @@ | ||
| 1 | 1 | package com.androidremote.daemon |
| 2 | 2 | |
| 3 | 추가: import android.os.Looper | |
| 4 | 추가: import java.io.File | |
| 5 | 추가: | |
| 3 | 6 | /** |
| 4 | 7 | * shell 권한 데몬 진입점 (기획서 5.4). |
| 5 | 8 | * |
| 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다. | |
| 8 | 16 | */ |
| 9 | 17 | object DaemonMain { |
| 10 | 18 | 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 | |
| 11 | 23 | |
| 12 | 24 | @JvmStatic |
| 13 | 25 | fun main(args: Array<String>) { |
| 14 | 26 | 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 | |
| 16 | 51 | } |
| 17 | 52 | |
| 18 | 53 | 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" } | |
| 23 | 57 | return value |
| 24 | 58 | } |
| 25 | 59 | } |
| @@ -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 | 추가: } |
| @@ -1,14 +1,21 @@ | ||
| 1 | 1 | package com.androidremote.daemon |
| 2 | 2 | |
| 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 | 추가: | |
| 3 | 9 | /** |
| 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이라 그대로 쓴다. | |
| 6 | 12 | */ |
| 7 | 13 | object Protocol { |
| 8 | 14 | const val MAGIC: Int = 0x4152 |
| 9 | 15 | const val VERSION: Int = 0x01 |
| 10 | 16 | const val HEADER_LEN: Int = 12 |
| 11 | 17 | const val MAX_PAYLOAD_LEN: Int = 4 * 1024 * 1024 |
| 18 | 추가: const val VIDEO_HEADER_LEN: Int = 16 | |
| 12 | 19 | |
| 13 | 20 | object MsgType { |
| 14 | 21 | const val PING = 0x01 |
| @@ -29,5 +36,199 @@ object Protocol { | ||
| 29 | 36 | const val VIDEO_REQUEST_KEYFRAME = 0x42 |
| 30 | 37 | const val ACK = 0xF0 |
| 31 | 38 | 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 | |
| 32 | 233 | } |
| 33 | 234 | } |
| @@ -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 | 추가: } |
| @@ -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 | 추가: } |
| @@ -1,5 +1,9 @@ | ||
| 1 | 1 | [versions] |
| 2 | 2 | agp = "9.5.2" |
| 3 | 추가: bouncycastle = "1.87" | |
| 4 | 추가: | |
| 5 | 추가: [libraries] | |
| 6 | 추가: bouncycastle-prov = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bouncycastle" } | |
| 3 | 7 | |
| 4 | 8 | [plugins] |
| 5 | 9 | android-application = { id = "com.android.application", version.ref = "agp" } |
| @@ -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 | 추가: } |
| @@ -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" |