leejunyoung5819wayland-android-remote

공개

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

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