leejunyoung5819wayland-android-remote

공개

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

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