leejunyoung5819wayland-android-remote

공개

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

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