Skip to main content

qualia_core_db/net/peer/fabric/wire/
mod.rs

1//! CSCP v1 TLV helpers. `draft-webcivics-cscp-00` §4.
2
3use super::carrier::PathClass;
4use super::contact::LocatorKind;
5use super::kernel::FabricError;
6use crate::net::peer::connectivity::policy::Disclosure;
7
8pub const MAGIC: &[u8; 4] = b"CSCP";
9pub const VERSION: u8 = 1;
10pub const MAX_BODY: usize = 1024;
11pub const MAX_FIELDS: usize = 16;
12pub const TAG_CRITICAL: u8 = 0x80;
13
14pub const MSG_CONNECT_REQUEST: u8 = 1;
15pub const MSG_CONTACT: u8 = 2;
16pub const MSG_RELAY_LEASE: u8 = 3;
17pub const MSG_CUSTODY_LEASE: u8 = 4;
18pub const MSG_PATH_EVIDENCE: u8 = 5;
19pub const MSG_RECEIPT: u8 = 6;
20pub const MSG_CONNECT_ACCEPT: u8 = 7;
21pub const MSG_CONNECT_REJECT: u8 = 8;
22
23pub const TAG_PEER: u8 = 1;
24pub const TAG_PURPOSE: u8 = 2;
25pub const TAG_PROTECTION: u8 = 3;
26pub const TAG_BUDGET: u8 = 4;
27pub const TAG_DEADLINE: u8 = 5;
28pub const TAG_AUTHORITY: u8 = 6;
29
30mod connect_msg;
31mod records;
32
33pub use connect_msg::{connect_from_wire, decode_connect_request, encode_connect_request};
34pub use records::{
35    decode_accept, decode_contact, decode_custody, decode_evidence, decode_receipt, decode_reject,
36    decode_relay_lease, encode_accept, encode_contact, encode_custody, encode_evidence,
37    encode_receipt, encode_reject, encode_relay_lease, RejectReason,
38};
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum CscpError {
42    Truncated,
43    BadMagic,
44    UnknownCritical,
45    Duplicate,
46    Capacity,
47    Policy,
48    Malformed,
49}
50
51impl From<CscpError> for FabricError {
52    fn from(e: CscpError) -> Self {
53        match e {
54            CscpError::Policy => FabricError::PolicyDenied,
55            CscpError::Capacity => FabricError::Capacity,
56            _ => FabricError::Illegal,
57        }
58    }
59}
60
61/// Maps a `Disclosure` level to its wire byte.
62pub fn disclosure_byte(d: Disclosure) -> u8 {
63    match d {
64        Disclosure::DirectPermitted => 1,
65        Disclosure::ApprovedRelaysOnly => 2,
66        Disclosure::QualifiedMultiHop => 3,
67        Disclosure::Isolated => 4,
68    }
69}
70
71/// Decodes a `Disclosure` from its wire byte; `CscpError` on an unknown value — fails closed.
72pub fn disclosure_from(b: u8) -> Result<Disclosure, CscpError> {
73    match b {
74        1 => Ok(Disclosure::DirectPermitted),
75        2 => Ok(Disclosure::ApprovedRelaysOnly),
76        3 => Ok(Disclosure::QualifiedMultiHop),
77        4 => Ok(Disclosure::Isolated),
78        _ => Err(CscpError::Policy),
79    }
80}
81
82/// Maps a `PathClass` to its wire byte.
83pub fn path_class_byte(c: PathClass) -> u8 {
84    match c {
85        PathClass::DirectV6 => 1,
86        PathClass::DirectV4 => 2,
87        PathClass::Relayed => 3,
88        PathClass::BrowserGateway => 4,
89        PathClass::Offline => 5,
90    }
91}
92
93/// Decodes a `PathClass` from its wire byte; fails closed on unknown.
94pub fn path_class_from(b: u8) -> Result<PathClass, CscpError> {
95    match b {
96        1 => Ok(PathClass::DirectV6),
97        2 => Ok(PathClass::DirectV4),
98        3 => Ok(PathClass::Relayed),
99        4 => Ok(PathClass::BrowserGateway),
100        5 => Ok(PathClass::Offline),
101        _ => Err(CscpError::Malformed),
102    }
103}
104
105/// Maps a `LocatorKind` to its wire byte.
106pub fn locator_kind_byte(k: LocatorKind) -> u8 {
107    match k {
108        LocatorKind::Mailbox => 1,
109        LocatorKind::RelayHint => 2,
110        LocatorKind::Direct => 3,
111    }
112}
113
114/// Decodes a `LocatorKind` from its wire byte; fails closed on unknown.
115pub fn locator_kind_from(b: u8) -> Result<LocatorKind, CscpError> {
116    match b {
117        1 => Ok(LocatorKind::Mailbox),
118        2 => Ok(LocatorKind::RelayHint),
119        3 => Ok(LocatorKind::Direct),
120        _ => Err(CscpError::Malformed),
121    }
122}
123
124/// Writes the fixed CSCP message header (type byte + big-endian body length) into `out`.
125pub(crate) fn header(out: &mut [u8], msg: u8, body_len: u16) -> Result<usize, CscpError> {
126    if out.len() < 10 {
127        return Err(CscpError::Capacity);
128    }
129    out[..4].copy_from_slice(MAGIC);
130    out[4] = VERSION;
131    out[5] = msg;
132    out[6] = 0;
133    out[7] = 0;
134    out[8..10].copy_from_slice(&body_len.to_be_bytes());
135    Ok(10)
136}
137
138/// Appends one tag/length/value triple into `out`; errors when the buffer is too small.
139pub(crate) fn write_tlv(out: &mut [u8], tag: u8, val: &[u8]) -> Result<usize, CscpError> {
140    let n = 3 + val.len();
141    if out.len() < n {
142        return Err(CscpError::Capacity);
143    }
144    out[0] = tag;
145    out[1..3].copy_from_slice(&(val.len() as u16).to_be_bytes());
146    out[3..n].copy_from_slice(val);
147    Ok(n)
148}
149
150/// Validates the header and returns the body slice; `Malformed`/`Unsupported` on wrong type or truncation.
151pub(crate) fn parse_header(bytes: &[u8], expect: u8) -> Result<&[u8], CscpError> {
152    if bytes.len() < 10 {
153        return Err(CscpError::Truncated);
154    }
155    if &bytes[..4] != MAGIC || bytes[4] != VERSION {
156        return Err(CscpError::BadMagic);
157    }
158    if bytes[5] != expect {
159        return Err(CscpError::Policy);
160    }
161    if bytes[6] != 0 || bytes[7] != 0 {
162        return Err(CscpError::Malformed);
163    }
164    let blen = u16::from_be_bytes([bytes[8], bytes[9]]) as usize;
165    if blen > MAX_BODY || 10 + blen > bytes.len() {
166        return Err(CscpError::Capacity);
167    }
168    Ok(&bytes[10..10 + blen])
169}
170
171/// Iterates body TLVs, invoking `f(tag, val)` per entry; fails closed on truncated length fields.
172pub(crate) fn walk_tlvs(
173    body: &[u8],
174    known: fn(u8) -> bool,
175    mut visit: impl FnMut(u8, &[u8]) -> Result<(), CscpError>,
176) -> Result<(), CscpError> {
177    let mut seen = [false; 16];
178    let mut i = 0usize;
179    let mut fields = 0usize;
180    while i < body.len() {
181        if i + 3 > body.len() || fields >= MAX_FIELDS {
182            return Err(CscpError::Truncated);
183        }
184        let tag = body[i];
185        let len = u16::from_be_bytes([body[i + 1], body[i + 2]]) as usize;
186        i += 3;
187        if i + len > body.len() {
188            return Err(CscpError::Truncated);
189        }
190        let val = &body[i..i + len];
191        i += len;
192        let idx = (tag & 0x7f) as usize;
193        if idx < seen.len() {
194            if seen[idx] {
195                return Err(CscpError::Duplicate);
196            }
197            seen[idx] = true;
198        }
199        if tag & TAG_CRITICAL != 0 && !known(tag & 0x7f) {
200            return Err(CscpError::UnknownCritical);
201        }
202        visit(tag & 0x7f, val)?;
203        fields += 1;
204    }
205    Ok(())
206}
207
208/// As `walk_tlvs` plus a seen-tag bitmask for required-field validation.
209pub(crate) fn walk_tlvs_seen(
210    body: &[u8],
211    known: fn(u8) -> bool,
212    mut visit: impl FnMut(u8, &[u8]) -> Result<(), CscpError>,
213) -> Result<u16, CscpError> {
214    let mut seen_mask = 0u16;
215    walk_tlvs(body, known, |tag, val| {
216        if tag < 16 {
217            seen_mask |= 1u16 << tag;
218        }
219        visit(tag, val)
220    })?;
221    Ok(seen_mask)
222}
223
224/// `Ok` when every tag in `tags` appears in the `seen` bitmask, else `Incomplete`.
225pub(crate) fn require_tags(seen: u16, tags: &[u8]) -> Result<(), CscpError> {
226    for &t in tags {
227        if t >= 16 || seen & (1u16 << t) == 0 {
228            return Err(CscpError::Malformed);
229        }
230    }
231    Ok(())
232}
233
234/// Writes header + body as a complete message; returns total length.
235pub(crate) fn finish(out: &mut [u8], msg: u8, body: &[u8]) -> Result<usize, CscpError> {
236    if body.len() > MAX_BODY || 10 + body.len() > out.len() {
237        return Err(CscpError::Capacity);
238    }
239    header(out, msg, body.len() as u16)?;
240    out[10..10 + body.len()].copy_from_slice(body);
241    Ok(10 + body.len())
242}
243
244/// Decodes a big-endian u64; `Malformed` on short input.
245pub(crate) fn u64_be(v: &[u8]) -> Result<u64, CscpError> {
246    if v.len() != 8 {
247        return Err(CscpError::Malformed);
248    }
249    let mut b = [0u8; 8];
250    b.copy_from_slice(v);
251    Ok(u64::from_be_bytes(b))
252}
253
254/// Decodes a big-endian u32; `Malformed` on short input.
255pub(crate) fn u32_be(v: &[u8]) -> Result<u32, CscpError> {
256    if v.len() != 4 {
257        return Err(CscpError::Malformed);
258    }
259    let mut b = [0u8; 4];
260    b.copy_from_slice(v);
261    Ok(u32::from_be_bytes(b))
262}
263
264/// Decodes a big-endian u16; `Malformed` on short input.
265pub(crate) fn u16_be(v: &[u8]) -> Result<u16, CscpError> {
266    if v.len() != 2 {
267        return Err(CscpError::Malformed);
268    }
269    Ok(u16::from_be_bytes([v[0], v[1]]))
270}