leejunyoung5819wayland-android-remote

공개

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

1,847줄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}
757
758impl TouchEvent {
759 pub const LEN: usize = 20;
760
761 pub fn encode(&self, dst: &mut BytesMut) {
762 dst.reserve(Self::LEN);
763 dst.put_u8(self.action.into());
764 dst.put_u8(self.pointer_id);
765 dst.put_bytes(0, 2);
766 dst.put_u32(self.x);
767 dst.put_u32(self.y);
768 dst.put_u16(self.frame_width);
769 dst.put_u16(self.frame_height);
770 dst.put_u16(self.pressure);
771 dst.put_bytes(0, 2);
772 }
773
774 pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> {
775 const T: MsgType = MsgType::TouchEvent;
776 expect_len(T, payload, Self::LEN)?;
777 let mut b = payload;
778 let action =
779 TouchAction::try_from(b.get_u8()).map_err(|_| invalid(T, "알 수 없는 action"))?;
780 let pointer_id = b.get_u8();
781 b.advance(2);
782 Ok(Self {
783 action,
784 pointer_id,
785 x: b.get_u32(),
786 y: b.get_u32(),
787 frame_width: b.get_u16(),
788 frame_height: b.get_u16(),
789 pressure: b.get_u16(),
790 })
791 }
792}
793
794/// SCROLL_EVENT (0x31), 16B. 스크롤 양은 1/120 노치 단위, 위·오른쪽이 양수.
795#[derive(Debug, Clone, Copy, PartialEq, Eq)]
796pub struct ScrollEvent {
797 pub x: u32,
798 pub y: u32,
799 pub frame_width: u16,
800 pub frame_height: u16,
801 pub h_scroll: i16,
802 pub v_scroll: i16,
803}
804
805impl ScrollEvent {
806 pub const LEN: usize = 16;
807
808 pub fn encode(&self, dst: &mut BytesMut) {
809 dst.reserve(Self::LEN);
810 dst.put_u32(self.x);
811 dst.put_u32(self.y);
812 dst.put_u16(self.frame_width);
813 dst.put_u16(self.frame_height);
814 dst.put_i16(self.h_scroll);
815 dst.put_i16(self.v_scroll);
816 }
817
818 pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> {
819 expect_len(MsgType::ScrollEvent, payload, Self::LEN)?;
820 let mut b = payload;
821 Ok(Self {
822 x: b.get_u32(),
823 y: b.get_u32(),
824 frame_width: b.get_u16(),
825 frame_height: b.get_u16(),
826 h_scroll: b.get_i16(),
827 v_scroll: b.get_i16(),
828 })
829 }
830}
831
832// ---------------------------------------------------------------------------
833// 비디오 설정
834// ---------------------------------------------------------------------------
835
836/// VIDEO_CONFIG_REQUEST (0x40), 8B: 호스트가 원하는 인코딩 조건.
837#[derive(Debug, Clone, Copy, PartialEq, Eq)]
838pub struct VideoConfigRequest {
839 /// 긴 변 최대 픽셀. 0이면 기기 원본 해상도.
840 pub max_size: u16,
841 /// 0이면 기기 기본값.
842 pub max_fps: u8,
843 pub codecs: CodecMask,
844 /// bps.
845 pub bitrate: u32,
846}
847
848impl VideoConfigRequest {
849 pub const LEN: usize = 8;
850
851 pub fn encode(&self, dst: &mut BytesMut) {
852 dst.reserve(Self::LEN);
853 dst.put_u16(self.max_size);
854 dst.put_u8(self.max_fps);
855 dst.put_u8(self.codecs.bits());
856 dst.put_u32(self.bitrate);
857 }
858
859 pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> {
860 const T: MsgType = MsgType::VideoConfigRequest;
861 expect_len(T, payload, Self::LEN)?;
862 let mut b = payload;
863 let max_size = b.get_u16();
864 let max_fps = b.get_u8();
865 let codecs = CodecMask::from_bits(b.get_u8())
866 .ok_or_else(|| invalid(T, "codec_mask에 정의되지 않은 비트"))?;
867 Ok(Self {
868 max_size,
869 max_fps,
870 codecs,
871 bitrate: b.get_u32(),
872 })
873 }
874}
875
876/// VIDEO_CONFIG (0x41), 16B: 기기가 실제로 선택한 인코딩 설정.
877#[derive(Debug, Clone, Copy, PartialEq, Eq)]
878pub struct VideoConfig {
879 pub codec: VideoCodec,
880 /// 설정 세대. 비디오 패킷의 `config_gen`과 짝을 맞춘다.
881 pub config_gen: u8,
882 pub width: u16,
883 pub height: u16,
884 pub fps: u8,
885 pub bitrate: u32,
886 pub display_width: u16,
887 pub display_height: u16,
888}
889
890impl VideoConfig {
891 pub const LEN: usize = 16;
892
893 pub fn encode(&self, dst: &mut BytesMut) {
894 dst.reserve(Self::LEN);
895 dst.put_u8(self.codec.into());
896 dst.put_u8(self.config_gen);
897 dst.put_u16(self.width);
898 dst.put_u16(self.height);
899 dst.put_u8(self.fps);
900 dst.put_u8(0);
901 dst.put_u32(self.bitrate);
902 dst.put_u16(self.display_width);
903 dst.put_u16(self.display_height);
904 }
905
906 pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> {
907 const T: MsgType = MsgType::VideoConfig;
908 expect_len(T, payload, Self::LEN)?;
909 let mut b = payload;
910 let codec = VideoCodec::try_from(b.get_u8()).map_err(|_| invalid(T, "알 수 없는 codec"))?;
911 let config_gen = b.get_u8();
912 let width = b.get_u16();
913 let height = b.get_u16();
914 let fps = b.get_u8();
915 b.advance(1);
916 Ok(Self {
917 codec,
918 config_gen,
919 width,
920 height,
921 fps,
922 bitrate: b.get_u32(),
923 display_width: b.get_u16(),
924 display_height: b.get_u16(),
925 })
926 }
927}
928
929// ---------------------------------------------------------------------------
930// 오류
931// ---------------------------------------------------------------------------
932
933/// ERROR (0xFF): `code` u16 + UTF-8 사유(비어 있을 수 있음). 코드 값은 [`error_code`].
934#[derive(Debug, Clone, PartialEq, Eq)]
935pub struct ErrorMessage {
936 pub code: u16,
937 pub reason: String,
938}
939
940impl ErrorMessage {
941 pub fn encode(&self, dst: &mut BytesMut) {
942 dst.reserve(2 + self.reason.len());
943 dst.put_u16(self.code);
944 dst.put_slice(self.reason.as_bytes());
945 }
946
947 pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> {
948 const T: MsgType = MsgType::Error;
949 if payload.len() < 2 {
950 return Err(invalid(T, "페이로드 길이 불일치"));
951 }
952 let mut b = payload;
953 let code = b.get_u16();
954 Ok(Self {
955 code,
956 reason: utf8(T, b)?,
957 })
958 }
959}
960
961// ---------------------------------------------------------------------------
962// 파일 전송 (호스트 → 기기)
963// ---------------------------------------------------------------------------
964
965/// FILE_DATA 한 번에 담는 최대 바이트. 입력 메시지가 파일 데이터 뒤에서 오래 기다리지 않게 작게 둔다.
966pub const MAX_FILE_CHUNK: usize = 256 * 1024;
967/// 파일 이름 최대 길이 (UTF-8 바이트).
968pub const MAX_FILE_NAME_LEN: usize = 255;
969
970/// FILE_START (0x50), 12B + 이름. 새 파일 전송을 연다.
971#[derive(Debug, Clone, PartialEq, Eq)]
972pub struct FileStart {
973 pub transfer_id: u32,
974 pub size: u64,
975 /// 경로 없는 파일 이름 (1~255 바이트).
976 pub name: String,
977}
978
979impl FileStart {
980 pub fn encode(&self, dst: &mut BytesMut) {
981 dst.reserve(12 + self.name.len());
982 dst.put_u32(self.transfer_id);
983 dst.put_u64(self.size);
984 dst.put_slice(self.name.as_bytes());
985 }
986
987 pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> {
988 const T: MsgType = MsgType::FileStart;
989 if payload.len() < 13 || payload.len() > 12 + MAX_FILE_NAME_LEN {
990 return Err(invalid(T, "페이로드 길이 불일치"));
991 }
992 let mut b = payload;
993 let transfer_id = b.get_u32();
994 let size = b.get_u64();
995 Ok(Self {
996 transfer_id,
997 size,
998 name: utf8(T, b)?,
999 })
1000 }
1001}
1002
1003/// FILE_DATA (0x51), 4B + 1~[`MAX_FILE_CHUNK`]B. 앞에서부터 순서대로 보낸다.
1004#[derive(Debug, Clone, PartialEq, Eq)]
1005pub struct FileData {
1006 pub transfer_id: u32,
1007 pub data: Vec<u8>,
1008}
1009
1010impl FileData {
1011 pub fn encode(&self, dst: &mut BytesMut) {
1012 dst.reserve(4 + self.data.len());
1013 dst.put_u32(self.transfer_id);
1014 dst.put_slice(&self.data);
1015 }
1016
1017 pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> {
1018 if payload.len() < 5 || payload.len() > 4 + MAX_FILE_CHUNK {
1019 return Err(invalid(MsgType::FileData, "페이로드 길이 불일치"));
1020 }
1021 let mut b = payload;
1022 Ok(Self {
1023 transfer_id: b.get_u32(),
1024 data: b.to_vec(),
1025 })
1026 }
1027}
1028
1029/// FILE_END (0x52), 36B. 보낸 전체 내용의 SHA-256. 기기는 검증 뒤 FILE_RESULT로 답한다.
1030#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1031pub struct FileEnd {
1032 pub transfer_id: u32,
1033 pub sha256: [u8; 32],
1034}
1035
1036impl FileEnd {
1037 pub const LEN: usize = 36;
1038
1039 pub fn encode(&self, dst: &mut BytesMut) {
1040 dst.reserve(Self::LEN);
1041 dst.put_u32(self.transfer_id);
1042 dst.put_slice(&self.sha256);
1043 }
1044
1045 pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> {
1046 expect_len(MsgType::FileEnd, payload, Self::LEN)?;
1047 let mut b = payload;
1048 Ok(Self {
1049 transfer_id: b.get_u32(),
1050 sha256: get_array(&mut b),
1051 })
1052 }
1053}
1054
1055/// FILE_RESULT `status`.
1056#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1057#[repr(u8)]
1058pub enum FileStatus {
1059 /// 저장 완료. `message`는 기기에 저장된 경로.
1060 Ok = 0x00,
1061 /// 쓰기 실패 등. `message`가 사유.
1062 Failed = 0x01,
1063 /// 저장 공간 부족.
1064 NoSpace = 0x02,
1065 /// 받은 내용의 해시나 크기가 맞지 않음.
1066 Corrupt = 0x03,
1067}
1068
1069impl TryFrom<u8> for FileStatus {
1070 type Error = u8;
1071
1072 fn try_from(value: u8) -> Result<Self, u8> {
1073 Ok(match value {
1074 0x00 => Self::Ok,
1075 0x01 => Self::Failed,
1076 0x02 => Self::NoSpace,
1077 0x03 => Self::Corrupt,
1078 other => return Err(other),
1079 })
1080 }
1081}
1082
1083/// FILE_RESULT (0x53, 기기 → 호스트), 5B + 메시지. 실패하면 FILE_END 전에도 보낼 수 있고,
1084/// 호스트는 그 파일의 나머지를 보내지 않는다.
1085#[derive(Debug, Clone, PartialEq, Eq)]
1086pub struct FileResult {
1087 pub transfer_id: u32,
1088 pub status: FileStatus,
1089 pub message: String,
1090}
1091
1092impl FileResult {
1093 pub fn encode(&self, dst: &mut BytesMut) {
1094 dst.reserve(5 + self.message.len());
1095 dst.put_u32(self.transfer_id);
1096 dst.put_u8(self.status as u8);
1097 dst.put_slice(self.message.as_bytes());
1098 }
1099
1100 pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> {
1101 const T: MsgType = MsgType::FileResult;
1102 if payload.len() < 5 {
1103 return Err(invalid(T, "페이로드 길이 불일치"));
1104 }
1105 let mut b = payload;
1106 let transfer_id = b.get_u32();
1107 let status =
1108 FileStatus::try_from(b.get_u8()).map_err(|_| invalid(T, "알 수 없는 status"))?;
1109 Ok(Self {
1110 transfer_id,
1111 status,
1112 message: utf8(T, b)?,
1113 })
1114 }
1115}
1116
1117/// FILE_CANCEL (0x54), 4B. 받던 파일을 지운다.
1118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1119pub struct FileCancel {
1120 pub transfer_id: u32,
1121}
1122
1123impl FileCancel {
1124 pub const LEN: usize = 4;
1125
1126 pub fn encode(&self, dst: &mut BytesMut) {
1127 dst.put_u32(self.transfer_id);
1128 }
1129
1130 pub fn decode(payload: &[u8]) -> Result<Self, ProtocolError> {
1131 expect_len(MsgType::FileCancel, payload, Self::LEN)?;
1132 let mut b = payload;
1133 Ok(Self {
1134 transfer_id: b.get_u32(),
1135 })
1136 }
1137}
1138
1139// ---------------------------------------------------------------------------
1140// 비디오 채널 패킷 헤더 (제어 프레임 아님)
1141// ---------------------------------------------------------------------------
1142
1143/// 비디오 TCP 연결에서 각 패킷 앞에 붙는 16바이트 헤더. 뒤에 `data_len` 바이트가 따른다.
1144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1145pub struct VideoPacketHeader {
1146 pub pts_us: u64,
1147 /// 코덱 설정 데이터(SPS/PPS 등) 패킷.
1148 pub is_config: bool,
1149 pub is_keyframe: bool,
1150 pub config_gen: u8,
1151 /// 최대 [`MAX_VIDEO_DATA_LEN`].
1152 pub data_len: u32,
1153}
1154
1155impl VideoPacketHeader {
1156 pub const FLAG_CONFIG: u8 = 0x01;
1157 pub const FLAG_KEYFRAME: u8 = 0x02;
1158
1159 pub fn encode(&self, dst: &mut BytesMut) {
1160 debug_assert!(self.data_len <= MAX_VIDEO_DATA_LEN);
1161 let mut flags = 0;
1162 if self.is_config {
1163 flags |= Self::FLAG_CONFIG;
1164 }
1165 if self.is_keyframe {
1166 flags |= Self::FLAG_KEYFRAME;
1167 }
1168 dst.reserve(VIDEO_HEADER_LEN);
1169 dst.put_u64(self.pts_us);
1170 dst.put_u8(flags);
1171 dst.put_u8(self.config_gen);
1172 dst.put_bytes(0, 2);
1173 dst.put_u32(self.data_len);
1174 }
1175
1176 /// 헤더 16바이트만 해석한다. 길이가 정확히 [`VIDEO_HEADER_LEN`]이어야 한다.
1177 pub fn decode(header: &[u8]) -> Result<Self, ProtocolError> {
1178 if header.len() != VIDEO_HEADER_LEN {
1179 return Err(ProtocolError::InvalidVideoHeader("헤더 길이 불일치"));
1180 }
1181 let mut b = header;
1182 let pts_us = b.get_u64();
1183 let flags = b.get_u8();
1184 if flags & !(Self::FLAG_CONFIG | Self::FLAG_KEYFRAME) != 0 {
1185 return Err(ProtocolError::InvalidVideoHeader(
1186 "정의되지 않은 flags 비트",
1187 ));
1188 }
1189 let config_gen = b.get_u8();
1190 b.advance(2);
1191 let data_len = b.get_u32();
1192 if data_len > MAX_VIDEO_DATA_LEN {
1193 return Err(ProtocolError::VideoDataTooLarge(data_len));
1194 }
1195 Ok(Self {
1196 pts_us,
1197 is_config: flags & Self::FLAG_CONFIG != 0,
1198 is_keyframe: flags & Self::FLAG_KEYFRAME != 0,
1199 config_gen,
1200 data_len,
1201 })
1202 }
1203}
1204
1205// ---------------------------------------------------------------------------
1206// 통합 메시지
1207// ---------------------------------------------------------------------------
1208
1209/// 모든 제어 메시지. [`Frame`]과 상호 변환한다.
1210#[derive(Debug, Clone, PartialEq, Eq)]
1211pub enum Message {
1212 Ping,
1213 Pong,
1214 AuthHello(AuthHello),
1215 AuthChallenge(AuthChallenge),
1216 AuthResponse(AuthResponse),
1217 AuthResult(AuthResult),
1218 ChannelAttach(ChannelAttach),
1219 KeyEvent(KeyEvent),
1220 TextInput(TextInput),
1221 SystemAction(SystemAction),
1222 ClipboardSync(ClipboardSync),
1223 TouchEvent(TouchEvent),
1224 ScrollEvent(ScrollEvent),
1225 VideoConfigRequest(VideoConfigRequest),
1226 VideoConfig(VideoConfig),
1227 VideoRequestKeyframe,
1228 FileStart(FileStart),
1229 FileData(FileData),
1230 FileEnd(FileEnd),
1231 FileResult(FileResult),
1232 FileCancel(FileCancel),
1233 Ack,
1234 Error(ErrorMessage),
1235}
1236
1237impl Message {
1238 pub fn msg_type(&self) -> MsgType {
1239 match self {
1240 Self::Ping => MsgType::Ping,
1241 Self::Pong => MsgType::Pong,
1242 Self::AuthHello(_) => MsgType::AuthHello,
1243 Self::AuthChallenge(_) => MsgType::AuthChallenge,
1244 Self::AuthResponse(_) => MsgType::AuthResponse,
1245 Self::AuthResult(_) => MsgType::AuthResult,
1246 Self::ChannelAttach(_) => MsgType::ChannelAttach,
1247 Self::KeyEvent(_) => MsgType::KeyEvent,
1248 Self::TextInput(_) => MsgType::TextInput,
1249 Self::SystemAction(_) => MsgType::SystemAction,
1250 Self::ClipboardSync(_) => MsgType::ClipboardSync,
1251 Self::TouchEvent(_) => MsgType::TouchEvent,
1252 Self::ScrollEvent(_) => MsgType::ScrollEvent,
1253 Self::VideoConfigRequest(_) => MsgType::VideoConfigRequest,
1254 Self::VideoConfig(_) => MsgType::VideoConfig,
1255 Self::VideoRequestKeyframe => MsgType::VideoRequestKeyframe,
1256 Self::FileStart(_) => MsgType::FileStart,
1257 Self::FileData(_) => MsgType::FileData,
1258 Self::FileEnd(_) => MsgType::FileEnd,
1259 Self::FileResult(_) => MsgType::FileResult,
1260 Self::FileCancel(_) => MsgType::FileCancel,
1261 Self::Ack => MsgType::Ack,
1262 Self::Error(_) => MsgType::Error,
1263 }
1264 }
1265
1266 /// 페이로드만 `dst` 뒤에 붙인다.
1267 pub fn encode_payload(&self, dst: &mut BytesMut) {
1268 match self {
1269 Self::Ping | Self::Pong | Self::VideoRequestKeyframe | Self::Ack => {}
1270 Self::AuthHello(m) => m.encode(dst),
1271 Self::AuthChallenge(m) => m.encode(dst),
1272 Self::AuthResponse(m) => m.encode(dst),
1273 Self::AuthResult(m) => m.encode(dst),
1274 Self::ChannelAttach(m) => m.encode(dst),
1275 Self::KeyEvent(m) => m.encode(dst),
1276 Self::TextInput(m) => m.encode(dst),
1277 Self::SystemAction(m) => m.encode(dst),
1278 Self::ClipboardSync(m) => m.encode(dst),
1279 Self::TouchEvent(m) => m.encode(dst),
1280 Self::ScrollEvent(m) => m.encode(dst),
1281 Self::VideoConfigRequest(m) => m.encode(dst),
1282 Self::VideoConfig(m) => m.encode(dst),
1283 Self::FileStart(m) => m.encode(dst),
1284 Self::FileData(m) => m.encode(dst),
1285 Self::FileEnd(m) => m.encode(dst),
1286 Self::FileResult(m) => m.encode(dst),
1287 Self::FileCancel(m) => m.encode(dst),
1288 Self::Error(m) => m.encode(dst),
1289 }
1290 }
1291
1292 /// 헤더 `flags`가 0인 프레임을 만든다.
1293 pub fn to_frame(&self, seq_id: u16) -> Frame {
1294 let mut payload = BytesMut::new();
1295 self.encode_payload(&mut payload);
1296 Frame::new(self.msg_type(), seq_id, payload.freeze())
1297 }
1298
1299 pub fn decode(frame: &Frame) -> Result<Self, ProtocolError> {
1300 let t = frame.header.msg_type;
1301 let p = &frame.payload[..];
1302 Ok(match t {
1303 MsgType::Ping => check_empty(t, p).map(|()| Self::Ping)?,
1304 MsgType::Pong => check_empty(t, p).map(|()| Self::Pong)?,
1305 MsgType::AuthHello => Self::AuthHello(AuthHello::decode(p)?),
1306 MsgType::AuthChallenge => Self::AuthChallenge(AuthChallenge::decode(p)?),
1307 MsgType::AuthResponse => Self::AuthResponse(AuthResponse::decode(p)?),
1308 MsgType::AuthResult => Self::AuthResult(AuthResult::decode(p)?),
1309 MsgType::ChannelAttach => Self::ChannelAttach(ChannelAttach::decode(p)?),
1310 MsgType::KeyEvent => Self::KeyEvent(KeyEvent::decode(p)?),
1311 MsgType::TextInput => Self::TextInput(TextInput::decode(p)?),
1312 MsgType::SystemAction => Self::SystemAction(SystemAction::decode(p)?),
1313 MsgType::ClipboardSync => Self::ClipboardSync(ClipboardSync::decode(p)?),
1314 MsgType::TouchEvent => Self::TouchEvent(TouchEvent::decode(p)?),
1315 MsgType::ScrollEvent => Self::ScrollEvent(ScrollEvent::decode(p)?),
1316 MsgType::VideoConfigRequest => Self::VideoConfigRequest(VideoConfigRequest::decode(p)?),
1317 MsgType::VideoConfig => Self::VideoConfig(VideoConfig::decode(p)?),
1318 MsgType::FileStart => Self::FileStart(FileStart::decode(p)?),
1319 MsgType::FileData => Self::FileData(FileData::decode(p)?),
1320 MsgType::FileEnd => Self::FileEnd(FileEnd::decode(p)?),
1321 MsgType::FileResult => Self::FileResult(FileResult::decode(p)?),
1322 MsgType::FileCancel => Self::FileCancel(FileCancel::decode(p)?),
1323 MsgType::VideoRequestKeyframe => {
1324 check_empty(t, p).map(|()| Self::VideoRequestKeyframe)?
1325 }
1326 MsgType::Ack => check_empty(t, p).map(|()| Self::Ack)?,
1327 MsgType::Error => Self::Error(ErrorMessage::decode(p)?),
1328 })
1329 }
1330}
1331
1332#[cfg(test)]
1333mod tests {
1334 use super::*;
1335
1336 fn enc(m: &Message) -> Vec<u8> {
1337 let mut buf = BytesMut::new();
1338 m.encode_payload(&mut buf);
1339 buf.to_vec()
1340 }
1341
1342 fn invalid_of(err: Result<impl std::fmt::Debug, ProtocolError>, t: MsgType) {
1343 match err {
1344 Err(ProtocolError::InvalidPayload { msg_type, .. }) => assert_eq!(msg_type, t),
1345 other => panic!("InvalidPayload 기대, 실제 {other:?}"),
1346 }
1347 }
1348
1349 fn token(seed: u8) -> [u8; 32] {
1350 std::array::from_fn(|i| seed.wrapping_add(i as u8))
1351 }
1352
1353 fn sample_key_event() -> KeyEvent {
1354 KeyEvent {
1355 action: KeyAction::Click,
1356 keycode: 0x0042,
1357 meta_state: 0x0000_1001,
1358 repeat: 3,
1359 scancode: 0x001C,
1360 }
1361 }
1362
1363 fn sample_clipboard() -> ClipboardSync {
1364 ClipboardSync {
1365 origin: ClipboardOrigin::HostUbuntu,
1366 auto_paste: true,
1367 sha256: [0xAA; 32],
1368 content: ClipboardContent::Text("가a".into()),
1369 }
1370 }
1371
1372 fn all_messages() -> Vec<Message> {
1373 vec![
1374 Message::Ping,
1375 Message::Pong,
1376 Message::AuthHello(AuthHello {
1377 public_key: token(1),
1378 hostname: "ubuntu-데스크톱".into(),
1379 }),
1380 Message::AuthChallenge(AuthChallenge {
1381 status: AuthStatus::PendingUser,
1382 nonce: token(2),
1383 }),
1384 Message::AuthResponse(AuthResponse {
1385 signature: std::array::from_fn(|i| i as u8),
1386 }),
1387 Message::AuthResult(AuthResult {
1388 result: AuthResultCode::Ok,
1389 grant: AuthGrant::Once,
1390 session_token: token(3),
1391 daemon_version: 0x0001_0203,
1392 }),
1393 Message::AuthResult(AuthResult {
1394 result: AuthResultCode::Timeout,
1395 grant: AuthGrant::None,
1396 session_token: [0; 32],
1397 daemon_version: 7,
1398 }),
1399 Message::ChannelAttach(ChannelAttach {
1400 kind: ChannelKind::Video,
1401 session_token: token(4),
1402 }),
1403 Message::KeyEvent(sample_key_event()),
1404 Message::TextInput(TextInput {
1405 text: "한글 입력".into(),
1406 }),
1407 Message::SystemAction(SystemAction::Recents),
1408 Message::ClipboardSync(sample_clipboard()),
1409 Message::ClipboardSync(ClipboardSync {
1410 content: ClipboardContent::Text(String::new()),
1411 auto_paste: false,
1412 origin: ClipboardOrigin::AndroidDevice,
1413 ..sample_clipboard()
1414 }),
1415 Message::ClipboardSync(ClipboardSync {
1416 content: ClipboardContent::Png(vec![0x89, b'P', b'N', b'G', 0xFF]),
1417 ..sample_clipboard()
1418 }),
1419 Message::FileStart(FileStart {
1420 transfer_id: 7,
1421 size: 5_000_000_000,
1422 name: "사진 1.jpg".into(),
1423 }),
1424 Message::FileData(FileData {
1425 transfer_id: 7,
1426 data: vec![1, 2, 3],
1427 }),
1428 Message::FileEnd(FileEnd {
1429 transfer_id: 7,
1430 sha256: [0x5A; 32],
1431 }),
1432 Message::FileResult(FileResult {
1433 transfer_id: 7,
1434 status: FileStatus::NoSpace,
1435 message: "저장 공간 부족".into(),
1436 }),
1437 Message::FileCancel(FileCancel { transfer_id: 9 }),
1438 Message::ClipboardSync(ClipboardSync {
1439 content: ClipboardContent::Jpeg(vec![0xFF, 0xD8, 0xFF]),
1440 origin: ClipboardOrigin::AndroidDevice,
1441 ..sample_clipboard()
1442 }),
1443 Message::TouchEvent(TouchEvent {
1444 action: TouchAction::Move,
1445 pointer_id: 2,
1446 x: 540,
1447 y: 1200,
1448 frame_width: 1080,
1449 frame_height: 2400,
1450 pressure: 0xFFFF,
1451 }),
1452 Message::ScrollEvent(ScrollEvent {
1453 x: 10,
1454 y: 20,
1455 frame_width: 1080,
1456 frame_height: 2400,
1457 h_scroll: -120,
1458 v_scroll: 240,
1459 }),
1460 Message::VideoConfigRequest(VideoConfigRequest {
1461 max_size: 1920,
1462 max_fps: 60,
1463 codecs: CodecMask::H264 | CodecMask::H265,
1464 bitrate: 8_000_000,
1465 }),
1466 Message::VideoConfig(VideoConfig {
1467 codec: VideoCodec::H265,
1468 config_gen: 5,
1469 width: 1080,
1470 height: 2400,
1471 fps: 60,
1472 bitrate: 8_000_000,
1473 display_width: 1080,
1474 display_height: 2400,
1475 }),
1476 Message::VideoRequestKeyframe,
1477 Message::Ack,
1478 Message::Error(ErrorMessage {
1479 code: error_code::UNAUTHENTICATED,
1480 reason: "인증 필요".into(),
1481 }),
1482 Message::Error(ErrorMessage {
1483 code: error_code::INTERNAL,
1484 reason: String::new(),
1485 }),
1486 ]
1487 }
1488
1489 #[test]
1490 fn every_message_roundtrips_through_frame() {
1491 for (i, m) in all_messages().into_iter().enumerate() {
1492 let seq = i as u16 + 100;
1493 let frame = m.to_frame(seq);
1494 assert_eq!(frame.header.msg_type, m.msg_type());
1495 assert_eq!(frame.header.seq_id, seq);
1496 assert_eq!(frame.header.flags, 0);
1497 assert_eq!(Message::decode(&frame).as_ref(), Ok(&m), "{m:?}");
1498 }
1499 }
1500
1501 #[test]
1502 fn roundtrip_through_wire_encoding() {
1503 use crate::protocol::{FrameDecoder, encode_frame};
1504 let mut wire = BytesMut::new();
1505 let msgs = all_messages();
1506 for (i, m) in msgs.iter().enumerate() {
1507 encode_frame(&m.to_frame(i as u16), &mut wire);
1508 }
1509 let mut dec = FrameDecoder::new();
1510 dec.extend(&wire);
1511 for m in &msgs {
1512 let frame = dec.decode().unwrap().unwrap();
1513 assert_eq!(&Message::decode(&frame).unwrap(), m);
1514 }
1515 assert_eq!(dec.decode().unwrap(), None);
1516 }
1517
1518 #[test]
1519 fn key_event_layout() {
1520 assert_eq!(
1521 enc(&Message::KeyEvent(sample_key_event())),
1522 [
1523 0x02, 0x00, 0x00, 0x42, 0x00, 0x00, 0x10, 0x01, 0x00, 0x03, 0x00, 0x1C
1524 ]
1525 );
1526 }
1527
1528 #[test]
1529 fn clipboard_sync_layout() {
1530 let bytes = enc(&Message::ClipboardSync(sample_clipboard()));
1531 let mut expected = vec![0x01, 0x01, 0x01, 0x00];
1532 expected.extend([0xAA; 32]);
1533 expected.extend([0x00, 0x00, 0x00, 0x04]);
1534 expected.extend([0xEA, 0xB0, 0x80, b'a']);
1535 assert_eq!(bytes, expected);
1536 }
1537
1538 #[test]
1539 fn touch_event_layout() {
1540 let m = Message::TouchEvent(TouchEvent {
1541 action: TouchAction::Down,
1542 pointer_id: 1,
1543 x: 0x0102_0304,
1544 y: 0x0506_0708,
1545 frame_width: 0x090A,
1546 frame_height: 0x0B0C,
1547 pressure: 0x0D0E,
1548 });
1549 assert_eq!(
1550 enc(&m),
1551 [
1552 0x00, 0x01, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
1553 0x0B, 0x0C, 0x0D, 0x0E, 0x00, 0x00
1554 ]
1555 );
1556 }
1557
1558 #[test]
1559 fn auth_result_layout() {
1560 let m = Message::AuthResult(AuthResult {
1561 result: AuthResultCode::Ok,
1562 grant: AuthGrant::Always,
1563 session_token: [0x5A; 32],
1564 daemon_version: 0x0001_0002,
1565 });
1566 let mut expected = vec![0x00, 0x01, 0x00, 0x00];
1567 expected.extend([0x5A; 32]);
1568 expected.extend([0x00, 0x01, 0x00, 0x02]);
1569 assert_eq!(enc(&m), expected);
1570 }
1571
1572 #[test]
1573 fn video_config_layout() {
1574 let m = Message::VideoConfig(VideoConfig {
1575 codec: VideoCodec::Av1,
1576 config_gen: 9,
1577 width: 0x0438,
1578 height: 0x0960,
1579 fps: 60,
1580 bitrate: 0x007A_1200,
1581 display_width: 0x0438,
1582 display_height: 0x0960,
1583 });
1584 assert_eq!(
1585 enc(&m),
1586 [
1587 0x04, 0x09, 0x04, 0x38, 0x09, 0x60, 60, 0x00, 0x00, 0x7A, 0x12, 0x00, 0x04, 0x38,
1588 0x09, 0x60
1589 ]
1590 );
1591 }
1592
1593 #[test]
1594 fn video_packet_header_layout_and_roundtrip() {
1595 let h = VideoPacketHeader {
1596 pts_us: 0x0102_0304_0506_0708,
1597 is_config: false,
1598 is_keyframe: true,
1599 config_gen: 3,
1600 data_len: 0x0001_0000,
1601 };
1602 let mut buf = BytesMut::new();
1603 h.encode(&mut buf);
1604 assert_eq!(
1605 &buf[..],
1606 [
1607 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x02, 0x03, 0x00, 0x00, 0x00, 0x01,
1608 0x00, 0x00
1609 ]
1610 );
1611 assert_eq!(VideoPacketHeader::decode(&buf), Ok(h));
1612
1613 let cfg = VideoPacketHeader {
1614 is_config: true,
1615 is_keyframe: true,
1616 data_len: MAX_VIDEO_DATA_LEN,
1617 ..h
1618 };
1619 let mut buf = BytesMut::new();
1620 cfg.encode(&mut buf);
1621 assert_eq!(buf[8], 0x03);
1622 assert_eq!(VideoPacketHeader::decode(&buf), Ok(cfg));
1623 }
1624
1625 #[test]
1626 fn video_packet_header_rejects_bad_input() {
1627 let mut bytes = [0u8; VIDEO_HEADER_LEN];
1628 bytes[12..16].copy_from_slice(&(MAX_VIDEO_DATA_LEN + 1).to_be_bytes());
1629 assert_eq!(
1630 VideoPacketHeader::decode(&bytes),
1631 Err(ProtocolError::VideoDataTooLarge(MAX_VIDEO_DATA_LEN + 1))
1632 );
1633
1634 let mut bytes = [0u8; VIDEO_HEADER_LEN];
1635 bytes[8] = 0x04;
1636 assert!(matches!(
1637 VideoPacketHeader::decode(&bytes),
1638 Err(ProtocolError::InvalidVideoHeader(_))
1639 ));
1640 assert!(matches!(
1641 VideoPacketHeader::decode(&[0u8; 15]),
1642 Err(ProtocolError::InvalidVideoHeader(_))
1643 ));
1644 }
1645
1646 #[test]
1647 fn reserved_bytes_are_ignored_on_decode() {
1648 let mut bytes = enc(&Message::KeyEvent(sample_key_event()));
1649 bytes[1] = 0xFF;
1650 assert_eq!(KeyEvent::decode(&bytes), Ok(sample_key_event()));
1651
1652 let mut bytes = [0u8; VIDEO_HEADER_LEN];
1653 bytes[10] = 0xFF;
1654 bytes[11] = 0xFF;
1655 assert!(VideoPacketHeader::decode(&bytes).is_ok());
1656 }
1657
1658 #[test]
1659 fn fixed_size_payloads_reject_wrong_length() {
1660 let cases: [(MsgType, usize); 11] = [
1661 (MsgType::AuthChallenge, AuthChallenge::LEN),
1662 (MsgType::AuthResponse, AuthResponse::LEN),
1663 (MsgType::AuthResult, AuthResult::LEN),
1664 (MsgType::ChannelAttach, ChannelAttach::LEN),
1665 (MsgType::KeyEvent, KeyEvent::LEN),
1666 (MsgType::SystemAction, SystemAction::LEN),
1667 (MsgType::TouchEvent, TouchEvent::LEN),
1668 (MsgType::ScrollEvent, ScrollEvent::LEN),
1669 (MsgType::VideoConfigRequest, VideoConfigRequest::LEN),
1670 (MsgType::VideoConfig, VideoConfig::LEN),
1671 (MsgType::Ping, 0),
1672 ];
1673 for (t, len) in cases {
1674 for bad in [len.wrapping_sub(1), len + 1] {
1675 if bad > 1024 {
1676 continue;
1677 }
1678 // 첫 바이트를 유효한 코드로 맞춰 길이 검사만 걸리게 한다.
1679 let mut payload = vec![0u8; bad];
1680 if let Some(b) = payload.first_mut() {
1681 *b = 0x01;
1682 }
1683 let frame = Frame::new(t, 0, payload);
1684 invalid_of(Message::decode(&frame), t);
1685 }
1686 }
1687 for t in [MsgType::Pong, MsgType::Ack, MsgType::VideoRequestKeyframe] {
1688 invalid_of(Message::decode(&Frame::new(t, 0, vec![0])), t);
1689 }
1690 }
1691
1692 #[test]
1693 fn variable_payloads_reject_bad_length() {
1694 // AUTH_HELLO: 호스트명 0바이트, 256바이트.
1695 invalid_of(AuthHello::decode(&[0u8; 32]), MsgType::AuthHello);
1696 invalid_of(AuthHello::decode(&[b'a'; 32 + 256]), MsgType::AuthHello);
1697 assert!(AuthHello::decode(&[b'a'; 32 + 255]).is_ok());
1698 invalid_of(TextInput::decode(&[]), MsgType::TextInput);
1699 invalid_of(ErrorMessage::decode(&[0x00]), MsgType::Error);
1700 invalid_of(ClipboardSync::decode(&[0x01; 39]), MsgType::ClipboardSync);
1701 }
1702
1703 #[test]
1704 fn unknown_codes_are_rejected() {
1705 let mut ch = [0u8; AuthChallenge::LEN];
1706 ch[0] = 0x03;
1707 invalid_of(AuthChallenge::decode(&ch), MsgType::AuthChallenge);
1708
1709 let mut ar = [0u8; AuthResult::LEN];
1710 ar[0] = 0x05;
1711 invalid_of(AuthResult::decode(&ar), MsgType::AuthResult);
1712 ar[0] = 0x00;
1713 ar[1] = 0x03;
1714 invalid_of(AuthResult::decode(&ar), MsgType::AuthResult);
1715
1716 let mut ca = [0u8; ChannelAttach::LEN];
1717 invalid_of(ChannelAttach::decode(&ca), MsgType::ChannelAttach);
1718 ca[0] = 0x02;
1719 assert_eq!(ChannelAttach::decode(&ca).unwrap().kind, ChannelKind::Audio);
1720
1721 let mut ke = [0u8; KeyEvent::LEN];
1722 ke[0] = 0x03;
1723 invalid_of(KeyEvent::decode(&ke), MsgType::KeyEvent);
1724
1725 invalid_of(
1726 SystemAction::decode(&[0x05, 0, 0, 0]),
1727 MsgType::SystemAction,
1728 );
1729 invalid_of(
1730 SystemAction::decode(&[0x00, 0, 0, 0]),
1731 MsgType::SystemAction,
1732 );
1733
1734 let mut te = [0u8; TouchEvent::LEN];
1735 te[0] = 0x04;
1736 invalid_of(TouchEvent::decode(&te), MsgType::TouchEvent);
1737
1738 let mut vr = [0u8; VideoConfigRequest::LEN];
1739 vr[3] = 0x08;
1740 invalid_of(VideoConfigRequest::decode(&vr), MsgType::VideoConfigRequest);
1741
1742 let mut vc = [0u8; VideoConfig::LEN];
1743 vc[0] = 0x03; // 비트 두 개 = 코덱 하나가 아님
1744 invalid_of(VideoConfig::decode(&vc), MsgType::VideoConfig);
1745
1746 let base = enc(&Message::ClipboardSync(sample_clipboard()));
1747 for (idx, bad) in [(0, 0x03), (1, 0x02), (2, 0x04)] {
1748 let mut cs = base.clone();
1749 cs[idx] = bad;
1750 invalid_of(ClipboardSync::decode(&cs), MsgType::ClipboardSync);
1751 }
1752 }
1753
1754 #[test]
1755 fn clipboard_rejects_len_mismatch_and_bad_utf8() {
1756 let base = enc(&Message::ClipboardSync(sample_clipboard()));
1757
1758 let mut longer = base.clone();
1759 longer.push(b'x');
1760 invalid_of(ClipboardSync::decode(&longer), MsgType::ClipboardSync);
1761
1762 let mut shorter = base.clone();
1763 shorter.pop();
1764 invalid_of(ClipboardSync::decode(&shorter), MsgType::ClipboardSync);
1765
1766 let mut bad = base.clone();
1767 bad[40] = 0xFF;
1768 invalid_of(ClipboardSync::decode(&bad), MsgType::ClipboardSync);
1769 }
1770
1771 #[test]
1772 fn text_payloads_reject_bad_utf8() {
1773 let mut hello = vec![0u8; 32];
1774 hello.extend([0xC3, 0x28]);
1775 invalid_of(AuthHello::decode(&hello), MsgType::AuthHello);
1776 invalid_of(TextInput::decode(&[0xFF]), MsgType::TextInput);
1777 invalid_of(ErrorMessage::decode(&[0, 1, 0xFF]), MsgType::Error);
1778 }
1779
1780 #[test]
1781 fn auth_result_consistency() {
1782 let ok = AuthResult {
1783 result: AuthResultCode::Ok,
1784 grant: AuthGrant::Always,
1785 session_token: token(9),
1786 daemon_version: 1,
1787 };
1788 let encode = |r: AuthResult| {
1789 let mut buf = BytesMut::new();
1790 r.encode(&mut buf);
1791 buf
1792 };
1793
1794 // 실패인데 grant가 NONE이 아님.
1795 let rejected_with_grant = AuthResult {
1796 result: AuthResultCode::Rejected,
1797 session_token: [0; 32],
1798 ..ok
1799 };
1800 invalid_of(
1801 AuthResult::decode(&encode(rejected_with_grant)),
1802 MsgType::AuthResult,
1803 );
1804
1805 // 실패인데 토큰이 0이 아님.
1806 let rejected_with_token = AuthResult {
1807 result: AuthResultCode::Revoked,
1808 grant: AuthGrant::None,
1809 ..ok
1810 };
1811 invalid_of(
1812 AuthResult::decode(&encode(rejected_with_token)),
1813 MsgType::AuthResult,
1814 );
1815
1816 // 성공인데 grant가 NONE.
1817 let ok_without_grant = AuthResult {
1818 grant: AuthGrant::None,
1819 ..ok
1820 };
1821 invalid_of(
1822 AuthResult::decode(&encode(ok_without_grant)),
1823 MsgType::AuthResult,
1824 );
1825
1826 assert_eq!(AuthResult::decode(&encode(ok)), Ok(ok));
1827 }
1828
1829 #[test]
1830 fn codec_mask_bits() {
1831 let m = CodecMask::H264 | CodecMask::AV1;
1832 assert_eq!(m.bits(), 0x05);
1833 assert!(m.contains(CodecMask::H264));
1834 assert!(!m.contains(CodecMask::H265));
1835 assert!(!m.contains(CodecMask::ALL));
1836 assert!(m.contains_codec(VideoCodec::Av1));
1837 assert_eq!(CodecMask::from_bits(0x07), Some(CodecMask::ALL));
1838 assert_eq!(CodecMask::from_bits(0x10), None);
1839 }
1840
1841 #[test]
1842 fn signing_message_is_nonce_then_cert_hash() {
1843 let msg = auth_signing_message(&[1; 32], &[2; 32]);
1844 assert_eq!(&msg[..32], &[1; 32]);
1845 assert_eq!(&msg[32..], &[2; 32]);
1846 }
1847}