grippo 0.2.0

Parse, match and scrub data faster and more efficiently.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
// Project:   grippo
// File:      src/format/syslog.rs
// Purpose:   The syslog parser: RFC 5424 and BSD RFC 3164 headers
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! `<PRI>` then RFC 5424 when a version `1 ` follows, else the BSD form.
//!
//! A sender that writes the version and then a shorter header still parses:
//! timestamp, hostname, an app name when the next word could be one, then the
//! message. No line with a valid `<PRI>` is refused.
//!
//! A line with no `<PRI>` writes no `pri`, `facility` or `severity`. `syslog`
//! takes one only as a file holds it, `Mmm dd hh:mm:ss host tag: message`,
//! which is safe to detect. `syslog_nopri` takes any line with a timestamp the
//! BSD reader knows, and is never detected: an application's own log line
//! starts the same way.
//!
//! The header becomes fields, the message is written as `message` and handed
//! back as the body from its first non-space byte, hinted `cef`, `leef` or
//! `ndjson` when it starts that way,
//! so a nested format parses without a copy.

use std::borrow::Cow;
use std::ops::Range;

use crate::field::{Scan, field};
use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
use crate::path::key_part;
use crate::strmatch::{Signature, Specificity};
use crate::tier::MatcherTier;

/// The syslog parser: `syslog`, or `syslog_nopri` from [`Syslog::pri_optional`].
#[derive(Debug, Clone)]
pub struct Syslog {
    signature: Signature,
    no_pri: NoPri,
    levels: Levels,
}

/// How the parser writes `facility` and `severity`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Levels {
    /// Their codes, `20` and `5`.
    #[default]
    Numbers,
    /// Their names from [`FACILITIES`] and [`SEVERITIES`], `local4` and `notice`.
    Names,
}

/// Facility names, indexed by their RFC 5424 code.
pub const FACILITIES: [&str; 24] = [
    "kern", "user", "mail", "daemon", "auth", "syslog", "lpr", "news", "uucp", "cron", "authpriv",
    "ftp", "ntp", "audit", "alert", "clockd", "local0", "local1", "local2", "local3", "local4",
    "local5", "local6", "local7",
];

/// Severity names, indexed by their RFC 5424 code.
pub const SEVERITIES: [&str; 8] = [
    "emerg", "alert", "crit", "err", "warning", "notice", "info", "debug",
];

/// Severity words, indexed by their RFC 5424 code, the long form GELF
/// receivers write for a numeric `level`.
pub const SEVERITY_WORDS: [&str; 8] = [
    "emergency",
    "alert",
    "critical",
    "error",
    "warning",
    "notice",
    "informational",
    "debug",
];

/// The severity word for a code, or `None` past 7.
#[must_use]
pub fn severity_word(code: u8) -> Option<&'static str> {
    SEVERITY_WORDS.get(usize::from(code)).copied()
}

/// The facility name for a code, or `None` past 23.
#[must_use]
pub fn facility_name(code: u8) -> Option<&'static str> {
    FACILITIES.get(usize::from(code)).copied()
}

/// The severity name for a code, or `None` past 7.
#[must_use]
pub fn severity_name(code: u8) -> Option<&'static str> {
    SEVERITIES.get(usize::from(code)).copied()
}

/// The code for a facility name, exact and lower case.
#[must_use]
pub fn facility_code(name: &str) -> Option<u8> {
    FACILITIES
        .iter()
        .position(|f| *f == name)
        .and_then(|i| u8::try_from(i).ok())
}

/// The code for a severity name, exact and lower case.
#[must_use]
pub fn severity_code(name: &str) -> Option<u8> {
    SEVERITIES
        .iter()
        .position(|s| *s == name)
        .and_then(|i| u8::try_from(i).ok())
}

/// What a line with no `<PRI>` has to be for the parser to take it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NoPri {
    /// The header a file holds, whole: timestamp, hostname, tag.
    FileHeader,
    /// Any timestamp the BSD reader knows.
    AnyStamp,
}

impl Default for Syslog {
    fn default() -> Self {
        Self::new()
    }
}

impl Syslog {
    /// The parser `auto` can pick: a line with a `<PRI>`, or one a file
    /// holds, `Mmm dd hh:mm:ss host tag: message`.
    ///
    /// # Panics
    ///
    /// Never: the signature's literals are fixed and non-empty.
    #[must_use]
    pub fn new() -> Self {
        let signature = Signature::builder()
            .anchored(std::iter::once("<").chain(MONTHS))
            .verify(|span, _| pri(span).is_some() || file_header(span).is_some())
            .specificity(Specificity::Generic)
            .build()
            .unwrap_or_else(|_| unreachable!("invariant: the literals are non-empty"));
        Self {
            signature,
            no_pri: NoPri::FileHeader,
            levels: Levels::Numbers,
        }
    }

    /// The parser for a source known to send syslog with no `<PRI>`: any
    /// line that starts with a timestamp is read as a BSD header. It has no
    /// signature, so `auto` never picks it.
    ///
    /// # Panics
    ///
    /// Never: an empty signature always builds.
    #[must_use]
    pub fn pri_optional() -> Self {
        let signature = Signature::builder()
            .build()
            .unwrap_or_else(|_| unreachable!("invariant: an empty signature always builds"));
        Self {
            signature,
            no_pri: NoPri::AnyStamp,
            levels: Levels::Numbers,
        }
    }

    /// This parser, writing `facility` and `severity` as `levels` says.
    #[must_use]
    pub const fn levels(mut self, levels: Levels) -> Self {
        self.levels = levels;
        self
    }
}

/// The month names a header with no `<PRI>` may start with.
const MONTHS: [&str; 12] = [
    "Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", "Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec ",
];

/// `min` to `max` digits at `i`: their value, and where they end.
fn digits(h: &[u8], i: usize, min: usize, max: usize) -> Option<(u16, usize)> {
    let run = h.get(i..)?;
    let n = run
        .iter()
        .take(max)
        .take_while(|b| b.is_ascii_digit())
        .count();
    let value = run[..n]
        .iter()
        .fold(0_u16, |v, &d| v * 10 + u16::from(d - b'0'));
    (n >= min).then_some((value, i + n))
}

/// Where `Mmm dd hh:mm:ss` at the start ends, or that with a four-digit year
/// after the day. Stricter than the field primitives, which read `9:00` as a
/// time: nothing else says this line is syslog.
fn file_stamp(h: &[u8]) -> Option<usize> {
    let month = h.get(..4)?;
    if !MONTHS.iter().any(|m| m.as_bytes() == month) {
        return None;
    }
    let padded = usize::from(h.get(4) == Some(&b' '));
    let (day, mut at) = digits(h, 4 + padded, 1, 2 - padded)?;
    if let Some((_, year)) = digits(h, at + 1, 4, 4).filter(|_| h.get(at) == Some(&b' ')) {
        at = year;
    }
    let (hour, colon) = digits(h, at + 1, 2, 2).filter(|_| h.get(at) == Some(&b' '))?;
    let (minute, at) = digits(h, colon + 1, 2, 2).filter(|_| h.get(colon) == Some(&b':'))?;
    let (second, end) = digits(h, at + 1, 2, 2).filter(|_| h.get(at) == Some(&b':'))?;
    ((1..=31).contains(&day) && hour < 24 && minute < 60 && second < 61).then_some(end)
}

