Skip to main content

qualia_core_db/p2p/connectivity/
wss_frame.rs

1//! RFC 6455 binary/close framing with retained WouldBlock cursors.
2//!
3//! Client frames take a fresh 4-byte mask from `fill_os` per seal. Server
4//! frames stay unmasked. WouldBlock retains the sealed wire bytes / recv
5//! buffer; the mask is never regenerated mid-frame.
6
7#![cfg(not(target_arch = "wasm32"))]
8
9use std::io::{ErrorKind, Read, Write};
10
11use crate::crypto::network::entropy::fill_os;
12use crate::net::qdnf::errors::QdnfError;
13
14use super::{ENVELOPE_HDR, MAX_FRAME};
15
16/// RFC 6455 binary opcode. FIN is set at encode.
17pub const OP_BINARY: u8 = 0x2;
18/// RFC 6455 close opcode. FIN is set at encode.
19pub const OP_CLOSE: u8 = 0x8;
20/// 2-byte base + 2-byte ext-len + 4-byte mask.
21pub const WS_HDR_MAX: usize = 8;
22/// Sealed WS frame capacity (`WS_HDR_MAX + MAX_FRAME`).
23pub const WIRE_CAP: usize = WS_HDR_MAX + MAX_FRAME;
24
25const _: () = assert!(MAX_FRAME == 2048);
26const _: () = assert!(ENVELOPE_HDR == 12);
27const _: () = assert!(WIRE_CAP == 2056);
28
29/// Fill a 4-byte client mask from OS entropy. Fail closed on entropy failure.
30pub fn fresh_client_mask() -> Result<[u8; 4], QdnfError> {
31    let mut mask = [0u8; 4];
32    fill_os(&mut mask).map_err(|_| QdnfError::EntropyFailure)?;
33    Ok(mask)
34}
35
36/// Map `std::io::Error` onto a QDNF outcome. Recovers a wrapped `QdnfError`.
37pub fn map_io(err: std::io::Error) -> QdnfError {
38    if let Some(&inner) = err.get_ref().and_then(|e| e.downcast_ref::<QdnfError>()) {
39        return inner;
40    }
41    match err.kind() {
42        ErrorKind::WouldBlock | ErrorKind::Interrupted => QdnfError::WouldBlock,
43        ErrorKind::UnexpectedEof
44        | ErrorKind::BrokenPipe
45        | ErrorKind::ConnectionReset
46        | ErrorKind::ConnectionAborted
47        | ErrorKind::NotConnected => QdnfError::Closed,
48        ErrorKind::InvalidData => QdnfError::Malformed,
49        ErrorKind::InvalidInput => QdnfError::Capacity,
50        ErrorKind::AlreadyExists => QdnfError::Conflict,
51        ErrorKind::PermissionDenied => QdnfError::Denied,
52        ErrorKind::TimedOut => QdnfError::Expired,
53        _ => QdnfError::Closed,
54    }
55}
56
57/// Wrap a QDNF outcome as `io::Error` so existing `send_datagram` callers keep
58/// `io::Result`. Bearer paths downcast via [`map_io`].
59pub fn io_from_qdnf(err: QdnfError) -> std::io::Error {
60    let kind = match err {
61        QdnfError::WouldBlock => ErrorKind::WouldBlock,
62        QdnfError::Closed => ErrorKind::ConnectionAborted,
63        QdnfError::Capacity | QdnfError::Range => ErrorKind::InvalidInput,
64        QdnfError::Malformed
65        | QdnfError::Truncated
66        | QdnfError::Unsupported
67        | QdnfError::StaleGeneration
68        | QdnfError::Unauthorized => ErrorKind::InvalidData,
69        QdnfError::EntropyFailure => ErrorKind::Other,
70        QdnfError::Conflict => ErrorKind::AlreadyExists,
71        QdnfError::Denied => ErrorKind::PermissionDenied,
72        _ => ErrorKind::Other,
73    };
74    std::io::Error::new(kind, err)
75}
76
77struct WsHeader {
78    opcode: u8,
79    masked: bool,
80    mask: [u8; 4],
81    hdr_len: usize,
82    payload_len: usize,
83}
84
85/// Header size from the first two bytes. Refuses RSV, FIN=0, 8-byte length,
86/// and opcodes other than binary/close.
87fn header_need(b0: u8, b1: u8) -> Result<usize, QdnfError> {
88    if b0 & 0x70 != 0 {
89        return Err(QdnfError::Malformed);
90    }
91    if b0 & 0x80 == 0 {
92        return Err(QdnfError::Unsupported);
93    }
94    let opcode = b0 & 0x0f;
95    if opcode != OP_BINARY && opcode != OP_CLOSE {
96        return Err(QdnfError::Unsupported);
97    }
98    let len7 = b1 & 0x7f;
99    if len7 == 127 {
100        return Err(QdnfError::Unsupported);
101    }
102    let mut n = 2usize;
103    if len7 == 126 {
104        n += 2;
105    }
106    if b1 & 0x80 != 0 {
107        n += 4;
108    }
109    Ok(n)
110}
111
112fn parse_header(buf: &[u8]) -> Result<WsHeader, QdnfError> {
113    if buf.len() < 2 {
114        return Err(QdnfError::Truncated);
115    }
116    let hdr_len = header_need(buf[0], buf[1])?;
117    if buf.len() < hdr_len {
118        return Err(QdnfError::Truncated);
119    }
120    let len7 = buf[1] & 0x7f;
121    let payload_len = if len7 == 126 {
122        u16::from_be_bytes([buf[2], buf[3]]) as usize
123    } else {
124        len7 as usize
125    };
126    if payload_len > MAX_FRAME {
127        return Err(QdnfError::Capacity);
128    }
129    let masked = buf[1] & 0x80 != 0;
130    let mut mask = [0u8; 4];
131    if masked {
132        let off = hdr_len - 4;
133        mask.copy_from_slice(&buf[off..hdr_len]);
134    }
135    Ok(WsHeader {
136        opcode: buf[0] & 0x0f,
137        masked,
138        mask,
139        hdr_len,
140        payload_len,
141    })
142}
143
144/// Encode one FIN binary/close frame into `out`. Never uses 8-byte length.
145pub fn encode_ws_frame(
146    out: &mut [u8],
147    opcode: u8,
148    payload: &[u8],
149    mask: Option<[u8; 4]>,
150) -> Result<usize, QdnfError> {
151    if opcode != OP_BINARY && opcode != OP_CLOSE {
152        return Err(QdnfError::Unsupported);
153    }
154    if payload.len() > MAX_FRAME || payload.len() > 0xffff {
155        return Err(QdnfError::Capacity);
156    }
157    let mut n = 2usize;
158    if payload.len() >= 126 {
159        n += 2;
160    }
161    if mask.is_some() {
162        n += 4;
163    }
164    let total = n.checked_add(payload.len()).ok_or(QdnfError::Range)?;
165    if out.len() < total {
166        return Err(QdnfError::Capacity);
167    }
168    out[0] = 0x80 | opcode;
169    if payload.len() < 126 {
170        out[1] = payload.len() as u8;
171    } else {
172        out[1] = 126;
173        out[2..4].copy_from_slice(&(payload.len() as u16).to_be_bytes());
174    }
175    if let Some(m) = mask {
176        out[1] |= 0x80;
177        let mask_off = n - 4;
178        out[mask_off..n].copy_from_slice(&m);
179        for (i, b) in payload.iter().enumerate() {
180            out[n + i] = b ^ m[i % 4];
181        }
182    } else if !payload.is_empty() {
183        out[n..total].copy_from_slice(payload);
184    }
185    Ok(total)
186}
187
188/// Sealed pending write. WouldBlock retains exact wire bytes; `off` advances
189/// only on `Ok(n > 0)`. A different payload while pending is Conflict.
190pub struct WriteCursor {
191    buf: [u8; WIRE_CAP],
192    len: u16,
193    off: u16,
194}
195
196impl WriteCursor {
197    /// Empty cursor.
198    pub const fn new() -> Self {
199        Self {
200            buf: [0u8; WIRE_CAP],
201            len: 0,
202            off: 0,
203        }
204    }
205
206    /// `true` while a sealed frame is not fully accepted.
207    #[inline]
208    pub const fn pending(&self) -> bool {
209        self.len != 0
210    }
211
212    /// Bytes the sink has accepted.
213    #[inline]
214    pub const fn accepted(&self) -> usize {
215        self.off as usize
216    }
217
218    /// Sealed wire length, including the WS header and mask.
219    #[inline]
220    pub const fn sealed_len(&self) -> usize {
221        self.len as usize
222    }
223
224    /// Exact sealed bytes. Empty when idle.
225    #[inline]
226    pub fn sealed_bytes(&self) -> &[u8] {
227        &self.buf[..self.len as usize]
228    }
229
230    /// Opcode of the sealed frame.
231    #[inline]
232    pub fn sealed_opcode(&self) -> Option<u8> {
233        if self.len == 0 {
234            None
235        } else {
236            Some(self.buf[0] & 0x0f)
237        }
238    }
239
240    /// Mask bytes of a sealed client frame.
241    pub fn client_mask(&self) -> Option<[u8; 4]> {
242        if self.len < 2 || self.buf[1] & 0x80 == 0 {
243            return None;
244        }
245        parse_header(&self.buf[..self.len as usize])
246            .ok()
247            .map(|h| h.mask)
248    }
249
250    /// Seal `payload` as a FIN frame. Same opcode+payload while pending
251    /// resumes (mask argument is ignored). A different payload is Conflict
252    /// and does not reseal or rewind `off`.
253    pub fn seal(
254        &mut self,
255        opcode: u8,
256        payload: &[u8],
257        mask: Option<[u8; 4]>,
258    ) -> Result<(), QdnfError> {
259        if self.len != 0 {
260            if self.sealed_opcode() == Some(opcode) && self.unmasked_payload_eq(payload) {
261                return Ok(());
262            }
263            return Err(QdnfError::Conflict);
264        }
265        let n = encode_ws_frame(&mut self.buf, opcode, payload, mask)?;
266        self.len = n as u16;
267        self.off = 0;
268        Ok(())
269    }
270
271    /// Write remaining sealed bytes. Advances `off` only on `Ok(n > 0)`.
272    pub fn flush<W: Write + ?Sized>(&mut self, sink: &mut W) -> Result<(), QdnfError> {
273        if self.len == 0 {
274            return Ok(());
275        }
276        while (self.off as usize) < (self.len as usize) {
277            let remaining = &self.buf[self.off as usize..self.len as usize];
278            match sink.write(remaining) {
279                Ok(0) => return Err(QdnfError::WouldBlock),
280                Ok(n) => {
281                    if n > remaining.len() {
282                        return Err(QdnfError::Range);
283                    }
284                    self.off += n as u16;
285                }
286                Err(e) if e.kind() == ErrorKind::Interrupted => continue,
287                Err(e) if e.kind() == ErrorKind::WouldBlock => {
288                    return Err(QdnfError::WouldBlock);
289                }
290                Err(e) => return Err(map_io(e)),
291            }
292        }
293        self.abort();
294        Ok(())
295    }
296
297    /// Drop sealed bytes without sending.
298    pub fn abort(&mut self) {
299        self.len = 0;
300        self.off = 0;
301    }
302
303    fn unmasked_payload_eq(&self, payload: &[u8]) -> bool {
304        let hdr = match parse_header(&self.buf[..self.len as usize]) {
305            Ok(h) => h,
306            Err(_) => return false,
307        };
308        let start = hdr.hdr_len;
309        let end = self.len as usize;
310        if end < start || end - start != payload.len() {
311            return false;
312        }
313        let body = &self.buf[start..end];
314        if hdr.masked {
315            body.iter()
316                .enumerate()
317                .all(|(i, b)| *b ^ hdr.mask[i % 4] == payload[i])
318        } else {
319            body == payload
320        }
321    }
322}
323
324impl Default for WriteCursor {
325    fn default() -> Self {
326        Self::new()
327    }
328}
329
330/// Partial-read assembly. Oversize / 8-byte / fragmented poisons the cursor.
331/// A short `out` after a complete frame is Capacity and does not drop it.
332pub struct ReadCursor {
333    buf: [u8; WIRE_CAP],
334    filled: u16,
335    expected: u16,
336    hdr: u8,
337    opcode: u8,
338    complete: bool,
339    unmasked: bool,
340    refused: bool,
341}
342
343impl ReadCursor {
344    /// Empty cursor.
345    pub const fn new() -> Self {
346        Self {
347            buf: [0u8; WIRE_CAP],
348            filled: 0,
349            expected: 0,
350            hdr: 0,
351            opcode: 0,
352            complete: false,
353            unmasked: false,
354            refused: false,
355        }
356    }
357
358    /// Bytes buffered toward the current frame.
359    #[inline]
360    pub const fn filled(&self) -> usize {
361        self.filled as usize
362    }
363
364    /// `true` while a header or body is incomplete, or a complete frame is
365    /// waiting to be taken.
366    #[inline]
367    pub const fn pending(&self) -> bool {
368        self.filled != 0 || self.expected != 0 || self.complete
369    }
370
371    /// Sticky framing refusal.
372    #[inline]
373    pub const fn refused(&self) -> bool {
374        self.refused
375    }
376
377    /// Pull until one complete unmasked payload is copied into `out`.
378    /// `expect_masked`: `Some(true)` requires a mask, `Some(false)` forbids it,
379    /// `None` accepts either.
380    pub fn recv<R: Read + ?Sized>(
381        &mut self,
382        src: &mut R,
383        out: &mut [u8],
384        expect_masked: Option<bool>,
385    ) -> Result<(u8, usize), QdnfError> {
386        if self.refused {
387            return Err(QdnfError::Capacity);
388        }
389        self.assemble(src, expect_masked)?;
390        let hdr_len = self.hdr as usize;
391        let payload_len = self.expected as usize - hdr_len;
392        if out.len() < payload_len {
393            return Err(QdnfError::Capacity);
394        }
395        if payload_len != 0 {
396            out[..payload_len].copy_from_slice(&self.buf[hdr_len..hdr_len + payload_len]);
397        }
398        let opcode = self.opcode;
399        self.reset();
400        Ok((opcode, payload_len))
401    }
402
403    /// Drop partial assembly. Does not clear oversize poison.
404    pub fn abort(&mut self) {
405        self.filled = 0;
406        self.expected = 0;
407        self.hdr = 0;
408        self.opcode = 0;
409        self.complete = false;
410        self.unmasked = false;
411    }
412
413    fn reset(&mut self) {
414        self.abort();
415    }
416
417    fn refuse(&mut self) {
418        self.abort();
419        self.refused = true;
420    }
421
422    fn assemble<R: Read + ?Sized>(
423        &mut self,
424        src: &mut R,
425        expect_masked: Option<bool>,
426    ) -> Result<(), QdnfError> {
427        if self.complete {
428            return Ok(());
429        }
430        if self.expected == 0 {
431            self.pull(src, 2)?;
432            let need = match header_need(self.buf[0], self.buf[1]) {
433                Ok(n) => n,
434                Err(e) => {
435                    self.refuse();
436                    return Err(e);
437                }
438            };
439            self.pull(src, need)?;
440            let hdr = match parse_header(&self.buf[..need]) {
441                Ok(h) => h,
442                Err(e) => {
443                    self.refuse();
444                    return Err(e);
445                }
446            };
447            if let Some(expect) = expect_masked {
448                if hdr.masked != expect {
449                    self.refuse();
450                    return Err(QdnfError::Malformed);
451                }
452            }
453            if hdr.payload_len > MAX_FRAME {
454                self.refuse();
455                return Err(QdnfError::Capacity);
456            }
457            let total = hdr
458                .hdr_len
459                .checked_add(hdr.payload_len)
460                .ok_or(QdnfError::Range)?;
461            if total > WIRE_CAP {
462                self.refuse();
463                return Err(QdnfError::Capacity);
464            }
465            self.hdr = hdr.hdr_len as u8;
466            self.opcode = hdr.opcode;
467            self.expected = total as u16;
468        }
469        self.pull(src, self.expected as usize)?;
470        if !self.unmasked {
471            let start = self.hdr as usize;
472            let hdr = parse_header(&self.buf[..start]).map_err(|e| {
473                self.refuse();
474                e
475            })?;
476            if hdr.masked {
477                let body = &mut self.buf[start..self.expected as usize];
478                for (i, b) in body.iter_mut().enumerate() {
479                    *b ^= hdr.mask[i % 4];
480                }
481            }
482            self.unmasked = true;
483        }
484        self.complete = true;
485        Ok(())
486    }
487
488    fn pull<R: Read + ?Sized>(&mut self, src: &mut R, want: usize) -> Result<(), QdnfError> {
489        while (self.filled as usize) < want {
490            let dest = &mut self.buf[self.filled as usize..want];
491            match src.read(dest) {
492                Ok(0) => {
493                    let idle = self.filled == 0 && self.expected == 0 && !self.complete;
494                    self.abort();
495                    return Err(if idle {
496                        QdnfError::Closed
497                    } else {
498                        QdnfError::Truncated
499                    });
500                }
501                Ok(n) => {
502                    if n > dest.len() {
503                        return Err(QdnfError::Range);
504                    }
505                    self.filled += n as u16;
506                }
507                Err(e) if e.kind() == ErrorKind::Interrupted => continue,
508                Err(e) if e.kind() == ErrorKind::WouldBlock => {
509                    return Err(QdnfError::WouldBlock);
510                }
511                Err(e) => return Err(map_io(e)),
512            }
513        }
514        Ok(())
515    }
516}
517
518impl Default for ReadCursor {
519    fn default() -> Self {
520        Self::new()
521    }
522}