leejunyoung5819wayland-android-remote

공개

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

316줄12 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 const val VIDEO_HEADER_LEN: Int = 16
19
20 object MsgType {
21 const val PING = 0x01
22 const val PONG = 0x02
23 const val AUTH_HELLO = 0x03
24 const val AUTH_CHALLENGE = 0x04
25 const val AUTH_RESPONSE = 0x05
26 const val AUTH_RESULT = 0x06
27 const val CHANNEL_ATTACH = 0x07
28 const val KEY_EVENT = 0x10
29 const val TEXT_INPUT = 0x11
30 const val SYSTEM_ACTION = 0x12
31 const val CLIPBOARD_SYNC = 0x20
32 const val TOUCH_EVENT = 0x30
33 const val SCROLL_EVENT = 0x31
34 const val VIDEO_CONFIG_REQUEST = 0x40
35 const val VIDEO_CONFIG = 0x41
36 const val VIDEO_REQUEST_KEYFRAME = 0x42
37 const val ACK = 0xF0
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 const val ROTATE = 0x20
88 const val SCREEN_OFF = 0x21
89 const val SCREEN_ON = 0x22
90 }
91}
92
93/** 프레임 경계가 깨졌거나 규격에 맞지 않는 데이터. 받으면 연결을 끊는다. */
94class ProtocolException(message: String) : IOException(message)
95
96class Frame(val type: Int, val flags: Int, val seq: Int, val payload: ByteArray)
97
98/** TLS 스트림 위에서 12바이트 헤더 + 페이로드 프레임을 읽고 쓴다. */
99class FrameIO(private val input: DataInputStream, private val output: OutputStream) {
100 private var nextSeq = 0
101 private val writeLock = Any()
102
103 /** 프레임 하나를 끝까지 읽는다. 상대가 정상 종료했으면 null. */
104 fun read(): Frame? {
105 val header = ByteArray(Protocol.HEADER_LEN)
106 try {
107 input.readFully(header)
108 } catch (e: EOFException) {
109 return null
110 }
111 val b = ByteBuffer.wrap(header)
112 val magic = b.short.toInt() and 0xFFFF
113 val version = b.get().toInt() and 0xFF
114 val type = b.get().toInt() and 0xFF
115 val flags = b.short.toInt() and 0xFFFF
116 val seq = b.short.toInt() and 0xFFFF
117 val len = b.int.toLong() and 0xFFFFFFFFL
118 if (magic != Protocol.MAGIC) throw ProtocolException("잘못된 magic: 0x%04x".format(magic))
119 if (version != Protocol.VERSION) throw ProtocolException("지원하지 않는 버전: $version")
120 if (len > Protocol.MAX_PAYLOAD_LEN) throw ProtocolException("payload_len 초과: $len")
121 val payload = ByteArray(len.toInt())
122 input.readFully(payload)
123 return Frame(type, flags, seq, payload)
124 }
125
126 /** 다음 순환 seq_id로 보낸다. */
127 fun send(type: Int, payload: ByteArray = ByteArray(0)): Int = synchronized(writeLock) {
128 val seq = nextSeq
129 nextSeq = (nextSeq + 1) and 0xFFFF
130 sendWithSeq(type, seq, payload)
131 seq
132 }
133
134 /** PONG처럼 요청의 seq_id를 되돌려줄 때 쓴다. */
135 fun sendWithSeq(type: Int, seq: Int, payload: ByteArray = ByteArray(0)) = synchronized(writeLock) {
136 val buf = ByteBuffer.allocate(Protocol.HEADER_LEN + payload.size)
137 buf.putShort(Protocol.MAGIC.toShort())
138 buf.put(Protocol.VERSION.toByte())
139 buf.put(type.toByte())
140 buf.putShort(0)
141 buf.putShort(seq.toShort())
142 buf.putInt(payload.size)
143 buf.put(payload)
144 output.write(buf.array())
145 output.flush()
146 }
147
148 fun sendError(code: Int, reason: String) {
149 val text = reason.toByteArray(Charsets.UTF_8)
150 val p = ByteBuffer.allocate(2 + text.size).putShort(code.toShort()).put(text).array()
151 send(Protocol.MsgType.ERROR, p)
152 }
153}
154
155/** 메시지별 페이로드 인코딩/디코딩. 길이가 맞지 않으면 [ProtocolException]. */
156object Messages {
157 class AuthHello(val publicKey: ByteArray, val hostname: String)
158
159 fun decodeAuthHello(p: ByteArray): AuthHello {
160 if (p.size < 33 || p.size > 32 + 255) throw ProtocolException("AUTH_HELLO 길이 오류: ${p.size}")
161 val host = Utf8.decodeStrict(p.copyOfRange(32, p.size))
162 ?: throw ProtocolException("AUTH_HELLO 호스트명 UTF-8 오류")
163 return AuthHello(p.copyOfRange(0, 32), host)
164 }
165
166 fun encodeAuthChallenge(status: Int, nonce: ByteArray): ByteArray =
167 ByteBuffer.allocate(36).put(status.toByte()).put(ByteArray(3)).put(nonce).array()
168
169 fun decodeAuthResponse(p: ByteArray): ByteArray {
170 if (p.size != 64) throw ProtocolException("AUTH_RESPONSE 길이 오류: ${p.size}")
171 return p
172 }
173
174 fun encodeAuthResult(result: Int, grant: Int, token: ByteArray, daemonVersion: Int): ByteArray =
175 ByteBuffer.allocate(40)
176 .put(result.toByte()).put(grant.toByte()).putShort(0)
177 .put(token).putInt(daemonVersion)
178 .array()
179
180 class ChannelAttach(val kind: Int, val token: ByteArray)
181
182 fun decodeChannelAttach(p: ByteArray): ChannelAttach {
183 if (p.size != 36) throw ProtocolException("CHANNEL_ATTACH 길이 오류: ${p.size}")
184 return ChannelAttach(p[0].toInt() and 0xFF, p.copyOfRange(4, 36))
185 }
186
187 fun decodeSystemAction(p: ByteArray): Int {
188 if (p.size != 4) throw ProtocolException("SYSTEM_ACTION 길이 오류: ${p.size}")
189 return p[0].toInt() and 0xFF
190 }
191
192 class TouchEvent(
193 val action: Int, val pointerId: Int, val x: Int, val y: Int,
194 val frameWidth: Int, val frameHeight: Int, val pressure: Int,
195 )
196
197 fun decodeTouchEvent(p: ByteArray): TouchEvent {
198 if (p.size != 20) throw ProtocolException("TOUCH_EVENT 길이 오류: ${p.size}")
199 val b = ByteBuffer.wrap(p)
200 val action = b.get().toInt() and 0xFF
201 val pointerId = b.get().toInt() and 0xFF
202 b.short
203 val x = b.int
204 val y = b.int
205 val fw = b.short.toInt() and 0xFFFF
206 val fh = b.short.toInt() and 0xFFFF
207 val pressure = b.short.toInt() and 0xFFFF
208 if (action > 3) throw ProtocolException("TOUCH_EVENT action 오류: $action")
209 if (fw == 0 || fh == 0) throw ProtocolException("TOUCH_EVENT 프레임 크기 0")
210 return TouchEvent(action, pointerId, x, y, fw, fh, pressure)
211 }
212
213 class ScrollEvent(val x: Int, val y: Int, val frameWidth: Int, val frameHeight: Int, val hScroll: Int, val vScroll: Int)
214
215 fun decodeScrollEvent(p: ByteArray): ScrollEvent {
216 if (p.size != 16) throw ProtocolException("SCROLL_EVENT 길이 오류: ${p.size}")
217 val b = ByteBuffer.wrap(p)
218 val x = b.int
219 val y = b.int
220 val fw = b.short.toInt() and 0xFFFF
221 val fh = b.short.toInt() and 0xFFFF
222 if (fw == 0 || fh == 0) throw ProtocolException("SCROLL_EVENT 프레임 크기 0")
223 return ScrollEvent(x, y, fw, fh, b.short.toInt(), b.short.toInt())
224 }
225
226 class KeyEvent(val action: Int, val keycode: Int, val metaState: Int, val repeat: Int, val scancode: Int)
227
228 fun decodeKeyEvent(p: ByteArray): KeyEvent {
229 if (p.size != 12) throw ProtocolException("KEY_EVENT 길이 오류: ${p.size}")
230 val b = ByteBuffer.wrap(p)
231 val action = b.get().toInt() and 0xFF
232 b.get()
233 val keycode = b.short.toInt() and 0xFFFF
234 val meta = b.int
235 val repeat = b.short.toInt() and 0xFFFF
236 val scancode = b.short.toInt() and 0xFFFF
237 if (action > 2) throw ProtocolException("KEY_EVENT action 오류: $action")
238 return KeyEvent(action, keycode, meta, repeat, scancode)
239 }
240
241 fun decodeTextInput(p: ByteArray): String {
242 if (p.isEmpty()) throw ProtocolException("TEXT_INPUT 빈 문자열")
243 return Utf8.decodeStrict(p) ?: throw ProtocolException("TEXT_INPUT UTF-8 오류")
244 }
245
246 class ClipboardSync(val origin: Int, val autoPaste: Boolean, val sha256: ByteArray, val text: String)
247
248 fun decodeClipboardSync(p: ByteArray): ClipboardSync {
249 if (p.size < 40) throw ProtocolException("CLIPBOARD_SYNC 길이 오류: ${p.size}")
250 val b = ByteBuffer.wrap(p)
251 val origin = b.get().toInt() and 0xFF
252 val autoPaste = b.get().toInt() and 0xFF
253 b.get()
254 b.get()
255 val sha = ByteArray(32).also { b.get(it) }
256 val len = b.int.toLong() and 0xFFFFFFFFL
257 if (len != (p.size - 40).toLong()) throw ProtocolException("CLIPBOARD_SYNC text_len 불일치")
258 val text = Utf8.decodeStrict(p.copyOfRange(40, p.size)) ?: throw ProtocolException("CLIPBOARD_SYNC UTF-8 오류")
259 return ClipboardSync(origin, autoPaste == 1, sha, text)
260 }
261
262 /** origin 0x02(기기), auto_paste 0, mime 0x01(text/plain). */
263 fun encodeClipboardSyncFromDevice(sha256: ByteArray, text: String): ByteArray {
264 val bytes = text.toByteArray(Charsets.UTF_8)
265 return ByteBuffer.allocate(40 + bytes.size)
266 .put(0x02).put(0x00).put(0x01).put(0x00)
267 .put(sha256).putInt(bytes.size).put(bytes)
268 .array()
269 }
270
271 class VideoConfigRequest(val maxSize: Int, val maxFps: Int, val codecMask: Int, val bitrate: Long)
272
273 fun decodeVideoConfigRequest(p: ByteArray): VideoConfigRequest {
274 if (p.size != 8) throw ProtocolException("VIDEO_CONFIG_REQUEST 길이 오류: ${p.size}")
275 val b = ByteBuffer.wrap(p)
276 return VideoConfigRequest(
277 maxSize = b.short.toInt() and 0xFFFF,
278 maxFps = b.get().toInt() and 0xFF,
279 codecMask = b.get().toInt() and 0xFF,
280 bitrate = b.int.toLong() and 0xFFFFFFFFL,
281 )
282 }
283
284 class VideoConfig(
285 val codec: Int,
286 val configGen: Int,
287 val width: Int,
288 val height: Int,
289 val fps: Int,
290 val bitrate: Long,
291 val displayWidth: Int,
292 val displayHeight: Int,
293 )
294
295 fun encodeVideoConfig(c: VideoConfig): ByteArray =
296 ByteBuffer.allocate(16)
297 .put(c.codec.toByte()).put(c.configGen.toByte())
298 .putShort(c.width.toShort()).putShort(c.height.toShort())
299 .put(c.fps.toByte()).put(0)
300 .putInt(c.bitrate.toInt())
301 .putShort(c.displayWidth.toShort()).putShort(c.displayHeight.toShort())
302 .array()
303}
304
305object Utf8 {
306 /** 잘못된 UTF-8이면 null. */
307 fun decodeStrict(bytes: ByteArray): String? = try {
308 Charsets.UTF_8.newDecoder()
309 .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
310 .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT)
311 .decode(ByteBuffer.wrap(bytes))
312 .toString()
313 } catch (e: java.nio.charset.CharacterCodingException) {
314 null
315 }
316}