/// The header of a line with no `<PRI>`: where its timestamp and its hostname
/// end. A tag or a nested format has to follow the hostname, so prose that
/// starts with a date isn't taken.
fn file_header(h: &[u8]) -> Option<(usize, usize)> {
    let stamp = file_stamp(h)?;
    let name = h
        .get(stamp + 1..)?
        .iter()
        .take_while(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'))
        .count();
    let host = stamp + 1 + name;
    if h[stamp] != b' ' || name == 0 || h.get(host) != Some(&b' ') {
        return None;
    }
    (hint(&h[host + 1..]).is_some() || file_tag(&h[host + 1..])).then_some((stamp, host))
}

/// A tag as a file's header holds one, `name:` or `name[pid]:`, with no
/// space and no `=` in it. The BSD reader's looser tag is for a line a
/// `<PRI>` or the caller has already called syslog.
fn file_tag(rest: &[u8]) -> bool {
    let name = rest
        .iter()
        .take_while(|b| {
            b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'/' | b'-' | b'(' | b')' | b'@')
        })
        .count();
    let mut end = name;
    if rest.get(end) == Some(&b'[') {
        let pid = rest[end + 1..]
            .iter()
            .take_while(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
            .count();
        if pid == 0 || rest.get(end + 1 + pid) != Some(&b']') {
            return false;
        }
        end += pid + 2;
    }
    (1..=48).contains(&name)
        && rest.get(end) == Some(&b':')
        && rest.get(end + 1).is_none_or(|&b| b == b' ')
}

/// `<PRI>` at the start: the value, up to 191, and where the header resumes.
fn pri(span: &[u8]) -> Option<(u16, usize)> {
    if span.first() != Some(&b'<') {
        return None;
    }
    let n = span[1..]
        .iter()
        .take(4)
        .take_while(|b| b.is_ascii_digit())
        .count();
    if !(1..=3).contains(&n) || span.get(1 + n) != Some(&b'>') {
        return None;
    }
    let value = span[1..=n]
        .iter()
        .fold(0_u16, |v, &d| v * 10 + u16::from(d - b'0'));
    (value <= 191).then_some((value, n + 2))
}

const fn text(bytes: &[u8]) -> FieldValue<'_> {
    FieldValue::borrowed(bytes, Hint::Text)
}

fn number(n: u16) -> FieldValue<'static> {
    FieldValue::owned(n.to_string().into_bytes(), Hint::Int)
}

/// The token from `i` to the next space, and where the next token starts.
fn token(h: &[u8], i: usize) -> Option<(&[u8], usize)> {
    let rest = h.get(i..)?;
    let n = rest.iter().position(|&b| b == b' ').unwrap_or(rest.len());
    (n > 0).then(|| (&rest[..n], (i + n + 1).min(h.len())))
}

/// The format a message starts with, when it names one.
fn hint(message: &[u8]) -> Option<&'static str> {
    if message.starts_with(b"CEF:") {
        Some("cef")
    } else if message.starts_with(b"LEEF:") {
        Some("leef")
    } else if message.first() == Some(&b'{') {
        Some("ndjson")
    } else {
        None
    }
}

/// An RFC 5424 SD-PARAM value with `\"`, `\\` and `\]` unescaped.
fn sd_value(raw: &[u8]) -> FieldValue<'_> {
    if !raw.contains(&b'\\') {
        return text(raw);
    }
    let mut out = Vec::with_capacity(raw.len());
    let mut i = 0;
    while i < raw.len() {
        if raw[i] == b'\\' && matches!(raw.get(i + 1), Some(b'"' | b'\\' | b']')) {
            out.push(raw[i + 1]);
            i += 2;
        } else {
            out.push(raw[i]);
            i += 1;
        }
    }
    FieldValue {
        bytes: Cow::Owned(out),
        hint: Hint::Text,
    }
}

/// One SD-ELEMENT's params from `j`, the space after its id: writes each and
/// returns where the closing `]` should be.
fn sd_params<'a>(h: &'a [u8], mut j: usize, out: &mut dyn FieldSink<'a>) -> Option<usize> {
    while h.get(j) == Some(&b' ') {
        let eq = j + 1 + h[j + 1..].iter().position(|&b| b == b'=')?;
        let name = std::str::from_utf8(&h[j + 1..eq]).ok()?;
        if h.get(eq + 1) != Some(&b'"') {
            return None;
        }
        let mut k = eq + 2;
        while *h.get(k)? != b'"' {
            k += if h[k] == b'\\' { 2 } else { 1 };
        }
        out.field(&key_part(Cow::Borrowed(name)), sd_value(&h[eq + 2..k]));
        j = k + 1;
    }
    Some(j)
}

/// RFC 5424 STRUCTURED-DATA from `i`: writes `structured_data.<id>.<param>`
/// and returns the end, or `None` when it is malformed.
fn structured_data<'a>(h: &'a [u8], mut i: usize, out: &mut dyn FieldSink<'a>) -> Option<usize> {
    if h.get(i) == Some(&b'-') {
        return Some(i + 1);
    }
    let mut seen = false;
    while h.get(i) == Some(&b'[') {
        seen = true;
        let id_end = i + 1 + h[i + 1..].iter().position(|&b| b == b' ' || b == b']')?;
        let id = std::str::from_utf8(&h[i + 1..id_end]).ok()?;
        out.push_prefix("structured_data.");
        out.push_prefix(&key_part(Cow::Borrowed(id)));
        out.push_prefix(".");
        let params = sd_params(h, id_end, out);
        out.pop_prefix();
        out.pop_prefix();
        out.pop_prefix();
        let j = params?;
        if h.get(j) != Some(&b']') {
            return None;
        }
        i = j + 1;
    }
    seen.then_some(i)
}

/// The header some senders write after the version: a timestamp and a
/// hostname, then an app name when the next word could be one, then the
/// message. `None` unless a timestamp starts it.
fn short_header<'a>(h: &'a [u8], start: usize, out: &mut dyn FieldSink<'a>) -> Option<usize> {
    let (stamp, at) = token(h, start)?;
    let dated = stamp.first().is_some_and(u8::is_ascii_digit)
        && stamp
            .iter()
            .all(|b| b.is_ascii_digit() || matches!(b, b'T' | b'Z' | b':' | b'.' | b'+' | b'-'));
    if !dated && stamp != b"-" {
        return None;
    }
    let (host, mut at) = token(h, at)?;
    if dated {
        out.field("timestamp", text(stamp));
    }
    if host != b"-" {
        out.field("hostname", text(host));
    }
    let named = |b: &u8| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.' | b'/');
    if let Some((app, next)) = token(h, at)
        && next < h.len()
        && app.len() <= 48
        && app.iter().all(named)
    {
        out.field("appname", text(app));
        at = next;
        // Senders that stop before the structured data still write a process
        // id and a nil message id.
        if let Some((pid, after_pid)) = token(h, at)
            && (pid == b"-" || pid.iter().all(u8::is_ascii_digit))
            && let Some(([b'-'], after_msgid)) = token(h, after_pid)
            && after_msgid < h.len()
        {
            if pid != b"-" {
                out.field("procid", text(pid));
            }
            at = after_msgid;
        }
    }
    Some(at)
}

