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 | 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 | /** 프레임 경계가 깨졌거나 규격에 맞지 않는 데이터. 받으면 연결을 끊는다. */ |
| 91 | class ProtocolException(message: String) : IOException(message) |
| 92 | |
| 93 | class Frame(val type: Int, val flags: Int, val seq: Int, val payload: ByteArray) |
| 94 | |
| 95 | /** TLS 스트림 위에서 12바이트 헤더 + 페이로드 프레임을 읽고 쓴다. */ |
| 96 | class 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]. */ |
| 153 | object 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 VideoConfigRequest(val maxSize: Int, val maxFps: Int, val codecMask: Int, val bitrate: Long) |
| 190 | |
| 191 | fun decodeVideoConfigRequest(p: ByteArray): VideoConfigRequest { |
| 192 | if (p.size != 8) throw ProtocolException("VIDEO_CONFIG_REQUEST 길이 오류: ${p.size}") |
| 193 | val b = ByteBuffer.wrap(p) |
| 194 | return VideoConfigRequest( |
| 195 | maxSize = b.short.toInt() and 0xFFFF, |
| 196 | maxFps = b.get().toInt() and 0xFF, |
| 197 | codecMask = b.get().toInt() and 0xFF, |
| 198 | bitrate = b.int.toLong() and 0xFFFFFFFFL, |
| 199 | ) |
| 200 | } |
| 201 | |
| 202 | class VideoConfig( |
| 203 | val codec: Int, |
| 204 | val configGen: Int, |
| 205 | val width: Int, |
| 206 | val height: Int, |
| 207 | val fps: Int, |
| 208 | val bitrate: Long, |
| 209 | val displayWidth: Int, |
| 210 | val displayHeight: Int, |
| 211 | ) |
| 212 | |
| 213 | fun encodeVideoConfig(c: VideoConfig): ByteArray = |
| 214 | ByteBuffer.allocate(16) |
| 215 | .put(c.codec.toByte()).put(c.configGen.toByte()) |
| 216 | .putShort(c.width.toShort()).putShort(c.height.toShort()) |
| 217 | .put(c.fps.toByte()).put(0) |
| 218 | .putInt(c.bitrate.toInt()) |
| 219 | .putShort(c.displayWidth.toShort()).putShort(c.displayHeight.toShort()) |
| 220 | .array() |
| 221 | } |
| 222 | |
| 223 | object Utf8 { |
| 224 | /** 잘못된 UTF-8이면 null. */ |
| 225 | fun decodeStrict(bytes: ByteArray): String? = try { |
| 226 | Charsets.UTF_8.newDecoder() |
| 227 | .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) |
| 228 | .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) |
| 229 | .decode(ByteBuffer.wrap(bytes)) |
| 230 | .toString() |
| 231 | } catch (e: java.nio.charset.CharacterCodingException) { |
| 232 | null |
| 233 | } |
| 234 | } |