leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | //! 제어 메시지 페이로드 인코더/디코더 (기획서 7절). |
| 2 | //! |
| 3 | //! 모든 필드는 Big-Endian이다. 예약(reserved) 바이트는 0으로 쓰고 디코딩 시 무시한다. |
| 4 | //! 고정 길이 페이로드는 길이가 정확히 일치해야 하며, 코드 값 필드는 모르는 값을 거부한다. |
| 5 | |
| 6 | use bytes::{Buf, BufMut, BytesMut}; |
| 7 | |
| 8 | use super::{Frame, MsgType, ProtocolError}; |
| 9 | |
| 10 | /// 비디오 패킷 헤더 길이 (바이트). |
| 11 | pub const VIDEO_HEADER_LEN: usize = 16; |
| 12 | /// 비디오 패킷 `data_len` 상한 (8 MiB). 이보다 크면 OOM 방지를 위해 거부한다. |
| 13 | pub const MAX_VIDEO_DATA_LEN: u32 = 8 * 1024 * 1024; |
| 14 | |
| 15 | /// AUTH_HELLO 호스트명 최대 길이 (바이트). |
| 16 | pub const MAX_HOSTNAME_LEN: usize = 255; |
| 17 | |
| 18 | /// ERROR 메시지 `code` 값. |
| 19 | pub mod error_code { |
| 20 | pub const PAYLOAD_TOO_LARGE: u16 = 0x0001; |
| 21 | pub const BAD_FRAME: u16 = 0x0002; |
| 22 | pub const UNAUTHENTICATED: u16 = 0x0003; |
| 23 | pub const PERMISSION_DENIED: u16 = 0x0004; |
| 24 | pub const INTERNAL: u16 = 0x0005; |
| 25 | } |
| 26 | |
| 27 | fn invalid(msg_type: MsgType, reason: &'static str) -> ProtocolError { |
| 28 | ProtocolError::InvalidPayload { msg_type, reason } |
| 29 | } |
| 30 | |
| 31 | fn expect_len(msg_type: MsgType, payload: &[u8], len: usize) -> Result<(), ProtocolError> { |
| 32 | if payload.len() == len { |
| 33 | Ok(()) |
| 34 | } else { |
| 35 | Err(invalid(msg_type, "페이로드 길이 불일치")) |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | fn utf8(msg_type: MsgType, bytes: &[u8]) -> Result<String, ProtocolError> { |
| 40 | std::str::from_utf8(bytes) |
| 41 | .map(str::to_owned) |
| 42 | .map_err(|_| invalid(msg_type, "UTF-8이 아닌 텍스트")) |
| 43 | } |
| 44 | |
| 45 | fn get_array<const N: usize>(b: &mut &[u8]) -> [u8; N] { |
| 46 | let mut out = [0u8; N]; |
| 47 | b.copy_to_slice(&mut out); |
| 48 | out |
| 49 | } |
| 50 | |
| 51 | /// 빈 페이로드 메시지(PING, PONG, ACK, VIDEO_REQUEST_KEYFRAME)의 페이로드를 검사한다. |
| 52 | pub fn check_empty(msg_type: MsgType, payload: &[u8]) -> Result<(), ProtocolError> { |
| 53 | expect_len(msg_type, payload, 0) |
| 54 | } |
| 55 | |
| 56 | /// AUTH_RESPONSE 서명 대상 메시지: nonce(32B) || 기기 TLS 인증서 SHA-256(32B) (기획서 7.3). |
| 57 | pub fn auth_signing_message(nonce: &[u8; 32], device_cert_sha256: &[u8; 32]) -> [u8; 64] { |
| 58 | let mut out = [0u8; 64]; |
| 59 | out[..32].copy_from_slice(nonce); |
| 60 | out[32..].copy_from_slice(device_cert_sha256); |
| 61 | out |
| 62 | } |
| 63 | |
| 64 | // --------------------------------------------------------------------------- |
| 65 | // 코드 값 enum |
| 66 | // --------------------------------------------------------------------------- |
| 67 | |
| 68 | /// AUTH_CHALLENGE `status` (기획서 7.3). |
| 69 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 70 | #[repr(u8)] |
| 71 | pub enum AuthStatus { |
| 72 | /// 이미 화이트리스트에 있음. |
| 73 | Approved = 0x00, |
| 74 | /// 폰에서 사용자 승인 필요. |
| 75 | PendingUser = 0x01, |
| 76 | Rejected = 0x02, |
| 77 | } |
| 78 | |
| 79 | impl TryFrom<u8> for AuthStatus { |
| 80 | type Error = u8; |
| 81 | |
| 82 | fn try_from(value: u8) -> Result<Self, u8> { |
| 83 | Ok(match value { |
| 84 | 0x00 => Self::Approved, |
| 85 | 0x01 => Self::PendingUser, |
| 86 | 0x02 => Self::Rejected, |
| 87 | other => return Err(other), |
| 88 | }) |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | /// AUTH_RESULT `result` (기획서 7.3). |
| 93 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 94 | #[repr(u8)] |
| 95 | pub enum AuthResultCode { |
| 96 | Ok = 0x00, |
| 97 | Rejected = 0x01, |
| 98 | Timeout = 0x02, |
| 99 | SignatureInvalid = 0x03, |
| 100 | Revoked = 0x04, |
| 101 | } |
| 102 | |
| 103 | impl TryFrom<u8> for AuthResultCode { |
| 104 | type Error = u8; |
| 105 | |
| 106 | fn try_from(value: u8) -> Result<Self, u8> { |
| 107 | Ok(match value { |
| 108 | 0x00 => Self::Ok, |
| 109 | 0x01 => Self::Rejected, |
| 110 | 0x02 => Self::Timeout, |
| 111 | 0x03 => Self::SignatureInvalid, |
| 112 | 0x04 => Self::Revoked, |
| 113 | other => return Err(other), |
| 114 | }) |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | /// AUTH_RESULT `grant` (기획서 7.3). `result`가 OK가 아니면 반드시 `None`. |
| 119 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 120 | #[repr(u8)] |
| 121 | pub enum AuthGrant { |
| 122 | None = 0x00, |
| 123 | /// 화이트리스트에 등록됨. |
| 124 | Always = 0x01, |
| 125 | /// 이번 세션만 허용. |
| 126 | Once = 0x02, |
| 127 | } |
| 128 | |
| 129 | impl TryFrom<u8> for AuthGrant { |
| 130 | type Error = u8; |
| 131 | |
| 132 | fn try_from(value: u8) -> Result<Self, u8> { |
| 133 | Ok(match value { |
| 134 | 0x00 => Self::None, |
| 135 | 0x01 => Self::Always, |
| 136 | 0x02 => Self::Once, |
| 137 | other => return Err(other), |
| 138 | }) |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | /// CHANNEL_ATTACH `channel_kind`. |
| 143 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 144 | #[repr(u8)] |
| 145 | pub enum ChannelKind { |
| 146 | Video = 0x01, |
| 147 | /// 예약됨 (아직 미구현). |
| 148 | Audio = 0x02, |
| 149 | } |
| 150 | |
| 151 | impl TryFrom<u8> for ChannelKind { |
| 152 | type Error = u8; |
| 153 | |
| 154 | fn try_from(value: u8) -> Result<Self, u8> { |
| 155 | Ok(match value { |
| 156 | 0x01 => Self::Video, |
| 157 | 0x02 => Self::Audio, |
| 158 | other => return Err(other), |
| 159 | }) |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | /// KEY_EVENT `action`. |
| 164 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 165 | #[repr(u8)] |
| 166 | pub enum KeyAction { |
| 167 | Down = 0x00, |
| 168 | Up = 0x01, |
| 169 | /// DOWN과 UP을 한 번에 보낸다. |
| 170 | Click = 0x02, |
| 171 | } |
| 172 | |
| 173 | impl TryFrom<u8> for KeyAction { |
| 174 | type Error = u8; |
| 175 | |
| 176 | fn try_from(value: u8) -> Result<Self, u8> { |
| 177 | Ok(match value { |
| 178 | 0x00 => Self::Down, |
| 179 | 0x01 => Self::Up, |
| 180 | 0x02 => Self::Click, |
| 181 | other => return Err(other), |
| 182 | }) |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | /// CLIPBOARD_SYNC `origin`. |
| 187 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 188 | #[repr(u8)] |
| 189 | pub enum ClipboardOrigin { |
| 190 | HostUbuntu = 0x01, |
| 191 | AndroidDevice = 0x02, |
| 192 | } |
| 193 | |
| 194 | impl TryFrom<u8> for ClipboardOrigin { |
| 195 | type Error = u8; |
| 196 | |
| 197 | fn try_from(value: u8) -> Result<Self, u8> { |
| 198 | Ok(match value { |
| 199 | 0x01 => Self::HostUbuntu, |
| 200 | 0x02 => Self::AndroidDevice, |
| 201 | other => return Err(other), |
| 202 | }) |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | /// CLIPBOARD_SYNC `mime_type`. 현재는 UTF-8 text/plain만 지원한다. |
| 207 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 208 | #[repr(u8)] |
| 209 | pub enum ClipboardMime { |
| 210 | TextPlainUtf8 = 0x01, |
| 211 | } |
| 212 | |
| 213 | impl TryFrom<u8> for ClipboardMime { |
| 214 | type Error = u8; |
| 215 | |
| 216 | fn try_from(value: u8) -> Result<Self, u8> { |
| 217 | match value { |
| 218 | 0x01 => Ok(Self::TextPlainUtf8), |
| 219 | other => Err(other), |
| 220 | } |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | /// TOUCH_EVENT `action`. |
| 225 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 226 | #[repr(u8)] |
| 227 | pub enum TouchAction { |
| 228 | Down = 0x00, |
| 229 | Up = 0x01, |
| 230 | Move = 0x02, |
| 231 | Cancel = 0x03, |
| 232 | } |
| 233 | |
| 234 | impl TryFrom<u8> for TouchAction { |
| 235 | type Error = u8; |
| 236 | |
| 237 | fn try_from(value: u8) -> Result<Self, u8> { |
| 238 | Ok(match value { |
| 239 | 0x00 => Self::Down, |
| 240 | 0x01 => Self::Up, |
| 241 | 0x02 => Self::Move, |
| 242 | 0x03 => Self::Cancel, |
| 243 | other => return Err(other), |
| 244 | }) |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | /// VIDEO_CONFIG `codec`. 값은 [`CodecMask`] 비트와 같다. |
| 249 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 250 | #[repr(u8)] |
| 251 | pub enum VideoCodec { |
| 252 | H264 = 0x01, |
| 253 | H265 = 0x02, |
| 254 | Av1 = 0x04, |
| 255 | } |
| 256 | |
| 257 | impl TryFrom<u8> for VideoCodec { |
| 258 | type Error = u8; |
| 259 | |
| 260 | fn try_from(value: u8) -> Result<Self, u8> { |
| 261 | Ok(match value { |
| 262 | 0x01 => Self::H264, |
| 263 | 0x02 => Self::H265, |
| 264 | 0x04 => Self::Av1, |
| 265 | other => return Err(other), |
| 266 | }) |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | macro_rules! impl_into_u8 { |
| 271 | ($($t:ty),*) => { |
| 272 | $(impl From<$t> for u8 { |
| 273 | fn from(value: $t) -> Self { |
| 274 | value as u8 |
| 275 | } |
| 276 | })* |
| 277 | }; |
| 278 | } |
| 279 | |
| 280 | impl_into_u8!( |
| 281 | AuthStatus, |
| 282 | AuthResultCode, |
| 283 | AuthGrant, |
| 284 | ChannelKind, |
| 285 | KeyAction, |
| 286 | SystemAction, |
| 287 | ClipboardOrigin, |
| 288 | ClipboardMime, |
| 289 | TouchAction, |
| 290 | VideoCodec |
| 291 | ); |
| 292 | |
| 293 | /// VIDEO_CONFIG_REQUEST `codec_mask`. 호스트가 디코딩할 수 있는 코덱 비트 집합. |
| 294 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] |
| 295 | pub struct CodecMask(u8); |
| 296 | |
| 297 | impl CodecMask { |
| 298 | pub const H264: Self = Self(0x01); |
| 299 | pub const H265: Self = Self(0x02); |
| 300 | pub const AV1: Self = Self(0x04); |
| 301 | pub const ALL: Self = Self(0x07); |
| 302 | pub const EMPTY: Self = Self(0x00); |
| 303 | |
| 304 | /// 정의되지 않은 비트가 있으면 `None`. |
| 305 | pub fn from_bits(bits: u8) -> Option<Self> { |
| 306 | (bits & !Self::ALL.0 == 0).then_some(Self(bits)) |
| 307 | } |
| 308 | |
| 309 | pub fn bits(self) -> u8 { |
| 310 | self.0 |
| 311 | } |
| 312 | |
| 313 | pub fn contains(self, other: Self) -> bool { |
| 314 | self.0 & other.0 == other.0 |
| 315 | } |
| 316 | |
| 317 | pub fn contains_codec(self, codec: VideoCodec) -> bool { |
| 318 | self.0 & codec as u8 != 0 |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | impl std::ops::BitOr for CodecMask { |
| 323 | type Output = Self; |
| 324 | |
| 325 | fn bitor(self, rhs: Self) -> Self { |
| 326 | Self(self.0 | rhs.0) |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | impl From<VideoCodec> for CodecMask { |
| 331 | fn from(codec: VideoCodec) -> Self { |
| 332 | Self(codec as u8) |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | // --------------------------------------------------------------------------- |
| 337 | // 인증 (기획서 7.3) |
| 338 | // --------------------------------------------------------------------------- |
| 339 | |
| 340 | /// AUTH_HELLO (0x03, Host→Device): Ed25519 공개키 + 호스트명. |
| 341 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 342 | pub struct AuthHello { |
| 343 | pub public_key: [u8; 32], |
| 344 | /// UTF-8, 1..=255 바이트. |
| 345 | pub hostname: String, |
| 346 | } |
| 347 | |
| 348 | impl AuthHello { |
| 349 | pub fn encode(&self, dst: &mut BytesMut) { |
| 350 | debug_assert!((1..=MAX_HOSTNAME_LEN).contains(&self.hostname.len())); |
| 351 | dst.reserve(32 + self.hostname.len()); |
| 352 | dst.put_slice(&self.public_key); |
| 353 | dst.put_slice(self.hostname.as_bytes()); |
| 354 | } |
| 355 | |
| 356 | pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> { |
| 357 | const T: MsgType = MsgType::AuthHello; |
| 358 | if payload.len() < 32 + 1 { |
| 359 | return Err(invalid(T, "호스트명이 비어 있거나 페이로드가 너무 짧음")); |
| 360 | } |
| 361 | if payload.len() > 32 + MAX_HOSTNAME_LEN { |
| 362 | return Err(invalid(T, "호스트명이 255바이트를 넘음")); |
| 363 | } |
| 364 | let mut b = payload; |
| 365 | let public_key = get_array(&mut b); |
| 366 | let hostname = utf8(T, b)?; |
| 367 | Ok(Self { |
| 368 | public_key, |
| 369 | hostname, |
| 370 | }) |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | /// AUTH_CHALLENGE (0x04, Device→Host), 36B. |
| 375 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 376 | pub struct AuthChallenge { |
| 377 | pub status: AuthStatus, |
| 378 | pub nonce: [u8; 32], |
| 379 | } |
| 380 | |
| 381 | impl AuthChallenge { |
| 382 | pub const LEN: usize = 36; |
| 383 | |
| 384 | pub fn encode(&self, dst: &mut BytesMut) { |
| 385 | dst.reserve(Self::LEN); |
| 386 | dst.put_u8(self.status.into()); |
| 387 | dst.put_bytes(0, 3); |
| 388 | dst.put_slice(&self.nonce); |
| 389 | } |
| 390 | |
| 391 | pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> { |
| 392 | const T: MsgType = MsgType::AuthChallenge; |
| 393 | expect_len(T, payload, Self::LEN)?; |
| 394 | let mut b = payload; |
| 395 | let status = |
| 396 | AuthStatus::try_from(b.get_u8()).map_err(|_| invalid(T, "알 수 없는 status"))?; |
| 397 | b.advance(3); |
| 398 | Ok(Self { |
| 399 | status, |
| 400 | nonce: get_array(&mut b), |
| 401 | }) |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | /// AUTH_RESPONSE (0x05, Host→Device), 64B: [`auth_signing_message`]에 대한 Ed25519 서명. |
| 406 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 407 | pub struct AuthResponse { |
| 408 | pub signature: [u8; 64], |
| 409 | } |
| 410 | |
| 411 | impl AuthResponse { |
| 412 | pub const LEN: usize = 64; |
| 413 | |
| 414 | pub fn encode(&self, dst: &mut BytesMut) { |
| 415 | dst.put_slice(&self.signature); |
| 416 | } |
| 417 | |
| 418 | pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> { |
| 419 | expect_len(MsgType::AuthResponse, payload, Self::LEN)?; |
| 420 | let mut b = payload; |
| 421 | Ok(Self { |
| 422 | signature: get_array(&mut b), |
| 423 | }) |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | /// AUTH_RESULT (0x06, Device→Host), 40B. |
| 428 | /// |
| 429 | /// `result`가 OK가 아니면 `grant`는 `None`, `session_token`은 모두 0이어야 한다. |
| 430 | /// OK이면 `grant`는 `Always` 또는 `Once`여야 한다. |
| 431 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 432 | pub struct AuthResult { |
| 433 | pub result: AuthResultCode, |
| 434 | pub grant: AuthGrant, |
| 435 | pub session_token: [u8; 32], |
| 436 | pub daemon_version: u32, |
| 437 | } |
| 438 | |
| 439 | impl AuthResult { |
| 440 | pub const LEN: usize = 40; |
| 441 | |
| 442 | pub fn encode(&self, dst: &mut BytesMut) { |
| 443 | dst.reserve(Self::LEN); |
| 444 | dst.put_u8(self.result.into()); |
| 445 | dst.put_u8(self.grant.into()); |
| 446 | dst.put_bytes(0, 2); |
| 447 | dst.put_slice(&self.session_token); |
| 448 | dst.put_u32(self.daemon_version); |
| 449 | } |
| 450 | |
| 451 | pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> { |
| 452 | const T: MsgType = MsgType::AuthResult; |
| 453 | expect_len(T, payload, Self::LEN)?; |
| 454 | let mut b = payload; |
| 455 | let result = |
| 456 | AuthResultCode::try_from(b.get_u8()).map_err(|_| invalid(T, "알 수 없는 result"))?; |
| 457 | let grant = AuthGrant::try_from(b.get_u8()).map_err(|_| invalid(T, "알 수 없는 grant"))?; |
| 458 | b.advance(2); |
| 459 | let session_token: [u8; 32] = get_array(&mut b); |
| 460 | let daemon_version = b.get_u32(); |
| 461 | |
| 462 | if result == AuthResultCode::Ok { |
| 463 | if grant == AuthGrant::None { |
| 464 | return Err(invalid(T, "result OK인데 grant가 NONE")); |
| 465 | } |
| 466 | } else { |
| 467 | if grant != AuthGrant::None { |
| 468 | return Err(invalid(T, "result가 OK가 아닌데 grant가 NONE이 아님")); |
| 469 | } |
| 470 | if session_token != [0; 32] { |
| 471 | return Err(invalid(T, "result가 OK가 아닌데 session_token이 0이 아님")); |
| 472 | } |
| 473 | } |
| 474 | Ok(Self { |
| 475 | result, |
| 476 | grant, |
| 477 | session_token, |
| 478 | daemon_version, |
| 479 | }) |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | /// CHANNEL_ATTACH (0x07, Host→Device), 36B: 보조 채널(비디오 등)을 세션에 붙인다. |
| 484 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 485 | pub struct ChannelAttach { |
| 486 | pub kind: ChannelKind, |
| 487 | pub session_token: [u8; 32], |
| 488 | } |
| 489 | |
| 490 | impl ChannelAttach { |
| 491 | pub const LEN: usize = 36; |
| 492 | |
| 493 | pub fn encode(&self, dst: &mut BytesMut) { |
| 494 | dst.reserve(Self::LEN); |
| 495 | dst.put_u8(self.kind.into()); |
| 496 | dst.put_bytes(0, 3); |
| 497 | dst.put_slice(&self.session_token); |
| 498 | } |
| 499 | |
| 500 | pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> { |
| 501 | const T: MsgType = MsgType::ChannelAttach; |
| 502 | expect_len(T, payload, Self::LEN)?; |
| 503 | let mut b = payload; |
| 504 | let kind = |
| 505 | ChannelKind::try_from(b.get_u8()).map_err(|_| invalid(T, "알 수 없는 channel_kind"))?; |
| 506 | b.advance(3); |
| 507 | Ok(Self { |
| 508 | kind, |
| 509 | session_token: get_array(&mut b), |
| 510 | }) |
| 511 | } |
| 512 | } |
| 513 | |
| 514 | // --------------------------------------------------------------------------- |
| 515 | // 입력 |
| 516 | // --------------------------------------------------------------------------- |
| 517 | |
| 518 | /// KEY_EVENT (0x10), 12B. 값은 Android `KeyEvent` 기준이다. |
| 519 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 520 | pub struct KeyEvent { |
| 521 | pub action: KeyAction, |
| 522 | /// Android `KEYCODE_*`. |
| 523 | pub keycode: u16, |
| 524 | /// Android `META_*` 비트마스크. |
| 525 | pub meta_state: u32, |
| 526 | pub repeat: u16, |
| 527 | pub scancode: u16, |
| 528 | } |
| 529 | |
| 530 | impl KeyEvent { |
| 531 | pub const LEN: usize = 12; |
| 532 | |
| 533 | pub fn encode(&self, dst: &mut BytesMut) { |
| 534 | dst.reserve(Self::LEN); |
| 535 | dst.put_u8(self.action.into()); |
| 536 | dst.put_u8(0); |
| 537 | dst.put_u16(self.keycode); |
| 538 | dst.put_u32(self.meta_state); |
| 539 | dst.put_u16(self.repeat); |
| 540 | dst.put_u16(self.scancode); |
| 541 | } |
| 542 | |
| 543 | pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> { |
| 544 | const T: MsgType = MsgType::KeyEvent; |
| 545 | expect_len(T, payload, Self::LEN)?; |
| 546 | let mut b = payload; |
| 547 | let action = |
| 548 | KeyAction::try_from(b.get_u8()).map_err(|_| invalid(T, "알 수 없는 action"))?; |
| 549 | b.advance(1); |
| 550 | Ok(Self { |
| 551 | action, |
| 552 | keycode: b.get_u16(), |
| 553 | meta_state: b.get_u32(), |
| 554 | repeat: b.get_u16(), |
| 555 | scancode: b.get_u16(), |
| 556 | }) |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | /// TEXT_INPUT (0x11): 페이로드 전체가 비어 있지 않은 UTF-8 텍스트. |
| 561 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 562 | pub struct TextInput { |
| 563 | pub text: String, |
| 564 | } |
| 565 | |
| 566 | impl TextInput { |
| 567 | pub fn encode(&self, dst: &mut BytesMut) { |
| 568 | debug_assert!(!self.text.is_empty()); |
| 569 | dst.put_slice(self.text.as_bytes()); |
| 570 | } |
| 571 | |
| 572 | pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> { |
| 573 | const T: MsgType = MsgType::TextInput; |
| 574 | if payload.is_empty() { |
| 575 | return Err(invalid(T, "빈 텍스트")); |
| 576 | } |
| 577 | Ok(Self { |
| 578 | text: utf8(T, payload)?, |
| 579 | }) |
| 580 | } |
| 581 | } |
| 582 | |
| 583 | /// SYSTEM_ACTION (0x12), 4B: `action_code` 1바이트 + 예약 3바이트. |
| 584 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 585 | #[repr(u8)] |
| 586 | pub enum SystemAction { |
| 587 | Copy = 0x01, |
| 588 | Paste = 0x02, |
| 589 | Cut = 0x03, |
| 590 | SelectAll = 0x04, |
| 591 | Home = 0x10, |
| 592 | Back = 0x11, |
| 593 | Recents = 0x12, |
| 594 | /// 기기 화면 방향을 세로 ↔ 가로로 바꾼다 (자동 회전 대신 고정). |
| 595 | Rotate = 0x20, |
| 596 | /// 미러링은 유지한 채 기기의 실제 화면만 끈다. |
| 597 | ScreenOff = 0x21, |
| 598 | /// 기기 화면을 다시 켠다. |
| 599 | ScreenOn = 0x22, |
| 600 | } |
| 601 | |
| 602 | impl TryFrom<u8> for SystemAction { |
| 603 | type Error = u8; |
| 604 | |
| 605 | fn try_from(value: u8) -> Result<Self, u8> { |
| 606 | Ok(match value { |
| 607 | 0x01 => Self::Copy, |
| 608 | 0x02 => Self::Paste, |
| 609 | 0x03 => Self::Cut, |
| 610 | 0x04 => Self::SelectAll, |
| 611 | 0x10 => Self::Home, |
| 612 | 0x11 => Self::Back, |
| 613 | 0x12 => Self::Recents, |
| 614 | 0x20 => Self::Rotate, |
| 615 | 0x21 => Self::ScreenOff, |
| 616 | 0x22 => Self::ScreenOn, |
| 617 | other => return Err(other), |
| 618 | }) |
| 619 | } |
| 620 | } |
| 621 | |
| 622 | impl SystemAction { |
| 623 | pub const LEN: usize = 4; |
| 624 | |
| 625 | pub fn encode(&self, dst: &mut BytesMut) { |
| 626 | dst.reserve(Self::LEN); |
| 627 | dst.put_u8((*self).into()); |
| 628 | dst.put_bytes(0, 3); |
| 629 | } |
| 630 | |
| 631 | pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> { |
| 632 | const T: MsgType = MsgType::SystemAction; |
| 633 | expect_len(T, payload, Self::LEN)?; |
| 634 | Self::try_from(payload[0]).map_err(|_| invalid(T, "알 수 없는 action_code")) |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | // --------------------------------------------------------------------------- |
| 639 | // 클립보드 |
| 640 | // --------------------------------------------------------------------------- |
| 641 | |
| 642 | /// CLIPBOARD_SYNC (0x20), 40B + N. |
| 643 | /// |
| 644 | /// `sha256`은 받은 값을 그대로 보관하며 여기서 검증하지 않는다. |
| 645 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 646 | pub struct ClipboardSync { |
| 647 | pub origin: ClipboardOrigin, |
| 648 | pub auto_paste: bool, |
| 649 | pub mime: ClipboardMime, |
| 650 | pub sha256: [u8; 32], |
| 651 | pub text: String, |
| 652 | } |
| 653 | |
| 654 | impl ClipboardSync { |
| 655 | /// 텍스트 앞 고정 부분 길이. |
| 656 | pub const FIXED_LEN: usize = 40; |
| 657 | |
| 658 | pub fn encode(&self, dst: &mut BytesMut) { |
| 659 | let text_len = u32::try_from(self.text.len()).expect("clipboard text exceeds u32"); |
| 660 | dst.reserve(Self::FIXED_LEN + self.text.len()); |
| 661 | dst.put_u8(self.origin.into()); |
| 662 | dst.put_u8(self.auto_paste.into()); |
| 663 | dst.put_u8(self.mime.into()); |
| 664 | dst.put_u8(0); |
| 665 | dst.put_slice(&self.sha256); |
| 666 | dst.put_u32(text_len); |
| 667 | dst.put_slice(self.text.as_bytes()); |
| 668 | } |
| 669 | |
| 670 | pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> { |
| 671 | const T: MsgType = MsgType::ClipboardSync; |
| 672 | if payload.len() < Self::FIXED_LEN { |
| 673 | return Err(invalid(T, "페이로드 길이 불일치")); |
| 674 | } |
| 675 | let mut b = payload; |
| 676 | let origin = |
| 677 | ClipboardOrigin::try_from(b.get_u8()).map_err(|_| invalid(T, "알 수 없는 origin"))?; |
| 678 | let auto_paste = match b.get_u8() { |
| 679 | 0x00 => false, |
| 680 | 0x01 => true, |
| 681 | _ => return Err(invalid(T, "auto_paste가 0 또는 1이 아님")), |
| 682 | }; |
| 683 | let mime = |
| 684 | ClipboardMime::try_from(b.get_u8()).map_err(|_| invalid(T, "알 수 없는 mime_type"))?; |
| 685 | b.advance(1); |
| 686 | let sha256 = get_array(&mut b); |
| 687 | let text_len = b.get_u32(); |
| 688 | if text_len as usize != b.len() { |
| 689 | return Err(invalid(T, "text_len이 남은 페이로드 길이와 다름")); |
| 690 | } |
| 691 | Ok(Self { |
| 692 | origin, |
| 693 | auto_paste, |
| 694 | mime, |
| 695 | sha256, |
| 696 | text: utf8(T, b)?, |
| 697 | }) |
| 698 | } |
| 699 | } |
| 700 | |
| 701 | // --------------------------------------------------------------------------- |
| 702 | // 포인터 |
| 703 | // --------------------------------------------------------------------------- |
| 704 | |
| 705 | /// TOUCH_EVENT (0x30), 20B. 좌표는 `frame_width`×`frame_height` 기준 화면 좌표다. |
| 706 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 707 | pub struct TouchEvent { |
| 708 | pub action: TouchAction, |
| 709 | pub pointer_id: u8, |
| 710 | pub x: u32, |
| 711 | pub y: u32, |
| 712 | pub frame_width: u16, |
| 713 | pub frame_height: u16, |
| 714 | pub pressure: u16, |
| 715 | } |
| 716 | |
| 717 | impl TouchEvent { |
| 718 | pub const LEN: usize = 20; |
| 719 | |
| 720 | pub fn encode(&self, dst: &mut BytesMut) { |
| 721 | dst.reserve(Self::LEN); |
| 722 | dst.put_u8(self.action.into()); |
| 723 | dst.put_u8(self.pointer_id); |
| 724 | dst.put_bytes(0, 2); |
| 725 | dst.put_u32(self.x); |
| 726 | dst.put_u32(self.y); |
| 727 | dst.put_u16(self.frame_width); |
| 728 | dst.put_u16(self.frame_height); |
| 729 | dst.put_u16(self.pressure); |
| 730 | dst.put_bytes(0, 2); |
| 731 | } |
| 732 | |
| 733 | pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> { |
| 734 | const T: MsgType = MsgType::TouchEvent; |
| 735 | expect_len(T, payload, Self::LEN)?; |
| 736 | let mut b = payload; |
| 737 | let action = |
| 738 | TouchAction::try_from(b.get_u8()).map_err(|_| invalid(T, "알 수 없는 action"))?; |
| 739 | let pointer_id = b.get_u8(); |
| 740 | b.advance(2); |
| 741 | Ok(Self { |
| 742 | action, |
| 743 | pointer_id, |
| 744 | x: b.get_u32(), |
| 745 | y: b.get_u32(), |
| 746 | frame_width: b.get_u16(), |
| 747 | frame_height: b.get_u16(), |
| 748 | pressure: b.get_u16(), |
| 749 | }) |
| 750 | } |
| 751 | } |
| 752 | |
| 753 | /// SCROLL_EVENT (0x31), 16B. 스크롤 양은 1/120 노치 단위, 위·오른쪽이 양수. |
| 754 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 755 | pub struct ScrollEvent { |
| 756 | pub x: u32, |
| 757 | pub y: u32, |
| 758 | pub frame_width: u16, |
| 759 | pub frame_height: u16, |
| 760 | pub h_scroll: i16, |
| 761 | pub v_scroll: i16, |
| 762 | } |
| 763 | |
| 764 | impl ScrollEvent { |
| 765 | pub const LEN: usize = 16; |
| 766 | |
| 767 | pub fn encode(&self, dst: &mut BytesMut) { |
| 768 | dst.reserve(Self::LEN); |
| 769 | dst.put_u32(self.x); |
| 770 | dst.put_u32(self.y); |
| 771 | dst.put_u16(self.frame_width); |
| 772 | dst.put_u16(self.frame_height); |
| 773 | dst.put_i16(self.h_scroll); |
| 774 | dst.put_i16(self.v_scroll); |
| 775 | } |
| 776 | |
| 777 | pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> { |
| 778 | expect_len(MsgType::ScrollEvent, payload, Self::LEN)?; |
| 779 | let mut b = payload; |
| 780 | Ok(Self { |
| 781 | x: b.get_u32(), |
| 782 | y: b.get_u32(), |
| 783 | frame_width: b.get_u16(), |
| 784 | frame_height: b.get_u16(), |
| 785 | h_scroll: b.get_i16(), |
| 786 | v_scroll: b.get_i16(), |
| 787 | }) |
| 788 | } |
| 789 | } |
| 790 | |
| 791 | // --------------------------------------------------------------------------- |
| 792 | // 비디오 설정 |
| 793 | // --------------------------------------------------------------------------- |
| 794 | |
| 795 | /// VIDEO_CONFIG_REQUEST (0x40), 8B: 호스트가 원하는 인코딩 조건. |
| 796 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 797 | pub struct VideoConfigRequest { |
| 798 | /// 긴 변 최대 픽셀. 0이면 기기 원본 해상도. |
| 799 | pub max_size: u16, |
| 800 | /// 0이면 기기 기본값. |
| 801 | pub max_fps: u8, |
| 802 | pub codecs: CodecMask, |
| 803 | /// bps. |
| 804 | pub bitrate: u32, |
| 805 | } |
| 806 | |
| 807 | impl VideoConfigRequest { |
| 808 | pub const LEN: usize = 8; |
| 809 | |
| 810 | pub fn encode(&self, dst: &mut BytesMut) { |
| 811 | dst.reserve(Self::LEN); |
| 812 | dst.put_u16(self.max_size); |
| 813 | dst.put_u8(self.max_fps); |
| 814 | dst.put_u8(self.codecs.bits()); |
| 815 | dst.put_u32(self.bitrate); |
| 816 | } |
| 817 | |
| 818 | pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> { |
| 819 | const T: MsgType = MsgType::VideoConfigRequest; |
| 820 | expect_len(T, payload, Self::LEN)?; |
| 821 | let mut b = payload; |
| 822 | let max_size = b.get_u16(); |
| 823 | let max_fps = b.get_u8(); |
| 824 | let codecs = CodecMask::from_bits(b.get_u8()) |
| 825 | .ok_or_else(|| invalid(T, "codec_mask에 정의되지 않은 비트"))?; |
| 826 | Ok(Self { |
| 827 | max_size, |
| 828 | max_fps, |
| 829 | codecs, |
| 830 | bitrate: b.get_u32(), |
| 831 | }) |
| 832 | } |
| 833 | } |
| 834 | |
| 835 | /// VIDEO_CONFIG (0x41), 16B: 기기가 실제로 선택한 인코딩 설정. |
| 836 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 837 | pub struct VideoConfig { |
| 838 | pub codec: VideoCodec, |
| 839 | /// 설정 세대. 비디오 패킷의 `config_gen`과 짝을 맞춘다. |
| 840 | pub config_gen: u8, |
| 841 | pub width: u16, |
| 842 | pub height: u16, |
| 843 | pub fps: u8, |
| 844 | pub bitrate: u32, |
| 845 | pub display_width: u16, |
| 846 | pub display_height: u16, |
| 847 | } |
| 848 | |
| 849 | impl VideoConfig { |
| 850 | pub const LEN: usize = 16; |
| 851 | |
| 852 | pub fn encode(&self, dst: &mut BytesMut) { |
| 853 | dst.reserve(Self::LEN); |
| 854 | dst.put_u8(self.codec.into()); |
| 855 | dst.put_u8(self.config_gen); |
| 856 | dst.put_u16(self.width); |
| 857 | dst.put_u16(self.height); |
| 858 | dst.put_u8(self.fps); |
| 859 | dst.put_u8(0); |
| 860 | dst.put_u32(self.bitrate); |
| 861 | dst.put_u16(self.display_width); |
| 862 | dst.put_u16(self.display_height); |
| 863 | } |
| 864 | |
| 865 | pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> { |
| 866 | const T: MsgType = MsgType::VideoConfig; |
| 867 | expect_len(T, payload, Self::LEN)?; |
| 868 | let mut b = payload; |
| 869 | let codec = VideoCodec::try_from(b.get_u8()).map_err(|_| invalid(T, "알 수 없는 codec"))?; |
| 870 | let config_gen = b.get_u8(); |
| 871 | let width = b.get_u16(); |
| 872 | let height = b.get_u16(); |
| 873 | let fps = b.get_u8(); |
| 874 | b.advance(1); |
| 875 | Ok(Self { |
| 876 | codec, |
| 877 | config_gen, |
| 878 | width, |
| 879 | height, |
| 880 | fps, |
| 881 | bitrate: b.get_u32(), |
| 882 | display_width: b.get_u16(), |
| 883 | display_height: b.get_u16(), |
| 884 | }) |
| 885 | } |
| 886 | } |
| 887 | |
| 888 | // --------------------------------------------------------------------------- |
| 889 | // 오류 |
| 890 | // --------------------------------------------------------------------------- |
| 891 | |
| 892 | /// ERROR (0xFF): `code` u16 + UTF-8 사유(비어 있을 수 있음). 코드 값은 [`error_code`]. |
| 893 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 894 | pub struct ErrorMessage { |
| 895 | pub code: u16, |
| 896 | pub reason: String, |
| 897 | } |
| 898 | |
| 899 | impl ErrorMessage { |
| 900 | pub fn encode(&self, dst: &mut BytesMut) { |
| 901 | dst.reserve(2 + self.reason.len()); |
| 902 | dst.put_u16(self.code); |
| 903 | dst.put_slice(self.reason.as_bytes()); |
| 904 | } |
| 905 | |
| 906 | pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> { |
| 907 | const T: MsgType = MsgType::Error; |
| 908 | if payload.len() < 2 { |
| 909 | return Err(invalid(T, "페이로드 길이 불일치")); |
| 910 | } |
| 911 | let mut b = payload; |
| 912 | let code = b.get_u16(); |
| 913 | Ok(Self { |
| 914 | code, |
| 915 | reason: utf8(T, b)?, |
| 916 | }) |
| 917 | } |
| 918 | } |
| 919 | |
| 920 | // --------------------------------------------------------------------------- |
| 921 | // 비디오 채널 패킷 헤더 (제어 프레임 아님) |
| 922 | // --------------------------------------------------------------------------- |
| 923 | |
| 924 | /// 비디오 TCP 연결에서 각 패킷 앞에 붙는 16바이트 헤더. 뒤에 `data_len` 바이트가 따른다. |
| 925 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 926 | pub struct VideoPacketHeader { |
| 927 | pub pts_us: u64, |
| 928 | /// 코덱 설정 데이터(SPS/PPS 등) 패킷. |
| 929 | pub is_config: bool, |
| 930 | pub is_keyframe: bool, |
| 931 | pub config_gen: u8, |
| 932 | /// 최대 [`MAX_VIDEO_DATA_LEN`]. |
| 933 | pub data_len: u32, |
| 934 | } |
| 935 | |
| 936 | impl VideoPacketHeader { |
| 937 | pub const FLAG_CONFIG: u8 = 0x01; |
| 938 | pub const FLAG_KEYFRAME: u8 = 0x02; |
| 939 | |
| 940 | pub fn encode(&self, dst: &mut BytesMut) { |
| 941 | debug_assert!(self.data_len <= MAX_VIDEO_DATA_LEN); |
| 942 | let mut flags = 0; |
| 943 | if self.is_config { |
| 944 | flags |= Self::FLAG_CONFIG; |
| 945 | } |
| 946 | if self.is_keyframe { |
| 947 | flags |= Self::FLAG_KEYFRAME; |
| 948 | } |
| 949 | dst.reserve(VIDEO_HEADER_LEN); |
| 950 | dst.put_u64(self.pts_us); |
| 951 | dst.put_u8(flags); |
| 952 | dst.put_u8(self.config_gen); |
| 953 | dst.put_bytes(0, 2); |
| 954 | dst.put_u32(self.data_len); |
| 955 | } |
| 956 | |
| 957 | /// 헤더 16바이트만 해석한다. 길이가 정확히 [`VIDEO_HEADER_LEN`]이어야 한다. |
| 958 | pub fn decode(header: &[u8]) -> Result<Self, ProtocolError> { |
| 959 | if header.len() != VIDEO_HEADER_LEN { |
| 960 | return Err(ProtocolError::InvalidVideoHeader("헤더 길이 불일치")); |
| 961 | } |
| 962 | let mut b = header; |
| 963 | let pts_us = b.get_u64(); |
| 964 | let flags = b.get_u8(); |
| 965 | if flags & !(Self::FLAG_CONFIG | Self::FLAG_KEYFRAME) != 0 { |
| 966 | return Err(ProtocolError::InvalidVideoHeader( |
| 967 | "정의되지 않은 flags 비트", |
| 968 | )); |
| 969 | } |
| 970 | let config_gen = b.get_u8(); |
| 971 | b.advance(2); |
| 972 | let data_len = b.get_u32(); |
| 973 | if data_len > MAX_VIDEO_DATA_LEN { |
| 974 | return Err(ProtocolError::VideoDataTooLarge(data_len)); |
| 975 | } |
| 976 | Ok(Self { |
| 977 | pts_us, |
| 978 | is_config: flags & Self::FLAG_CONFIG != 0, |
| 979 | is_keyframe: flags & Self::FLAG_KEYFRAME != 0, |
| 980 | config_gen, |
| 981 | data_len, |
| 982 | }) |
| 983 | } |
| 984 | } |
| 985 | |
| 986 | // --------------------------------------------------------------------------- |
| 987 | // 통합 메시지 |
| 988 | // --------------------------------------------------------------------------- |
| 989 | |
| 990 | /// 모든 제어 메시지. [`Frame`]과 상호 변환한다. |
| 991 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 992 | pub enum Message { |
| 993 | Ping, |
| 994 | Pong, |
| 995 | AuthHello(AuthHello), |
| 996 | AuthChallenge(AuthChallenge), |
| 997 | AuthResponse(AuthResponse), |
| 998 | AuthResult(AuthResult), |
| 999 | ChannelAttach(ChannelAttach), |
| 1000 | KeyEvent(KeyEvent), |
| 1001 | TextInput(TextInput), |
| 1002 | SystemAction(SystemAction), |
| 1003 | ClipboardSync(ClipboardSync), |
| 1004 | TouchEvent(TouchEvent), |
| 1005 | ScrollEvent(ScrollEvent), |
| 1006 | VideoConfigRequest(VideoConfigRequest), |
| 1007 | VideoConfig(VideoConfig), |
| 1008 | VideoRequestKeyframe, |
| 1009 | Ack, |
| 1010 | Error(ErrorMessage), |
| 1011 | } |
| 1012 | |
| 1013 | impl Message { |
| 1014 | pub fn msg_type(&self) -> MsgType { |
| 1015 | match self { |
| 1016 | Self::Ping => MsgType::Ping, |
| 1017 | Self::Pong => MsgType::Pong, |
| 1018 | Self::AuthHello(_) => MsgType::AuthHello, |
| 1019 | Self::AuthChallenge(_) => MsgType::AuthChallenge, |
| 1020 | Self::AuthResponse(_) => MsgType::AuthResponse, |
| 1021 | Self::AuthResult(_) => MsgType::AuthResult, |
| 1022 | Self::ChannelAttach(_) => MsgType::ChannelAttach, |
| 1023 | Self::KeyEvent(_) => MsgType::KeyEvent, |
| 1024 | Self::TextInput(_) => MsgType::TextInput, |
| 1025 | Self::SystemAction(_) => MsgType::SystemAction, |
| 1026 | Self::ClipboardSync(_) => MsgType::ClipboardSync, |
| 1027 | Self::TouchEvent(_) => MsgType::TouchEvent, |
| 1028 | Self::ScrollEvent(_) => MsgType::ScrollEvent, |
| 1029 | Self::VideoConfigRequest(_) => MsgType::VideoConfigRequest, |
| 1030 | Self::VideoConfig(_) => MsgType::VideoConfig, |
| 1031 | Self::VideoRequestKeyframe => MsgType::VideoRequestKeyframe, |
| 1032 | Self::Ack => MsgType::Ack, |
| 1033 | Self::Error(_) => MsgType::Error, |
| 1034 | } |
| 1035 | } |
| 1036 | |
| 1037 | /// 페이로드만 `dst` 뒤에 붙인다. |
| 1038 | pub fn encode_payload(&self, dst: &mut BytesMut) { |
| 1039 | match self { |
| 1040 | Self::Ping | Self::Pong | Self::VideoRequestKeyframe | Self::Ack => {} |
| 1041 | Self::AuthHello(m) => m.encode(dst), |
| 1042 | Self::AuthChallenge(m) => m.encode(dst), |
| 1043 | Self::AuthResponse(m) => m.encode(dst), |
| 1044 | Self::AuthResult(m) => m.encode(dst), |
| 1045 | Self::ChannelAttach(m) => m.encode(dst), |
| 1046 | Self::KeyEvent(m) => m.encode(dst), |
| 1047 | Self::TextInput(m) => m.encode(dst), |
| 1048 | Self::SystemAction(m) => m.encode(dst), |
| 1049 | Self::ClipboardSync(m) => m.encode(dst), |
| 1050 | Self::TouchEvent(m) => m.encode(dst), |
| 1051 | Self::ScrollEvent(m) => m.encode(dst), |
| 1052 | Self::VideoConfigRequest(m) => m.encode(dst), |
| 1053 | Self::VideoConfig(m) => m.encode(dst), |
| 1054 | Self::Error(m) => m.encode(dst), |
| 1055 | } |
| 1056 | } |
| 1057 | |
| 1058 | /// 헤더 `flags`가 0인 프레임을 만든다. |
| 1059 | pub fn to_frame(&self, seq_id: u16) -> Frame { |
| 1060 | let mut payload = BytesMut::new(); |
| 1061 | self.encode_payload(&mut payload); |
| 1062 | Frame::new(self.msg_type(), seq_id, payload.freeze()) |
| 1063 | } |
| 1064 | |
| 1065 | pub fn decode(frame: &Frame) -> Result<Self, ProtocolError> { |
| 1066 | let t = frame.header.msg_type; |
| 1067 | let p = &frame.payload[..]; |
| 1068 | Ok(match t { |
| 1069 | MsgType::Ping => check_empty(t, p).map(|()| Self::Ping)?, |
| 1070 | MsgType::Pong => check_empty(t, p).map(|()| Self::Pong)?, |
| 1071 | MsgType::AuthHello => Self::AuthHello(AuthHello::decode(p)?), |
| 1072 | MsgType::AuthChallenge => Self::AuthChallenge(AuthChallenge::decode(p)?), |
| 1073 | MsgType::AuthResponse => Self::AuthResponse(AuthResponse::decode(p)?), |
| 1074 | MsgType::AuthResult => Self::AuthResult(AuthResult::decode(p)?), |
| 1075 | MsgType::ChannelAttach => Self::ChannelAttach(ChannelAttach::decode(p)?), |
| 1076 | MsgType::KeyEvent => Self::KeyEvent(KeyEvent::decode(p)?), |
| 1077 | MsgType::TextInput => Self::TextInput(TextInput::decode(p)?), |
| 1078 | MsgType::SystemAction => Self::SystemAction(SystemAction::decode(p)?), |
| 1079 | MsgType::ClipboardSync => Self::ClipboardSync(ClipboardSync::decode(p)?), |
| 1080 | MsgType::TouchEvent => Self::TouchEvent(TouchEvent::decode(p)?), |
| 1081 | MsgType::ScrollEvent => Self::ScrollEvent(ScrollEvent::decode(p)?), |
| 1082 | MsgType::VideoConfigRequest => Self::VideoConfigRequest(VideoConfigRequest::decode(p)?), |
| 1083 | MsgType::VideoConfig => Self::VideoConfig(VideoConfig::decode(p)?), |
| 1084 | MsgType::VideoRequestKeyframe => { |
| 1085 | check_empty(t, p).map(|()| Self::VideoRequestKeyframe)? |
| 1086 | } |
| 1087 | MsgType::Ack => check_empty(t, p).map(|()| Self::Ack)?, |
| 1088 | MsgType::Error => Self::Error(ErrorMessage::decode(p)?), |
| 1089 | }) |
| 1090 | } |
| 1091 | } |
| 1092 | |
| 1093 | #[cfg(test)] |
| 1094 | mod tests { |
| 1095 | use super::*; |
| 1096 | |
| 1097 | fn enc(m: &Message) -> Vec<u8> { |
| 1098 | let mut buf = BytesMut::new(); |
| 1099 | m.encode_payload(&mut buf); |
| 1100 | buf.to_vec() |
| 1101 | } |
| 1102 | |
| 1103 | fn invalid_of(err: Result<impl std::fmt::Debug, ProtocolError>, t: MsgType) { |
| 1104 | match err { |
| 1105 | Err(ProtocolError::InvalidPayload { msg_type, .. }) => assert_eq!(msg_type, t), |
| 1106 | other => panic!("InvalidPayload 기대, 실제 {other:?}"), |
| 1107 | } |
| 1108 | } |
| 1109 | |
| 1110 | fn token(seed: u8) -> [u8; 32] { |
| 1111 | std::array::from_fn(|i| seed.wrapping_add(i as u8)) |
| 1112 | } |
| 1113 | |
| 1114 | fn sample_key_event() -> KeyEvent { |
| 1115 | KeyEvent { |
| 1116 | action: KeyAction::Click, |
| 1117 | keycode: 0x0042, |
| 1118 | meta_state: 0x0000_1001, |
| 1119 | repeat: 3, |
| 1120 | scancode: 0x001C, |
| 1121 | } |
| 1122 | } |
| 1123 | |
| 1124 | fn sample_clipboard() -> ClipboardSync { |
| 1125 | ClipboardSync { |
| 1126 | origin: ClipboardOrigin::HostUbuntu, |
| 1127 | auto_paste: true, |
| 1128 | mime: ClipboardMime::TextPlainUtf8, |
| 1129 | sha256: [0xAA; 32], |
| 1130 | text: "가a".into(), |
| 1131 | } |
| 1132 | } |
| 1133 | |
| 1134 | fn all_messages() -> Vec<Message> { |
| 1135 | vec![ |
| 1136 | Message::Ping, |
| 1137 | Message::Pong, |
| 1138 | Message::AuthHello(AuthHello { |
| 1139 | public_key: token(1), |
| 1140 | hostname: "ubuntu-데스크톱".into(), |
| 1141 | }), |
| 1142 | Message::AuthChallenge(AuthChallenge { |
| 1143 | status: AuthStatus::PendingUser, |
| 1144 | nonce: token(2), |
| 1145 | }), |
| 1146 | Message::AuthResponse(AuthResponse { |
| 1147 | signature: std::array::from_fn(|i| i as u8), |
| 1148 | }), |
| 1149 | Message::AuthResult(AuthResult { |
| 1150 | result: AuthResultCode::Ok, |
| 1151 | grant: AuthGrant::Once, |
| 1152 | session_token: token(3), |
| 1153 | daemon_version: 0x0001_0203, |
| 1154 | }), |
| 1155 | Message::AuthResult(AuthResult { |
| 1156 | result: AuthResultCode::Timeout, |
| 1157 | grant: AuthGrant::None, |
| 1158 | session_token: [0; 32], |
| 1159 | daemon_version: 7, |
| 1160 | }), |
| 1161 | Message::ChannelAttach(ChannelAttach { |
| 1162 | kind: ChannelKind::Video, |
| 1163 | session_token: token(4), |
| 1164 | }), |
| 1165 | Message::KeyEvent(sample_key_event()), |
| 1166 | Message::TextInput(TextInput { |
| 1167 | text: "한글 입력".into(), |
| 1168 | }), |
| 1169 | Message::SystemAction(SystemAction::Recents), |
| 1170 | Message::ClipboardSync(sample_clipboard()), |
| 1171 | Message::ClipboardSync(ClipboardSync { |
| 1172 | text: String::new(), |
| 1173 | auto_paste: false, |
| 1174 | origin: ClipboardOrigin::AndroidDevice, |
| 1175 | ..sample_clipboard() |
| 1176 | }), |
| 1177 | Message::TouchEvent(TouchEvent { |
| 1178 | action: TouchAction::Move, |
| 1179 | pointer_id: 2, |
| 1180 | x: 540, |
| 1181 | y: 1200, |
| 1182 | frame_width: 1080, |
| 1183 | frame_height: 2400, |
| 1184 | pressure: 0xFFFF, |
| 1185 | }), |
| 1186 | Message::ScrollEvent(ScrollEvent { |
| 1187 | x: 10, |
| 1188 | y: 20, |
| 1189 | frame_width: 1080, |
| 1190 | frame_height: 2400, |
| 1191 | h_scroll: -120, |
| 1192 | v_scroll: 240, |
| 1193 | }), |
| 1194 | Message::VideoConfigRequest(VideoConfigRequest { |
| 1195 | max_size: 1920, |
| 1196 | max_fps: 60, |
| 1197 | codecs: CodecMask::H264 | CodecMask::H265, |
| 1198 | bitrate: 8_000_000, |
| 1199 | }), |
| 1200 | Message::VideoConfig(VideoConfig { |
| 1201 | codec: VideoCodec::H265, |
| 1202 | config_gen: 5, |
| 1203 | width: 1080, |
| 1204 | height: 2400, |
| 1205 | fps: 60, |
| 1206 | bitrate: 8_000_000, |
| 1207 | display_width: 1080, |
| 1208 | display_height: 2400, |
| 1209 | }), |
| 1210 | Message::VideoRequestKeyframe, |
| 1211 | Message::Ack, |
| 1212 | Message::Error(ErrorMessage { |
| 1213 | code: error_code::UNAUTHENTICATED, |
| 1214 | reason: "인증 필요".into(), |
| 1215 | }), |
| 1216 | Message::Error(ErrorMessage { |
| 1217 | code: error_code::INTERNAL, |
| 1218 | reason: String::new(), |
| 1219 | }), |
| 1220 | ] |
| 1221 | } |
| 1222 | |
| 1223 | #[test] |
| 1224 | fn every_message_roundtrips_through_frame() { |
| 1225 | for (i, m) in all_messages().into_iter().enumerate() { |
| 1226 | let seq = i as u16 + 100; |
| 1227 | let frame = m.to_frame(seq); |
| 1228 | assert_eq!(frame.header.msg_type, m.msg_type()); |
| 1229 | assert_eq!(frame.header.seq_id, seq); |
| 1230 | assert_eq!(frame.header.flags, 0); |
| 1231 | assert_eq!(Message::decode(&frame).as_ref(), Ok(&m), "{m:?}"); |
| 1232 | } |
| 1233 | } |
| 1234 | |
| 1235 | #[test] |
| 1236 | fn roundtrip_through_wire_encoding() { |
| 1237 | use crate::protocol::{FrameDecoder, encode_frame}; |
| 1238 | let mut wire = BytesMut::new(); |
| 1239 | let msgs = all_messages(); |
| 1240 | for (i, m) in msgs.iter().enumerate() { |
| 1241 | encode_frame(&m.to_frame(i as u16), &mut wire); |
| 1242 | } |
| 1243 | let mut dec = FrameDecoder::new(); |
| 1244 | dec.extend(&wire); |
| 1245 | for m in &msgs { |
| 1246 | let frame = dec.decode().unwrap().unwrap(); |
| 1247 | assert_eq!(&Message::decode(&frame).unwrap(), m); |
| 1248 | } |
| 1249 | assert_eq!(dec.decode().unwrap(), None); |
| 1250 | } |
| 1251 | |
| 1252 | #[test] |
| 1253 | fn key_event_layout() { |
| 1254 | assert_eq!( |
| 1255 | enc(&Message::KeyEvent(sample_key_event())), |
| 1256 | [ |
| 1257 | 0x02, 0x00, 0x00, 0x42, 0x00, 0x00, 0x10, 0x01, 0x00, 0x03, 0x00, 0x1C |
| 1258 | ] |
| 1259 | ); |
| 1260 | } |
| 1261 | |
| 1262 | #[test] |
| 1263 | fn clipboard_sync_layout() { |
| 1264 | let bytes = enc(&Message::ClipboardSync(sample_clipboard())); |
| 1265 | let mut expected = vec![0x01, 0x01, 0x01, 0x00]; |
| 1266 | expected.extend([0xAA; 32]); |
| 1267 | expected.extend([0x00, 0x00, 0x00, 0x04]); |
| 1268 | expected.extend([0xEA, 0xB0, 0x80, b'a']); |
| 1269 | assert_eq!(bytes, expected); |
| 1270 | } |
| 1271 | |
| 1272 | #[test] |
| 1273 | fn touch_event_layout() { |
| 1274 | let m = Message::TouchEvent(TouchEvent { |
| 1275 | action: TouchAction::Down, |
| 1276 | pointer_id: 1, |
| 1277 | x: 0x0102_0304, |
| 1278 | y: 0x0506_0708, |
| 1279 | frame_width: 0x090A, |
| 1280 | frame_height: 0x0B0C, |
| 1281 | pressure: 0x0D0E, |
| 1282 | }); |
| 1283 | assert_eq!( |
| 1284 | enc(&m), |
| 1285 | [ |
| 1286 | 0x00, 0x01, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, |
| 1287 | 0x0B, 0x0C, 0x0D, 0x0E, 0x00, 0x00 |
| 1288 | ] |
| 1289 | ); |
| 1290 | } |
| 1291 | |
| 1292 | #[test] |
| 1293 | fn auth_result_layout() { |
| 1294 | let m = Message::AuthResult(AuthResult { |
| 1295 | result: AuthResultCode::Ok, |
| 1296 | grant: AuthGrant::Always, |
| 1297 | session_token: [0x5A; 32], |
| 1298 | daemon_version: 0x0001_0002, |
| 1299 | }); |
| 1300 | let mut expected = vec![0x00, 0x01, 0x00, 0x00]; |
| 1301 | expected.extend([0x5A; 32]); |
| 1302 | expected.extend([0x00, 0x01, 0x00, 0x02]); |
| 1303 | assert_eq!(enc(&m), expected); |
| 1304 | } |
| 1305 | |
| 1306 | #[test] |
| 1307 | fn video_config_layout() { |
| 1308 | let m = Message::VideoConfig(VideoConfig { |
| 1309 | codec: VideoCodec::Av1, |
| 1310 | config_gen: 9, |
| 1311 | width: 0x0438, |
| 1312 | height: 0x0960, |
| 1313 | fps: 60, |
| 1314 | bitrate: 0x007A_1200, |
| 1315 | display_width: 0x0438, |
| 1316 | display_height: 0x0960, |
| 1317 | }); |
| 1318 | assert_eq!( |
| 1319 | enc(&m), |
| 1320 | [ |
| 1321 | 0x04, 0x09, 0x04, 0x38, 0x09, 0x60, 60, 0x00, 0x00, 0x7A, 0x12, 0x00, 0x04, 0x38, |
| 1322 | 0x09, 0x60 |
| 1323 | ] |
| 1324 | ); |
| 1325 | } |
| 1326 | |
| 1327 | #[test] |
| 1328 | fn video_packet_header_layout_and_roundtrip() { |
| 1329 | let h = VideoPacketHeader { |
| 1330 | pts_us: 0x0102_0304_0506_0708, |
| 1331 | is_config: false, |
| 1332 | is_keyframe: true, |
| 1333 | config_gen: 3, |
| 1334 | data_len: 0x0001_0000, |
| 1335 | }; |
| 1336 | let mut buf = BytesMut::new(); |
| 1337 | h.encode(&mut buf); |
| 1338 | assert_eq!( |
| 1339 | &buf[..], |
| 1340 | [ |
| 1341 | 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x02, 0x03, 0x00, 0x00, 0x00, 0x01, |
| 1342 | 0x00, 0x00 |
| 1343 | ] |
| 1344 | ); |
| 1345 | assert_eq!(VideoPacketHeader::decode(&buf), Ok(h)); |
| 1346 | |
| 1347 | let cfg = VideoPacketHeader { |
| 1348 | is_config: true, |
| 1349 | is_keyframe: true, |
| 1350 | data_len: MAX_VIDEO_DATA_LEN, |
| 1351 | ..h |
| 1352 | }; |
| 1353 | let mut buf = BytesMut::new(); |
| 1354 | cfg.encode(&mut buf); |
| 1355 | assert_eq!(buf[8], 0x03); |
| 1356 | assert_eq!(VideoPacketHeader::decode(&buf), Ok(cfg)); |
| 1357 | } |
| 1358 | |
| 1359 | #[test] |
| 1360 | fn video_packet_header_rejects_bad_input() { |
| 1361 | let mut bytes = [0u8; VIDEO_HEADER_LEN]; |
| 1362 | bytes[12..16].copy_from_slice(&(MAX_VIDEO_DATA_LEN + 1).to_be_bytes()); |
| 1363 | assert_eq!( |
| 1364 | VideoPacketHeader::decode(&bytes), |
| 1365 | Err(ProtocolError::VideoDataTooLarge(MAX_VIDEO_DATA_LEN + 1)) |
| 1366 | ); |
| 1367 | |
| 1368 | let mut bytes = [0u8; VIDEO_HEADER_LEN]; |
| 1369 | bytes[8] = 0x04; |
| 1370 | assert!(matches!( |
| 1371 | VideoPacketHeader::decode(&bytes), |
| 1372 | Err(ProtocolError::InvalidVideoHeader(_)) |
| 1373 | )); |
| 1374 | assert!(matches!( |
| 1375 | VideoPacketHeader::decode(&[0u8; 15]), |
| 1376 | Err(ProtocolError::InvalidVideoHeader(_)) |
| 1377 | )); |
| 1378 | } |
| 1379 | |
| 1380 | #[test] |
| 1381 | fn reserved_bytes_are_ignored_on_decode() { |
| 1382 | let mut bytes = enc(&Message::KeyEvent(sample_key_event())); |
| 1383 | bytes[1] = 0xFF; |
| 1384 | assert_eq!(KeyEvent::decode(&bytes), Ok(sample_key_event())); |
| 1385 | |
| 1386 | let mut bytes = [0u8; VIDEO_HEADER_LEN]; |
| 1387 | bytes[10] = 0xFF; |
| 1388 | bytes[11] = 0xFF; |
| 1389 | assert!(VideoPacketHeader::decode(&bytes).is_ok()); |
| 1390 | } |
| 1391 | |
| 1392 | #[test] |
| 1393 | fn fixed_size_payloads_reject_wrong_length() { |
| 1394 | let cases: [(MsgType, usize); 11] = [ |
| 1395 | (MsgType::AuthChallenge, AuthChallenge::LEN), |
| 1396 | (MsgType::AuthResponse, AuthResponse::LEN), |
| 1397 | (MsgType::AuthResult, AuthResult::LEN), |
| 1398 | (MsgType::ChannelAttach, ChannelAttach::LEN), |
| 1399 | (MsgType::KeyEvent, KeyEvent::LEN), |
| 1400 | (MsgType::SystemAction, SystemAction::LEN), |
| 1401 | (MsgType::TouchEvent, TouchEvent::LEN), |
| 1402 | (MsgType::ScrollEvent, ScrollEvent::LEN), |
| 1403 | (MsgType::VideoConfigRequest, VideoConfigRequest::LEN), |
| 1404 | (MsgType::VideoConfig, VideoConfig::LEN), |
| 1405 | (MsgType::Ping, 0), |
| 1406 | ]; |
| 1407 | for (t, len) in cases { |
| 1408 | for bad in [len.wrapping_sub(1), len + 1] { |
| 1409 | if bad > 1024 { |
| 1410 | continue; |
| 1411 | } |
| 1412 | // 첫 바이트를 유효한 코드로 맞춰 길이 검사만 걸리게 한다. |
| 1413 | let mut payload = vec![0u8; bad]; |
| 1414 | if let Some(b) = payload.first_mut() { |
| 1415 | *b = 0x01; |
| 1416 | } |
| 1417 | let frame = Frame::new(t, 0, payload); |
| 1418 | invalid_of(Message::decode(&frame), t); |
| 1419 | } |
| 1420 | } |
| 1421 | for t in [MsgType::Pong, MsgType::Ack, MsgType::VideoRequestKeyframe] { |
| 1422 | invalid_of(Message::decode(&Frame::new(t, 0, vec![0])), t); |
| 1423 | } |
| 1424 | } |
| 1425 | |
| 1426 | #[test] |
| 1427 | fn variable_payloads_reject_bad_length() { |
| 1428 | // AUTH_HELLO: 호스트명 0바이트, 256바이트. |
| 1429 | invalid_of(AuthHello::decode(&[0u8; 32]), MsgType::AuthHello); |
| 1430 | invalid_of(AuthHello::decode(&[b'a'; 32 + 256]), MsgType::AuthHello); |
| 1431 | assert!(AuthHello::decode(&[b'a'; 32 + 255]).is_ok()); |
| 1432 | invalid_of(TextInput::decode(&[]), MsgType::TextInput); |
| 1433 | invalid_of(ErrorMessage::decode(&[0x00]), MsgType::Error); |
| 1434 | invalid_of(ClipboardSync::decode(&[0x01; 39]), MsgType::ClipboardSync); |
| 1435 | } |
| 1436 | |
| 1437 | #[test] |
| 1438 | fn unknown_codes_are_rejected() { |
| 1439 | let mut ch = [0u8; AuthChallenge::LEN]; |
| 1440 | ch[0] = 0x03; |
| 1441 | invalid_of(AuthChallenge::decode(&ch), MsgType::AuthChallenge); |
| 1442 | |
| 1443 | let mut ar = [0u8; AuthResult::LEN]; |
| 1444 | ar[0] = 0x05; |
| 1445 | invalid_of(AuthResult::decode(&ar), MsgType::AuthResult); |
| 1446 | ar[0] = 0x00; |
| 1447 | ar[1] = 0x03; |
| 1448 | invalid_of(AuthResult::decode(&ar), MsgType::AuthResult); |
| 1449 | |
| 1450 | let mut ca = [0u8; ChannelAttach::LEN]; |
| 1451 | invalid_of(ChannelAttach::decode(&ca), MsgType::ChannelAttach); |
| 1452 | ca[0] = 0x02; |
| 1453 | assert_eq!(ChannelAttach::decode(&ca).unwrap().kind, ChannelKind::Audio); |
| 1454 | |
| 1455 | let mut ke = [0u8; KeyEvent::LEN]; |
| 1456 | ke[0] = 0x03; |
| 1457 | invalid_of(KeyEvent::decode(&ke), MsgType::KeyEvent); |
| 1458 | |
| 1459 | invalid_of( |
| 1460 | SystemAction::decode(&[0x05, 0, 0, 0]), |
| 1461 | MsgType::SystemAction, |
| 1462 | ); |
| 1463 | invalid_of( |
| 1464 | SystemAction::decode(&[0x00, 0, 0, 0]), |
| 1465 | MsgType::SystemAction, |
| 1466 | ); |
| 1467 | |
| 1468 | let mut te = [0u8; TouchEvent::LEN]; |
| 1469 | te[0] = 0x04; |
| 1470 | invalid_of(TouchEvent::decode(&te), MsgType::TouchEvent); |
| 1471 | |
| 1472 | let mut vr = [0u8; VideoConfigRequest::LEN]; |
| 1473 | vr[3] = 0x08; |
| 1474 | invalid_of(VideoConfigRequest::decode(&vr), MsgType::VideoConfigRequest); |
| 1475 | |
| 1476 | let mut vc = [0u8; VideoConfig::LEN]; |
| 1477 | vc[0] = 0x03; // 비트 두 개 = 코덱 하나가 아님 |
| 1478 | invalid_of(VideoConfig::decode(&vc), MsgType::VideoConfig); |
| 1479 | |
| 1480 | let base = enc(&Message::ClipboardSync(sample_clipboard())); |
| 1481 | for (idx, bad) in [(0, 0x03), (1, 0x02), (2, 0x02)] { |
| 1482 | let mut cs = base.clone(); |
| 1483 | cs[idx] = bad; |
| 1484 | invalid_of(ClipboardSync::decode(&cs), MsgType::ClipboardSync); |
| 1485 | } |
| 1486 | } |
| 1487 | |
| 1488 | #[test] |
| 1489 | fn clipboard_rejects_len_mismatch_and_bad_utf8() { |
| 1490 | let base = enc(&Message::ClipboardSync(sample_clipboard())); |
| 1491 | |
| 1492 | let mut longer = base.clone(); |
| 1493 | longer.push(b'x'); |
| 1494 | invalid_of(ClipboardSync::decode(&longer), MsgType::ClipboardSync); |
| 1495 | |
| 1496 | let mut shorter = base.clone(); |
| 1497 | shorter.pop(); |
| 1498 | invalid_of(ClipboardSync::decode(&shorter), MsgType::ClipboardSync); |
| 1499 | |
| 1500 | let mut bad = base.clone(); |
| 1501 | bad[40] = 0xFF; |
| 1502 | invalid_of(ClipboardSync::decode(&bad), MsgType::ClipboardSync); |
| 1503 | } |
| 1504 | |
| 1505 | #[test] |
| 1506 | fn text_payloads_reject_bad_utf8() { |
| 1507 | let mut hello = vec![0u8; 32]; |
| 1508 | hello.extend([0xC3, 0x28]); |
| 1509 | invalid_of(AuthHello::decode(&hello), MsgType::AuthHello); |
| 1510 | invalid_of(TextInput::decode(&[0xFF]), MsgType::TextInput); |
| 1511 | invalid_of(ErrorMessage::decode(&[0, 1, 0xFF]), MsgType::Error); |
| 1512 | } |
| 1513 | |
| 1514 | #[test] |
| 1515 | fn auth_result_consistency() { |
| 1516 | let ok = AuthResult { |
| 1517 | result: AuthResultCode::Ok, |
| 1518 | grant: AuthGrant::Always, |
| 1519 | session_token: token(9), |
| 1520 | daemon_version: 1, |
| 1521 | }; |
| 1522 | let encode = |r: AuthResult| { |
| 1523 | let mut buf = BytesMut::new(); |
| 1524 | r.encode(&mut buf); |
| 1525 | buf |
| 1526 | }; |
| 1527 | |
| 1528 | // 실패인데 grant가 NONE이 아님. |
| 1529 | let rejected_with_grant = AuthResult { |
| 1530 | result: AuthResultCode::Rejected, |
| 1531 | session_token: [0; 32], |
| 1532 | ..ok |
| 1533 | }; |
| 1534 | invalid_of( |
| 1535 | AuthResult::decode(&encode(rejected_with_grant)), |
| 1536 | MsgType::AuthResult, |
| 1537 | ); |
| 1538 | |
| 1539 | // 실패인데 토큰이 0이 아님. |
| 1540 | let rejected_with_token = AuthResult { |
| 1541 | result: AuthResultCode::Revoked, |
| 1542 | grant: AuthGrant::None, |
| 1543 | ..ok |
| 1544 | }; |
| 1545 | invalid_of( |
| 1546 | AuthResult::decode(&encode(rejected_with_token)), |
| 1547 | MsgType::AuthResult, |
| 1548 | ); |
| 1549 | |
| 1550 | // 성공인데 grant가 NONE. |
| 1551 | let ok_without_grant = AuthResult { |
| 1552 | grant: AuthGrant::None, |
| 1553 | ..ok |
| 1554 | }; |
| 1555 | invalid_of( |
| 1556 | AuthResult::decode(&encode(ok_without_grant)), |
| 1557 | MsgType::AuthResult, |
| 1558 | ); |
| 1559 | |
| 1560 | assert_eq!(AuthResult::decode(&encode(ok)), Ok(ok)); |
| 1561 | } |
| 1562 | |
| 1563 | #[test] |
| 1564 | fn codec_mask_bits() { |
| 1565 | let m = CodecMask::H264 | CodecMask::AV1; |
| 1566 | assert_eq!(m.bits(), 0x05); |
| 1567 | assert!(m.contains(CodecMask::H264)); |
| 1568 | assert!(!m.contains(CodecMask::H265)); |
| 1569 | assert!(!m.contains(CodecMask::ALL)); |
| 1570 | assert!(m.contains_codec(VideoCodec::Av1)); |
| 1571 | assert_eq!(CodecMask::from_bits(0x07), Some(CodecMask::ALL)); |
| 1572 | assert_eq!(CodecMask::from_bits(0x10), None); |
| 1573 | } |
| 1574 | |
| 1575 | #[test] |
| 1576 | fn signing_message_is_nonce_then_cert_hash() { |
| 1577 | let msg = auth_signing_message(&[1; 32], &[2; 32]); |
| 1578 | assert_eq!(&msg[..32], &[1; 32]); |
| 1579 | assert_eq!(&msg[32..], &[2; 32]); |
| 1580 | } |
| 1581 | } |