leejunyoung5819wayland-android-remote

공개

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

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