leejunyoung5819wayland-android-remote

공개

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

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