forked from Cistern/sflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decoder.go
101 lines (80 loc) · 2.12 KB
/
decoder.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
package sflow
import (
"encoding/binary"
"errors"
"io"
)
const (
// MaximumRecordLength defines the maximum length acceptable for decoded records.
// This maximum prevents from excessive memory allocation.
// The value is derived from MAX_PKT_SIZ 65536 in the reference sFlow implementation
// https://github.com/sflow/sflowtool/blob/bd3df6e11bdf/src/sflowtool.c#L4313.
MaximumRecordLength = 65536
// MaximumHeaderLength defines the maximum length acceptable for decoded flow samples.
// This maximum prevents from excessive memory allocation.
// The value is set to maximum transmission unit (MTU), as the header of a network packet
// may not exceed the MTU.
MaximumHeaderLength = 1500
)
var ErrUnsupportedDatagramVersion = errors.New("sflow: unsupported datagram version")
type Decoder struct {
reader io.ReadSeeker
}
func NewDecoder(r io.ReadSeeker) *Decoder {
return &Decoder{
reader: r,
}
}
func (d *Decoder) Use(r io.ReadSeeker) {
d.reader = r
}
func (d *Decoder) Decode() (*Datagram, error) {
// Decode headers first
dgram := &Datagram{}
var err error
err = binary.Read(d.reader, binary.BigEndian, &dgram.Version)
if err != nil {
return nil, err
}
if dgram.Version != 5 {
return nil, ErrUnsupportedDatagramVersion
}
err = binary.Read(d.reader, binary.BigEndian, &dgram.IpVersion)
if err != nil {
return nil, err
}
ipLen := 4
if dgram.IpVersion == 2 {
ipLen = 16
}
ipBuf := make([]byte, ipLen)
_, err = d.reader.Read(ipBuf)
if err != nil {
return nil, err
}
dgram.IpAddress = ipBuf
err = binary.Read(d.reader, binary.BigEndian, &dgram.SubAgentId)
if err != nil {
return nil, err
}
err = binary.Read(d.reader, binary.BigEndian, &dgram.SequenceNumber)
if err != nil {
return nil, err
}
err = binary.Read(d.reader, binary.BigEndian, &dgram.Uptime)
if err != nil {
return nil, err
}
err = binary.Read(d.reader, binary.BigEndian, &dgram.NumSamples)
if err != nil {
return nil, err
}
for i := dgram.NumSamples; i > 0; i-- {
sample, err := decodeSample(d.reader)
if err != nil {
return nil, err
}
dgram.Samples = append(dgram.Samples, sample)
}
return dgram, nil
}