-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
common.go
104 lines (97 loc) · 2.34 KB
/
common.go
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
// SPDX-FileCopyrightText: 2021-2023 Winni Neessen <wn@neessen.dev>
//
// SPDX-License-Identifier: MIT
package parsesyslog
import (
"bufio"
"bytes"
"fmt"
"math"
)
// ReadMsgLength reads the first bytes of the log message which represent the total length of
// the log message
func ReadMsgLength(r *bufio.Reader) (int, error) {
ls, _, err := ReadBytesUntilSpace(r)
if err != nil {
return 0, err
}
return Atoi(ls)
}
// ReadBytesUntilSpace is a helper method that takes a io.Reader and reads all bytes until it hits
// a Space character. It returns the read bytes, the amount of bytes read and an error if one
// occurred
func ReadBytesUntilSpace(r *bufio.Reader) ([]byte, int, error) {
buf, err := r.ReadSlice(' ')
if err != nil {
return buf, len(buf), err
}
if len(buf) > 0 {
return buf[:len(buf)-1], len(buf), nil
}
return buf, len(buf), nil
}
// ReadBytesUntilSpaceOrNilValue is a helper method that takes a io.Reader and reads all bytes until
// it hits a Space character or the NILVALUE ("-"). It returns the read bytes, the amount of bytes read
// and an error if one occurred
func ReadBytesUntilSpaceOrNilValue(r *bufio.Reader, buf *bytes.Buffer) (int, error) {
buf.Reset()
tb := 0
for {
b, err := r.ReadByte()
if err != nil {
return tb, err
}
tb++
if b == ' ' {
return tb, nil
}
if b == '-' && (buf.Len() > 0 && buf.Bytes()[tb-2] == ' ') {
return tb, nil
}
buf.WriteByte(b)
}
}
// ParsePriority will try to parse the priority part of the RFC3164 header
// See: https://tools.ietf.org/search/rfc3164#section-4.1.1
func ParsePriority(r *bufio.Reader, buf *bytes.Buffer, lm *LogMsg) error {
buf.Reset()
b, err := r.ReadByte()
if err != nil {
return err
}
if b != '<' {
return ErrWrongFormat
}
for {
b, err = r.ReadByte()
if err != nil {
return err
}
if b == '>' {
break
}
buf.WriteByte(b)
}
p, err := Atoi(buf.Bytes())
if err != nil {
return ErrInvalidPrio
}
lm.Priority = Priority(p)
lm.Facility = FacilityFromPrio(lm.Priority)
lm.Severity = SeverityFromPrio(lm.Priority)
return nil
}
// Atoi performs allocation free ASCII number to integer conversion
func Atoi(b []byte) (int, error) {
z := 0
c := 0
for x := len(b); x > 0; x-- {
y := int(b[x-1]) - 0x30
if y > 10 {
return 0, fmt.Errorf("not a number: %s", string(b[x-1]))
}
z += y * int(math.Pow10(c))
c++
}
return z, nil
}