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 | class Server( |
| 23 | private val port: Int, |
| 24 | private val identity: DeviceIdentity, |
| 25 | private val whitelist: Whitelist, |
| 26 | private val policy: ApprovePolicy, |
| 27 | private val daemonVersion: Int, |
| 28 | ) { |
| 29 | private val random = SecureRandom() |
| 30 | /** 세션 토큰(16진수) -> 세션. 제어 연결이 살아 있는 동안만 들어 있다. */ |
| 31 | private val sessions = ConcurrentHashMap<String, Session>() |
| 32 | |
| 33 | private class Session(val token: ByteArray) { |
| 34 | val videoAttached = AtomicBoolean(false) |
| 35 | val closeables = mutableListOf<Closeable>() |
| 36 | |
| 37 | @Synchronized |
| 38 | fun track(c: Closeable) = closeables.add(c) |
| 39 | |
| 40 | @Synchronized |
| 41 | fun closeAll() = closeables.forEach { runCatching { it.close() } } |
| 42 | } |
| 43 | |
| 44 | fun run() { |
| 45 | val ctx = identity.sslContext() |
| 46 | val ss = ctx.serverSocketFactory |
| 47 | .createServerSocket(port, 16, InetAddress.getByName("0.0.0.0")) as SSLServerSocket |
| 48 | ss.enabledProtocols = arrayOf("TLSv1.3") |
| 49 | ss.needClientAuth = false |
| 50 | Log.i("수신 대기: 0.0.0.0:$port (TLS 1.3)") |
| 51 | while (true) { |
| 52 | val socket = ss.accept() as SSLSocket |
| 53 | Thread({ handle(socket) }, "conn-${socket.inetAddress.hostAddress}").start() |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | private fun handle(socket: SSLSocket) { |
| 58 | val peer = "${socket.inetAddress.hostAddress}:${socket.port}" |
| 59 | try { |
| 60 | socket.tcpNoDelay = true |
| 61 | socket.startHandshake() |
| 62 | val io = FrameIO( |
| 63 | DataInputStream(BufferedInputStream(socket.inputStream)), |
| 64 | BufferedOutputStream(socket.outputStream), |
| 65 | ) |
| 66 | val first = io.read() ?: return |
| 67 | when (first.type) { |
| 68 | Protocol.MsgType.AUTH_HELLO -> handleControl(socket, io, first, peer) |
| 69 | Protocol.MsgType.CHANNEL_ATTACH -> handleVideo(socket, first, peer) |
| 70 | else -> { |
| 71 | Log.w("$peer: 인증 전 메시지 0x%02x".format(first.type)) |
| 72 | io.sendError(Protocol.ErrorCode.UNAUTHENTICATED, "AUTH_HELLO가 먼저 와야 합니다") |
| 73 | } |
| 74 | } |
| 75 | } catch (e: SocketException) { |
| 76 | Log.i("$peer: 연결 종료 (${e.message})") |
| 77 | } catch (e: IOException) { |
| 78 | Log.w("$peer: $e") |
| 79 | } catch (e: Exception) { |
| 80 | Log.w("$peer: 처리 중 오류 $e") |
| 81 | } finally { |
| 82 | runCatching { socket.close() } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | private fun handleControl(socket: SSLSocket, io: FrameIO, helloFrame: Frame, peer: String) { |
| 87 | val hello = Messages.decodeAuthHello(helloFrame.payload) |
| 88 | val keyHex = Hex.encode(hello.publicKey) |
| 89 | val known = whitelist.contains(hello.publicKey) |
| 90 | Log.i("$peer: AUTH_HELLO host=${hello.hostname} key=${keyHex.take(16)}… 허용목록=${known}") |
| 91 | |
| 92 | val nonce = ByteArray(32).also { random.nextBytes(it) } |
| 93 | val status = if (known) Protocol.AuthStatus.APPROVED else Protocol.AuthStatus.PENDING_USER |
| 94 | io.send(Protocol.MsgType.AUTH_CHALLENGE, Messages.encodeAuthChallenge(status, nonce)) |
| 95 | |
| 96 | val resp = readExpect(io, Protocol.MsgType.AUTH_RESPONSE) ?: return |
| 97 | val signature = Messages.decodeAuthResponse(resp.payload) |
| 98 | if (!Ed25519.verify(hello.publicKey, nonce + identity.fingerprint, signature)) { |
| 99 | Log.w("$peer: 서명 검증 실패") |
| 100 | io.send(Protocol.MsgType.AUTH_RESULT, Messages.encodeAuthResult( |
| 101 | Protocol.AuthResultCode.SIGNATURE_INVALID, Protocol.Grant.NONE, ByteArray(32), daemonVersion)) |
| 102 | return |
| 103 | } |
| 104 | |
| 105 | val grant = if (known) { |
| 106 | Protocol.Grant.ALWAYS |
| 107 | } else { |
| 108 | Log.i("$peer: 새 PC 승인 요청 host=${hello.hostname} 확인 코드=${identity.confirmCode} 정책=$policy") |
| 109 | when (policy) { |
| 110 | ApprovePolicy.ALWAYS -> { |
| 111 | whitelist.add(hello.publicKey, hello.hostname) |
| 112 | Protocol.Grant.ALWAYS |
| 113 | } |
| 114 | ApprovePolicy.ONCE -> Protocol.Grant.ONCE |
| 115 | ApprovePolicy.REJECT -> { |
| 116 | io.send(Protocol.MsgType.AUTH_RESULT, Messages.encodeAuthResult( |
| 117 | Protocol.AuthResultCode.REJECTED, Protocol.Grant.NONE, ByteArray(32), daemonVersion)) |
| 118 | return |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | val token = ByteArray(32).also { random.nextBytes(it) } |
| 124 | val session = Session(token) |
| 125 | session.track(socket) |
| 126 | sessions[Hex.encode(token)] = session |
| 127 | try { |
| 128 | io.send(Protocol.MsgType.AUTH_RESULT, Messages.encodeAuthResult( |
| 129 | Protocol.AuthResultCode.OK, grant, token, daemonVersion)) |
| 130 | Log.i("$peer: 인증 완료 grant=${if (grant == Protocol.Grant.ALWAYS) "ALWAYS" else "ONCE"}") |
| 131 | serveControl(io, peer) |
| 132 | } finally { |
| 133 | sessions.remove(Hex.encode(token)) |
| 134 | session.closeAll() |
| 135 | Log.i("$peer: 세션 종료") |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | /** 인증 중에는 PING만 응답하고 기다리던 메시지를 돌려준다. */ |
| 140 | private fun readExpect(io: FrameIO, type: Int): Frame? { |
| 141 | while (true) { |
| 142 | val f = io.read() ?: return null |
| 143 | when { |
| 144 | f.type == type -> return f |
| 145 | f.type == Protocol.MsgType.PING -> io.sendWithSeq(Protocol.MsgType.PONG, f.seq) |
| 146 | !Protocol.MsgType.allowedBeforeAuth(f.type) -> { |
| 147 | io.sendError(Protocol.ErrorCode.UNAUTHENTICATED, "인증 전입니다") |
| 148 | return null |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | private var configGen = 0 |
| 155 | |
| 156 | private fun serveControl(io: FrameIO, peer: String) { |
| 157 | while (true) { |
| 158 | val f = io.read() ?: return |
| 159 | try { |
| 160 | when (f.type) { |
| 161 | Protocol.MsgType.PING -> io.sendWithSeq(Protocol.MsgType.PONG, f.seq) |
| 162 | Protocol.MsgType.PONG -> Unit |
| 163 | Protocol.MsgType.SYSTEM_ACTION -> handleSystemAction(Messages.decodeSystemAction(f.payload), peer) |
| 164 | Protocol.MsgType.VIDEO_CONFIG_REQUEST -> { |
| 165 | val req = Messages.decodeVideoConfigRequest(f.payload) |
| 166 | val cfg = videoConfigFor(req) |
| 167 | if (cfg == null) { |
| 168 | io.sendError(Protocol.ErrorCode.INTERNAL, "지원하는 코덱이 없습니다") |
| 169 | } else { |
| 170 | io.send(Protocol.MsgType.VIDEO_CONFIG, Messages.encodeVideoConfig(cfg)) |
| 171 | Log.i("$peer: VIDEO_CONFIG ${cfg.width}x${cfg.height} ${cfg.fps}fps codec=${cfg.codec}") |
| 172 | } |
| 173 | } |
| 174 | else -> Log.i("$peer: 아직 처리하지 않는 메시지 0x%02x".format(f.type)) |
| 175 | } |
| 176 | } catch (e: ProtocolException) { |
| 177 | Log.w("$peer: 잘못된 페이로드 $e") |
| 178 | io.sendError(Protocol.ErrorCode.BAD_FRAME, e.message ?: "") |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | private fun handleSystemAction(code: Int, peer: String) { |
| 184 | val keycode = when (code) { |
| 185 | Protocol.SystemAction.BACK -> KeyEvent.KEYCODE_BACK |
| 186 | Protocol.SystemAction.HOME -> KeyEvent.KEYCODE_HOME |
| 187 | Protocol.SystemAction.RECENTS -> KeyEvent.KEYCODE_APP_SWITCH |
| 188 | Protocol.SystemAction.COPY -> KeyEvent.KEYCODE_COPY |
| 189 | Protocol.SystemAction.PASTE -> KeyEvent.KEYCODE_PASTE |
| 190 | Protocol.SystemAction.CUT -> KeyEvent.KEYCODE_CUT |
| 191 | else -> { |
| 192 | Log.w("$peer: 처리하지 않는 SYSTEM_ACTION 0x%02x".format(code)) |
| 193 | return |
| 194 | } |
| 195 | } |
| 196 | SystemAccess.pressKey(keycode) |
| 197 | Log.i("$peer: SYSTEM_ACTION 0x%02x -> keycode $keycode".format(code)) |
| 198 | } |
| 199 | |
| 200 | /** 1단계: 인코더 없이 기기 화면 크기로 영상 설정만 계산한다. 인코딩은 2단계에서 붙인다. */ |
| 201 | @Synchronized |
| 202 | private fun videoConfigFor(req: Messages.VideoConfigRequest): Messages.VideoConfig? { |
| 203 | val codec = when { |
| 204 | req.codecMask and Protocol.Codec.H264 != 0 -> Protocol.Codec.H264 |
| 205 | req.codecMask and Protocol.Codec.H265 != 0 -> Protocol.Codec.H265 |
| 206 | else -> return null |
| 207 | } |
| 208 | val (dw, dh) = SystemAccess.displaySize() ?: (1080 to 2400) |
| 209 | val long = maxOf(dw, dh) |
| 210 | val scale = if (req.maxSize == 0 || req.maxSize >= long) 1.0 else req.maxSize.toDouble() / long |
| 211 | val w = ((dw * scale).toInt()) and 1.inv() |
| 212 | val h = ((dh * scale).toInt()) and 1.inv() |
| 213 | configGen = (configGen % 255) + 1 |
| 214 | val fps = if (req.maxFps == 0) 60 else minOf(req.maxFps, 120) |
| 215 | return Messages.VideoConfig(codec, configGen, w, h, fps, req.bitrate, dw, dh) |
| 216 | } |
| 217 | |
| 218 | private fun handleVideo(socket: SSLSocket, first: Frame, peer: String) { |
| 219 | val attach = Messages.decodeChannelAttach(first.payload) |
| 220 | val session = sessions.values.firstOrNull { |
| 221 | MessageDigest.isEqual(it.token, attach.token) |
| 222 | } |
| 223 | if (attach.kind != 0x01 || session == null || !session.videoAttached.compareAndSet(false, true)) { |
| 224 | Log.w("$peer: CHANNEL_ATTACH 거부 (토큰 없음, 재사용 또는 종류 오류)") |
| 225 | return |
| 226 | } |
| 227 | session.track(socket) |
| 228 | Log.i("$peer: 영상 채널 연결 (인코더는 2단계에서 구현)") |
| 229 | // 호스트는 영상 채널로 아무것도 보내지 않는다. 연결이 닫힐 때까지 기다린다. |
| 230 | val buf = ByteArray(256) |
| 231 | while (socket.inputStream.read(buf) >= 0) Unit |
| 232 | } |
| 233 | } |