leejunyoung5819wayland-android-remote

공개

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

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