/// The header after `<PRI>1 `: RFC 5424 in full, else the short form, else
/// `None` for a line that only looks versioned.
fn rfc5424<'a>(h: &'a [u8], start: usize, out: &mut dyn FieldSink<'a>) -> Option<usize> {
    let version = text(&h[start - 2..start - 1]);
    let mark = out.mark();
    out.field("version", version.clone());
    if let Some(end) = full_header(h, start, out) {
        return Some(end);
    }
    out.rollback(mark);
    out.field("version", version);
    let end = short_header(h, start, out);
    if end.is_none() {
        out.rollback(mark);
    }
    end
}

/// The full RFC 5424 header from `start`: five fields, then structured data.
fn full_header<'a>(h: &'a [u8], start: usize, out: &mut dyn FieldSink<'a>) -> Option<usize> {
    let mut i = start;
    for name in ["timestamp", "hostname", "appname", "procid", "msgid"] {
        let (tok, next) = token(h, i)?;
        if tok != b"-" {
            out.field(name, text(tok));
        }
        i = next;
    }
    let end = structured_data(h, i, out)?;
    Some(if h.get(end) == Some(&b' ') {
        end + 1
    } else {
        end
    })
}

fn scan(name: &str, h: &[u8], at: usize) -> Option<usize> {
    match field(name).map(|f| (f.scan)(h, at)) {
        Some(Scan::Match(end)) => Some(end),
        _ => None,
    }
}

/// `MMM DD YYYY HH:MM:SS`, Cisco's form with the year.
fn with_year(h: &[u8], i: usize) -> Option<usize> {
    let month = scan("MONTH", h, i)?;
    let day = Some(skip_spaces(h, month))
        .filter(|&at| at > month)
        .and_then(|at| scan("MONTHDAY", h, at))?;
    let year = scan("YEAR", h, day + 1).filter(|_| h.get(day) == Some(&b' '))?;
    scan("TIME", h, year + 1).filter(|_| h.get(year) == Some(&b' '))
}

/// Where a BSD, ISO 8601 or Cisco timestamp at `i` ends, when a space or
/// `: ` follows it.
fn stamp_end(h: &[u8], i: usize) -> Option<usize> {
    let end = scan("SYSLOGTIMESTAMP", h, i)
        .or_else(|| scan("TIMESTAMP_ISO8601", h, i))
        .or_else(|| with_year(h, i))?;
    match h.get(end) {
        Some(b' ') => Some(end),
        Some(b':') if h.get(end + 1).is_none_or(|&b| b == b' ') => Some(end),
        _ => None,
    }
}

/// [`stamp_end`], reading a month in any case, such as `OCT`, as `Oct`.
fn timestamp_end(h: &[u8], i: usize) -> Option<usize> {
    stamp_end(h, i).or_else(|| {
        let rest = h.get(i..)?;
        let letters = rest.iter().take_while(|b| b.is_ascii_alphabetic()).count();
        if letters < 3 {
            return None;
        }
        let mut buf = [0_u8; 40];
        let len = rest.len().min(buf.len());
        buf[..len].copy_from_slice(&rest[..len]);
        buf[0].make_ascii_uppercase();
        buf[1..letters.min(len)].make_ascii_lowercase();
        (buf[..len] != rest[..len])
            .then(|| stamp_end(&buf[..len], 0))
            .flatten()
            .map(|end| i + end)
    })
}

fn skip_spaces(h: &[u8], i: usize) -> usize {
    i + h[i..].iter().take_while(|&&b| b == b' ').count()
}

/// Whether a timestamp the BSD reader knows could start here: a digit, or
/// a month's first three letters in any case.
fn stamp_could_start(rest: &[u8]) -> bool {
    rest.first().is_some_and(u8::is_ascii_digit)
        || rest.get(..3).is_some_and(|start| {
            MONTHS
                .iter()
                .any(|month| month.as_bytes()[..3].eq_ignore_ascii_case(start))
        })
}

/// Whether the BSD reader gives up when it finds no timestamp.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Stamp {
    /// A `<PRI>` already said syslog.
    IfThere,
    /// Nothing else has.
    Needed,
}

/// A tag at `i`, `name:` or `name[pid]:`: the name, the pid, and where the
/// message starts.
fn tag(h: &[u8], i: usize) -> Option<(&[u8], Option<&[u8]>, usize)> {
    let len = h
        .get(i..)?
        .iter()
        .take_while(|&&b| b.is_ascii_graphic() && !matches!(b, b'[' | b':' | b'{' | b'"'))
        .count();
    if len == 0 {
        return None;
    }
    let mut j = i + len;
    let mut procid = None;
    if h.get(j) == Some(&b'[')
        && let Some(close) = h[j..].iter().position(|&b| b == b']')
    {
        procid = Some(&h[j + 1..j + close]);
        j += close + 1;
    }
    (h.get(j) == Some(&b':') && h.get(j + 1).is_none_or(|&b| b == b' '))
        .then(|| (&h[i..i + len], procid, (j + 2).min(h.len())))
}

/// What follows the hostname: a lone `:`, or a tag. Returns where the message
/// starts.
fn after_host<'a>(h: &'a [u8], i: usize, out: &mut dyn FieldSink<'a>) -> usize {
    if h.get(i) == Some(&b':') && h.get(i + 1).is_none_or(|&b| b == b' ') {
        return (i + 2).min(h.len());
    }
    let Some((name, procid, message)) = tag(h, i) else {
        return i;
    };
    out.field("appname", text(name));
    if let Some(p) = procid {
        out.field("procid", text(p));
    }
    message
}

/// The BSD header from `i`: where the message starts, or `None` with nothing
/// written when a timestamp is needed and there is none.
fn rfc3164<'a>(
    h: &'a [u8],
    start: usize,
    stamp: Stamp,
    out: &mut dyn FieldSink<'a>,
) -> Option<usize> {
    let start = skip_spaces(h, start);
    let seq = h[start..].iter().take_while(|b| b.is_ascii_digit()).count();
    let numbered = seq > 0 && h.get(start + seq..start + seq + 2) == Some(b": ");
    let mut i = if numbered {
        skip_spaces(h, start + seq + 2)
    } else {
        start
    };
    // Cisco marks a clock that isn't set with `*` and one not synced with `.`.
    if matches!(h.get(i), Some(b'*' | b'.')) && h.get(i + 1).is_some_and(u8::is_ascii_alphabetic) {
        i += 1;
    }
    // A line that isn't syslog leaves here on its first bytes, before the
    // three timestamp scans.
    if stamp == Stamp::Needed && !stamp_could_start(&h[i.min(h.len())..]) {
        return None;
    }
    let end = timestamp_end(h, i);
    if stamp == Stamp::Needed && end.is_none() {
        return None;
    }
    if numbered {
        out.field("sequence", text(&h[start..start + seq]));
    }
    if let Some(end) = end {
        out.field("timestamp", text(&h[i..end]));
        i = skip_spaces(h, end + usize::from(h.get(end) == Some(&b':')));
    }
    // A comma is in no hostname, and `<` starts a level some relays write.
    if let Some((tok, next)) = token(h, i)
        && !tok.ends_with(b":")
        && !tok.starts_with(b"<")
        && !tok.iter().any(|b| matches!(b, b'[' | b'|' | b','))
        && h.get(next..).is_some_and(|rest| !rest.is_empty())
    {
        out.field("hostname", text(tok));
        i = skip_spaces(h, next);
    }
    Some(after_host(h, i, out))
}

