leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | //! 기기 접속과 인증 (기획서 7.6 "세션 수립 순서"). |
| 2 | |
| 3 | use std::net::SocketAddr; |
| 4 | use std::sync::Arc; |
| 5 | use std::time::Duration; |
| 6 | |
| 7 | use bytes::Bytes; |
| 8 | use rustls::client::ClientSessionMemoryCache; |
| 9 | use rustls::pki_types::ServerName; |
| 10 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 11 | use tokio::net::TcpStream; |
| 12 | use tokio::time::timeout; |
| 13 | use tokio_rustls::TlsConnector; |
| 14 | use tokio_rustls::client::TlsStream; |
| 15 | |
| 16 | use super::framed::{FramedError, FramedStream}; |
| 17 | use super::identity::HostIdentity; |
| 18 | use super::tls::{PinnedVerifier, client_config}; |
| 19 | use crate::protocol::{ |
| 20 | AuthGrant, AuthHello, AuthResponse, AuthResultCode, AuthStatus, ChannelAttach, ChannelKind, |
| 21 | Message, VIDEO_HEADER_LEN, VideoPacketHeader, auth_signing_message, confirm_code, |
| 22 | }; |
| 23 | |
| 24 | /// 기기와 주고받는 TLS 스트림. |
| 25 | pub type DeviceStream = TlsStream<TcpStream>; |
| 26 | |
| 27 | #[derive(Debug, Clone, Copy)] |
| 28 | pub struct ConnectOptions { |
| 29 | /// TCP 접속과 TLS 핸드셰이크 제한 시간. |
| 30 | pub connect_timeout: Duration, |
| 31 | /// 승인 대기가 없는 인증 단계 하나의 제한 시간. |
| 32 | pub step_timeout: Duration, |
| 33 | /// 휴대폰 승인 대기 제한 시간. 기기는 60초에 TIMEOUT을 보내므로 그보다 조금 길게 둔다. |
| 34 | pub approval_timeout: Duration, |
| 35 | } |
| 36 | |
| 37 | impl Default for ConnectOptions { |
| 38 | fn default() -> Self { |
| 39 | Self { |
| 40 | connect_timeout: Duration::from_secs(5), |
| 41 | step_timeout: Duration::from_secs(10), |
| 42 | approval_timeout: Duration::from_secs(65), |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | /// 접속 진행 상황. UI가 대기 화면에 확인 코드를 보여줄 때 쓴다. |
| 48 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 49 | pub enum ConnectEvent { |
| 50 | /// TLS 연결 완료. `pinned`가 false면 처음 보는 기기다. |
| 51 | TlsEstablished { |
| 52 | fingerprint: [u8; 32], |
| 53 | confirm_code: String, |
| 54 | pinned: bool, |
| 55 | }, |
| 56 | /// 처음 접속하는 PC라 휴대폰 승인 팝업을 기다린다. |
| 57 | AwaitingApproval { confirm_code: String }, |
| 58 | } |
| 59 | |
| 60 | #[derive(Debug)] |
| 61 | pub enum ConnectError { |
| 62 | Io(std::io::Error), |
| 63 | Tls(std::io::Error), |
| 64 | Timeout(&'static str), |
| 65 | /// 저장된 지문과 다른 인증서를 받았다 (기획서 5.5 "지문 불일치"). |
| 66 | FingerprintMismatch { |
| 67 | expected: [u8; 32], |
| 68 | actual: [u8; 32], |
| 69 | }, |
| 70 | /// 기기가 AUTH_CHALLENGE 단계에서 거부했다. |
| 71 | ChallengeRejected, |
| 72 | /// AUTH_RESULT가 OK가 아니다. |
| 73 | AuthFailed(AuthResultCode), |
| 74 | Protocol(FramedError), |
| 75 | Unexpected(&'static str), |
| 76 | } |
| 77 | |
| 78 | impl std::fmt::Display for ConnectError { |
| 79 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 80 | match self { |
| 81 | Self::Io(e) => write!(f, "접속 실패: {e}"), |
| 82 | Self::Tls(e) => write!(f, "TLS 연결 실패: {e}"), |
| 83 | Self::Timeout(step) => write!(f, "{step} 시간 초과"), |
| 84 | Self::FingerprintMismatch { .. } => { |
| 85 | f.write_str("저장된 기기와 인증서가 다릅니다. 기기를 초기화했다면 기기 기록을 지운 뒤 다시 연결하세요") |
| 86 | } |
| 87 | Self::ChallengeRejected => f.write_str("기기가 연결을 거부했습니다"), |
| 88 | Self::AuthFailed(code) => match code { |
| 89 | AuthResultCode::Rejected => f.write_str("연결이 거부되었습니다"), |
| 90 | AuthResultCode::Timeout => f.write_str("승인 대기 시간이 지났습니다"), |
| 91 | AuthResultCode::SignatureInvalid => f.write_str("PC 서명 검증에 실패했습니다"), |
| 92 | AuthResultCode::Revoked => f.write_str("이 PC의 권한이 철회되었습니다"), |
| 93 | AuthResultCode::Ok => f.write_str("인증 실패"), |
| 94 | }, |
| 95 | Self::Protocol(e) => write!(f, "{e}"), |
| 96 | Self::Unexpected(what) => write!(f, "예상하지 못한 응답: {what}"), |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | impl std::error::Error for ConnectError {} |
| 102 | |
| 103 | impl From<FramedError> for ConnectError { |
| 104 | fn from(e: FramedError) -> Self { |
| 105 | Self::Protocol(e) |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | /// 인증이 끝난 기기 세션. |
| 110 | pub struct Session { |
| 111 | pub target: SocketAddr, |
| 112 | /// 기기 TLS 인증서 지문. |
| 113 | pub fingerprint: [u8; 32], |
| 114 | pub grant: AuthGrant, |
| 115 | pub daemon_version: u32, |
| 116 | session_token: [u8; 32], |
| 117 | sessions: Arc<ClientSessionMemoryCache>, |
| 118 | control: FramedStream<DeviceStream>, |
| 119 | } |
| 120 | |
| 121 | /// 기기에 접속해 TLS 1.3 핸드셰이크와 Ed25519 인증을 마친다. |
| 122 | /// |
| 123 | /// `pinned`는 이 IP에 저장된 기기 지문이다. 결과의 `grant`가 [`AuthGrant::Always`]이면 |
| 124 | /// 호출 측이 `fingerprint`를 [`super::KnownDevices`]에 저장한다. |
| 125 | pub async fn connect( |
| 126 | target: SocketAddr, |
| 127 | identity: &HostIdentity, |
| 128 | pinned: Option<[u8; 32]>, |
| 129 | options: ConnectOptions, |
| 130 | mut on_event: impl FnMut(ConnectEvent), |
| 131 | ) -> Result<Session, ConnectError> { |
| 132 | let sessions = Arc::new(ClientSessionMemoryCache::new(8)); |
| 133 | let verifier = PinnedVerifier::new(pinned); |
| 134 | let tls = timeout( |
| 135 | options.connect_timeout, |
| 136 | open_tls(target, verifier.clone(), sessions.clone()), |
| 137 | ) |
| 138 | .await |
| 139 | .map_err(|_| ConnectError::Timeout("연결"))?; |
| 140 | |
| 141 | let stream = match tls { |
| 142 | Ok(s) => s, |
| 143 | Err(e) => { |
| 144 | return Err(match (pinned, verifier.seen()) { |
| 145 | (Some(expected), Some(actual)) if expected != actual => { |
| 146 | ConnectError::FingerprintMismatch { expected, actual } |
| 147 | } |
| 148 | _ => e, |
| 149 | }); |
| 150 | } |
| 151 | }; |
| 152 | let fingerprint = verifier |
| 153 | .seen() |
| 154 | .ok_or(ConnectError::Unexpected("기기 인증서를 받지 못함"))?; |
| 155 | let code = confirm_code(&fingerprint); |
| 156 | on_event(ConnectEvent::TlsEstablished { |
| 157 | fingerprint, |
| 158 | confirm_code: code.clone(), |
| 159 | pinned: pinned.is_some(), |
| 160 | }); |
| 161 | |
| 162 | let mut control = FramedStream::new(stream); |
| 163 | control |
| 164 | .send(&Message::AuthHello(AuthHello { |
| 165 | public_key: identity.public_key(), |
| 166 | hostname: identity.hostname().to_owned(), |
| 167 | })) |
| 168 | .await?; |
| 169 | |
| 170 | let challenge = match read(&mut control, options.step_timeout, "인증 요청").await? { |
| 171 | Message::AuthChallenge(c) => c, |
| 172 | _ => return Err(ConnectError::Unexpected("AUTH_CHALLENGE 대신 다른 메시지")), |
| 173 | }; |
| 174 | let wait = match challenge.status { |
| 175 | AuthStatus::Approved => options.step_timeout, |
| 176 | AuthStatus::PendingUser => { |
| 177 | on_event(ConnectEvent::AwaitingApproval { confirm_code: code }); |
| 178 | options.approval_timeout |
| 179 | } |
| 180 | AuthStatus::Rejected => return Err(ConnectError::ChallengeRejected), |
| 181 | }; |
| 182 | |
| 183 | let signature = identity.sign(&auth_signing_message(&challenge.nonce, &fingerprint)); |
| 184 | control |
| 185 | .send(&Message::AuthResponse(AuthResponse { signature })) |
| 186 | .await?; |
| 187 | |
| 188 | let result = match read(&mut control, wait, "휴대폰 승인").await? { |
| 189 | Message::AuthResult(r) => r, |
| 190 | _ => return Err(ConnectError::Unexpected("AUTH_RESULT 대신 다른 메시지")), |
| 191 | }; |
| 192 | if result.result != AuthResultCode::Ok { |
| 193 | return Err(ConnectError::AuthFailed(result.result)); |
| 194 | } |
| 195 | |
| 196 | Ok(Session { |
| 197 | target, |
| 198 | fingerprint, |
| 199 | grant: result.grant, |
| 200 | daemon_version: result.daemon_version, |
| 201 | session_token: result.session_token, |
| 202 | sessions, |
| 203 | control, |
| 204 | }) |
| 205 | } |
| 206 | |
| 207 | impl Session { |
| 208 | /// 제어 채널. 입력·클립보드·영상 설정 메시지를 주고받는다. |
| 209 | pub fn control(&mut self) -> &mut FramedStream<DeviceStream> { |
| 210 | &mut self.control |
| 211 | } |
| 212 | |
| 213 | /// 같은 포트로 두 번째 연결을 열어 영상 채널로 묶는다 (기획서 7.6 "4단계"). |
| 214 | /// 세션 토큰은 한 번만 쓸 수 있으므로 세션당 한 번만 호출한다. |
| 215 | pub async fn open_video(&self, connect_timeout: Duration) -> Result<VideoStream, ConnectError> { |
| 216 | let verifier = PinnedVerifier::new(Some(self.fingerprint)); |
| 217 | let stream = timeout( |
| 218 | connect_timeout, |
| 219 | open_tls(self.target, verifier, self.sessions.clone()), |
| 220 | ) |
| 221 | .await |
| 222 | .map_err(|_| ConnectError::Timeout("영상 채널 연결"))??; |
| 223 | |
| 224 | let mut framed = FramedStream::new(stream); |
| 225 | framed |
| 226 | .send(&Message::ChannelAttach(ChannelAttach { |
| 227 | kind: ChannelKind::Video, |
| 228 | session_token: self.session_token, |
| 229 | })) |
| 230 | .await?; |
| 231 | Ok(VideoStream { |
| 232 | stream: framed.into_inner(), |
| 233 | }) |
| 234 | } |
| 235 | |
| 236 | pub fn into_control(self) -> FramedStream<DeviceStream> { |
| 237 | self.control |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | /// 영상 채널. 기기에서 호스트로 영상 패킷만 흐른다. |
| 242 | pub struct VideoStream { |
| 243 | stream: DeviceStream, |
| 244 | } |
| 245 | |
| 246 | impl VideoStream { |
| 247 | /// 영상 패킷 하나(16바이트 헤더 + 인코딩 데이터)를 읽는다. |
| 248 | pub async fn read_packet(&mut self) -> Result<(VideoPacketHeader, Bytes), FramedError> { |
| 249 | let mut header = [0u8; VIDEO_HEADER_LEN]; |
| 250 | read_exact_or_closed(&mut self.stream, &mut header).await?; |
| 251 | let header = VideoPacketHeader::decode(&header)?; |
| 252 | let mut data = vec![0u8; header.data_len as usize]; |
| 253 | read_exact_or_closed(&mut self.stream, &mut data).await?; |
| 254 | Ok((header, Bytes::from(data))) |
| 255 | } |
| 256 | |
| 257 | pub async fn shutdown(mut self) { |
| 258 | let _ = self.stream.shutdown().await; |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | async fn read_exact_or_closed( |
| 263 | stream: &mut DeviceStream, |
| 264 | buf: &mut [u8], |
| 265 | ) -> Result<(), FramedError> { |
| 266 | match stream.read_exact(buf).await { |
| 267 | Ok(_) => Ok(()), |
| 268 | Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Err(FramedError::Closed), |
| 269 | Err(e) => Err(FramedError::Io(e)), |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | async fn open_tls( |
| 274 | target: SocketAddr, |
| 275 | verifier: Arc<PinnedVerifier>, |
| 276 | sessions: Arc<ClientSessionMemoryCache>, |
| 277 | ) -> Result<DeviceStream, ConnectError> { |
| 278 | let config = client_config(verifier, sessions) |
| 279 | .map_err(|e| ConnectError::Tls(std::io::Error::other(e)))?; |
| 280 | let tcp = TcpStream::connect(target).await.map_err(ConnectError::Io)?; |
| 281 | tcp.set_nodelay(true).map_err(ConnectError::Io)?; |
| 282 | let name = ServerName::IpAddress(target.ip().into()); |
| 283 | TlsConnector::from(Arc::new(config)) |
| 284 | .connect(name, tcp) |
| 285 | .await |
| 286 | .map_err(ConnectError::Tls) |
| 287 | } |
| 288 | |
| 289 | async fn read( |
| 290 | control: &mut FramedStream<DeviceStream>, |
| 291 | limit: Duration, |
| 292 | step: &'static str, |
| 293 | ) -> Result<Message, ConnectError> { |
| 294 | loop { |
| 295 | let (_, msg) = timeout(limit, control.read_message()) |
| 296 | .await |
| 297 | .map_err(|_| ConnectError::Timeout(step))??; |
| 298 | match msg { |
| 299 | Message::Ping | Message::Pong => continue, |
| 300 | Message::Error(e) => { |
| 301 | log::warn!("기기 오류 응답: {:#06x} {}", e.code, e.reason); |
| 302 | return Err(ConnectError::Unexpected("인증 중 ERROR 응답")); |
| 303 | } |
| 304 | other => return Ok(other), |
| 305 | } |
| 306 | } |
| 307 | } |