leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | package com.androidremote.daemon |
| 2 | |
| 3 | import android.view.KeyEvent |
| 4 | import java.io.BufferedInputStream |
| 5 | import java.io.BufferedOutputStream |
| 6 | import java.io.Closeable |
| 7 | import java.io.DataInputStream |
| 8 | import java.io.IOException |
| 9 | import java.net.InetAddress |
| 10 | import java.net.SocketException |
| 11 | import java.security.MessageDigest |
| 12 | import java.security.SecureRandom |
| 13 | import java.util.concurrent.ConcurrentHashMap |
| 14 | import java.util.concurrent.atomic.AtomicBoolean |
| 15 | import javax.net.ssl.SSLServerSocket |
| 16 | import javax.net.ssl.SSLSocket |
| 17 | |
| 18 | /** |
| 19 | * 제어·영상 연결을 받는 TLS 1.3 서버 (기획서 5.5, 7.6). 연결마다 스레드 하나를 쓴다. |
| 20 | * 첫 프레임이 AUTH_HELLO면 제어 연결, CHANNEL_ATTACH면 영상 연결이다. |
| 21 | */ |
| 22 | /** 클립보드 동기화 최대 크기. 제어 채널 페이로드 상한(4MB)보다 작게 둔다. */ |
| 23 | private const val MAX_CLIPBOARD_BYTES = 1024 * 1024 |
| 24 | |
| 25 | class Server( |
| 26 | private val port: Int, |
| 27 | private val identity: DeviceIdentity, |
| 28 | private val whitelist: Whitelist, |
| 29 | private val policy: ApprovePolicy, |
| 30 | private val daemonVersion: Int, |
| 31 | ) { |
| 32 | private val random = SecureRandom() |
| 33 | /** 세션 토큰(16진수) -> 세션. 제어 연결이 살아 있는 동안만 들어 있다. */ |
| 34 | private val sessions = ConcurrentHashMap<String, Session>() |
| 35 | |
| 36 | private class Session(val token: ByteArray) { |
| 37 | val videoAttached = AtomicBoolean(false) |
| 38 | val closeables = mutableListOf<Closeable>() |
| 39 | /** 마지막 VIDEO_CONFIG. 영상 채널이 붙으면 이 설정으로 인코딩을 시작한다. */ |
| 40 | @Volatile var videoConfig: Messages.VideoConfig? = null |
| 41 | @Volatile var streamer: VideoStreamer? = null |
| 42 | var configGen = 0 |
| 43 | val input = InputInjector() |
| 44 | /** 제어 채널. 영상 스레드가 회전 시 VIDEO_CONFIG를 보낼 때도 쓴다. */ |
| 45 | @Volatile var io: FrameIO? = null |
| 46 | /** 마지막 영상 설정 요청. 회전하면 같은 요청으로 다시 계산한다. */ |
| 47 | @Volatile var lastRequest = Messages.VideoConfigRequest(1920, 60, Protocol.Codec.H264 or Protocol.Codec.H265, 8_000_000) |
| 48 | @Volatile var screenOff = false |
| 49 | val keepAwake = KeepAwake() |
| 50 | var clipboardListener: Any? = null |
| 51 | |
| 52 | @Synchronized |
| 53 | fun track(c: Closeable) = closeables.add(c) |
| 54 | |
| 55 | @Synchronized |
| 56 | fun closeAll() { |
| 57 | streamer?.stop() |
| 58 | closeables.forEach { runCatching { it.close() } } |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | fun run() { |
| 63 | val ctx = identity.sslContext() |
| 64 | val ss = ctx.serverSocketFactory |
| 65 | .createServerSocket(port, 16, InetAddress.getByName("0.0.0.0")) as SSLServerSocket |
| 66 | ss.enabledProtocols = arrayOf("TLSv1.3") |
| 67 | ss.needClientAuth = false |
| 68 | Log.i("수신 대기: 0.0.0.0:$port (TLS 1.3)") |
| 69 | while (true) { |
| 70 | val socket = ss.accept() as SSLSocket |
| 71 | Thread({ handle(socket) }, "conn-${socket.inetAddress.hostAddress}").start() |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | private fun handle(socket: SSLSocket) { |
| 76 | val peer = "${socket.inetAddress.hostAddress}:${socket.port}" |
| 77 | try { |
| 78 | socket.tcpNoDelay = true |
| 79 | socket.startHandshake() |
| 80 | val io = FrameIO( |
| 81 | DataInputStream(BufferedInputStream(socket.inputStream)), |
| 82 | BufferedOutputStream(socket.outputStream), |
| 83 | ) |
| 84 | val first = io.read() ?: return |
| 85 | when (first.type) { |
| 86 | Protocol.MsgType.AUTH_HELLO -> handleControl(socket, io, first, peer) |
| 87 | Protocol.MsgType.CHANNEL_ATTACH -> handleVideo(socket, first, peer) |
| 88 | else -> { |
| 89 | Log.w("$peer: 인증 전 메시지 0x%02x".format(first.type)) |
| 90 | io.sendError(Protocol.ErrorCode.UNAUTHENTICATED, "AUTH_HELLO가 먼저 와야 합니다") |
| 91 | } |
| 92 | } |
| 93 | } catch (e: SocketException) { |
| 94 | Log.i("$peer: 연결 종료 (${e.message})") |
| 95 | } catch (e: IOException) { |
| 96 | Log.w("$peer: $e") |
| 97 | } catch (e: Exception) { |
| 98 | Log.w("$peer: 처리 중 오류 $e") |
| 99 | } finally { |
| 100 | runCatching { socket.close() } |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | private fun handleControl(socket: SSLSocket, io: FrameIO, helloFrame: Frame, peer: String) { |
| 105 | val hello = Messages.decodeAuthHello(helloFrame.payload) |
| 106 | val keyHex = Hex.encode(hello.publicKey) |
| 107 | val known = whitelist.contains(hello.publicKey) |
| 108 | Log.i("$peer: AUTH_HELLO host=${hello.hostname} key=${keyHex.take(16)}… 허용목록=${known}") |
| 109 | |
| 110 | val nonce = ByteArray(32).also { random.nextBytes(it) } |
| 111 | val status = if (known) Protocol.AuthStatus.APPROVED else Protocol.AuthStatus.PENDING_USER |
| 112 | io.send(Protocol.MsgType.AUTH_CHALLENGE, Messages.encodeAuthChallenge(status, nonce)) |
| 113 | |
| 114 | val resp = readExpect(io, Protocol.MsgType.AUTH_RESPONSE) ?: return |
| 115 | val signature = Messages.decodeAuthResponse(resp.payload) |
| 116 | if (!Ed25519.verify(hello.publicKey, nonce + identity.fingerprint, signature)) { |
| 117 | Log.w("$peer: 서명 검증 실패") |
| 118 | io.send(Protocol.MsgType.AUTH_RESULT, Messages.encodeAuthResult( |
| 119 | Protocol.AuthResultCode.SIGNATURE_INVALID, Protocol.Grant.NONE, ByteArray(32), daemonVersion)) |
| 120 | return |
| 121 | } |
| 122 | |
| 123 | val grant = if (known) { |
| 124 | Protocol.Grant.ALWAYS |
| 125 | } else { |
| 126 | Log.i("$peer: 새 PC 승인 요청 host=${hello.hostname} 확인 코드=${identity.confirmCode} 정책=$policy") |
| 127 | when (policy) { |
| 128 | ApprovePolicy.ALWAYS -> { |
| 129 | whitelist.add(hello.publicKey, hello.hostname) |
| 130 | Protocol.Grant.ALWAYS |
| 131 | } |
| 132 | ApprovePolicy.ONCE -> Protocol.Grant.ONCE |
| 133 | ApprovePolicy.REJECT -> { |
| 134 | io.send(Protocol.MsgType.AUTH_RESULT, Messages.encodeAuthResult( |
| 135 | Protocol.AuthResultCode.REJECTED, Protocol.Grant.NONE, ByteArray(32), daemonVersion)) |
| 136 | return |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | val token = ByteArray(32).also { random.nextBytes(it) } |
| 142 | val session = Session(token) |
| 143 | session.track(socket) |
| 144 | sessions[Hex.encode(token)] = session |
| 145 | try { |
| 146 | io.send(Protocol.MsgType.AUTH_RESULT, Messages.encodeAuthResult( |
| 147 | Protocol.AuthResultCode.OK, grant, token, daemonVersion)) |
| 148 | Log.i("$peer: 인증 완료 grant=${if (grant == Protocol.Grant.ALWAYS) "ALWAYS" else "ONCE"}") |
| 149 | session.io = io |
| 150 | session.keepAwake.start() |
| 151 | session.clipboardListener = ClipboardAccess.addListener { |
| 152 | // 기기에서 복사하면 호스트 클립보드로 보낸다 (기획서 7.4 1항). |
| 153 | val (text, hash) = ClipboardSync.changedText() ?: return@addListener |
| 154 | if (text.toByteArray(Charsets.UTF_8).size > MAX_CLIPBOARD_BYTES) { |
| 155 | Log.w("$peer: 클립보드가 너무 커서 보내지 않음") |
| 156 | return@addListener |
| 157 | } |
| 158 | runCatching { io.send(Protocol.MsgType.CLIPBOARD_SYNC, Messages.encodeClipboardSyncFromDevice(hash, text)) } |
| 159 | Log.i("$peer: 기기 클립보드 -> 호스트 (${text.length}자)") |
| 160 | } |
| 161 | serveControl(io, peer, session) |
| 162 | } finally { |
| 163 | sessions.remove(Hex.encode(token)) |
| 164 | runCatching { session.input.releaseAll() } |
| 165 | session.clipboardListener?.let { ClipboardAccess.removeListener(it) } |
| 166 | session.keepAwake.stop() |
| 167 | // 세션이 끝나면 화면 전원과 회전 설정을 원래대로 돌린다. |
| 168 | if (session.screenOff) DisplayPower.set(true) |
| 169 | Rotation.restore() |
| 170 | session.closeAll() |
| 171 | Log.i("$peer: 세션 종료") |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | /** 인증 중에는 PING만 응답하고 기다리던 메시지를 돌려준다. */ |
| 176 | private fun readExpect(io: FrameIO, type: Int): Frame? { |
| 177 | while (true) { |
| 178 | val f = io.read() ?: return null |
| 179 | when { |
| 180 | f.type == type -> return f |
| 181 | f.type == Protocol.MsgType.PING -> io.sendWithSeq(Protocol.MsgType.PONG, f.seq) |
| 182 | !Protocol.MsgType.allowedBeforeAuth(f.type) -> { |
| 183 | io.sendError(Protocol.ErrorCode.UNAUTHENTICATED, "인증 전입니다") |
| 184 | return null |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | private fun serveControl(io: FrameIO, peer: String, session: Session) { |
| 191 | while (true) { |
| 192 | val f = io.read() ?: return |
| 193 | try { |
| 194 | when (f.type) { |
| 195 | Protocol.MsgType.PING -> io.sendWithSeq(Protocol.MsgType.PONG, f.seq) |
| 196 | Protocol.MsgType.PONG -> Unit |
| 197 | Protocol.MsgType.VIDEO_REQUEST_KEYFRAME -> session.streamer?.requestKeyframe() |
| 198 | Protocol.MsgType.SYSTEM_ACTION -> handleSystemAction(Messages.decodeSystemAction(f.payload), peer, session) |
| 199 | Protocol.MsgType.CLIPBOARD_SYNC -> { |
| 200 | val c = Messages.decodeClipboardSync(f.payload) |
| 201 | ClipboardSync.fromHost(c.text, c.autoPaste) |
| 202 | Log.i("$peer: 호스트 클립보드 -> 기기 (${c.text.length}자, 붙여넣기=${c.autoPaste})") |
| 203 | } |
| 204 | Protocol.MsgType.TOUCH_EVENT -> { |
| 205 | val t = Messages.decodeTouchEvent(f.payload) |
| 206 | // 회전 직후처럼 프레임 크기가 현재 설정과 다르면 엉뚱한 곳을 누르지 않도록 버린다 (기획서 7.3 4항). |
| 207 | if (frameMatches(session, t.frameWidth, t.frameHeight)) session.input.touch(t) |
| 208 | } |
| 209 | Protocol.MsgType.SCROLL_EVENT -> { |
| 210 | val s = Messages.decodeScrollEvent(f.payload) |
| 211 | if (frameMatches(session, s.frameWidth, s.frameHeight)) session.input.scroll(s) |
| 212 | } |
| 213 | Protocol.MsgType.KEY_EVENT -> { |
| 214 | val k = Messages.decodeKeyEvent(f.payload) |
| 215 | session.input.key(k.action, k.keycode, k.metaState, k.repeat, k.scancode) |
| 216 | } |
| 217 | Protocol.MsgType.TEXT_INPUT -> session.input.text(Messages.decodeTextInput(f.payload)) |
| 218 | Protocol.MsgType.VIDEO_CONFIG_REQUEST -> { |
| 219 | val req = Messages.decodeVideoConfigRequest(f.payload) |
| 220 | session.lastRequest = req |
| 221 | val cfg = videoConfigFor(req, session) |
| 222 | if (cfg == null) { |
| 223 | io.sendError(Protocol.ErrorCode.INTERNAL, "지원하는 하드웨어 코덱이 없습니다") |
| 224 | } else { |
| 225 | // 기획서 7.6: VIDEO_CONFIG 통지 후 영상 채널에 CONFIG -> KEYFRAME 순으로 보낸다. |
| 226 | io.send(Protocol.MsgType.VIDEO_CONFIG, Messages.encodeVideoConfig(cfg)) |
| 227 | session.videoConfig = cfg |
| 228 | session.streamer?.reconfigure(cfg) |
| 229 | Log.i("$peer: VIDEO_CONFIG ${cfg.width}x${cfg.height} ${cfg.fps}fps codec=${cfg.codec} gen=${cfg.configGen}") |
| 230 | } |
| 231 | } |
| 232 | else -> Log.i("$peer: 아직 처리하지 않는 메시지 0x%02x".format(f.type)) |
| 233 | } |
| 234 | } catch (e: ProtocolException) { |
| 235 | Log.w("$peer: 잘못된 페이로드 $e") |
| 236 | io.sendError(Protocol.ErrorCode.BAD_FRAME, e.message ?: "") |
| 237 | } |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | private fun frameMatches(session: Session, w: Int, h: Int): Boolean { |
| 242 | val cfg = session.videoConfig ?: return false |
| 243 | return cfg.width == w && cfg.height == h |
| 244 | } |
| 245 | |
| 246 | private fun handleSystemAction(code: Int, peer: String, session: Session) { |
| 247 | val keycode = when (code) { |
| 248 | Protocol.SystemAction.ROTATE -> { |
| 249 | Rotation.toggle() |
| 250 | return |
| 251 | } |
| 252 | Protocol.SystemAction.SCREEN_OFF -> { |
| 253 | session.screenOff = DisplayPower.set(false) |
| 254 | return |
| 255 | } |
| 256 | Protocol.SystemAction.SCREEN_ON -> { |
| 257 | if (DisplayPower.set(true)) session.screenOff = false |
| 258 | return |
| 259 | } |
| 260 | Protocol.SystemAction.BACK -> KeyEvent.KEYCODE_BACK |
| 261 | Protocol.SystemAction.HOME -> KeyEvent.KEYCODE_HOME |
| 262 | Protocol.SystemAction.RECENTS -> KeyEvent.KEYCODE_APP_SWITCH |
| 263 | Protocol.SystemAction.COPY -> KeyEvent.KEYCODE_COPY |
| 264 | Protocol.SystemAction.PASTE -> KeyEvent.KEYCODE_PASTE |
| 265 | Protocol.SystemAction.CUT -> KeyEvent.KEYCODE_CUT |
| 266 | Protocol.SystemAction.SELECT_ALL -> { |
| 267 | SystemAccess.pressKey(KeyEvent.KEYCODE_A, KeyEvent.META_CTRL_ON or KeyEvent.META_CTRL_LEFT_ON) |
| 268 | Log.i("$peer: SYSTEM_ACTION SELECT_ALL -> Ctrl+A") |
| 269 | return |
| 270 | } |
| 271 | else -> { |
| 272 | Log.w("$peer: 처리하지 않는 SYSTEM_ACTION 0x%02x".format(code)) |
| 273 | return |
| 274 | } |
| 275 | } |
| 276 | SystemAccess.pressKey(keycode) |
| 277 | Log.i("$peer: SYSTEM_ACTION 0x%02x -> keycode $keycode".format(code)) |
| 278 | } |
| 279 | |
| 280 | /** 요청과 기기 하드웨어 인코더로 실제 영상 설정을 정한다. 크기는 인코더 호환을 위해 16의 배수로 맞춘다. */ |
| 281 | private fun videoConfigFor(req: Messages.VideoConfigRequest, session: Session): Messages.VideoConfig? { |
| 282 | val codec = Encoders.choose(req.codecMask) ?: return null |
| 283 | val (dw, dh) = SystemAccess.displaySize() ?: (1080 to 2400) |
| 284 | val long = maxOf(dw, dh) |
| 285 | val scale = if (req.maxSize == 0 || req.maxSize >= long) 1.0 else req.maxSize.toDouble() / long |
| 286 | val w = (dw * scale).toInt() and 15.inv() |
| 287 | val h = (dh * scale).toInt() and 15.inv() |
| 288 | val fps = if (req.maxFps == 0) 60 else minOf(req.maxFps, 120) |
| 289 | synchronized(session) { |
| 290 | session.configGen = (session.configGen % 255) + 1 |
| 291 | return Messages.VideoConfig(codec, session.configGen, w, h, fps, req.bitrate, dw, dh) |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | /** 기기 화면 방향이 바뀌면 새 크기로 설정을 다시 계산해 통지하고 인코더를 다시 만든다 (기획서 7.6). */ |
| 296 | private fun onDisplayRotated(session: Session, peer: String) { |
| 297 | val cfg = videoConfigFor(session.lastRequest, session) ?: return |
| 298 | session.io?.let { io -> |
| 299 | runCatching { io.send(Protocol.MsgType.VIDEO_CONFIG, Messages.encodeVideoConfig(cfg)) } |
| 300 | } |
| 301 | session.videoConfig = cfg |
| 302 | session.streamer?.reconfigure(cfg) |
| 303 | Log.i("$peer: 회전 감지 -> VIDEO_CONFIG ${cfg.width}x${cfg.height} gen=${cfg.configGen}") |
| 304 | } |
| 305 | |
| 306 | private fun handleVideo(socket: SSLSocket, first: Frame, peer: String) { |
| 307 | val attach = Messages.decodeChannelAttach(first.payload) |
| 308 | val session = sessions.values.firstOrNull { |
| 309 | MessageDigest.isEqual(it.token, attach.token) |
| 310 | } |
| 311 | if (attach.kind != 0x01 || session == null || !session.videoAttached.compareAndSet(false, true)) { |
| 312 | Log.w("$peer: CHANNEL_ATTACH 거부 (토큰 없음, 재사용 또는 종류 오류)") |
| 313 | return |
| 314 | } |
| 315 | session.track(socket) |
| 316 | val config = session.videoConfig ?: videoConfigFor( |
| 317 | Messages.VideoConfigRequest(1920, 60, Protocol.Codec.H264 or Protocol.Codec.H265, 8_000_000), session, |
| 318 | ) |
| 319 | if (config == null) { |
| 320 | Log.w("$peer: 하드웨어 인코더가 없어 영상 채널을 닫습니다") |
| 321 | return |
| 322 | } |
| 323 | session.videoConfig = config |
| 324 | val streamer = VideoStreamer(java.io.BufferedOutputStream(socket.outputStream, 256 * 1024), peer) { |
| 325 | onDisplayRotated(session, peer) |
| 326 | } |
| 327 | session.streamer = streamer |
| 328 | Log.i("$peer: 영상 채널 연결") |
| 329 | streamer.start(config) |
| 330 | try { |
| 331 | // 호스트는 영상 채널로 아무것도 보내지 않는다. 연결이 닫힐 때까지 기다린다. |
| 332 | val buf = ByteArray(256) |
| 333 | while (socket.inputStream.read(buf) >= 0) Unit |
| 334 | } finally { |
| 335 | streamer.stop() |
| 336 | session.streamer = null |
| 337 | } |
| 338 | } |
| 339 | } |