leejunyoung5819wayland-android-remote

공개

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

190줄7.3 KB
1package com.androidremote.daemon
2
3import org.json.JSONArray
4import org.json.JSONObject
5import java.io.BufferedReader
6import java.io.InputStreamReader
7import java.io.OutputStreamWriter
8import java.net.InetAddress
9import java.net.ServerSocket
10import java.net.Socket
11import java.security.MessageDigest
12import java.security.SecureRandom
13import java.util.concurrent.CompletableFuture
14import java.util.concurrent.CopyOnWriteArrayList
15import java.util.concurrent.TimeUnit
16import java.util.concurrent.TimeoutException
17import java.util.concurrent.atomic.AtomicInteger
18
19/**
20 * 동반 앱과의 로컬 통신 (기획서 5.4 "4. 동반 앱과 데몬 간 로컬 통신").
21 *
22 * 일반 앱(untrusted_app)은 SELinux 정책상 shell 프로세스의 유닉스 소켓에 접속할 수 없으므로
23 * 127.0.0.1 TCP 포트를 쓴다. 대신 데몬이 시작할 때 만든 임의 토큰을 명시적 브로드캐스트로
24 * 동반 앱에만 전달하고(수신기는 shell·system만 가진 DUMP 권한으로 보호), 첫 메시지의 토큰이
25 * 맞는 연결만 받는다. 메시지는 한 줄에 JSON 하나다.
26 * - 앱 → 데몬 첫 줄: `hello`(token)
27 * - 데몬 → 앱: `state`(확인 코드, 지문, 포트, 허용 목록, 연결 중인 PC), `approval`(승인 요청), `approval_done`
28 * - 앱 → 데몬: `get_state`, `decide`(id, grant: always|once|reject), `revoke`(key)
29 */
30class AppBridge(
31 private val appPackage: String,
32 private val port: Int,
33 private val stateProvider: () -> JSONObject,
34 private val onRevoke: (String) -> Unit,
35) {
36 private val clients = CopyOnWriteArrayList<Client>()
37 private val pending = HashMap<Int, CompletableFuture<String>>()
38 private val nextId = AtomicInteger(1)
39 private val token: String = ByteArray(32).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
40
41 private inner class Client(val socket: Socket) {
42 private val writer = OutputStreamWriter(socket.outputStream, Charsets.UTF_8)
43
44 @Synchronized
45 fun send(obj: JSONObject) {
46 writer.write(obj.toString())
47 writer.write("\n")
48 writer.flush()
49 }
50 }
51
52 fun start() {
53 val server = ServerSocket(port, 8, InetAddress.getByName("127.0.0.1"))
54 Log.i("동반 앱 연결 대기: 127.0.0.1:$port")
55 sendToken()
56 Thread({
57 while (true) {
58 val socket = server.accept()
59 Thread({ serve(socket) }, "app-bridge").start()
60 }
61 }, "app-bridge-accept").start()
62 }
63
64 private fun serve(socket: Socket) {
65 val reader = BufferedReader(InputStreamReader(socket.inputStream, Charsets.UTF_8))
66 val hello = runCatching {
67 socket.soTimeout = 3000
68 JSONObject(reader.readLine() ?: "")
69 }.getOrNull()
70 val given = hello?.optString("token").orEmpty()
71 if (hello?.optString("type") != "hello" ||
72 !MessageDigest.isEqual(given.toByteArray(), token.toByteArray())
73 ) {
74 Log.w("동반 앱 토큰이 맞지 않는 접속 거부")
75 runCatching { socket.close() }
76 return
77 }
78 socket.soTimeout = 0
79 val client = Client(socket)
80 clients.add(client)
81 try {
82 client.send(stateMessage())
83 synchronized(pending) {
84 // 앱이 늦게 붙어도 진행 중인 승인 요청을 받을 수 있게 다시 보낸다.
85 pendingRequests.values.forEach { client.send(it) }
86 }
87 while (true) {
88 val line = reader.readLine() ?: break
89 handle(JSONObject(line), client)
90 }
91 } catch (e: Exception) {
92 Log.i("동반 앱 연결 종료 (${e.message})")
93 } finally {
94 clients.remove(client)
95 runCatching { socket.close() }
96 }
97 }
98
99 private fun handle(msg: JSONObject, client: Client) {
100 when (msg.optString("type")) {
101 "get_state" -> {
102 client.send(stateMessage())
103 synchronized(pending) { pendingRequests.values.forEach { client.send(it) } }
104 }
105 "decide" -> {
106 val id = msg.optInt("id")
107 val grant = msg.optString("grant")
108 synchronized(pending) { pending[id] }?.complete(grant)
109 }
110 "revoke" -> {
111 onRevoke(msg.optString("key"))
112 broadcastState()
113 }
114 else -> Log.w("알 수 없는 앱 메시지: $msg")
115 }
116 }
117
118 private fun stateMessage() = stateProvider().put("type", "state")
119
120 fun broadcastState() {
121 val msg = stateMessage()
122 clients.forEach { runCatching { it.send(msg) } }
123 }
124
125 private val pendingRequests = HashMap<Int, JSONObject>()
126
127 /**
128 * 휴대폰 사용자에게 새 PC 승인을 묻는다. 승인 창을 띄우고 결정을 기다린다.
129 * 돌려주는 값: "always", "once", "reject", 시간 초과면 "timeout".
130 */
131 fun requestApproval(host: String, ip: String, key: String, confirm: String, timeoutMs: Long): String {
132 val id = nextId.getAndIncrement()
133 val future = CompletableFuture<String>()
134 val request = JSONObject()
135 .put("type", "approval").put("id", id).put("host", host)
136 .put("ip", ip).put("key", key).put("confirm", confirm)
137 .put("timeout_ms", timeoutMs)
138 synchronized(pending) {
139 pending[id] = future
140 pendingRequests[id] = request
141 }
142 clients.forEach { runCatching { it.send(request) } }
143 launchApprovalActivity(id)
144 return try {
145 future.get(timeoutMs, TimeUnit.MILLISECONDS)
146 } catch (e: TimeoutException) {
147 "timeout"
148 } finally {
149 synchronized(pending) {
150 pending.remove(id)
151 pendingRequests.remove(id)
152 }
153 val done = JSONObject().put("type", "approval_done").put("id", id)
154 clients.forEach { runCatching { it.send(done) } }
155 }
156 }
157
158 /** 동반 앱에 접속 토큰과 포트를 알린다. 앱이 한 번도 실행되지 않았어도 받도록 중지된 앱도 포함한다. */
159 private fun sendToken() {
160 try {
161 Runtime.getRuntime().exec(arrayOf(
162 "am", "broadcast", "--include-stopped-packages",
163 "-n", "$appPackage/.companion.TokenReceiver",
164 "--es", "token", token, "--ei", "port", port.toString(),
165 )).waitFor()
166 } catch (e: Exception) {
167 Log.w("동반 앱 토큰 전달 실패: $e")
168 }
169 }
170
171 /** 승인 창은 앱이 실행 중이 아니어도 뜨도록 shell 권한의 am 명령으로 띄운다. 토큰도 함께 넘긴다. */
172 private fun launchApprovalActivity(id: Int) {
173 try {
174 Runtime.getRuntime().exec(arrayOf(
175 "am", "start", "-n", "$appPackage/.companion.ApprovalActivity",
176 "--ei", "id", id.toString(), "--es", "token", token, "--ei", "port", port.toString(),
177 )).waitFor()
178 } catch (e: Exception) {
179 Log.w("승인 창 실행 실패: $e")
180 }
181 }
182
183 companion object {
184 fun whitelistJson(entries: Map<String, String>): JSONArray {
185 val arr = JSONArray()
186 entries.forEach { (key, host) -> arr.put(JSONObject().put("key", key).put("host", host)) }
187 return arr
188 }
189 }
190}