heika_packet/
extension.rs1use crate::DecodeError;
11
12pub const RANGE_START: u32 = 0x8000_0000;
14
15pub const PUSH_CAPABILITIES: u32 = RANGE_START;
18
19pub const ENVELOPE: u32 = RANGE_START + 1;
26
27pub const SOURCE_ZIP: &str = "source/zip";
30
31pub const BLOCKS_ALL: &str = "blocks/all";
34
35pub const MAX_CAPABILITIES: usize = 64;
37
38pub fn is_extension(packet_type: u32) -> bool {
40 packet_type >= RANGE_START
41}
42
43pub fn is_capability_name(name: &str) -> bool {
45 (1..=255).contains(&name.len()) && name.bytes().all(|byte| byte.is_ascii_graphic())
46}
47
48pub fn capabilities_body(names: &[&str]) -> Vec<u8> {
52 assert!(names.len() <= MAX_CAPABILITIES, "capability が多すぎます");
53 let mut body = Vec::new();
54 body.extend_from_slice(&(names.len() as u16).to_le_bytes());
55 for name in names {
56 assert!(
57 is_capability_name(name),
58 "capability の名前 {name:?} は使えません"
59 );
60 body.push(name.len() as u8);
61 body.extend_from_slice(name.as_bytes());
62 }
63 body
64}
65
66pub fn read_capabilities(body: &[u8]) -> Result<Vec<String>, DecodeError> {
68 let truncated = |needed: usize, remaining: usize| DecodeError::Truncated { needed, remaining };
69 let (count, mut rest) = body
70 .split_first_chunk::<2>()
71 .ok_or(truncated(2, body.len()))?;
72 let count = u16::from_le_bytes(*count) as usize;
73 if count > MAX_CAPABILITIES {
74 return Err(DecodeError::InvalidValue("capability が多すぎます"));
75 }
76 let mut names = Vec::with_capacity(count);
77 for _ in 0..count {
78 let (&length, after) = rest.split_first().ok_or(truncated(1, 0))?;
79 let length = length as usize;
80 if after.len() < length {
81 return Err(truncated(length, after.len()));
82 }
83 let (name, after) = after.split_at(length);
84 let name = std::str::from_utf8(name)
85 .ok()
86 .filter(|name| is_capability_name(name))
87 .ok_or(DecodeError::InvalidValue(
88 "capability の名前に使えない文字があります",
89 ))?;
90 names.push(name.to_owned());
91 rest = after;
92 }
93 if !rest.is_empty() {
94 return Err(DecodeError::SizeMismatch {
95 declared: body.len() - rest.len(),
96 actual: body.len(),
97 });
98 }
99 Ok(names)
100}
101
102pub fn envelope_body(name: &str, content: &[u8]) -> Vec<u8> {
104 assert!(is_capability_name(name), "封筒の名前 {name:?} は使えません");
105 let mut body = Vec::with_capacity(1 + name.len() + content.len());
106 body.push(name.len() as u8);
107 body.extend_from_slice(name.as_bytes());
108 body.extend_from_slice(content);
109 body
110}
111
112pub fn read_envelope(body: &[u8]) -> Result<(&str, &[u8]), DecodeError> {
114 let (&length, rest) = body.split_first().ok_or(DecodeError::Truncated {
115 needed: 1,
116 remaining: 0,
117 })?;
118 let length = length as usize;
119 if rest.len() < length {
120 return Err(DecodeError::Truncated {
121 needed: length,
122 remaining: rest.len(),
123 });
124 }
125 let (name, content) = rest.split_at(length);
126 let name = std::str::from_utf8(name)
127 .ok()
128 .filter(|name| is_capability_name(name))
129 .ok_or(DecodeError::InvalidValue(
130 "封筒の名前に使えない文字があります",
131 ))?;
132 Ok((name, content))
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138
139 #[test]
140 fn round_trips_capabilities() {
141 assert_eq!(capabilities_body(&[]), [0, 0]);
142 assert_eq!(read_capabilities(&[0, 0]).unwrap(), Vec::<String>::new());
143 let body = capabilities_body(&["source-zip", "block-compression/zstd"]);
144 assert_eq!(&body[..3], [2, 0, 10]);
145 assert_eq!(
146 read_capabilities(&body).unwrap(),
147 ["source-zip", "block-compression/zstd"]
148 );
149 }
150
151 #[test]
152 fn rejects_malformed_capabilities() {
153 assert!(read_capabilities(&[]).is_err());
154 assert!(read_capabilities(&[1, 0]).is_err());
155 assert!(read_capabilities(&[1, 0, 3, b'a', b'b']).is_err());
156 assert!(read_capabilities(&[1, 0, 2, b'a', b' ']).is_err());
157 assert!(read_capabilities(&[1, 0, 0]).is_err());
158 assert!(read_capabilities(&[0, 0, 0]).is_err());
159 assert!(read_capabilities(&[65, 0]).is_err());
160 }
161
162 #[test]
163 fn round_trips_envelopes() {
164 let body = envelope_body(SOURCE_ZIP, b"PK");
165 assert_eq!(body, [&[10][..], b"source/zip", b"PK"].concat());
166 assert_eq!(read_envelope(&body).unwrap(), (SOURCE_ZIP, &b"PK"[..]));
167 assert_eq!(read_envelope(&[1, b'a']).unwrap(), ("a", &[][..]));
168 assert!(read_envelope(&[]).is_err());
169 assert!(read_envelope(&[0]).is_err());
170 assert!(read_envelope(&[3, b'a']).is_err());
171 assert!(read_envelope(&[1, b' ']).is_err());
172 }
173
174 #[test]
175 fn reserves_the_upper_range() {
176 assert!(!is_extension(0x135));
177 assert!(is_extension(PUSH_CAPABILITIES));
178 assert!(is_extension(u32::MAX));
179 }
180}