impl Parser for Syslog {
    fn name(&self) -> &'static str {
        match self.no_pri {
            NoPri::FileHeader => "syslog",
            NoPri::AnyStamp => "syslog_nopri",
        }
    }

    fn tier(&self) -> MatcherTier {
        MatcherTier::Field
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    /// An SD-PARAM value, between `="` and `"`, escapes `"`, `\` and `]` as
    /// RFC 5424 has it, and so does a value asked for with no record around
    /// it. A header field has no escape and goes in as it is.
    fn escape_value(
        &self,
        input: &[u8],
        _field: usize,
        at: Range<usize>,
        value: &[u8],
        out: &mut Vec<u8>,
    ) -> Option<Range<usize>> {
        let param = input.is_empty()
            || (at
                .start
                .checked_sub(2)
                .and_then(|open| input.get(open..at.start))
                == Some(b"=\"")
                && input.get(at.end) == Some(&b'"'));
        for &b in value {
            if param && matches!(b, b'"' | b'\\' | b']') {
                out.push(b'\\');
            }
            out.push(b);
        }
        Some(at)
    }

    fn parse<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Parsed, ParseError> {
        let body = if let Some((value, at)) = pri(input) {
            out.field("pri", number(value));
            match self.levels {
                Levels::Numbers => {
                    out.field("facility", number(value / 8));
                    out.field("severity", number(value % 8));
                }
                Levels::Names => {
                    let facility = u8::try_from(value / 8).ok().and_then(facility_name);
                    let severity = u8::try_from(value % 8).ok().and_then(severity_name);
                    if let Some(name) = facility {
                        out.field(
                            "facility",
                            FieldValue::borrowed(name.as_bytes(), Hint::Text),
                        );
                    }
                    if let Some(name) = severity {
                        out.field(
                            "severity",
                            FieldValue::borrowed(name.as_bytes(), Hint::Text),
                        );
                    }
                }
            }
            let versioned = (input.get(at..at + 2) == Some(b"1 "))
                .then(|| rfc5424(input, at + 2, out))
                .flatten();
            versioned
                .or_else(|| rfc3164(input, at, Stamp::IfThere, out))
                .unwrap_or(at)
        } else if self.no_pri == NoPri::AnyStamp {
            let Some(body) = rfc3164(input, 0, Stamp::Needed, out) else {
                return Ok(Parsed::NoMatch);
            };
            body
        } else if let Some((stamp, host)) = file_header(input) {
            out.field("timestamp", text(&input[..stamp]));
            out.field("hostname", text(&input[stamp + 1..host]));
            after_host(input, host + 1, out)
        } else {
            return Ok(Parsed::NoMatch);
        };
        let mut body = skip_spaces(input, body.min(input.len()));
        // RFC 5424 6.4: a BOM marks the message as UTF-8 and isn't part of it.
        if input[body..].starts_with(b"\xEF\xBB\xBF") {
            body += 3;
        }
        // A NUL ends a frame on some TCP senders.
        let trail = input[body..]
            .iter()
            .rev()
            .take_while(|&&b| matches!(b, b'\n' | b'\r' | b'\0'))
            .count();
        let end = input.len() - trail;
        let message = &input[body.min(end)..end];
        out.body_field("message", text(message));
        Ok(Parsed::Body {
            span: body.min(end)..end,
            hint: hint(message),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parse::Fields;

    fn parse(line: &str) -> (Result<Parsed, ParseError>, Vec<(String, String)>) {
        let mut out = Fields::new();
        let p = Syslog::new().parse(line.as_bytes(), &mut out);
        let fields = out
            .as_slice()
            .iter()
            .map(|(n, v)| (n.clone(), String::from_utf8_lossy(&v.bytes).into_owned()))
            .collect();
        (p, fields)
    }

    fn get<'f>(fields: &'f [(String, String)], name: &str) -> Option<&'f str> {
        fields
            .iter()
            .find(|(n, _)| n == name)
            .map(|(_, v)| v.as_str())
    }

    #[test]
    fn a_dotted_sd_id_and_param_are_written_quoted_and_read_back_whole() {
        let line =
            r#"<165>1 2026-11-26T11:22:33.003Z host app - ID47 [ex.id@1 k.v="x" plain="y"] msg"#;
        for (name, value) in [
            (r#"structured_data["ex.id@1"]["k.v"]"#, "x"),
            (r#"structured_data["ex.id@1"].plain"#, "y"),
        ] {
            let mut out = Fields::new();
            Syslog::new().parse(line.as_bytes(), &mut out).unwrap();
            let got = out
                .get(name)
                .map(|v| String::from_utf8_lossy(&v.bytes).into_owned());
            assert_eq!(got.as_deref(), Some(value), "{name}");
            #[cfg(feature = "record")]
            {
                use crate::record::Record;
                let keys: Vec<_> = crate::path::keys(name).collect();
                let at = (&out).find(&keys[..]).unwrap();
                assert_eq!((&out).text(at).unwrap(), value, "{name}");
            }
        }
    }

    #[test]
    fn levels_as_names_write_the_names_receivers_write() {
        let cases = [
            (
                "<165>1 2026-11-30T10:00:00Z h a - - - m",
                "local4",
                "notice",
            ),
            ("<0>Nov 30 10:00:00 h a: m", "kern", "emerg"),
            ("<13>Nov 30 10:00:00 h a: m", "user", "notice"),
            ("<191>Nov 30 10:00:00 h a: m", "local7", "debug"),
            ("<36>m", "auth", "warning"),
        ];
        for (line, facility, severity) in cases {
            let mut out = Fields::new();
            let p = Syslog::new()
                .levels(Levels::Names)
                .parse(line.as_bytes(), &mut out);
            assert!(p.is_ok(), "{line}: {p:?}");
            let fields: Vec<(String, String)> = out
                .as_slice()
                .iter()
                .map(|(n, v)| (n.clone(), String::from_utf8_lossy(&v.bytes).into_owned()))
                .collect();
            assert_eq!(get(&fields, "facility"), Some(facility), "{line}");
            assert_eq!(get(&fields, "severity"), Some(severity), "{line}");
            assert_eq!(
                get(&fields, "pri"),
                Some(line[1..].split('>').next().unwrap_or("")),
                "{line}"
            );
        }
        for code in 0..=u8::MAX {
            match facility_name(code) {
                Some(name) => assert_eq!(facility_code(name), Some(code)),
                None => assert!(code > 23),
            }
            match severity_name(code) {
                Some(name) => assert_eq!(severity_code(name), Some(code)),
                None => assert!(code > 7),
            }
        }
        assert_eq!(severity_word(6), Some("informational"));
        assert_eq!(severity_word(8), None);
        for bad in ["", "LOCAL4", "local8", "warn", "Notice"] {
            assert_eq!(facility_code(bad), None, "{bad}");
            assert_eq!(severity_code(bad), None, "{bad}");
        }
    }

    #[test]
    fn rfc5424_with_structured_data() {
        let line = r#"<165>1 2026-11-26T11:22:33.003Z mymachine.example.com evntslog - ID47 [exampleSDID@32473 iut="3" eventSource="App\"lication"][x@1 a="b"] An application event"#;
        let (p, f) = parse(line);
        let Ok(Parsed::Body { span, hint }) = p else {
            panic!("{p:?}")
        };
        assert_eq!(&line[span], "An application event");
        assert_eq!(hint, None);
        assert_eq!(get(&f, "facility"), Some("20"));
        assert_eq!(get(&f, "severity"), Some("5"));
        assert_eq!(get(&f, "hostname"), Some("mymachine.example.com"));
        assert_eq!(get(&f, "procid"), None, "a nil field writes nothing");
        assert_eq!(get(&f, "msgid"), Some("ID47"));
        assert_eq!(
            get(&f, "structured_data.exampleSDID@32473.eventSource"),
            Some("App\"lication")
        );
        assert_eq!(get(&f, "structured_data.x@1.a"), Some("b"));
    }

    /// `value` written over `at` of `record`: the record after.
    fn written(record: &str, at: Range<usize>, value: &str) -> String {
        let mut text = Vec::new();
        let span = Syslog::new()
            .escape_value(record.as_bytes(), 0, at, value.as_bytes(), &mut text)
            .unwrap();
        let text = String::from_utf8(text).unwrap();
        [&record[..span.start], &text, &record[span.end..]].concat()
    }

    #[test]
    fn an_sd_param_value_escapes_and_a_header_field_does_not() {
        let line = r#"<165>1 - host app - - [x@1 a="b" c="d"] msg"#;
        let sd = line.find("\"b\"").unwrap() + 1;
        let host = line.find("host").unwrap();
        let cases: &[(Range<usize>, &str, &str)] = &[
            (sd..sd + 1, r#"q"b\s]"#, r#"[x@1 a="q\"b\\s\]" c="d"]"#),
            (sd..sd + 1, "", r#"[x@1 a="" c="d"]"#),
            (host..host + 4, r#"h"\]"#, r#"<165>1 - h"\] app"#),
        ];
        for (at, value, want) in cases {
            let after = written(line, at.clone(), value);
            assert!(after.contains(want), "{after}");
        }
        let mut out = Vec::new();
        Syslog::new().escape_value(b"", 0, 0..0, br#"a"b"#, &mut out);
        assert_eq!(out, br#"a\"b"#);
    }

    proptest::proptest! {
        /// An escaped SD-PARAM value reads back as written, the params either
        /// side unchanged.
        #[test]
        fn an_escaped_sd_param_reads_back(value in r#"[a-z "\\\]=\[]{0,10}"#) {
            let line = r#"<165>1 - host app - - [x@1 a="1" b="v" c="2"] msg"#;
            let sd = line.find("\"v\"").unwrap() + 1;
            let after = written(line, sd..sd + 1, &value);
            let (p, f) = parse(&after);
            proptest::prop_assert!(p.is_ok());
            proptest::prop_assert_eq!(get(&f, "structured_data.x@1.a"), Some("1"));
            proptest::prop_assert_eq!(get(&f, "structured_data.x@1.b"), Some(value.as_str()));
            proptest::prop_assert_eq!(get(&f, "structured_data.x@1.c"), Some("2"));
        }
    }

    #[test]
    fn bsd_syslog_with_tag_and_pid() {
        let line = "<34>Oct 11 22:14:15 mymachine su[123]: 'su root' failed\n";
        let (p, f) = parse(line);
        let Ok(Parsed::Body { span, .. }) = p else {
            panic!("{p:?}")
        };
        assert_eq!(&line[span], "'su root' failed");
        assert_eq!(get(&f, "timestamp"), Some("Oct 11 22:14:15"));
        assert_eq!(get(&f, "hostname"), Some("mymachine"));
        assert_eq!(get(&f, "appname"), Some("su"));
        assert_eq!(get(&f, "procid"), Some("123"));
    }

    #[test]
    fn bsd_syslog_without_a_hostname_carries_a_cef_body() {
        let line = "<13>Nov  6 08:01:02 CEF:0|v|p|1|id|n|5|src=1.2.3.4";
        let (p, f) = parse(line);
        let Ok(Parsed::Body { span, hint }) = p else {
            panic!("{p:?}")
        };
        assert_eq!(&line[span], "CEF:0|v|p|1|id|n|5|src=1.2.3.4");
        assert_eq!(hint, Some("cef"));
        assert_eq!(get(&f, "hostname"), None);
        assert_eq!(get(&f, "appname"), None);
    }

    /// BSD headers seen in the wild: (line, timestamp, hostname,
    /// appname, procid, message).
    #[test]
    fn bsd_header_variants() {
        type Row = (
            &'static str,
            Option<&'static str>,
            Option<&'static str>,
            Option<&'static str>,
            Option<&'static str>,
            &'static str,
        );
        let rows: [Row; 9] = [
            (
                "<34>Oct 11 22:14:15 : a message",
                Some("Oct 11 22:14:15"),
                None,
                None,
                None,
                "a message",
            ),
            (
                "<34>OCT 11 22:14:15 : a message",
                Some("OCT 11 22:14:15"),
                None,
                None,
                None,
                "a message",
            ),
            (
                "<34>october 11 22:14:15 host app: m",
                Some("october 11 22:14:15"),
                Some("host"),
                Some("app"),
                None,
                "m",
            ),
            (
                "<54> 1970-01-01T00:01:31+00:00 host :",
                Some("1970-01-01T00:01:31+00:00"),
                Some("host"),
                None,
                None,
                "",
            ),
            (
                "<34>2020-10-11T22:14:15.00Z mymachine app[323]: a message",
                Some("2020-10-11T22:14:15.00Z"),
                Some("mymachine"),
                Some("app"),
                Some("323"),
                "a message",
            ),
            (
                r#"<134>Oct 30 16:05:54 opsaudit  {"username": "admin"}"#,
                Some("Oct 30 16:05:54"),
                Some("opsaudit"),
                None,
                None,
                r#"{"username": "admin"}"#,
            ),
            // A tag needs its colon, so a bare word after the host is message.
            (
                "<131>Jun 8 11:54:08 master apache_error [Tue Jun 08 2021] [php7:emerg] rest",
                Some("Jun 8 11:54:08"),
                Some("master"),
                None,
                None,
                "apache_error [Tue Jun 08 2021] [php7:emerg] rest",
            ),
            // One word then a colon is a tag, as from a local socket.
            (
                "<34>Oct 11 22:14:15 mymachine: a message",
                Some("Oct 11 22:14:15"),
                None,
                Some("mymachine"),
                None,
                "a message",
            ),
            (
                "<34>Oxt 11 22:14:15 host app: m",
                None,
                Some("Oxt"),
                None,
                None,
                "11 22:14:15 host app: m",
            ),
        ];
        for (line, timestamp, hostname, appname, procid, message) in rows {
            let (p, f) = parse(line);
            let Ok(Parsed::Body { span, .. }) = p else {
                panic!("{line}: {p:?}")
            };
            assert_eq!(&line[span], message, "{line}");
            assert_eq!(get(&f, "timestamp"), timestamp, "{line}");
            assert_eq!(get(&f, "hostname"), hostname, "{line}");
            assert_eq!(get(&f, "appname"), appname, "{line}");
            assert_eq!(get(&f, "procid"), procid, "{line}");
        }
    }

    /// Cisco IOS: (line, sequence, timestamp, hostname, appname, message).
    #[test]
    fn cisco_headers() {
        let rows = [
            (
                "<189>81: *Mar  1 00:04:11.123: %SYS-5-CONFIG_I: Configured from console",
                Some("81"),
                "Mar  1 00:04:11.123",
                None,
                "%SYS-5-CONFIG_I",
                "Configured from console",
            ),
            (
                "<187>Dec 28 2008 16:49:07 router1 %LINK-3-UPDOWN: Interface down",
                None,
                "Dec 28 2008 16:49:07",
                Some("router1"),
                "%LINK-3-UPDOWN",
                "Interface down",
            ),
            (
                "<34>.Dec 28 16:49:07: host app: m",
                None,
                "Dec 28 16:49:07",
                Some("host"),
                "app",
                "m",
            ),
        ];
        for (line, sequence, timestamp, hostname, appname, message) in rows {
            let (p, f) = parse(line);
            let Ok(Parsed::Body { span, .. }) = p else {
                panic!("{line}: {p:?}")
            };
            assert_eq!(&line[span], message, "{line}");
            assert_eq!(get(&f, "sequence"), sequence, "{line}");
            assert_eq!(get(&f, "timestamp"), Some(timestamp), "{line}");
            assert_eq!(get(&f, "hostname"), hostname, "{line}");
            assert_eq!(get(&f, "appname"), Some(appname), "{line}");
        }
    }

    /// (line, timestamp, hostname, appname, procid, message, hint).
    type NoPriRow = (
        &'static str,
        &'static str,
        Option<&'static str>,
        Option<&'static str>,
        Option<&'static str>,
        &'static str,
        Option<&'static str>,
    );

    fn reads(parser: &Syslog, rows: &[NoPriRow]) {
        for &(line, timestamp, hostname, appname, procid, message, hinted) in rows {
            let mut out = Fields::new();
            let p = parser.parse(line.as_bytes(), &mut out);
            let Ok(Parsed::Body { span, hint }) = p else {
                panic!("{line}: {p:?}")
            };
            let field = |name: &str| out.get(name).map(|v| &*v.bytes);
            assert_eq!(&line[span], message, "{line}");
            assert_eq!(hint, hinted, "{line}");
            assert_eq!(field("timestamp"), Some(timestamp.as_bytes()), "{line}");
            assert_eq!(field("hostname"), hostname.map(str::as_bytes), "{line}");
            assert_eq!(field("appname"), appname.map(str::as_bytes), "{line}");
            assert_eq!(field("procid"), procid.map(str::as_bytes), "{line}");
            for absent in ["pri", "facility", "severity"] {
                assert_eq!(field(absent), None, "{line}");
            }
        }
    }

    const FILE_LINES: &[NoPriRow] = &[
        (
            "Mar 15 08:00:01 web-01 sshd[1234]: Accepted publickey for deploy from 10.10.1.5",
            "Mar 15 08:00:01",
            Some("web-01"),
            Some("sshd"),
            Some("1234"),
            "Accepted publickey for deploy from 10.10.1.5",
            None,
        ),
        (
            "Nov  6 08:01:02 gw01 kernel: [BLOCK] IN=eth0 OUT= SRC=198.51.100.26",
            "Nov  6 08:01:02",
            Some("gw01"),
            Some("kernel"),
            None,
            "[BLOCK] IN=eth0 OUT= SRC=198.51.100.26",
            None,
        ),
        (
            "Jan 5 23:59:60 10.0.0.7 postfix/smtpd[77]: connect from mail.example.com",
            "Jan 5 23:59:60",
            Some("10.0.0.7"),
            Some("postfix/smtpd"),
            Some("77"),
            "connect from mail.example.com",
            None,
        ),
        (
            "Jan 15 2024 09:00:01 fw-01 sshd[1]: a year after the day",
            "Jan 15 2024 09:00:01",
            Some("fw-01"),
            Some("sshd"),
            Some("1"),
            "a year after the day",
            None,
        ),
        (
            "Jan 15 09:00:01 relay01 LEEF:1.0|Acme|Gate|7.3|Allow|src=203.0.113.10\tdst=10.0.0.50",
            "Jan 15 09:00:01",
            Some("relay01"),
            None,
            None,
            "LEEF:1.0|Acme|Gate|7.3|Allow|src=203.0.113.10\tdst=10.0.0.50",
            Some("leef"),
        ),
        (
            "Oct 11 22:14:15 app01 {\"a\":1}",
            "Oct 11 22:14:15",
            Some("app01"),
            None,
            None,
            "{\"a\":1}",
            Some("ndjson"),
        ),
        (
            "Oct 11 22:14:15 app01 cron: ",
            "Oct 11 22:14:15",
            Some("app01"),
            Some("cron"),
            None,
            "",
            None,
        ),
    ];

    #[test]
    fn a_file_header_with_no_pri_is_read() {
        reads(&Syslog::new(), FILE_LINES);
        for row in FILE_LINES {
            let fires = Syslog::new().signature().may_match(row.0.as_bytes());
            assert!(fires, "{}", row.0);
        }
    }

    /// With no `<PRI>`, `syslog` wants the whole file header. The signature
    /// agrees with the parser on every line, since either may run first.
    #[test]
    fn syslog_takes_no_other_line_that_lacks_a_pri() {
        for line in [
            "2026-11-28T09:30:00+11:00 web-01 sshd[1234]: Accepted publickey",
            "2026-11-28T09:30:00Z ERROR main: connection lost",
            "2026-11-26T00:22:33.123456789Z stdout F a container line",
            "Jan",
            "Jan 15",
            "Jan 15 09:00:01",
            "Jan 15 09:00:01 ",
            "Jan 15 09:00:01  \r\n",
            "Jan 15 09:00:01 web-01",
            "Jan 15 09:00:01 web-01 ",
            "Jan 15 09:00:01: no host",
            "Jan 15 09:00:01 INFO Starting service",
            "Jan 15 09:00:01 GET /health HTTP/1.1",
            "Jan 15 09:00:01 Disk full on /var",
            "Jan 15 09:00:01 devname=\"HQ-01\" action=deny",
            "Jan 15 09:00:01 {\"x\":1, \"y\":2}",
            "Jan 15 09:00:01 [initandlisten] waiting for connections",
            "Jan 15 09:00:01 sshd[1234]: no hostname",
            "Jan 15 09:00:01 Disk error[read failed]: retrying",
            "Jan 15 09:00:01 backup status=failed: retrying",
            "Jan 15 09:00:01 fw-01 %GATE-6-302013: Built inbound TCP connection",
            "Jan 15 09:00:01 web-01 sshd[]: an empty pid",
            "Jan 15 09:00:01 web-01 sshd[12: an open bracket",
            "Jan 15 2024 09:00:01 fw-01 devname=\"HQ-01\" type=\"traffic\"",
            "Jan 15 2024 09:00:01 fw-02 : %GATE-6-302013: Built inbound TCP connection",
            "Jan 15 09:00:01 1,2024/01/15 09:00:01,0072,TRAFFIC",
            "January 15 09:00:01 web-01 sshd[1]: x",
            "JAN 15 09:00:01 web-01 sshd[1]: x",
            "jan 15 09:00:01 web-01 sshd[1]: x",
            "Janet 15 09:00:01 web-01 sshd[1]: x",
            "Jan 15 9:00 web-01 sshd[1]: x",
            "Jan 15 9:00:01 web-01 sshd[1]: x",
            "Jan 15 09:00 web-01 sshd[1]: x",
            "Jan 15 09:00:01.123 web-01 sshd[1]: x",
            "Jan 99 09:00:01 web-01 sshd[1]: x",
            "Jan 0 09:00:01 web-01 sshd[1]: x",
            "Jan 15 24:00:01 web-01 sshd[1]: x",
            "Jan 15 09:60:01 web-01 sshd[1]: x",
            "Jan 15 24 09:00:01 web-01 sshd[1]: x",
            "Jan   5 09:00:01 web-01 sshd[1]: x",
            " Jan 15 09:00:01 web-01 sshd[1]: x",
            "Mon Jan 15 09:00:01 2024 web-01 x",
            "May 4 10:30 meeting notes",
            "March 15 notes",
        ] {
            assert!(matches!(parse(line).0, Ok(Parsed::NoMatch)), "{line}");
            let fires = Syslog::new().signature().may_match(line.as_bytes());
            assert!(!fires, "{line}");
        }
    }

    /// The header's layout can't tell a hostname from a level an application
    /// wrote there. This is the line the rule gets wrong.
    #[test]
    fn a_level_where_the_hostname_goes_is_read_as_one() {
        let (p, f) = parse("Jan 15 09:00:01 ERROR main: lost connection");
        assert!(matches!(p, Ok(Parsed::Body { .. })));
        assert_eq!(get(&f, "hostname"), Some("ERROR"));
        assert_eq!(get(&f, "appname"), Some("main"));
    }

    #[test]
    fn the_pri_optional_parser_reads_any_line_with_a_timestamp() {
        let parser = Syslog::pri_optional();
        assert_eq!(parser.name(), "syslog_nopri");
        reads(&parser, FILE_LINES);
        reads(
            &parser,
            &[
                (
                    "2026-11-28T09:30:00.123456+11:00 web-01 sshd[1234]: Accepted publickey",
                    "2026-11-28T09:30:00.123456+11:00",
                    Some("web-01"),
                    Some("sshd"),
                    Some("1234"),
                    "Accepted publickey",
                    None,
                ),
                (
                    "Jan 15 2024 09:00:01 fw-01 devname=\"HQ-01\" type=\"traffic\"",
                    "Jan 15 2024 09:00:01",
                    Some("fw-01"),
                    None,
                    None,
                    "devname=\"HQ-01\" type=\"traffic\"",
                    None,
                ),
                (
                    "Jan 15 2024 09:00:01 fw-02 : %GATE-6-302013: Built inbound TCP connection",
                    "Jan 15 2024 09:00:01",
                    Some("fw-02"),
                    None,
                    None,
                    "%GATE-6-302013: Built inbound TCP connection",
                    None,
                ),
                (
                    "Jan 15 2024 09:00:01: %GATE-6-302013: Built inbound TCP connection",
                    "Jan 15 2024 09:00:01",
                    None,
                    Some("%GATE-6-302013"),
                    None,
                    "Built inbound TCP connection",
                    None,
                ),
                (
                    "*Mar  1 00:04:11.123: %SYS-5-CONFIG_I: Configured from console",
                    "Mar  1 00:04:11.123",
                    None,
                    Some("%SYS-5-CONFIG_I"),
                    None,
                    "Configured from console",
                    None,
                ),
                (
                    "Jan 15 09:00:01 1,2024/01/15 09:00:01,0072,TRAFFIC,end",
                    "Jan 15 09:00:01",
                    None,
                    None,
                    None,
                    "1,2024/01/15 09:00:01,0072,TRAFFIC,end",
                    None,
                ),
                (
                    "Jan 15 09:00:01 fw-03 1,2024/01/15 09:00:01,0072,TRAFFIC,end",
                    "Jan 15 09:00:01",
                    Some("fw-03"),
                    None,
                    None,
                    "1,2024/01/15 09:00:01,0072,TRAFFIC,end",
                    None,
                ),
                (
                    "Jan 15 09:00:01 <local0.info> 10.1.2.3 CEF:0|Acme|Gate|1|100|n|5|src=10.0.0.1",
                    "Jan 15 09:00:01",
                    None,
                    None,
                    None,
                    "<local0.info> 10.1.2.3 CEF:0|Acme|Gate|1|100|n|5|src=10.0.0.1",
                    None,
                ),
            ],
        );
        reads(
            &parser,
            &[(
                "OCT 11 22:14:15 gw01 su[123]: a month in capitals",
                "OCT 11 22:14:15",
                Some("gw01"),
                Some("su"),
                Some("123"),
                "a month in capitals",
                None,
            )],
        );
        for line in [
            "",
            "no stamp here",
            "ERROR main: lost",
            "{\"a\":1}",
            "<999>x",
            "Ja",
            "Janitor started the sweep",
            "9 lives",
        ] {
            let got = parser.parse(line.as_bytes(), &mut Fields::new());
            assert!(matches!(got, Ok(Parsed::NoMatch)), "{line}");
        }
    }

    /// A `<PRI>` line reads the same through either parser.
    #[test]
    fn both_parsers_read_a_line_with_a_pri_alike() {
        for line in [
            "<34>Oct 11 22:14:15 mymachine su[123]: 'su root' failed",
            "<165>1 2026-11-26T11:22:33.003Z host.example.com evntslog - ID47 - An event",
            "<13>Nov  6 08:01:02 CEF:0|v|p|1|id|n|5|src=1.2.3.4",
            "<189>81: *Mar  1 00:04:11.123: %SYS-5-CONFIG_I: Configured from console",
        ] {
            let (mut plain, mut optional) = (Fields::new(), Fields::new());
            let a = Syslog::new().parse(line.as_bytes(), &mut plain);
            let b = Syslog::pri_optional().parse(line.as_bytes(), &mut optional);
            assert_eq!(format!("{a:?}"), format!("{b:?}"), "{line}");
            assert_eq!(plain.as_slice(), optional.as_slice(), "{line}");
        }
    }

    /// A word with a comma, or a level in angle brackets, is no hostname,
    /// with a `<PRI>` or without.
    #[test]
    fn a_token_no_hostname_could_be_starts_the_message() {
        let line = "<14>Jan 15 09:00:01 1,2024/01/15 09:00:01,0072,TRAFFIC,end";
        let (p, f) = parse(line);
        let Ok(Parsed::Body { span, .. }) = p else {
            panic!("{p:?}")
        };
        assert_eq!(&line[span], "1,2024/01/15 09:00:01,0072,TRAFFIC,end");
        assert_eq!(get(&f, "hostname"), None);
        let line = "<14>Jan 15 09:00:01 <local0.info> 10.1.2.3 text";
        let (_, f) = parse(line);
        assert_eq!(get(&f, "hostname"), None);
    }

    #[test]
    fn a_bad_pri_is_no_match() {
        assert!(matches!(parse("<999>x").0, Ok(Parsed::NoMatch)));
        assert!(matches!(parse("no pri").0, Ok(Parsed::NoMatch)));
        assert!(!Syslog::new().signature().may_match(b"<x>"));
    }

    /// Senders that write the version and then fewer fields than RFC 5424
    /// asks for: the record still parses, and the message starts where the
    /// header stops.
    #[test]
    fn a_short_versioned_header_still_parses() {
        // (line, timestamp, hostname, appname, message)
        let cases = [
            (
                "<134>1 1647479503.348215340 edge01 flows src=10.0.2.170 dst=10.0.0.34 protocol=udp",
                Some("1647479503.348215340"),
                Some("edge01"),
                Some("flows"),
                "src=10.0.2.170 dst=10.0.0.34 protocol=udp",
            ),
            (
                r#"<5>1 2021-03-08T18:07:51Z vault01 {"format":"x","n":1}"#,
                Some("2021-03-08T18:07:51Z"),
                Some("vault01"),
                None,
                r#"{"format":"x","n":1}"#,
            ),
            (
                r#"<13>1 2026-11-28T01:02:03Z host app 1 id [x@1 a="unterminated"#,
                Some("2026-11-28T01:02:03Z"),
                Some("host"),
                Some("app"),
                r#"1 id [x@1 a="unterminated"#,
            ),
            ("<13>1 - host01 lone", None, Some("host01"), None, "lone"),
        ];
        for (line, timestamp, hostname, appname, message) in cases {
            let (p, f) = parse(line);
            let Ok(Parsed::Body { span, .. }) = p else {
                panic!("{line}: {p:?}")
            };
            assert_eq!(&line[span], message, "{line}");
            assert_eq!(get(&f, "version"), Some("1"), "{line}");
            assert!(get(&f, "pri").is_some(), "{line}");
            assert_eq!(get(&f, "timestamp"), timestamp, "{line}");
            assert_eq!(get(&f, "hostname"), hostname, "{line}");
            assert_eq!(get(&f, "appname"), appname, "{line}");
            assert_eq!(get(&f, "procid"), None, "{line}");
        }
    }

    #[test]
    fn five_header_fields_and_no_structured_data() {
        let line = "<30>1 2026-11-28T08:00:01.000Z web01 sshd 1234 - accepted key for deploy";
        let (p, f) = parse(line);
        let Ok(Parsed::Body { span, .. }) = p else {
            panic!("{p:?}")
        };
        assert_eq!(&line[span], "accepted key for deploy");
        assert_eq!(get(&f, "appname"), Some("sshd"));
        assert_eq!(get(&f, "procid"), Some("1234"));

        let line = "<30>1 2026-11-28T08:00:01.000Z web01 cron - - job done";
        let (p, f) = parse(line);
        let Ok(Parsed::Body { span, .. }) = p else {
            panic!("{p:?}")
        };
        assert_eq!(&line[span], "job done");
        assert_eq!(get(&f, "appname"), Some("cron"));
        assert_eq!(get(&f, "procid"), None);
    }

    #[test]
    fn a_one_that_starts_no_header_is_read_as_bsd() {
        let line = "<13>1 apples and pears";
        let (p, f) = parse(line);
        assert!(matches!(p, Ok(Parsed::Body { .. })), "{p:?}");
        assert_eq!(get(&f, "version"), None);
        assert_eq!(get(&f, "pri"), Some("13"));
    }

    #[test]
    fn the_message_starts_at_its_first_byte_and_ends_before_framing() {
        let cases = [
            (
                "<174>May 24 13:09:53 gw01 uvm[0]:  {\"login\":\"admin\"}",
                "{\"login\":\"admin\"}",
                Some("ndjson"),
            ),
            (
                "<165>1 2026-11-30T10:00:00Z h a - - - \u{FEFF}CEF:0|v|p|1|1|n|5|",
                "CEF:0|v|p|1|1|n|5|",
                Some("cef"),
            ),
            (
                "<165>1 2026-11-30T10:00:00Z h a - - - \u{FEFF}plain",
                "plain",
                None,
            ),
            ("<13>Nov 30 10:00:00 h a: m\0", "m", None),
            ("<13>Nov 30 10:00:00 h a: m\r\n\0", "m", None),
            (
                "<13>Nov 30 10:00:00 h a: \u{FEFF}{\"a\":1}\0\n",
                "{\"a\":1}",
                Some("ndjson"),
            ),
        ];
        for (line, message, want) in cases {
            let (p, f) = parse(line);
            let Ok(Parsed::Body { span, hint }) = p else {
                panic!("{line:?}: {p:?}")
            };
            assert_eq!(&line[span], message, "{line:?}");
            assert_eq!(hint, want, "{line:?}");
            assert_eq!(get(&f, "message"), Some(message), "{line:?}");
        }
        let (_, f) = parse(r#"<174>May 24 13:09:53 gw01 uvm[0]:  {"login":"admin"}"#);
        assert_eq!(get(&f, "appname"), Some("uvm"));
    }

    #[test]
    fn broken_structured_data_leaves_no_prefix_on_the_sink() {
        let mut out = Fields::new();
        let line = br#"<13>1 2026-11-28T01:02:03Z host app 1 id [x@1 a="unterminated"#;
        let parsed = Syslog::new().parse(line, &mut out);
        assert!(matches!(parsed, Ok(Parsed::Body { .. })));
        out.field("after", text(b"1"));
        let last = out.as_slice().last().map(|(n, _)| n.as_str());
        assert_eq!(last, Some("after"));
        assert!(
            out.as_slice()
                .iter()
                .all(|(n, _)| !n.starts_with("structured_data."))
        );
    }
}