1use crate::{Alphabet, Diag};
4
5pub(crate) fn is_printable(t: &str) -> bool {
7 t.chars().all(printable_char)
8}
9
10pub(crate) fn printable_ratio(t: &str) -> f64 {
12 let (mut total, mut ok) = (0usize, 0usize);
13 for c in t.chars() {
14 total += 1;
15 if printable_char(c) {
16 ok += 1;
17 }
18 }
19 if total == 0 {
20 1.0
21 } else {
22 ok as f64 / total as f64
23 }
24}
25
26fn printable_char(c: char) -> bool {
27 !c.is_control() || matches!(c, '\n' | '\r' | '\t')
28}
29
30pub(crate) struct HexInfo {
33 tokens: usize,
34 all_pairs: bool,
35 has_0x: bool,
36 all_decimal: bool,
37}
38
39fn is_hex_sep(c: u8) -> bool {
40 c.is_ascii_whitespace() || c == b':'
41}
42
43fn hex_val(c: u8) -> u8 {
44 match c {
45 b'0'..=b'9' => c - b'0',
46 b'a'..=b'f' => c - b'a' + 10,
47 _ => c - b'A' + 10,
48 }
49}
50
51pub(crate) fn hex_scan(s: &str) -> Result<(Vec<u8>, HexInfo), Diag> {
52 let base = s.len() - s.trim_start().len();
53 let b = s.trim().as_bytes();
54 let mut digits = Vec::with_capacity(b.len());
55 let mut info = HexInfo {
56 tokens: 0,
57 all_pairs: true,
58 has_0x: false,
59 all_decimal: true,
60 };
61 let mut i = 0;
62 while i < b.len() {
63 if is_hex_sep(b[i]) {
64 i += 1;
65 continue;
66 }
67 let start = i;
68 while i < b.len() && !is_hex_sep(b[i]) {
69 i += 1;
70 }
71 let mut tok_start = start;
72 if i - start >= 2 && b[start] == b'0' && (b[start + 1] | 0x20) == b'x' {
73 tok_start += 2;
74 info.has_0x = true;
75 }
76 let tok = &b[tok_start..i];
77 if tok.is_empty() {
78 continue;
79 }
80 if !tok.len().is_multiple_of(2) {
81 return Err(Diag::new(
82 "ODD_LENGTH",
83 "hex token has an odd number of digits",
84 Some(base + start),
85 ));
86 }
87 for (j, &c) in tok.iter().enumerate() {
88 if !c.is_ascii_hexdigit() {
89 return Err(Diag::new(
90 "INVALID_CHAR",
91 format!("byte 0x{c:02x} is not a hex digit"),
92 Some(base + tok_start + j),
93 ));
94 }
95 if !c.is_ascii_digit() {
96 info.all_decimal = false;
97 }
98 digits.push(c);
99 }
100 info.tokens += 1;
101 if tok.len() != 2 {
102 info.all_pairs = false;
103 }
104 }
105 if digits.is_empty() {
106 return Err(Diag::new("EMPTY", "no hex digits found", None));
107 }
108 let bytes = digits
109 .chunks_exact(2)
110 .map(|p| (hex_val(p[0]) << 4) | hex_val(p[1]))
111 .collect();
112 Ok((bytes, info))
113}
114
115pub fn decode_hex(s: &str) -> Result<Vec<u8>, Diag> {
118 hex_scan(s).map(|(b, _)| b)
119}
120
121pub(crate) fn hex_candidate(s: &str) -> Option<(Vec<u8>, f64)> {
122 let (bytes, info) = hex_scan(s).ok()?;
123 let mut conf = if info.has_0x || (info.tokens > 1 && info.all_pairs) {
124 0.95
125 } else if info.tokens > 1 {
126 0.85
127 } else if bytes.len() >= 4 {
128 0.9
129 } else {
130 0.6
131 };
132 if info.all_decimal && info.tokens == 1 && !info.has_0x && !s.trim().starts_with('0') {
135 conf *= 0.5;
136 }
137 Some((bytes, conf))
138}
139
140#[derive(Debug, Clone, PartialEq, Eq)]
144pub struct B64 {
145 pub alphabet: Alphabet,
146 pub padded: bool,
148 pub bytes: Vec<u8>,
149 pub noncanonical: bool,
151}
152
153pub fn decode_b64(s: &str) -> Result<B64, Diag> {
157 let base = s.len() - s.trim_start().len();
158 let t = s.trim();
159 let mut sextets: Vec<u8> = Vec::with_capacity(t.len());
160 let (mut std_at, mut url_at) = (None::<usize>, None::<usize>);
161 let (mut pad, mut pad_at) = (0usize, None::<usize>);
162 for (i, &c) in t.as_bytes().iter().enumerate() {
163 let off = base + i;
164 if c == b'\n' || c == b'\r' {
165 continue;
166 }
167 if c == b'=' {
168 pad += 1;
169 pad_at.get_or_insert(off);
170 continue;
171 }
172 if pad > 0 {
173 return Err(Diag::new(
174 "BAD_PADDING",
175 "data after '=' padding",
176 Some(off),
177 ));
178 }
179 let v = match c {
180 b'A'..=b'Z' => c - b'A',
181 b'a'..=b'z' => c - b'a' + 26,
182 b'0'..=b'9' => c - b'0' + 52,
183 b'+' | b'/' => {
184 std_at.get_or_insert(off);
185 if c == b'+' { 62 } else { 63 }
186 }
187 b'-' | b'_' => {
188 url_at.get_or_insert(off);
189 if c == b'-' { 62 } else { 63 }
190 }
191 _ => {
192 return Err(Diag::new(
193 "INVALID_CHAR",
194 format!("byte 0x{c:02x} is not a base64 character"),
195 Some(off),
196 ));
197 }
198 };
199 sextets.push(v);
200 }
201 if let (Some(_), Some(u)) = (std_at, url_at) {
202 return Err(Diag::new(
203 "MIXED_ALPHABET",
204 "mixes standard (+/) and URL-safe (-_) base64 characters",
205 Some(u),
206 ));
207 }
208 let n = sextets.len();
209 if n == 0 {
210 return Err(Diag::new("EMPTY", "no base64 characters found", None));
211 }
212 if n % 4 == 1 {
213 return Err(Diag::new(
214 "INVALID_LENGTH",
215 format!("{n} base64 characters cannot encode whole bytes"),
216 None,
217 ));
218 }
219 if pad > 0 && pad != (4 - n % 4) % 4 {
220 return Err(Diag::new(
221 "BAD_PADDING",
222 format!("{pad} '=' characters do not match the data length"),
223 pad_at,
224 ));
225 }
226 let mut out = Vec::with_capacity(n * 3 / 4);
227 let mut noncanonical = false;
228 for c in sextets.chunks(4) {
229 let s = |i: usize| u32::from(c[i]);
230 match c.len() {
231 4 => {
232 let v = (s(0) << 18) | (s(1) << 12) | (s(2) << 6) | s(3);
233 out.extend_from_slice(&[(v >> 16) as u8, (v >> 8) as u8, v as u8]);
234 }
235 3 => {
236 let v = (s(0) << 18) | (s(1) << 12) | (s(2) << 6);
237 out.extend_from_slice(&[(v >> 16) as u8, (v >> 8) as u8]);
238 noncanonical |= c[2] & 0x03 != 0;
239 }
240 _ => {
241 let v = (s(0) << 18) | (s(1) << 12);
242 out.push((v >> 16) as u8);
243 noncanonical |= c[1] & 0x0f != 0;
244 }
245 }
246 }
247 Ok(B64 {
248 alphabet: if url_at.is_some() {
249 Alphabet::Url
250 } else {
251 Alphabet::Std
252 },
253 padded: pad > 0 || n.is_multiple_of(4),
254 bytes: out,
255 noncanonical,
256 })
257}
258
259pub(crate) fn b64_candidate(s: &str) -> Option<(B64, f64)> {
260 let b = decode_b64(s).ok()?;
261 let t = s.trim();
262 let (mut len, mut digit, mut special, mut all_hex) = (0usize, false, false, true);
263 for c in t.bytes().filter(|c| !matches!(c, b'\n' | b'\r' | b'=')) {
264 len += 1;
265 digit |= c.is_ascii_digit();
266 special |= matches!(c, b'+' | b'/' | b'-' | b'_');
267 all_hex &= c.is_ascii_hexdigit();
268 }
269 let mut conf: f64 = 0.75;
270 if len >= 16 {
271 conf += 0.1;
272 }
273 if special || t.contains('=') {
274 conf += 0.1;
275 }
276 if !b.padded {
277 conf -= 0.05;
278 }
279 if b.noncanonical {
280 conf *= 0.3;
281 }
282 if all_hex {
283 conf *= 0.5;
284 }
285 if !digit && !special {
287 conf *= 0.6;
288 }
289 Some((b, conf.min(0.99)))
290}
291
292pub(crate) fn noncanonical_diag() -> Diag {
293 Diag::new(
294 "NONCANONICAL_BASE64",
295 "unused trailing bits are not zero; this may not really be base64",
296 None,
297 )
298}
299
300pub(crate) struct PemBlock {
304 pub label: String,
305 pub b64: B64,
306 pub range: [usize; 2],
308}
309
310pub(crate) struct PemBundle {
312 pub blocks: Vec<PemBlock>,
313 pub ignored: usize,
315 pub error: Option<Diag>,
318}
319
320pub(crate) fn decode_pem(s: &str) -> Option<Result<PemBundle, Diag>> {
328 const BEGIN: &str = "-----BEGIN ";
329 let mut blocks: Vec<PemBlock> = Vec::new();
330 let mut cursor = 0;
331 let mut stop_at = s.len();
332 let mut error: Option<Diag> = None;
333 while let Some(rel) = s[cursor..].find(BEGIN) {
334 let begin = cursor + rel;
335 let after = &s[begin + BEGIN.len()..];
336 let Some(label_end) = after.find("-----") else {
337 if blocks.is_empty() {
339 return None;
340 }
341 stop_at = begin;
342 break;
343 };
344 let label = &after[..label_end];
345 if label.contains('\n') {
346 if blocks.is_empty() {
347 return None;
348 }
349 stop_at = begin;
350 break;
351 }
352 let body_start = begin + BEGIN.len() + label_end + 5;
353 let end_marker = format!("-----END {label}-----");
354 let Some(rel_end) = s[body_start..].find(&end_marker) else {
355 let d = Diag::new(
356 "PEM_UNTERMINATED",
357 format!("missing {end_marker}"),
358 Some(begin),
359 );
360 if blocks.is_empty() {
361 return Some(Err(d));
362 }
363 stop_at = begin;
364 error = Some(d);
365 break;
366 };
367 let body: String = s[body_start..body_start + rel_end]
368 .lines()
369 .filter(|l| !l.contains(':')) .map(str::trim)
371 .collect();
372 let b64 = match decode_b64(&body) {
373 Ok(b) => b,
374 Err(mut e) => {
375 e.offset = Some(body_start);
376 if blocks.is_empty() {
377 return Some(Err(e));
378 }
379 stop_at = begin;
380 error = Some(e);
381 break;
382 }
383 };
384 let end = body_start + rel_end + end_marker.len();
385 blocks.push(PemBlock {
386 label: label.to_string(),
387 b64,
388 range: [begin, end],
389 });
390 cursor = end;
391 }
392 if blocks.is_empty() {
393 return None;
394 }
395 let ignored = count_ignored(s, &blocks, stop_at);
396 Some(Ok(PemBundle {
397 blocks,
398 ignored,
399 error,
400 }))
401}
402
403fn count_ignored(s: &str, blocks: &[PemBlock], limit: usize) -> usize {
407 let mut ignored = 0;
408 let mut cursor = 0;
409 for b in blocks {
410 if b.range[0] >= limit {
411 break;
412 }
413 ignored += non_ws(&s[cursor..b.range[0]]);
414 cursor = b.range[1];
415 }
416 ignored + non_ws(&s[cursor..limit])
417}
418
419fn non_ws(t: &str) -> usize {
420 t.bytes().filter(|b| !b.is_ascii_whitespace()).count()
421}