leejunyoung5819wayland-android-remote

공개

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

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