Debian Codegraph @

rfc5424/rfc5424.go

raw symbols SCIP
1 package rfc5424
2
3 import (
4 "bytes"
5 "fmt"
6 "math"
7 "strconv"
8 "time"
9
10 "github.com/jeromer/syslogparser"
11 "github.com/jeromer/syslogparser/parsercommon"
12 )
13
14 const (
15 NILVALUE = '-'
16
17 // according to https://tools.ietf.org/html/rfc5424#section-6.1
18 // the length of the packet MUST be 2048 bytes or less.
19 // However we will accept a bit more while protecting from exhaustion
20 MAX_PACKET_LEN = 3048
21 )
22
23 var (
24 ErrYearInvalid = &parsercommon.ParserError{ErrorString: "Invalid year in timestamp"}
25 ErrMonthInvalid = &parsercommon.ParserError{ErrorString: "Invalid month in timestamp"}
26 ErrDayInvalid = &parsercommon.ParserError{ErrorString: "Invalid day in timestamp"}
27 ErrHourInvalid = &parsercommon.ParserError{ErrorString: "Invalid hour in timestamp"}
28 ErrMinuteInvalid = &parsercommon.ParserError{ErrorString: "Invalid minute in timestamp"}
29 ErrSecondInvalid = &parsercommon.ParserError{ErrorString: "Invalid second in timestamp"}
30 ErrSecFracInvalid = &parsercommon.ParserError{ErrorString: "Invalid fraction of second in timestamp"}
31 ErrTimeZoneInvalid = &parsercommon.ParserError{ErrorString: "Invalid time zone in timestamp"}
32 ErrInvalidTimeFormat = &parsercommon.ParserError{ErrorString: "Invalid time format"}
33 ErrInvalidAppName = &parsercommon.ParserError{ErrorString: "Invalid app name"}
34 ErrInvalidProcId = &parsercommon.ParserError{ErrorString: "Invalid proc ID"}
35 ErrInvalidMsgId = &parsercommon.ParserError{ErrorString: "Invalid msg ID"}
36 ErrNoStructuredData = &parsercommon.ParserError{ErrorString: "No structured data"}
37 )
38
39 type Parser struct {
40 buff []byte
41 cursor int
42 l int
43 header *header
44 structuredData string
45 message string
46
47 tmpHostname string
48 tmpPriority *parsercommon.Priority
49 }
50
51 type header struct {
52 priority *parsercommon.Priority
53 version int
54 timestamp time.Time
55 hostname string
56 appName string
57 procId string
58 msgId string
59 }
60
61 type partialTime struct {
62 hour int
63 minute int
64 seconds int
65 secFrac float64
66 }
67
68 type fullTime struct {
69 pt *partialTime
70 loc *time.Location
71 }
72
73 type fullDate struct {
74 year int
75 month int
76 day int
77 }
78
79 func NewParser(buff []byte) *Parser {
80 return &Parser{
81 buff: buff,
82 cursor: 0,
83 l: int(
84 math.Min(
85 float64(len(buff)),
86 MAX_PACKET_LEN,
87 ),
88 ),
89 }
90 }
91
92 // Forces a priority for this parser. Priority will not be parsed.
93 func (p *Parser) WithPriority(pri *parsercommon.Priority) {
94 p.tmpPriority = pri
95 }
96
97 // Noop as RFC5424 syslog always has a timezone
98 func (p *Parser) WithLocation(l *time.Location) {}
99
100 // Noop as RFC5424 is strict about timestamp format
101 func (p *Parser) WithTimestampFormat(s string) {}
102
103 // Forces a hostname. Hostname will not be parsed
104 func (p *Parser) WithHostname(h string) {
105 p.tmpHostname = h
106 }
107
108 // Noop as RFC5424 as no tag per se:
109 // The TAG has been split into APP-NAME, PROCID, and MSGID.
110 // Ref: https://tools.ietf.org/html/rfc5424#appendix-A.1
111 func (p *Parser) WithTag(t string) {
112 }
113
114 // DEPRECATED. Use WithLocation() instead
115 func (p *Parser) Location(location *time.Location) {
116 }
117
118 func (p *Parser) Parse() error {
119 hdr, err := p.parseHeader()
120 if err != nil {
121 return err
122 }
123
124 p.header = hdr
125
126 sd, err := p.parseStructuredData()
127 if err != nil {
128 return err
129 }
130
131 p.structuredData = sd
132 p.cursor++
133
134 if p.cursor < p.l {
135 p.message = string(
136 bytes.Trim(
137 p.buff[p.cursor:p.l], " ",
138 ),
139 )
140 }
141
142 return nil
143 }
144
145 func (p *Parser) Dump() syslogparser.LogParts {
146 return syslogparser.LogParts{
147 "priority": p.header.priority.P,
148 "facility": p.header.priority.F.Value,
149 "severity": p.header.priority.S.Value,
150 "version": p.header.version,
151 "timestamp": p.header.timestamp,
152 "hostname": p.header.hostname,
153 "app_name": p.header.appName,
154 "proc_id": p.header.procId,
155 "msg_id": p.header.msgId,
156 "structured_data": p.structuredData,
157 "message": p.message,
158 }
159 }
160
161 // HEADER = PRI VERSION SP TIMESTAMP SP HOSTNAME SP APP-NAME SP PROCID SP MSGID
162 func (p *Parser) parseHeader() (*header, error) {
163 pri, err := p.parsePriority()
164 if err != nil {
165 return nil, err
166 }
167
168 ver, err := p.parseVersion()
169 if err != nil {
170 return nil, err
171 }
172
173 p.cursor++
174
175 ts, err := p.parseTimestamp()
176 if err != nil {
177 return nil, err
178 }
179
180 p.cursor++
181
182 host, err := p.parseHostname()
183 if err != nil {
184 return nil, err
185 }
186
187 // cursor is moved in p.parseHostname()
188
189 appName, err := p.parseAppName()
190 if err != nil {
191 return nil, err
192 }
193
194 p.cursor++
195
196 procId, err := p.parseProcId()
197 if err != nil {
198 return nil, err
199 }
200
201 p.cursor++
202
203 msgId, err := p.parseMsgId()
204 if err != nil {
205 return nil, err
206 }
207
208 p.cursor++
209
210 hdr := &header{
211 version: ver,
212 timestamp: *ts,
213 priority: pri,
214 hostname: host,
215 procId: procId,
216 msgId: msgId,
217 appName: appName,
218 }
219
220 return hdr, nil
221 }
222
223 func (p *Parser) parsePriority() (*parsercommon.Priority, error) {
224 if p.tmpPriority != nil {
225 return p.tmpPriority, nil
226 }
227
228 return parsercommon.ParsePriority(
229 p.buff, &p.cursor, p.l,
230 )
231 }
232
233 func (p *Parser) parseVersion() (int, error) {
234 return parsercommon.ParseVersion(p.buff, &p.cursor, p.l)
235 }
236
237 // https://tools.ietf.org/html/rfc5424#section-6.2.3
238 func (p *Parser) parseTimestamp() (*time.Time, error) {
239 if p.buff[p.cursor] == NILVALUE {
240 p.cursor++
241 return new(time.Time), nil
242 }
243
244 fd, err := parseFullDate(
245 p.buff, &p.cursor, p.l,
246 )
247
248 if err != nil {
249 return nil, err
250 }
251
252 if p.buff[p.cursor] != 'T' {
253 return nil, ErrInvalidTimeFormat
254 }
255
256 p.cursor++
257
258 ft, err := parseFullTime(
259 p.buff, &p.cursor, p.l,
260 )
261
262 if err != nil {
263 return nil, parsercommon.ErrTimestampUnknownFormat
264 }
265
266 nSec, err := toNSec(
267 ft.pt.secFrac,
268 )
269
270 if err != nil {
271 return nil, err
272 }
273
274 ts := time.Date(
275 fd.year,
276 time.Month(fd.month),
277 fd.day,
278 ft.pt.hour,
279 ft.pt.minute,
280 ft.pt.seconds,
281 nSec,
282 ft.loc,
283 )
284
285 return &ts, nil
286 }
287
288 // HOSTNAME = NILVALUE / 1*255PRINTUSASCII
289 func (p *Parser) parseHostname() (string, error) {
290 if p.tmpHostname != "" {
291 return p.tmpHostname, nil
292 }
293
294 h, err := parsercommon.ParseHostname(p.buff, &p.cursor, p.l)
295
296 p.cursor++
297
298 return h, err
299 }
300
301 // APP-NAME = NILVALUE / 1*48PRINTUSASCII
302 func (p *Parser) parseAppName() (string, error) {
303 return parseUpToLen(p.buff, &p.cursor, p.l, 48, ErrInvalidAppName)
304 }
305
306 // PROCID = NILVALUE / 1*128PRINTUSASCII
307 func (p *Parser) parseProcId() (string, error) {
308 return parseUpToLen(p.buff, &p.cursor, p.l, 128, ErrInvalidProcId)
309 }
310
311 // MSGID = NILVALUE / 1*32PRINTUSASCII
312 func (p *Parser) parseMsgId() (string, error) {
313 return parseUpToLen(
314 p.buff, &p.cursor, p.l, 32, ErrInvalidMsgId,
315 )
316 }
317
318 func (p *Parser) parseStructuredData() (string, error) {
319 return parseStructuredData(p.buff, &p.cursor, p.l)
320 }
321
322 // ----------------------------------------------
323 // https://tools.ietf.org/html/rfc5424#section-6
324 // ----------------------------------------------
325
326 // XXX : bind them to Parser ?
327
328 // FULL-DATE : DATE-FULLYEAR "-" DATE-MONTH "-" DATE-MDAY
329 func parseFullDate(buff []byte, cursor *int, l int) (fullDate, error) {
330 var fd fullDate
331
332 year, err := parseYear(buff, cursor, l)
333 if err != nil {
334 return fd, err
335 }
336
337 if buff[*cursor] != '-' {
338 return fd, parsercommon.ErrTimestampUnknownFormat
339 }
340
341 *cursor++
342
343 month, err := parseMonth(buff, cursor, l)
344 if err != nil {
345 return fd, err
346 }
347
348 if buff[*cursor] != '-' {
349 return fd, parsercommon.ErrTimestampUnknownFormat
350 }
351
352 *cursor++
353
354 day, err := parseDay(buff, cursor, l)
355 if err != nil {
356 return fd, err
357 }
358
359 fd = fullDate{
360 year: year,
361 month: month,
362 day: day,
363 }
364
365 return fd, nil
366 }
367
368 // DATE-FULLYEAR = 4DIGIT
369 func parseYear(buff []byte, cursor *int, l int) (int, error) {
370 yearLen := 4
371
372 if *cursor+yearLen > l {
373 return 0, parsercommon.ErrEOL
374 }
375
376 // XXX : we do not check for a valid year (ie. 1999, 2013 etc)
377 // XXX : we only checks the format is correct
378 sub := string(buff[*cursor : *cursor+yearLen])
379
380 *cursor += yearLen
381
382 year, err := strconv.Atoi(sub)
383 if err != nil {
384 return 0, ErrYearInvalid
385 }
386
387 return year, nil
388 }
389
390 // DATE-MONTH = 2DIGIT ; 01-12
391 func parseMonth(buff []byte, cursor *int, l int) (int, error) {
392 return parsercommon.Parse2Digits(buff, cursor, l, 1, 12, ErrMonthInvalid)
393 }
394
395 // DATE-MDAY = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on month/year
396 func parseDay(buff []byte, cursor *int, l int) (int, error) {
397 // XXX : this is a relaxed constraint
398 // XXX : we do not check if valid regarding February or leap years
399 // XXX : we only checks that day is in range [01 -> 31]
400 // XXX : in other words this function will not rant if you provide Feb 31th
401 return parsercommon.Parse2Digits(buff, cursor, l, 1, 31, ErrDayInvalid)
402 }
403
404 // FULL-TIME = PARTIAL-TIME TIME-OFFSET
405 func parseFullTime(buff []byte, cursor *int, l int) (*fullTime, error) {
406 pt, err := parsePartialTime(buff, cursor, l)
407 if err != nil {
408 return nil, err
409 }
410
411 loc, err := parseTimeOffset(buff, cursor, l)
412 if err != nil {
413 return nil, err
414 }
415
416 ft := &fullTime{
417 pt: pt,
418 loc: loc,
419 }
420
421 return ft, nil
422 }
423
424 // PARTIAL-TIME = TIME-HOUR ":" TIME-MINUTE ":" TIME-SECOND[TIME-SECFRAC]
425 func parsePartialTime(buff []byte, cursor *int, l int) (*partialTime, error) {
426 hour, minute, err := getHourMinute(
427 buff, cursor, l,
428 )
429
430 if err != nil {
431 return nil, err
432 }
433
434 if buff[*cursor] != ':' {
435 return nil, ErrInvalidTimeFormat
436 }
437
438 *cursor++
439
440 // ----
441
442 seconds, err := parseSecond(
443 buff, cursor, l,
444 )
445
446 if err != nil {
447 return nil, err
448 }
449
450 pt := &partialTime{
451 hour: hour,
452 minute: minute,
453 seconds: seconds,
454 }
455
456 // ----
457
458 if buff[*cursor] != '.' {
459 return pt, nil
460 }
461
462 *cursor++
463
464 secFrac, err := parseSecFrac(
465 buff, cursor, l,
466 )
467
468 if err != nil {
469 return pt, nil
470 }
471
472 pt.secFrac = secFrac
473
474 return pt, nil
475 }
476
477 // TIME-HOUR = 2DIGIT ; 00-23
478 func parseHour(buff []byte, cursor *int, l int) (int, error) {
479 return parsercommon.Parse2Digits(buff, cursor, l, 0, 23, ErrHourInvalid)
480 }
481
482 // TIME-MINUTE = 2DIGIT ; 00-59
483 func parseMinute(buff []byte, cursor *int, l int) (int, error) {
484 return parsercommon.Parse2Digits(buff, cursor, l, 0, 59, ErrMinuteInvalid)
485 }
486
487 // TIME-SECOND = 2DIGIT ; 00-59
488 func parseSecond(buff []byte, cursor *int, l int) (int, error) {
489 return parsercommon.Parse2Digits(buff, cursor, l, 0, 59, ErrSecondInvalid)
490 }
491
492 // TIME-SECFRAC = "." 1*6DIGIT
493 func parseSecFrac(buff []byte, cursor *int, l int) (float64, error) {
494 maxDigitLen := 6
495
496 max := *cursor + maxDigitLen
497 from := *cursor
498 to := 0
499
500 for to = from; to < max; to++ {
501 if to >= l {
502 break
503 }
504
505 c := buff[to]
506 if !parsercommon.IsDigit(c) {
507 break
508 }
509 }
510
511 sub := string(buff[from:to])
512 if len(sub) == 0 {
513 return 0, ErrSecFracInvalid
514 }
515
516 secFrac, err := strconv.ParseFloat("0."+sub, 64)
517 *cursor = to
518 if err != nil {
519 return 0, ErrSecFracInvalid
520 }
521
522 return secFrac, nil
523 }
524
525 // TIME-OFFSET = "Z" / TIME-NUMOFFSET
526 func parseTimeOffset(buff []byte, cursor *int, l int) (*time.Location, error) {
527
528 if buff[*cursor] == 'Z' {
529 *cursor++
530 return time.UTC, nil
531 }
532
533 return parseNumericalTimeOffset(buff, cursor, l)
534 }
535
536 // TIME-NUMOFFSET = ("+" / "-") TIME-HOUR ":" TIME-MINUTE
537 func parseNumericalTimeOffset(buff []byte, cursor *int, l int) (*time.Location, error) {
538 var loc = new(time.Location)
539
540 sign := buff[*cursor]
541
542 if (sign != '+') && (sign != '-') {
543 return loc, ErrTimeZoneInvalid
544 }
545
546 *cursor++
547
548 hour, minute, err := getHourMinute(buff, cursor, l)
549 if err != nil {
550 return loc, err
551 }
552
553 tzStr := fmt.Sprintf("%s%02d:%02d", string(sign), hour, minute)
554 tmpTs, err := time.Parse("-07:00", tzStr)
555 if err != nil {
556 return loc, err
557 }
558
559 return tmpTs.Location(), nil
560 }
561
562 func getHourMinute(buff []byte, cursor *int, l int) (int, int, error) {
563 hour, err := parseHour(buff, cursor, l)
564 if err != nil {
565 return 0, 0, err
566 }
567
568 if buff[*cursor] != ':' {
569 return 0, 0, ErrInvalidTimeFormat
570 }
571
572 *cursor++
573
574 minute, err := parseMinute(buff, cursor, l)
575 if err != nil {
576 return 0, 0, err
577 }
578
579 return hour, minute, nil
580 }
581
582 func toNSec(sec float64) (int, error) {
583 _, frac := math.Modf(sec)
584 fracStr := strconv.FormatFloat(frac, 'f', 9, 64)
585 fracInt, err := strconv.Atoi(fracStr[2:])
586 if err != nil {
587 return 0, err
588 }
589
590 return fracInt, nil
591 }
592
593 // ------------------------------------------------
594 // https://tools.ietf.org/html/rfc5424#section-6.3
595 // ------------------------------------------------
596
597 func parseStructuredData(buff []byte, cursor *int, l int) (string, error) {
598 var sdData string
599 var found bool
600
601 if buff[*cursor] == NILVALUE {
602 *cursor++
603 return "-", nil
604 }
605
606 if buff[*cursor] != '[' {
607 return sdData, ErrNoStructuredData
608 }
609
610 from := *cursor
611 to := 0
612
613 for to = from; to < l; to++ {
614 if found {
615 break
616 }
617
618 b := buff[to]
619
620 if b == ']' {
621 switch t := to + 1; {
622 case t == l:
623 found = true
624 case t <= l && buff[t] == ' ':
625 found = true
626 }
627 }
628 }
629
630 if found {
631 *cursor = to
632 return string(buff[from:to]), nil
633 }
634
635 return sdData, ErrNoStructuredData
636 }
637
638 func parseUpToLen(buff []byte, cursor *int, l int, maxLen int, e error) (string, error) {
639 var to int
640 var found bool
641 var result string
642
643 max := *cursor + maxLen
644
645 for to = *cursor; (to < max) && (to < l); to++ {
646 if buff[to] == ' ' {
647 found = true
648 break
649 }
650 }
651
652 if found {
653 result = string(buff[*cursor:to])
654 }
655
656 *cursor = to
657
658 if found {
659 return result, nil
660 }
661
662 return "", e
663 }