leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | package com.androidremote.daemon |
| 2 | |
| 3 | import org.json.JSONArray |
| 4 | import org.json.JSONObject |
| 5 | import java.io.BufferedReader |
| 6 | import java.io.InputStreamReader |
| 7 | import java.io.OutputStreamWriter |
| 8 | import java.net.InetAddress |
| 9 | import java.net.ServerSocket |
| 10 | import java.net.Socket |
| 11 | import java.security.MessageDigest |
| 12 | import java.security.SecureRandom |
| 13 | import java.util.concurrent.CompletableFuture |
| 14 | import java.util.concurrent.CopyOnWriteArrayList |
| 15 | import java.util.concurrent.TimeUnit |
| 16 | import java.util.concurrent.TimeoutException |
| 17 | import 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 | * - 호스트 이미지 클립보드: 데몬이 ClipImageReceiver를 깨우면 앱이 `clip_image_get`(id)으로 요청하고, |
| 30 | * 데몬은 `clip_image`(id, mime, size) 한 줄 뒤에 이미지 바이트를 그대로 보낸다. 앱은 자기 |
| 31 | * ContentProvider URI로 클립보드에 넣은 뒤 `clip_image_set`(id, ok)으로 알린다. |
| 32 | */ |
| 33 | class AppBridge( |
| 34 | private val appPackage: String, |
| 35 | private val port: Int, |
| 36 | private val stateProvider: () -> JSONObject, |
| 37 | private val onRevoke: (String) -> Unit, |
| 38 | ) { |
| 39 | private val clients = CopyOnWriteArrayList<Client>() |
| 40 | private val pending = HashMap<Int, CompletableFuture<String>>() |
| 41 | private val nextId = AtomicInteger(1) |
| 42 | private val token: String = ByteArray(32).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) } |
| 43 | |
| 44 | private inner class Client(val socket: Socket) { |
| 45 | private val writer = OutputStreamWriter(socket.outputStream, Charsets.UTF_8) |
| 46 | |
| 47 | @Synchronized |
| 48 | fun send(obj: JSONObject) { |
| 49 | writer.write(obj.toString()) |
| 50 | writer.write("\n") |
| 51 | writer.flush() |
| 52 | } |
| 53 | |
| 54 | /** JSON 한 줄 뒤에 바이트를 그대로 붙여 보낸다. */ |
| 55 | @Synchronized |
| 56 | fun sendWithBytes(obj: JSONObject, data: ByteArray) { |
| 57 | send(obj) |
| 58 | socket.outputStream.write(data) |
| 59 | socket.outputStream.flush() |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | fun start() { |
| 64 | val server = ServerSocket(port, 8, InetAddress.getByName("127.0.0.1")) |
| 65 | Log.i("동반 앱 연결 대기: 127.0.0.1:$port") |
| 66 | sendToken() |
| 67 | Thread({ |
| 68 | while (true) { |
| 69 | val socket = server.accept() |
| 70 | Thread({ serve(socket) }, "app-bridge").start() |
| 71 | } |
| 72 | }, "app-bridge-accept").start() |
| 73 | } |
| 74 | |
| 75 | private fun serve(socket: Socket) { |
| 76 | val reader = BufferedReader(InputStreamReader(socket.inputStream, Charsets.UTF_8)) |
| 77 | val hello = runCatching { |
| 78 | socket.soTimeout = 3000 |
| 79 | JSONObject(reader.readLine() ?: "") |
| 80 | }.getOrNull() |
| 81 | val given = hello?.optString("token").orEmpty() |
| 82 | if (hello?.optString("type") != "hello" || |
| 83 | !MessageDigest.isEqual(given.toByteArray(), token.toByteArray()) |
| 84 | ) { |
| 85 | Log.w("동반 앱 토큰이 맞지 않는 접속 거부") |
| 86 | runCatching { socket.close() } |
| 87 | return |
| 88 | } |
| 89 | socket.soTimeout = 0 |
| 90 | val client = Client(socket) |
| 91 | clients.add(client) |
| 92 | try { |
| 93 | client.send(stateMessage()) |
| 94 | synchronized(pending) { |
| 95 | // 앱이 늦게 붙어도 진행 중인 승인 요청을 받을 수 있게 다시 보낸다. |
| 96 | pendingRequests.values.forEach { client.send(it) } |
| 97 | } |
| 98 | while (true) { |
| 99 | val line = reader.readLine() ?: break |
| 100 | handle(JSONObject(line), client) |
| 101 | } |
| 102 | } catch (e: Exception) { |
| 103 | Log.i("동반 앱 연결 종료 (${e.message})") |
| 104 | } finally { |
| 105 | clients.remove(client) |
| 106 | runCatching { socket.close() } |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | private fun handle(msg: JSONObject, client: Client) { |
| 111 | when (msg.optString("type")) { |
| 112 | "get_state" -> { |
| 113 | client.send(stateMessage()) |
| 114 | synchronized(pending) { pendingRequests.values.forEach { client.send(it) } } |
| 115 | } |
| 116 | "decide" -> { |
| 117 | val id = msg.optInt("id") |
| 118 | val grant = msg.optString("grant") |
| 119 | synchronized(pending) { pending[id] }?.complete(grant) |
| 120 | } |
| 121 | "revoke" -> { |
| 122 | onRevoke(msg.optString("key")) |
| 123 | broadcastState() |
| 124 | } |
| 125 | "clip_image_get" -> { |
| 126 | val id = msg.optInt("id") |
| 127 | val img = synchronized(clipImages) { clipImages[id] } |
| 128 | if (img == null) { |
| 129 | client.send(JSONObject().put("type", "clip_image").put("id", id).put("size", -1)) |
| 130 | } else { |
| 131 | client.sendWithBytes( |
| 132 | JSONObject().put("type", "clip_image").put("id", id) |
| 133 | .put("mime", if (img.first == Protocol.ClipMime.JPEG) "image/jpeg" else "image/png") |
| 134 | .put("size", img.second.size), |
| 135 | img.second, |
| 136 | ) |
| 137 | } |
| 138 | } |
| 139 | "clip_image_set" -> finishClipImage(msg.optInt("id"), msg.optBoolean("ok")) |
| 140 | else -> Log.w("알 수 없는 앱 메시지: $msg") |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | private fun stateMessage() = stateProvider().put("type", "state") |
| 145 | |
| 146 | fun broadcastState() { |
| 147 | val msg = stateMessage() |
| 148 | clients.forEach { runCatching { it.send(msg) } } |
| 149 | } |
| 150 | |
| 151 | private val pendingRequests = HashMap<Int, JSONObject>() |
| 152 | |
| 153 | /** 호스트에서 받아 동반 앱이 가져가기를 기다리는 이미지 (id -> mime, 바이트). 최신 하나만 둔다. */ |
| 154 | private val clipImages = HashMap<Int, Pair<Int, ByteArray>>() |
| 155 | private val clipCallbacks = HashMap<Int, (Boolean) -> Unit>() |
| 156 | |
| 157 | /** |
| 158 | * 호스트 이미지를 기기 클립보드에 넣는다. shell은 다른 앱이 읽을 수 있는 content URI를 만들 수 |
| 159 | * 없으므로 동반 앱을 깨워 앱의 ContentProvider로 넣게 한다. 끝나면(또는 10초 안에 안 되면) |
| 160 | * [onDone]을 부른다. |
| 161 | */ |
| 162 | fun pushClipImage(mime: Int, data: ByteArray, onDone: (Boolean) -> Unit) { |
| 163 | val id = nextId.getAndIncrement() |
| 164 | synchronized(clipImages) { |
| 165 | clipCallbacks.values.forEach { it(false) } |
| 166 | clipImages.clear() |
| 167 | clipCallbacks.clear() |
| 168 | clipImages[id] = mime to data |
| 169 | clipCallbacks[id] = onDone |
| 170 | } |
| 171 | Thread({ |
| 172 | try { |
| 173 | Runtime.getRuntime().exec(arrayOf( |
| 174 | "am", "broadcast", "--include-stopped-packages", |
| 175 | "-n", "$appPackage/.companion.ClipImageReceiver", |
| 176 | "--ei", "id", id.toString(), "--es", "token", token, "--ei", "port", port.toString(), |
| 177 | )).waitFor() |
| 178 | } catch (e: Exception) { |
| 179 | Log.w("동반 앱 이미지 클립보드 요청 실패: $e") |
| 180 | finishClipImage(id, false) |
| 181 | return@Thread |
| 182 | } |
| 183 | Thread.sleep(10_000) |
| 184 | finishClipImage(id, false) |
| 185 | }, "clip-image").start() |
| 186 | } |
| 187 | |
| 188 | private fun finishClipImage(id: Int, ok: Boolean) { |
| 189 | val cb = synchronized(clipImages) { |
| 190 | clipImages.remove(id) |
| 191 | clipCallbacks.remove(id) |
| 192 | } ?: return |
| 193 | if (!ok) Log.w("이미지 클립보드 설정 실패 또는 시간 초과 (id=$id)") |
| 194 | cb(ok) |
| 195 | } |
| 196 | |
| 197 | /** |
| 198 | * 휴대폰 사용자에게 새 PC 승인을 묻는다. 승인 창을 띄우고 결정을 기다린다. |
| 199 | * 돌려주는 값: "always", "once", "reject", 시간 초과면 "timeout". |
| 200 | */ |
| 201 | fun requestApproval(host: String, ip: String, key: String, confirm: String, timeoutMs: Long): String { |
| 202 | val id = nextId.getAndIncrement() |
| 203 | val future = CompletableFuture<String>() |
| 204 | val request = JSONObject() |
| 205 | .put("type", "approval").put("id", id).put("host", host) |
| 206 | .put("ip", ip).put("key", key).put("confirm", confirm) |
| 207 | .put("timeout_ms", timeoutMs) |
| 208 | synchronized(pending) { |
| 209 | pending[id] = future |
| 210 | pendingRequests[id] = request |
| 211 | } |
| 212 | clients.forEach { runCatching { it.send(request) } } |
| 213 | launchApprovalActivity(id) |
| 214 | return try { |
| 215 | future.get(timeoutMs, TimeUnit.MILLISECONDS) |
| 216 | } catch (e: TimeoutException) { |
| 217 | "timeout" |
| 218 | } finally { |
| 219 | synchronized(pending) { |
| 220 | pending.remove(id) |
| 221 | pendingRequests.remove(id) |
| 222 | } |
| 223 | val done = JSONObject().put("type", "approval_done").put("id", id) |
| 224 | clients.forEach { runCatching { it.send(done) } } |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | /** 동반 앱에 접속 토큰과 포트를 알린다. 앱이 한 번도 실행되지 않았어도 받도록 중지된 앱도 포함한다. */ |
| 229 | private fun sendToken() { |
| 230 | try { |
| 231 | Runtime.getRuntime().exec(arrayOf( |
| 232 | "am", "broadcast", "--include-stopped-packages", |
| 233 | "-n", "$appPackage/.companion.TokenReceiver", |
| 234 | "--es", "token", token, "--ei", "port", port.toString(), |
| 235 | )).waitFor() |
| 236 | } catch (e: Exception) { |
| 237 | Log.w("동반 앱 토큰 전달 실패: $e") |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | /** 승인 창은 앱이 실행 중이 아니어도 뜨도록 shell 권한의 am 명령으로 띄운다. 토큰도 함께 넘긴다. */ |
| 242 | private fun launchApprovalActivity(id: Int) { |
| 243 | try { |
| 244 | Runtime.getRuntime().exec(arrayOf( |
| 245 | "am", "start", "-n", "$appPackage/.companion.ApprovalActivity", |
| 246 | "--ei", "id", id.toString(), "--es", "token", token, "--ei", "port", port.toString(), |
| 247 | )).waitFor() |
| 248 | } catch (e: Exception) { |
| 249 | Log.w("승인 창 실행 실패: $e") |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | companion object { |
| 254 | fun whitelistJson(entries: Map<String, String>): JSONArray { |
| 255 | val arr = JSONArray() |
| 256 | entries.forEach { (key, host) -> arr.put(JSONObject().put("key", key).put("host", host)) } |
| 257 | return arr |
| 258 | } |
| 259 | } |
| 260 | } |