leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | package com.androidremote.daemon |
| 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 | |
| 9 | /** |
| 10 | * 제어 채널 프레이밍과 메시지 페이로드 (기획서 7.1 ~ 7.3). 호스트의 Rust `protocol` 모듈과 |
| 11 | * 바이트 배치가 같아야 한다. JVM ByteBuffer 기본 바이트 순서가 Big-Endian이라 그대로 쓴다. |
| 12 | */ |
| 13 | object Protocol { |
| 14 | const val MAGIC: Int = 0x4152 |
| 15 | const val VERSION: Int = 0x01 |
| 16 | const val HEADER_LEN: Int = 12 |
| 17 | const val MAX_PAYLOAD_LEN: Int = 4 * 1024 * 1024 |
| 18 | /** CLIPBOARD_SYNC는 이미지(PNG/JPEG)를 위해 상한이 더 크다. 호스트 `max_payload_len`과 같다. */ |
| 19 | const val MAX_CLIPBOARD_PAYLOAD_LEN: Int = 16 * 1024 * 1024 |
| 20 | |
| 21 | fun maxPayloadLen(type: Int): Int = |
| 22 | if (type == MsgType.CLIPBOARD_SYNC) MAX_CLIPBOARD_PAYLOAD_LEN else MAX_PAYLOAD_LEN |
| 23 | |
| 24 | /** CLIPBOARD_SYNC mime_type. */ |
| 25 | object ClipMime { |
| 26 | const val TEXT = 0x01 |
| 27 | const val PNG = 0x02 |
| 28 | const val JPEG = 0x03 |
| 29 | } |
| 30 | const val VIDEO_HEADER_LEN: Int = 16 |
| 31 | |
| 32 | object MsgType { |
| 33 | const val PING = 0x01 |
| 34 | const val PONG = 0x02 |
| 35 | const val AUTH_HELLO = 0x03 |
| 36 | const val AUTH_CHALLENGE = 0x04 |
| 37 | const val AUTH_RESPONSE = 0x05 |
| 38 | const val AUTH_RESULT = 0x06 |
| 39 | const val CHANNEL_ATTACH = 0x07 |
| 40 | const val KEY_EVENT = 0x10 |
| 41 | const val TEXT_INPUT = 0x11 |
| 42 | const val SYSTEM_ACTION = 0x12 |
| 43 | const val CLIPBOARD_SYNC = 0x20 |
| 44 | const val TOUCH_EVENT = 0x30 |
| 45 | const val SCROLL_EVENT = 0x31 |
| 46 | const val VIDEO_CONFIG_REQUEST = 0x40 |
| 47 | const val VIDEO_CONFIG = 0x41 |
| 48 | const val VIDEO_REQUEST_KEYFRAME = 0x42 |
| 49 | const val FILE_START = 0x50 |
| 50 | const val FILE_DATA = 0x51 |
| 51 | const val FILE_END = 0x52 |
| 52 | const val FILE_RESULT = 0x53 |
| 53 | const val FILE_CANCEL = 0x54 |
| 54 | const val ACK = 0xF0 |
| 55 | const val ERROR = 0xFF |
| 56 | |
| 57 | /** AUTH_RESULT(OK) 전에도 처리할 수 있는 메시지 (기획서 7.3 6항). */ |
| 58 | fun allowedBeforeAuth(type: Int): Boolean = |
| 59 | type == PING || type == PONG || type in AUTH_HELLO..AUTH_RESULT || type == ERROR |
| 60 | } |
| 61 | |
| 62 | object AuthStatus { |
| 63 | const val APPROVED = 0x00 |
| 64 | const val PENDING_USER = 0x01 |
| 65 | const val REJECTED = 0x02 |
| 66 | } |
| 67 | |
| 68 | object AuthResultCode { |
| 69 | const val OK = 0x00 |
| 70 | const val REJECTED = 0x01 |
| 71 | const val TIMEOUT = 0x02 |
| 72 | const val SIGNATURE_INVALID = 0x03 |
| 73 | const val REVOKED = 0x04 |
| 74 | } |
| 75 | |
| 76 | object Grant { |
| 77 | const val NONE = 0x00 |
| 78 | const val ALWAYS = 0x01 |
| 79 | const val ONCE = 0x02 |
| 80 | } |
| 81 | |
| 82 | object Codec { |
| 83 | const val H264 = 0x01 |
| 84 | const val H265 = 0x02 |
| 85 | const val AV1 = 0x04 |
| 86 | } |
| 87 | |
| 88 | object ErrorCode { |
| 89 | const val PAYLOAD_TOO_LARGE = 0x0001 |
| 90 | const val BAD_FRAME = 0x0002 |
| 91 | const val UNAUTHENTICATED = 0x0003 |
| 92 | const val PERMISSION_DENIED = 0x0004 |
| 93 | const val INTERNAL = 0x0005 |
| 94 | } |
| 95 | |
| 96 | object SystemAction { |
| 97 | const val COPY = 0x01 |
| 98 | const val PASTE = 0x02 |
| 99 | const val CUT = 0x03 |
| 100 | const val SELECT_ALL = 0x04 |
| 101 | const val HOME = 0x10 |
| 102 | const val BACK = 0x11 |
| 103 | const val RECENTS = 0x12 |
| 104 | const val ROTATE = 0x20 |
| 105 | const val SCREEN_OFF = 0x21 |
| 106 | const val SCREEN_ON = 0x22 |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | /** 프레임 경계가 깨졌거나 규격에 맞지 않는 데이터. 받으면 연결을 끊는다. */ |
| 111 | class ProtocolException(message: String) : IOException(message) |
| 112 | |
| 113 | class Frame(val type: Int, val flags: Int, val seq: Int, val payload: ByteArray) |
| 114 | |
| 115 | /** TLS 스트림 위에서 12바이트 헤더 + 페이로드 프레임을 읽고 쓴다. */ |
| 116 | class FrameIO(private val input: DataInputStream, private val output: OutputStream) { |
| 117 | private var nextSeq = 0 |
| 118 | private val writeLock = Any() |
| 119 | |
| 120 | /** 프레임 하나를 끝까지 읽는다. 상대가 정상 종료했으면 null. */ |
| 121 | fun read(): Frame? { |
| 122 | val header = ByteArray(Protocol.HEADER_LEN) |
| 123 | try { |
| 124 | input.readFully(header) |
| 125 | } catch (e: EOFException) { |
| 126 | return null |
| 127 | } |
| 128 | val b = ByteBuffer.wrap(header) |
| 129 | val magic = b.short.toInt() and 0xFFFF |
| 130 | val version = b.get().toInt() and 0xFF |
| 131 | val type = b.get().toInt() and 0xFF |
| 132 | val flags = b.short.toInt() and 0xFFFF |
| 133 | val seq = b.short.toInt() and 0xFFFF |
| 134 | val len = b.int.toLong() and 0xFFFFFFFFL |
| 135 | if (magic != Protocol.MAGIC) throw ProtocolException("잘못된 magic: 0x%04x".format(magic)) |
| 136 | if (version != Protocol.VERSION) throw ProtocolException("지원하지 않는 버전: $version") |
| 137 | if (len > Protocol.maxPayloadLen(type)) throw ProtocolException("payload_len 초과: $len") |
| 138 | val payload = ByteArray(len.toInt()) |
| 139 | input.readFully(payload) |
| 140 | return Frame(type, flags, seq, payload) |
| 141 | } |
| 142 | |
| 143 | /** 다음 순환 seq_id로 보낸다. */ |
| 144 | fun send(type: Int, payload: ByteArray = ByteArray(0)): Int = synchronized(writeLock) { |
| 145 | val seq = nextSeq |
| 146 | nextSeq = (nextSeq + 1) and 0xFFFF |
| 147 | sendWithSeq(type, seq, payload) |
| 148 | seq |
| 149 | } |
| 150 | |
| 151 | /** PONG처럼 요청의 seq_id를 되돌려줄 때 쓴다. */ |
| 152 | fun sendWithSeq(type: Int, seq: Int, payload: ByteArray = ByteArray(0)) = synchronized(writeLock) { |
| 153 | val buf = ByteBuffer.allocate(Protocol.HEADER_LEN + payload.size) |
| 154 | buf.putShort(Protocol.MAGIC.toShort()) |
| 155 | buf.put(Protocol.VERSION.toByte()) |
| 156 | buf.put(type.toByte()) |
| 157 | buf.putShort(0) |
| 158 | buf.putShort(seq.toShort()) |
| 159 | buf.putInt(payload.size) |
| 160 | buf.put(payload) |
| 161 | output.write(buf.array()) |
| 162 | output.flush() |
| 163 | } |
| 164 | |
| 165 | fun sendError(code: Int, reason: String) { |
| 166 | val text = reason.toByteArray(Charsets.UTF_8) |
| 167 | val p = ByteBuffer.allocate(2 + text.size).putShort(code.toShort()).put(text).array() |
| 168 | send(Protocol.MsgType.ERROR, p) |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | /** 메시지별 페이로드 인코딩/디코딩. 길이가 맞지 않으면 [ProtocolException]. */ |
| 173 | object Messages { |
| 174 | class AuthHello(val publicKey: ByteArray, val hostname: String) |
| 175 | |
| 176 | fun decodeAuthHello(p: ByteArray): AuthHello { |
| 177 | if (p.size < 33 || p.size > 32 + 255) throw ProtocolException("AUTH_HELLO 길이 오류: ${p.size}") |
| 178 | val host = Utf8.decodeStrict(p.copyOfRange(32, p.size)) |
| 179 | ?: throw ProtocolException("AUTH_HELLO 호스트명 UTF-8 오류") |
| 180 | return AuthHello(p.copyOfRange(0, 32), host) |
| 181 | } |
| 182 | |
| 183 | fun encodeAuthChallenge(status: Int, nonce: ByteArray): ByteArray = |
| 184 | ByteBuffer.allocate(36).put(status.toByte()).put(ByteArray(3)).put(nonce).array() |
| 185 | |
| 186 | fun decodeAuthResponse(p: ByteArray): ByteArray { |
| 187 | if (p.size != 64) throw ProtocolException("AUTH_RESPONSE 길이 오류: ${p.size}") |
| 188 | return p |
| 189 | } |
| 190 | |
| 191 | fun encodeAuthResult(result: Int, grant: Int, token: ByteArray, daemonVersion: Int): ByteArray = |
| 192 | ByteBuffer.allocate(40) |
| 193 | .put(result.toByte()).put(grant.toByte()).putShort(0) |
| 194 | .put(token).putInt(daemonVersion) |
| 195 | .array() |
| 196 | |
| 197 | class ChannelAttach(val kind: Int, val token: ByteArray) |
| 198 | |
| 199 | fun decodeChannelAttach(p: ByteArray): ChannelAttach { |
| 200 | if (p.size != 36) throw ProtocolException("CHANNEL_ATTACH 길이 오류: ${p.size}") |
| 201 | return ChannelAttach(p[0].toInt() and 0xFF, p.copyOfRange(4, 36)) |
| 202 | } |
| 203 | |
| 204 | fun decodeSystemAction(p: ByteArray): Int { |
| 205 | if (p.size != 4) throw ProtocolException("SYSTEM_ACTION 길이 오류: ${p.size}") |
| 206 | return p[0].toInt() and 0xFF |
| 207 | } |
| 208 | |
| 209 | /** [longPress]: flags 0x0001. DOWN을 바로 길게 누르기로 처리한다 (마우스 오른쪽 버튼). */ |
| 210 | class TouchEvent( |
| 211 | val action: Int, val pointerId: Int, val x: Int, val y: Int, |
| 212 | val frameWidth: Int, val frameHeight: Int, val pressure: Int, |
| 213 | val longPress: Boolean = false, |
| 214 | ) |
| 215 | |
| 216 | fun decodeTouchEvent(p: ByteArray): TouchEvent { |
| 217 | if (p.size != 20) throw ProtocolException("TOUCH_EVENT 길이 오류: ${p.size}") |
| 218 | val b = ByteBuffer.wrap(p) |
| 219 | val action = b.get().toInt() and 0xFF |
| 220 | val pointerId = b.get().toInt() and 0xFF |
| 221 | val flags = b.short.toInt() and 0xFFFF |
| 222 | val x = b.int |
| 223 | val y = b.int |
| 224 | val fw = b.short.toInt() and 0xFFFF |
| 225 | val fh = b.short.toInt() and 0xFFFF |
| 226 | val pressure = b.short.toInt() and 0xFFFF |
| 227 | if (action > 3) throw ProtocolException("TOUCH_EVENT action 오류: $action") |
| 228 | if (fw == 0 || fh == 0) throw ProtocolException("TOUCH_EVENT 프레임 크기 0") |
| 229 | return TouchEvent(action, pointerId, x, y, fw, fh, pressure, flags and 0x0001 != 0) |
| 230 | } |
| 231 | |
| 232 | class ScrollEvent(val x: Int, val y: Int, val frameWidth: Int, val frameHeight: Int, val hScroll: Int, val vScroll: Int) |
| 233 | |
| 234 | fun decodeScrollEvent(p: ByteArray): ScrollEvent { |
| 235 | if (p.size != 16) throw ProtocolException("SCROLL_EVENT 길이 오류: ${p.size}") |
| 236 | val b = ByteBuffer.wrap(p) |
| 237 | val x = b.int |
| 238 | val y = b.int |
| 239 | val fw = b.short.toInt() and 0xFFFF |
| 240 | val fh = b.short.toInt() and 0xFFFF |
| 241 | if (fw == 0 || fh == 0) throw ProtocolException("SCROLL_EVENT 프레임 크기 0") |
| 242 | return ScrollEvent(x, y, fw, fh, b.short.toInt(), b.short.toInt()) |
| 243 | } |
| 244 | |
| 245 | class KeyEvent(val action: Int, val keycode: Int, val metaState: Int, val repeat: Int, val scancode: Int) |
| 246 | |
| 247 | fun decodeKeyEvent(p: ByteArray): KeyEvent { |
| 248 | if (p.size != 12) throw ProtocolException("KEY_EVENT 길이 오류: ${p.size}") |
| 249 | val b = ByteBuffer.wrap(p) |
| 250 | val action = b.get().toInt() and 0xFF |
| 251 | b.get() |
| 252 | val keycode = b.short.toInt() and 0xFFFF |
| 253 | val meta = b.int |
| 254 | val repeat = b.short.toInt() and 0xFFFF |
| 255 | val scancode = b.short.toInt() and 0xFFFF |
| 256 | if (action > 2) throw ProtocolException("KEY_EVENT action 오류: $action") |
| 257 | return KeyEvent(action, keycode, meta, repeat, scancode) |
| 258 | } |
| 259 | |
| 260 | fun decodeTextInput(p: ByteArray): String { |
| 261 | if (p.isEmpty()) throw ProtocolException("TEXT_INPUT 빈 문자열") |
| 262 | return Utf8.decodeStrict(p) ?: throw ProtocolException("TEXT_INPUT UTF-8 오류") |
| 263 | } |
| 264 | |
| 265 | /** [text]는 mime이 텍스트일 때만 있다. 이미지면 [data]가 PNG/JPEG 파일 바이트다. */ |
| 266 | class ClipboardSync(val origin: Int, val autoPaste: Boolean, val mime: Int, val sha256: ByteArray, val data: ByteArray) { |
| 267 | val text: String? get() = if (mime == Protocol.ClipMime.TEXT) String(data, Charsets.UTF_8) else null |
| 268 | } |
| 269 | |
| 270 | fun decodeClipboardSync(p: ByteArray): ClipboardSync { |
| 271 | if (p.size < 40) throw ProtocolException("CLIPBOARD_SYNC 길이 오류: ${p.size}") |
| 272 | val b = ByteBuffer.wrap(p) |
| 273 | val origin = b.get().toInt() and 0xFF |
| 274 | val autoPaste = b.get().toInt() and 0xFF |
| 275 | val mime = b.get().toInt() and 0xFF |
| 276 | b.get() |
| 277 | val sha = ByteArray(32).also { b.get(it) } |
| 278 | val len = b.int.toLong() and 0xFFFFFFFFL |
| 279 | if (len != (p.size - 40).toLong()) throw ProtocolException("CLIPBOARD_SYNC text_len 불일치") |
| 280 | if (mime !in Protocol.ClipMime.TEXT..Protocol.ClipMime.JPEG) throw ProtocolException("CLIPBOARD_SYNC mime 오류: $mime") |
| 281 | val data = p.copyOfRange(40, p.size) |
| 282 | if (mime == Protocol.ClipMime.TEXT && Utf8.decodeStrict(data) == null) throw ProtocolException("CLIPBOARD_SYNC UTF-8 오류") |
| 283 | return ClipboardSync(origin, autoPaste == 1, mime, sha, data) |
| 284 | } |
| 285 | |
| 286 | class FileStart(val id: Int, val size: Long, val name: String) |
| 287 | |
| 288 | fun decodeFileStart(p: ByteArray): FileStart { |
| 289 | if (p.size < 13 || p.size > 12 + 255) throw ProtocolException("FILE_START 길이 오류: ${p.size}") |
| 290 | val b = ByteBuffer.wrap(p) |
| 291 | val id = b.int |
| 292 | val size = b.long |
| 293 | if (size < 0) throw ProtocolException("FILE_START 크기 오류") |
| 294 | val name = Utf8.decodeStrict(p.copyOfRange(12, p.size)) ?: throw ProtocolException("FILE_START 이름 UTF-8 오류") |
| 295 | return FileStart(id, size, name) |
| 296 | } |
| 297 | |
| 298 | /** FILE_DATA: (transfer_id, 데이터 시작 위치). 데이터는 payload의 4번째 바이트부터다. */ |
| 299 | fun decodeFileDataId(p: ByteArray): Int { |
| 300 | if (p.size < 5 || p.size > 4 + 256 * 1024) throw ProtocolException("FILE_DATA 길이 오류: ${p.size}") |
| 301 | return ByteBuffer.wrap(p).int |
| 302 | } |
| 303 | |
| 304 | class FileEnd(val id: Int, val sha256: ByteArray) |
| 305 | |
| 306 | fun decodeFileEnd(p: ByteArray): FileEnd { |
| 307 | if (p.size != 36) throw ProtocolException("FILE_END 길이 오류: ${p.size}") |
| 308 | val b = ByteBuffer.wrap(p) |
| 309 | val id = b.int |
| 310 | return FileEnd(id, ByteArray(32).also { b.get(it) }) |
| 311 | } |
| 312 | |
| 313 | fun decodeFileCancel(p: ByteArray): Int { |
| 314 | if (p.size != 4) throw ProtocolException("FILE_CANCEL 길이 오류: ${p.size}") |
| 315 | return ByteBuffer.wrap(p).int |
| 316 | } |
| 317 | |
| 318 | fun encodeFileResult(id: Int, status: Int, message: String): ByteArray { |
| 319 | val m = message.toByteArray(Charsets.UTF_8) |
| 320 | return ByteBuffer.allocate(5 + m.size).putInt(id).put(status.toByte()).put(m).array() |
| 321 | } |
| 322 | |
| 323 | /** origin 0x02(기기), auto_paste 0. */ |
| 324 | fun encodeClipboardSyncFromDevice(mime: Int, sha256: ByteArray, data: ByteArray): ByteArray = |
| 325 | ByteBuffer.allocate(40 + data.size) |
| 326 | .put(0x02).put(0x00).put(mime.toByte()).put(0x00) |
| 327 | .put(sha256).putInt(data.size).put(data) |
| 328 | .array() |
| 329 | |
| 330 | class VideoConfigRequest(val maxSize: Int, val maxFps: Int, val codecMask: Int, val bitrate: Long) |
| 331 | |
| 332 | fun decodeVideoConfigRequest(p: ByteArray): VideoConfigRequest { |
| 333 | if (p.size != 8) throw ProtocolException("VIDEO_CONFIG_REQUEST 길이 오류: ${p.size}") |
| 334 | val b = ByteBuffer.wrap(p) |
| 335 | return VideoConfigRequest( |
| 336 | maxSize = b.short.toInt() and 0xFFFF, |
| 337 | maxFps = b.get().toInt() and 0xFF, |
| 338 | codecMask = b.get().toInt() and 0xFF, |
| 339 | bitrate = b.int.toLong() and 0xFFFFFFFFL, |
| 340 | ) |
| 341 | } |
| 342 | |
| 343 | class VideoConfig( |
| 344 | val codec: Int, |
| 345 | val configGen: Int, |
| 346 | val width: Int, |
| 347 | val height: Int, |
| 348 | val fps: Int, |
| 349 | val bitrate: Long, |
| 350 | val displayWidth: Int, |
| 351 | val displayHeight: Int, |
| 352 | ) |
| 353 | |
| 354 | fun encodeVideoConfig(c: VideoConfig): ByteArray = |
| 355 | ByteBuffer.allocate(16) |
| 356 | .put(c.codec.toByte()).put(c.configGen.toByte()) |
| 357 | .putShort(c.width.toShort()).putShort(c.height.toShort()) |
| 358 | .put(c.fps.toByte()).put(0) |
| 359 | .putInt(c.bitrate.toInt()) |
| 360 | .putShort(c.displayWidth.toShort()).putShort(c.displayHeight.toShort()) |
| 361 | .array() |
| 362 | } |
| 363 | |
| 364 | object Utf8 { |
| 365 | /** 잘못된 UTF-8이면 null. */ |
| 366 | fun decodeStrict(bytes: ByteArray): String? = try { |
| 367 | Charsets.UTF_8.newDecoder() |
| 368 | .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) |
| 369 | .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) |
| 370 | .decode(ByteBuffer.wrap(bytes)) |
| 371 | .toString() |
| 372 | } catch (e: java.nio.charset.CharacterCodingException) { |
| 373 | null |
| 374 | } |
| 375 | } |