leejunyoung5819wayland-android-remote

공개

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

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