leejunyoung5819wayland-android-remote

공개

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

373줄15 KB
1package com.androidremote.daemon
2
3import java.io.DataInputStream
4import java.io.EOFException
5import java.io.IOException
6import java.io.OutputStream
7import java.nio.ByteBuffer
8
9/**
10 * 제어 채널 프레이밍과 메시지 페이로드 (기획서 7.1 ~ 7.3). 호스트의 Rust `protocol` 모듈과
11 * 바이트 배치가 같아야 한다. JVM ByteBuffer 기본 바이트 순서가 Big-Endian이라 그대로 쓴다.
12 */
13object 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/** 프레임 경계가 깨졌거나 규격에 맞지 않는 데이터. 받으면 연결을 끊는다. */
111class ProtocolException(message: String) : IOException(message)
112
113class Frame(val type: Int, val flags: Int, val seq: Int, val payload: ByteArray)
114
115/** TLS 스트림 위에서 12바이트 헤더 + 페이로드 프레임을 읽고 쓴다. */
116class 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]. */
173object 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 class TouchEvent(
210 val action: Int, val pointerId: Int, val x: Int, val y: Int,
211 val frameWidth: Int, val frameHeight: Int, val pressure: Int,
212 )
213
214 fun decodeTouchEvent(p: ByteArray): TouchEvent {
215 if (p.size != 20) throw ProtocolException("TOUCH_EVENT 길이 오류: ${p.size}")
216 val b = ByteBuffer.wrap(p)
217 val action = b.get().toInt() and 0xFF
218 val pointerId = b.get().toInt() and 0xFF
219 b.short
220 val x = b.int
221 val y = b.int
222 val fw = b.short.toInt() and 0xFFFF
223 val fh = b.short.toInt() and 0xFFFF
224 val pressure = b.short.toInt() and 0xFFFF
225 if (action > 3) throw ProtocolException("TOUCH_EVENT action 오류: $action")
226 if (fw == 0 || fh == 0) throw ProtocolException("TOUCH_EVENT 프레임 크기 0")
227 return TouchEvent(action, pointerId, x, y, fw, fh, pressure)
228 }
229
230 class ScrollEvent(val x: Int, val y: Int, val frameWidth: Int, val frameHeight: Int, val hScroll: Int, val vScroll: Int)
231
232 fun decodeScrollEvent(p: ByteArray): ScrollEvent {
233 if (p.size != 16) throw ProtocolException("SCROLL_EVENT 길이 오류: ${p.size}")
234 val b = ByteBuffer.wrap(p)
235 val x = b.int
236 val y = b.int
237 val fw = b.short.toInt() and 0xFFFF
238 val fh = b.short.toInt() and 0xFFFF
239 if (fw == 0 || fh == 0) throw ProtocolException("SCROLL_EVENT 프레임 크기 0")
240 return ScrollEvent(x, y, fw, fh, b.short.toInt(), b.short.toInt())
241 }
242
243 class KeyEvent(val action: Int, val keycode: Int, val metaState: Int, val repeat: Int, val scancode: Int)
244
245 fun decodeKeyEvent(p: ByteArray): KeyEvent {
246 if (p.size != 12) throw ProtocolException("KEY_EVENT 길이 오류: ${p.size}")
247 val b = ByteBuffer.wrap(p)
248 val action = b.get().toInt() and 0xFF
249 b.get()
250 val keycode = b.short.toInt() and 0xFFFF
251 val meta = b.int
252 val repeat = b.short.toInt() and 0xFFFF
253 val scancode = b.short.toInt() and 0xFFFF
254 if (action > 2) throw ProtocolException("KEY_EVENT action 오류: $action")
255 return KeyEvent(action, keycode, meta, repeat, scancode)
256 }
257
258 fun decodeTextInput(p: ByteArray): String {
259 if (p.isEmpty()) throw ProtocolException("TEXT_INPUT 빈 문자열")
260 return Utf8.decodeStrict(p) ?: throw ProtocolException("TEXT_INPUT UTF-8 오류")
261 }
262
263 /** [text]는 mime이 텍스트일 때만 있다. 이미지면 [data]가 PNG/JPEG 파일 바이트다. */
264 class ClipboardSync(val origin: Int, val autoPaste: Boolean, val mime: Int, val sha256: ByteArray, val data: ByteArray) {
265 val text: String? get() = if (mime == Protocol.ClipMime.TEXT) String(data, Charsets.UTF_8) else null
266 }
267
268 fun decodeClipboardSync(p: ByteArray): ClipboardSync {
269 if (p.size < 40) throw ProtocolException("CLIPBOARD_SYNC 길이 오류: ${p.size}")
270 val b = ByteBuffer.wrap(p)
271 val origin = b.get().toInt() and 0xFF
272 val autoPaste = b.get().toInt() and 0xFF
273 val mime = b.get().toInt() and 0xFF
274 b.get()
275 val sha = ByteArray(32).also { b.get(it) }
276 val len = b.int.toLong() and 0xFFFFFFFFL
277 if (len != (p.size - 40).toLong()) throw ProtocolException("CLIPBOARD_SYNC text_len 불일치")
278 if (mime !in Protocol.ClipMime.TEXT..Protocol.ClipMime.JPEG) throw ProtocolException("CLIPBOARD_SYNC mime 오류: $mime")
279 val data = p.copyOfRange(40, p.size)
280 if (mime == Protocol.ClipMime.TEXT && Utf8.decodeStrict(data) == null) throw ProtocolException("CLIPBOARD_SYNC UTF-8 오류")
281 return ClipboardSync(origin, autoPaste == 1, mime, sha, data)
282 }
283
284 class FileStart(val id: Int, val size: Long, val name: String)
285
286 fun decodeFileStart(p: ByteArray): FileStart {
287 if (p.size < 13 || p.size > 12 + 255) throw ProtocolException("FILE_START 길이 오류: ${p.size}")
288 val b = ByteBuffer.wrap(p)
289 val id = b.int
290 val size = b.long
291 if (size < 0) throw ProtocolException("FILE_START 크기 오류")
292 val name = Utf8.decodeStrict(p.copyOfRange(12, p.size)) ?: throw ProtocolException("FILE_START 이름 UTF-8 오류")
293 return FileStart(id, size, name)
294 }
295
296 /** FILE_DATA: (transfer_id, 데이터 시작 위치). 데이터는 payload의 4번째 바이트부터다. */
297 fun decodeFileDataId(p: ByteArray): Int {
298 if (p.size < 5 || p.size > 4 + 256 * 1024) throw ProtocolException("FILE_DATA 길이 오류: ${p.size}")
299 return ByteBuffer.wrap(p).int
300 }
301
302 class FileEnd(val id: Int, val sha256: ByteArray)
303
304 fun decodeFileEnd(p: ByteArray): FileEnd {
305 if (p.size != 36) throw ProtocolException("FILE_END 길이 오류: ${p.size}")
306 val b = ByteBuffer.wrap(p)
307 val id = b.int
308 return FileEnd(id, ByteArray(32).also { b.get(it) })
309 }
310
311 fun decodeFileCancel(p: ByteArray): Int {
312 if (p.size != 4) throw ProtocolException("FILE_CANCEL 길이 오류: ${p.size}")
313 return ByteBuffer.wrap(p).int
314 }
315
316 fun encodeFileResult(id: Int, status: Int, message: String): ByteArray {
317 val m = message.toByteArray(Charsets.UTF_8)
318 return ByteBuffer.allocate(5 + m.size).putInt(id).put(status.toByte()).put(m).array()
319 }
320
321 /** origin 0x02(기기), auto_paste 0. */
322 fun encodeClipboardSyncFromDevice(mime: Int, sha256: ByteArray, data: ByteArray): ByteArray =
323 ByteBuffer.allocate(40 + data.size)
324 .put(0x02).put(0x00).put(mime.toByte()).put(0x00)
325 .put(sha256).putInt(data.size).put(data)
326 .array()
327
328 class VideoConfigRequest(val maxSize: Int, val maxFps: Int, val codecMask: Int, val bitrate: Long)
329
330 fun decodeVideoConfigRequest(p: ByteArray): VideoConfigRequest {
331 if (p.size != 8) throw ProtocolException("VIDEO_CONFIG_REQUEST 길이 오류: ${p.size}")
332 val b = ByteBuffer.wrap(p)
333 return VideoConfigRequest(
334 maxSize = b.short.toInt() and 0xFFFF,
335 maxFps = b.get().toInt() and 0xFF,
336 codecMask = b.get().toInt() and 0xFF,
337 bitrate = b.int.toLong() and 0xFFFFFFFFL,
338 )
339 }
340
341 class VideoConfig(
342 val codec: Int,
343 val configGen: Int,
344 val width: Int,
345 val height: Int,
346 val fps: Int,
347 val bitrate: Long,
348 val displayWidth: Int,
349 val displayHeight: Int,
350 )
351
352 fun encodeVideoConfig(c: VideoConfig): ByteArray =
353 ByteBuffer.allocate(16)
354 .put(c.codec.toByte()).put(c.configGen.toByte())
355 .putShort(c.width.toShort()).putShort(c.height.toShort())
356 .put(c.fps.toByte()).put(0)
357 .putInt(c.bitrate.toInt())
358 .putShort(c.displayWidth.toShort()).putShort(c.displayHeight.toShort())
359 .array()
360}
361
362object Utf8 {
363 /** 잘못된 UTF-8이면 null. */
364 fun decodeStrict(bytes: ByteArray): String? = try {
365 Charsets.UTF_8.newDecoder()
366 .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
367 .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT)
368 .decode(ByteBuffer.wrap(bytes))
369 .toString()
370 } catch (e: java.nio.charset.CharacterCodingException) {
371 null
372 }
373}