1pub mod frame;
2pub mod message;
3pub mod origin;
4pub mod state;
5pub mod uri;
6
7use std::borrow::Cow;
8use std::fmt::Write as _;
9
10pub const DEFAULT_PORT: u16 = 1985;
12
13pub const MAX_FRAME_SIZE: u32 = 16 * 1024 * 1024;
15
16pub const MAX_CONTROL_MESSAGE_SIZE: usize = 16 * 1024;
18
19pub const MAX_INPUT_MESSAGE_SIZE: usize = 64 * 1024;
23
24pub const MAX_PAGE_MESSAGE_SIZE: usize = 1024 * 1024 + 64 * 1024;
26
27pub const MAX_PAGE_PATH_LEN: usize = 1024;
35
36pub const MAX_WASM_MODULE_SIZE: usize = 512 * 1024;
39
40pub const MAX_LIVE_UPDATE_SIZE: usize = 1024 * 1024;
46
47pub const HEADER_SIZE: usize = 6;
49
50pub const MAX_PROTOCOL_DIAGNOSTIC_BYTES: usize = 2048;
52
53pub const PROTOCOL_VERSION: &str = "0.2";
55
56pub const SUPPORTED_CAPABILITIES: &[&str] =
58 &["live-updates", "sessions", "wasm-effects", "page-path"];
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
62pub struct ProtocolVersion {
63 pub major: u16,
64 pub minor: u16,
65}
66
67impl ProtocolVersion {
68 pub fn parse(value: &str) -> Result<Self, ProtocolError> {
69 let (major, minor) = value.split_once('.').ok_or_else(|| {
70 ProtocolError::invalid_message(format_args!("invalid protocol version: {value}"))
71 })?;
72 let version = Self {
73 major: major.parse().map_err(|_| {
74 ProtocolError::invalid_message(format_args!("invalid protocol version: {value}"))
75 })?,
76 minor: minor.parse().map_err(|_| {
77 ProtocolError::invalid_message(format_args!("invalid protocol version: {value}"))
78 })?,
79 };
80 if version.to_string() != value {
81 return Err(ProtocolError::invalid_message(format_args!(
82 "non-canonical protocol version: {value}"
83 )));
84 }
85 Ok(version)
86 }
87}
88
89impl std::fmt::Display for ProtocolVersion {
90 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 write!(formatter, "{}.{}", self.major, self.minor)
92 }
93}
94
95#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
97pub struct NegotiatedCapabilities(u8);
98
99impl NegotiatedCapabilities {
100 const LIVE_UPDATES: u8 = 1 << 0;
101 const SESSIONS: u8 = 1 << 1;
102 const WASM_EFFECTS: u8 = 1 << 2;
103 const PAGE_PATH: u8 = 1 << 3;
104
105 pub fn negotiate(offered: &[String], accepted: &[String]) -> Self {
106 let mut bits = 0;
107 for capability in offered {
108 if !accepted.contains(capability) {
109 continue;
110 }
111 bits |= match capability.as_str() {
112 "live-updates" => Self::LIVE_UPDATES,
113 "sessions" => Self::SESSIONS,
114 "wasm-effects" => Self::WASM_EFFECTS,
115 "page-path" => Self::PAGE_PATH,
116 _ => 0,
117 };
118 }
119 Self(bits)
120 }
121
122 pub fn live_updates(self) -> bool {
123 self.0 & Self::LIVE_UPDATES != 0
124 }
125 pub fn sessions(self) -> bool {
126 self.0 & Self::SESSIONS != 0
127 }
128 pub fn wasm_effects(self) -> bool {
129 self.0 & Self::WASM_EFFECTS != 0
130 }
131 pub fn page_path(self) -> bool {
138 self.0 & Self::PAGE_PATH != 0
139 }
140}
141
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub struct NegotiatedProtocol {
145 pub version: ProtocolVersion,
146 pub capabilities: NegotiatedCapabilities,
147}
148
149#[derive(Debug)]
151pub enum ProtocolError {
152 FrameTooLarge(u32),
154 MessageTooLarge {
156 msg_type: frame::MessageType,
157 size: u32,
158 max: usize,
159 },
160 WrongDirection(frame::MessageType),
162 UnknownMessageType(u8),
164 InvalidMessage(Cow<'static, str>),
166 Io(std::io::Error),
168 Tls(Cow<'static, str>),
170 InvalidUri(Cow<'static, str>),
172 ConnectionClosed,
174 ResourceExhausted { requested: usize },
176 Timeout,
178}
179
180impl ProtocolError {
181 pub fn invalid_message(args: std::fmt::Arguments<'_>) -> Self {
182 match try_protocol_diagnostic(args) {
183 Ok(message) => Self::InvalidMessage(Cow::Owned(message)),
184 Err(requested) => Self::ResourceExhausted { requested },
185 }
186 }
187
188 pub fn invalid_uri(args: std::fmt::Arguments<'_>) -> Self {
189 match try_protocol_diagnostic(args) {
190 Ok(message) => Self::InvalidUri(Cow::Owned(message)),
191 Err(requested) => Self::ResourceExhausted { requested },
192 }
193 }
194
195 pub fn tls(args: std::fmt::Arguments<'_>) -> Self {
196 match try_protocol_diagnostic(args) {
197 Ok(message) => Self::Tls(Cow::Owned(message)),
198 Err(requested) => Self::ResourceExhausted { requested },
199 }
200 }
201}
202
203struct ProtocolDiagnosticWriter {
204 value: String,
205 requested: usize,
206 rejected: bool,
207 truncated: bool,
208}
209
210impl std::fmt::Write for ProtocolDiagnosticWriter {
211 fn write_str(&mut self, text: &str) -> std::fmt::Result {
212 self.requested = self.requested.saturating_add(text.len());
213 if self.truncated {
214 return Ok(());
215 }
216 let remaining = MAX_PROTOCOL_DIAGNOSTIC_BYTES.saturating_sub(self.value.len());
217 if remaining == 0 {
218 self.truncated = true;
219 return Ok(());
220 }
221 let mut take = remaining.min(text.len());
222 while take > 0 && !text.is_char_boundary(take) {
223 take -= 1;
224 }
225 if take == 0 {
226 self.truncated = true;
227 return Ok(());
228 }
229 #[cfg(test)]
230 if REJECT_PROTOCOL_DIAGNOSTIC_ALLOCATION.with(|reject| reject.replace(false)) {
231 self.rejected = true;
232 return Err(std::fmt::Error);
233 }
234 self.value.try_reserve_exact(take).map_err(|_| {
235 self.rejected = true;
236 std::fmt::Error
237 })?;
238 self.value.push_str(&text[..take]);
239 if take < text.len() {
240 self.truncated = true;
241 }
242 Ok(())
243 }
244}
245
246fn try_protocol_diagnostic(args: std::fmt::Arguments<'_>) -> Result<String, usize> {
247 let mut writer = ProtocolDiagnosticWriter {
248 value: String::new(),
249 requested: 0,
250 rejected: false,
251 truncated: false,
252 };
253 if writer.write_fmt(args).is_err() || writer.rejected {
254 return Err(writer.requested.max(1));
255 }
256 Ok(writer.value)
257}
258
259#[cfg(test)]
260thread_local! {
261 static REJECT_PROTOCOL_DIAGNOSTIC_ALLOCATION: std::cell::Cell<bool> =
262 const { std::cell::Cell::new(false) };
263}
264
265impl std::fmt::Display for ProtocolError {
266 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
267 match self {
268 ProtocolError::FrameTooLarge(size) => write!(f, "frame too large: {size} bytes"),
269 ProtocolError::MessageTooLarge {
270 msg_type,
271 size,
272 max,
273 } => {
274 write!(f, "{msg_type:?} body too large: {size} bytes (max {max})")
275 }
276 ProtocolError::WrongDirection(msg_type) => {
277 write!(
278 f,
279 "message {msg_type:?} is invalid in this protocol direction"
280 )
281 }
282 ProtocolError::UnknownMessageType(code) => {
283 write!(f, "unknown message type: 0x{code:02x}")
284 }
285 ProtocolError::InvalidMessage(msg) => write!(f, "invalid message: {msg}"),
286 ProtocolError::Io(e) => write!(f, "I/O error: {e}"),
287 ProtocolError::Tls(msg) => write!(f, "TLS error: {msg}"),
288 ProtocolError::InvalidUri(msg) => write!(f, "invalid URI: {msg}"),
289 ProtocolError::ConnectionClosed => write!(f, "connection closed"),
290 ProtocolError::ResourceExhausted { requested } => {
291 write!(
292 f,
293 "unable to reserve {requested} bytes for bounded protocol storage"
294 )
295 }
296 ProtocolError::Timeout => write!(f, "timeout"),
297 }
298 }
299}
300
301impl std::error::Error for ProtocolError {}
302
303impl From<std::io::Error> for ProtocolError {
304 fn from(e: std::io::Error) -> Self {
305 match e.kind() {
306 std::io::ErrorKind::UnexpectedEof => ProtocolError::ConnectionClosed,
307 std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock => ProtocolError::Timeout,
308 _ => ProtocolError::Io(e),
309 }
310 }
311}
312
313#[cfg(test)]
314mod diagnostic_tests {
315 use super::*;
316
317 #[test]
318 fn protocol_diagnostic_formatting_is_bounded_and_fallible() {
319 let ProtocolError::InvalidMessage(Cow::Borrowed(message)) =
320 ProtocolError::InvalidMessage("static diagnostic".into())
321 else {
322 panic!("static diagnostics must remain allocation-free");
323 };
324 assert_eq!(message, "static diagnostic");
325
326 let oversized = "é".repeat(MAX_PROTOCOL_DIAGNOSTIC_BYTES);
327 let ProtocolError::InvalidMessage(message) =
328 ProtocolError::invalid_message(format_args!("prefix:{oversized}"))
329 else {
330 panic!("bounded formatting must produce an invalid-message diagnostic");
331 };
332 assert!(message.len() <= MAX_PROTOCOL_DIAGNOSTIC_BYTES);
333 assert!(message.is_char_boundary(message.len()));
334 assert!(message.starts_with("prefix:"));
335
336 let prefix = "a".repeat(MAX_PROTOCOL_DIAGNOSTIC_BYTES - 1);
337 let ProtocolError::InvalidMessage(message) =
338 ProtocolError::invalid_message(format_args!("{prefix}{}{}", "é", "Z"))
339 else {
340 panic!("segmented formatting must remain a diagnostic");
341 };
342 assert_eq!(message.as_ref(), prefix);
343
344 REJECT_PROTOCOL_DIAGNOSTIC_ALLOCATION.with(|reject| reject.set(true));
345 assert!(matches!(
346 ProtocolError::invalid_message(format_args!("remote {oversized}")),
347 ProtocolError::ResourceExhausted { .. }
348 ));
349 }
350}