Skip to main content

bytepeel_core/
node.rs

1//! The decoded tree.
2//!
3//! Every `range` is a half-open `[start, end)` byte range into the buffer the
4//! node or field was parsed from. A `Layer` node starts a new buffer (its
5//! `decoded` bytes) for its child; a string's `decoded` node starts a new
6//! buffer at that string's bytes.
7
8use crate::Diag;
9use crate::value::Value;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum Alphabet {
13    Std,
14    Url,
15}
16
17impl Alphabet {
18    pub fn name(self) -> &'static str {
19        match self {
20            Alphabet::Std => "std",
21            Alphabet::Url => "url",
22        }
23    }
24}
25
26#[derive(Debug, Clone, PartialEq)]
27pub enum Codec {
28    Hex,
29    /// A hex dump with an offset column (`style` is `xxd` or `hexdump`).
30    /// `start` is the decimal offset the first line starts at (nonzero for
31    /// `xxd -s` / `hexdump -s`); child ranges stay 0-based.
32    Dump {
33        style: &'static str,
34        start: usize,
35    },
36    Base64 {
37        alphabet: Alphabet,
38        padded: bool,
39    },
40    Pem {
41        label: String,
42    },
43    /// Two or more PEM blocks: a certificate chain or a key + cert file.
44    Bundle,
45    /// A JSON Web Token; `kind` is `jws` (3 parts) or `jwe` (5 parts).
46    Jwt {
47        kind: &'static str,
48    },
49    /// gzip; `name` is the original file name from the header, if any.
50    Gzip {
51        name: Option<String>,
52    },
53    Zlib,
54    Zstd,
55    Protobuf,
56    Der,
57    /// CBOR (RFC 8949): a sequence of one or more [`Value`]s.
58    Cbor,
59    /// MessagePack: a sequence of one or more [`Value`]s.
60    Msgpack,
61    Utf8,
62    Bytes,
63}
64
65impl Codec {
66    pub fn name(&self) -> &'static str {
67        match self {
68            Codec::Hex => "hex",
69            Codec::Dump { .. } => "dump",
70            Codec::Base64 { .. } => "base64",
71            Codec::Pem { .. } => "pem",
72            Codec::Bundle => "bundle",
73            Codec::Jwt { .. } => "jwt",
74            Codec::Gzip { .. } => "gzip",
75            Codec::Zlib => "zlib",
76            Codec::Zstd => "zstd",
77            Codec::Protobuf => "protobuf",
78            Codec::Der => "der",
79            Codec::Cbor => "cbor",
80            Codec::Msgpack => "msgpack",
81            Codec::Utf8 => "utf8",
82            Codec::Bytes => "bytes",
83        }
84    }
85}
86
87#[derive(Debug, Clone, PartialEq)]
88pub struct Node {
89    pub codec: Codec,
90    pub range: [usize; 2],
91    /// How confident the detector is in `codec` (0..=1).
92    pub confidence: f64,
93    pub detail: Detail,
94    pub warnings: Vec<Diag>,
95}
96
97/// Bytes kept in a [`Detail::Bytes`] leaf for its preview.
98pub const BYTES_HEAD: usize = 64;
99
100/// Characters kept in a [`Detail::Text`] leaf.
101pub const TEXT_HEAD: usize = 1024;
102
103#[derive(Debug, Clone, PartialEq)]
104pub enum Detail {
105    /// A text encoding (hex/base64/PEM); `child` describes the decoded bytes.
106    Layer { decoded: Vec<u8>, child: Box<Node> },
107    /// A protobuf message.
108    Message { fields: Vec<Field> },
109    /// DER-encoded ASN.1: one or more top-level elements.
110    Der { items: Vec<Asn1> },
111    /// CBOR or MessagePack: normally one top-level value; a sequence may have
112    /// several when forced with `--as cbor` / `--as msgpack`.
113    Values { items: Vec<Value> },
114    /// A JWT or a PEM bundle: one node per part (base64 segments, or PEM
115    /// blocks). `times` is `Detail::Parts`' only JWT-specific field: the
116    /// top-level time claims of a JWS payload (`exp`, `nbf`, `iat`), in that
117    /// order, as `(claim, ISO-8601 UTC)`; it is empty for bundles.
118    Parts {
119        parts: Vec<Node>,
120        times: Vec<(&'static str, String)>,
121    },
122    /// Printable UTF-8 text. Only the first [`TEXT_HEAD`] characters are kept
123    /// (what the JSON shows): the full text is the parent's bytes, so a large
124    /// text is not stored twice.
125    Text {
126        /// The first `TEXT_HEAD` characters (all of a shorter text).
127        text: String,
128        /// Byte length of the whole text; `text` is all of it when equal.
129        len: usize,
130    },
131    /// Opaque bytes (nothing more specific was found, or the format is not
132    /// supported). Only the first [`BYTES_HEAD`] bytes are kept, for the
133    /// preview: the full bytes are the parent's (the input, a layer's
134    /// `decoded`, a field's or value's data), so a large leaf is not stored twice.
135    Bytes {
136        /// Length of the whole leaf.
137        len: usize,
138        /// Its first `min(len, BYTES_HEAD)` bytes.
139        head: Vec<u8>,
140    },
141}
142
143#[derive(Debug, Clone, PartialEq)]
144pub struct Field {
145    pub number: u32,
146    /// Range of the whole field, tag included.
147    pub range: [usize; 2],
148    pub value: FieldValue,
149}
150
151#[derive(Debug, Clone, PartialEq)]
152pub enum FieldValue {
153    Varint {
154        raw: Vec<u8>,
155        value: u64,
156    },
157    I64 {
158        value: u64,
159    },
160    I32 {
161        value: u32,
162    },
163    Len {
164        data_range: [usize; 2],
165        data: Vec<u8>,
166        /// Interpretations, best first. Scores sum to ~1 before truncation.
167        alts: Vec<Alt>,
168    },
169    Group {
170        fields: Vec<Field>,
171    },
172}
173
174impl FieldValue {
175    pub fn wire_name(&self) -> &'static str {
176        match self {
177            FieldValue::Varint { .. } => "VARINT",
178            FieldValue::I64 { .. } => "I64",
179            FieldValue::I32 { .. } => "I32",
180            FieldValue::Len { .. } => "LEN",
181            FieldValue::Group { .. } => "GROUP",
182        }
183    }
184}
185
186impl Field {
187    /// The field's payload bytes (tag excluded). `None` for groups.
188    pub fn payload(&self) -> Option<Vec<u8>> {
189        match &self.value {
190            FieldValue::Varint { raw, .. } => Some(raw.clone()),
191            FieldValue::I64 { value } => Some(value.to_le_bytes().to_vec()),
192            FieldValue::I32 { value } => Some(value.to_le_bytes().to_vec()),
193            FieldValue::Len { data, .. } => Some(data.clone()),
194            FieldValue::Group { .. } => None,
195        }
196    }
197}
198
199#[derive(Debug, Clone, PartialEq)]
200pub struct Alt {
201    pub kind: AltKind,
202    pub score: f64,
203}
204
205#[derive(Debug, Clone, PartialEq)]
206pub enum AltKind {
207    Message(Vec<Field>),
208    String {
209        text: String,
210        /// Set when the string itself decodes further (e.g. it is base64).
211        decoded: Option<Box<Node>>,
212    },
213    PackedVarint(Vec<u64>),
214    /// Little-endian 4-byte values (packed `fixed32` / `sfixed32` / `float`).
215    PackedFixed32(Vec<u32>),
216    /// Little-endian 8-byte values (packed `fixed64` / `sfixed64` / `double`).
217    PackedFixed64(Vec<u64>),
218    Bytes {
219        /// Set when the raw bytes are themselves another format (compressed,
220        /// DER, CBOR/MessagePack); see `docs/DESIGN.md` for the threshold.
221        decoded: Option<Box<Node>>,
222    },
223    Empty,
224}
225
226impl AltKind {
227    pub fn name(&self) -> &'static str {
228        match self {
229            AltKind::Message(_) => "message",
230            AltKind::String { .. } => "string",
231            AltKind::PackedVarint(_) => "packed_varint",
232            AltKind::PackedFixed32(_) => "packed_fixed32",
233            AltKind::PackedFixed64(_) => "packed_fixed64",
234            AltKind::Bytes { .. } => "bytes",
235            AltKind::Empty => "empty",
236        }
237    }
238}
239
240/// ASN.1 tag class.
241#[derive(Debug, Clone, Copy, PartialEq, Eq)]
242pub enum TagClass {
243    Universal,
244    Application,
245    Context,
246    Private,
247}
248
249/// One DER element (tag, length, value).
250#[derive(Debug, Clone, PartialEq)]
251pub struct Asn1 {
252    pub class: TagClass,
253    pub number: u32,
254    pub constructed: bool,
255    /// Range of the whole element, header included.
256    pub range: [usize; 2],
257    /// Range of the content (header excluded).
258    pub content: [usize; 2],
259    /// Content bytes of a primitive element (empty when constructed).
260    pub raw: Vec<u8>,
261    pub value: Asn1Value,
262}
263
264#[derive(Debug, Clone, PartialEq)]
265pub enum Asn1Value {
266    /// A constructed element (SEQUENCE, SET, `[0]`, ...).
267    Constructed(Vec<Asn1>),
268    /// A BIT STRING or OCTET STRING whose content is itself DER.
269    /// `unused_bits` is `Some(0)` for a BIT STRING.
270    Encapsulated {
271        unused_bits: Option<u8>,
272        items: Vec<Asn1>,
273    },
274    Bool(bool),
275    /// INTEGER or ENUMERATED; the value is `raw` (big-endian two's complement).
276    Int,
277    Null,
278    /// OBJECT IDENTIFIER or RELATIVE-OID in dotted form.
279    Oid(String),
280    /// A character string, decoded per its type.
281    Text(String),
282    /// UTCTime or GeneralizedTime; `iso` is set when the value is well formed.
283    Time {
284        text: String,
285        iso: Option<String>,
286    },
287    /// A BIT STRING that is not itself DER; the bits are `raw[1..]`.
288    BitString {
289        unused_bits: u8,
290    },
291    /// Anything else; the content is `raw`.
292    Bytes,
293}
294
295impl Asn1 {
296    /// Human-readable tag, e.g. `SEQUENCE`, `[0]`, `[APPLICATION 3]`.
297    pub fn tag_name(&self) -> String {
298        match self.class {
299            TagClass::Universal => match crate::der::universal_name(self.number) {
300                Some(n) => n.to_string(),
301                None => format!("[UNIVERSAL {}]", self.number),
302            },
303            TagClass::Application => format!("[APPLICATION {}]", self.number),
304            TagClass::Context => format!("[{}]", self.number),
305            TagClass::Private => format!("[PRIVATE {}]", self.number),
306        }
307    }
308
309    /// The element's payload: content bytes, minus the unused-bits byte for a
310    /// BIT STRING. `None` for constructed elements.
311    pub fn payload(&self) -> Option<Vec<u8>> {
312        if self.constructed {
313            return None;
314        }
315        match self.value {
316            Asn1Value::BitString { .. }
317            | Asn1Value::Encapsulated {
318                unused_bits: Some(_),
319                ..
320            } => Some(self.raw.get(1..).unwrap_or_default().to_vec()),
321            _ => Some(self.raw.clone()),
322        }
323    }
324
325    /// Child elements, for constructed or encapsulating elements.
326    pub fn children(&self) -> Option<&[Asn1]> {
327        match &self.value {
328            Asn1Value::Constructed(items) | Asn1Value::Encapsulated { items, .. } => Some(items),
329            _ => None,
330        }
331    }
332}