This repository has been archived by the owner on Nov 27, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
parser.go
588 lines (492 loc) · 13.3 KB
/
parser.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
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
package ipfix
import (
"bytes"
"crypto/sha1"
"encoding/binary"
"errors"
"io"
"sync"
)
// The version field in IPFIX messages should always have the value 10. If it
// does not, you get this error. It's probably a sign of a bug in the parser or
// the exporter and that we have lost synchronization with the data stream.
// Reestablishing the session is the only way forward at this point.
var ErrVersion = errors.New("incorrect version field in message header - out of sync?")
// ErrRead is returned when a packet is not long enough for the field it is
// supposed to contain. This is a sign of an earlier read error or a corrupted
// packet.
var ErrRead = errors.New("short read - malformed packet?")
// ErrProtocol is returned when impossible values that constitute a protocol
// error are encountered.
var ErrProtocol = errors.New("protocol error")
// A Message is the top level construct representing an IPFIX message. A well
// formed message contains one or more sets of data or template information.
type Message struct {
Header MessageHeader
DataRecords []DataRecord
TemplateRecords []TemplateRecord
}
// The MessageHeader provides metadata for the entire Message. The sequence
// number and domain ID can be used to gain knowledge of messages lost on an
// unreliable transport such as UDP.
type MessageHeader struct {
Version uint16 // Always 0x0a
Length uint16
ExportTime uint32 // Epoch seconds
SequenceNumber uint32
DomainID uint32
}
func (h *MessageHeader) unmarshal(s *slice) {
h.Version = s.Uint16()
h.Length = s.Uint16()
h.ExportTime = s.Uint32()
h.SequenceNumber = s.Uint32()
h.DomainID = s.Uint32()
}
type setHeader struct {
SetID uint16
Length uint16
}
func (h *setHeader) unmarshal(s *slice) {
h.SetID = s.Uint16()
h.Length = s.Uint16()
}
type templateHeader struct {
TemplateID uint16
FieldCount uint16
}
func (h *templateHeader) unmarshal(s *slice) {
h.TemplateID = s.Uint16()
h.FieldCount = s.Uint16()
}
// The DataRecord represents a single exported flow. The Fields each describe
// different aspects of the flow (source and destination address, counters,
// service, etc.).
type DataRecord struct {
TemplateID uint16
Fields [][]byte
}
// The TemplateRecord describes a data template, as used by DataRecords.
type TemplateRecord struct {
TemplateID uint16
FieldSpecifiers []TemplateFieldSpecifier
}
// The TemplateFieldSpecifier describes the ID and size of the corresponding
// Fields in a DataRecord.
type TemplateFieldSpecifier struct {
EnterpriseID uint32
FieldID uint16
Length uint16
}
// An option can be passed to New()
type Option func(*Session)
// WithIDAliasing enables or disables template id aliasing. The default is disabled.
func WithIDAliasing(v bool) Option {
return func(s *Session) {
s.withIDAliasing = v
}
}
// The Session is the context for IPFIX messages.
type Session struct {
buffers *sync.Pool
withIDAliasing bool
mut sync.RWMutex
minRecord map[uint16]uint16
signatures map[[sha1.Size]byte]uint16
specifiers map[uint16][]TemplateFieldSpecifier
aliases map[uint16]uint16
nextID uint16
}
// NewSession initializes a new Session based on the provided io.Reader.
func NewSession(opts ...Option) *Session {
var s Session
s.buffers = &sync.Pool{
New: func() interface{} {
return make([]byte, 65536)
},
}
for _, opt := range opts {
opt(&s)
}
if s.withIDAliasing {
s.signatures = make(map[[sha1.Size]byte]uint16)
s.aliases = make(map[uint16]uint16)
s.nextID = 256
}
s.specifiers = make(map[uint16][]TemplateFieldSpecifier)
s.minRecord = make(map[uint16]uint16)
return &s
}
const (
msgHeaderLength = 2 + 2 + 4 + 4 + 4
setHeaderLength = 2 + 2
)
// ParseReader extracts and returns one message from the IPFIX stream. As long
// as err is nil, further messages can be read from the stream. Errors are not
// recoverable -- once an error has been returned, ParseReader should not be
// called again on the same session.
//
// Deprecated: use ParseBuffer instead.
func (s *Session) ParseReader(r io.Reader) (Message, error) {
bs := s.buffers.Get().([]byte)
bs, hdr, err := Read(r, bs)
if err != nil {
return Message{}, err
}
sl := newSlice(bs[msgHeaderLength:])
var msg Message
msg.Header = hdr
msg.TemplateRecords, msg.DataRecords, err = s.readBuffer(sl)
s.buffers.Put(bs)
return msg, err
}
// ParseBuffer extracts one message from the given buffer and returns it. Err
// is nil if the buffer could be parsed correctly. ParseBuffer is goroutine safe.
func (s *Session) ParseBuffer(bs []byte) (Message, error) {
var msg Message
var err error
sl := newSlice(bs)
msg.Header.unmarshal(sl)
msg.TemplateRecords, msg.DataRecords, err = s.readBuffer(sl)
return msg, err
}
// ParseBufferAll extracts all message from the given buffer and returns them.
// Err is nil if the buffer could be parsed correctly. ParseBufferAll is
// goroutine safe.
func (s *Session) ParseBufferAll(bs []byte) ([]Message, error) {
var msgs []Message
var err error
sl := newSlice(bs)
for sl.Len() > 0 {
var msg Message
msg.Header.unmarshal(sl)
length := int(msg.Header.Length - msgHeaderLength)
cut := newSlice(sl.Cut(length))
if msg.TemplateRecords, msg.DataRecords, err = s.readBuffer(cut); err != nil {
break
}
msgs = append(msgs, msg)
}
return msgs, err
}
func (s *Session) readBuffer(sl *slice) ([]TemplateRecord, []DataRecord, error) {
var ts, trecs []TemplateRecord
var ds, drecs []DataRecord
var err error
for sl.Len() > 0 {
// Read a set header
var setHdr setHeader
setHdr.unmarshal(sl)
if debug {
dl.Printf("setHdr: %+v", setHdr)
}
if setHdr.Length < setHeaderLength {
// Set cannot be shorter than its header
if debug {
dl.Println("setHdr too short")
}
return nil, nil, io.ErrUnexpectedEOF
}
// Grab the bytes representing the set
setLen := int(setHdr.Length) - setHeaderLength
setSl := newSlice(sl.Cut(setLen))
if err := sl.Error(); err != nil {
if debug {
dl.Println("slice error")
}
return nil, nil, err
}
// Parse them
ts, ds, err = s.readSet(setHdr, setSl)
if err != nil {
if debug {
dl.Println("readSet:", err)
}
return nil, nil, err
}
trecs = append(trecs, ts...)
drecs = append(drecs, ds...)
}
return trecs, drecs, nil
}
func (s *Session) readSet(setHdr setHeader, sl *slice) ([]TemplateRecord, []DataRecord, error) {
var trecs []TemplateRecord
var drecs []DataRecord
minLen := int(s.getMinRecLen(setHdr.SetID))
for sl.Len() > 0 && sl.Error() == nil {
if sl.Len() < minLen {
if debug {
dl.Println("ignoring padding")
}
// Padding
return trecs, drecs, sl.Error()
}
// Set ID
//
// Identifies the Set. A value of 2 is reserved for Template Sets. A
// value of 3 is reserved for Options Template Sets. Values from 4 to
// 255 are reserved for future use. Values 256 and above are used for
// Data Sets. The Set ID values of 0 and 1 are not used, for
// historical reasons [RFC3954].
switch {
case setHdr.SetID < 2:
// Unused, shouldn't happen
if debug {
dl.Println("bad SetID", setHdr.SetID)
}
return nil, nil, ErrProtocol
case setHdr.SetID == 2:
// Template Set
if debug {
dl.Println("parsing template set")
}
tr := s.readTemplateRecord(sl)
s.registerTemplateRecord(&tr)
trecs = append(trecs, tr)
case setHdr.SetID == 3:
// Options Template Set, not handled
if debug {
dl.Println("skipping option template set")
}
sl.Cut(sl.Len())
case setHdr.SetID > 3 && setHdr.SetID < 256:
// Reserved, shouldn't happen
if debug {
dl.Println("bad SetID", setHdr.SetID)
}
return nil, nil, ErrProtocol
default:
// Data set
if debug {
dl.Println("parsing data set")
}
tpl := s.lookupTemplateFieldSpecifiers(setHdr.SetID)
if tpl != nil {
// Data set
ds, err := s.readDataRecord(sl, tpl)
if err != nil {
return nil, nil, err
}
ds.TemplateID = s.unaliasTemplateID(setHdr.SetID)
drecs = append(drecs, ds)
} else {
// Data set with unknown template
// We can't trust set length, because we might be out of sync.
// Consume rest of message.
return trecs, drecs, sl.Error()
}
}
}
return trecs, drecs, sl.Error()
}
func (s *Session) unaliasTemplateID(tid uint16) uint16 {
if s.withIDAliasing {
s.mut.RLock()
tid = s.aliases[tid]
s.mut.RUnlock()
}
return tid
}
func (s *Session) readDataRecord(sl *slice, tpl []TemplateFieldSpecifier) (DataRecord, error) {
var dr DataRecord
dr.Fields = make([][]byte, len(tpl))
var err error
total := 0
for i := range tpl {
var val []byte
if tpl[i].Length == 65535 {
val, err = s.readVariableLength(sl)
if err != nil {
return DataRecord{}, err
}
} else {
l := int(tpl[i].Length)
val = sl.Cut(l)
}
dr.Fields[i] = val
total += len(val)
}
// The loop above keeps slices of the original buffer. But that buffer
// will be recycled so we need to copy them to separate storage. It's more
// efficient to do it this way, with a single allocation at the end than
// doing individual allocations along the way.
cp := make([]byte, total)
next := 0
for i := range dr.Fields {
ln := copy(cp[next:], dr.Fields[i])
dr.Fields[i] = cp[next : next+ln]
next += ln
}
return dr, sl.Error()
}
func (s *Session) readTemplateRecord(sl *slice) TemplateRecord {
var th templateHeader
th.unmarshal(sl)
if debug {
dl.Printf("templateHeader: %+v", th)
}
var tr TemplateRecord
tr.TemplateID = th.TemplateID
tr.FieldSpecifiers = make([]TemplateFieldSpecifier, th.FieldCount)
for i := 0; i < int(th.FieldCount); i++ {
f := TemplateFieldSpecifier{}
f.FieldID = sl.Uint16()
f.Length = sl.Uint16()
if f.FieldID >= 0x8000 {
f.FieldID -= 0x8000
f.EnterpriseID = sl.Uint32()
}
tr.FieldSpecifiers[i] = f
}
return tr
}
func (s *Session) registerTemplateRecord(tr *TemplateRecord) {
if s.withIDAliasing {
tr.TemplateID = s.registerAliasedTemplateRecord(*tr)
} else {
s.registerUnaliasedTemplateRecord(*tr)
}
}
func (s *Session) registerUnaliasedTemplateRecord(tr TemplateRecord) {
// Update templates and minimum record cache
tid := tr.TemplateID
tpl := tr.FieldSpecifiers
minLen := calcMinRecLen(tpl)
s.mut.Lock()
defer s.mut.Unlock()
if minLen == 0 {
delete(s.specifiers, tid)
} else {
s.specifiers[tid] = tpl
}
s.minRecord[tid] = minLen
}
func (s *Session) registerAliasedTemplateRecord(tr TemplateRecord) uint16 {
var tid uint16
if len(tr.FieldSpecifiers) == 0 {
s.withdrawAliasedTemplateRecord(tr)
tid = tr.TemplateID
} else {
tid = s.aliasTemplateRecord(tr)
}
if debug {
dl.Printf("Mapped template id %d -> %d", tr.TemplateID, tid)
}
return tid
}
func (s *Session) aliasTemplateRecord(tr TemplateRecord) uint16 {
var buffer bytes.Buffer
binary.Write(&buffer, binary.BigEndian, tr.FieldSpecifiers)
hash := sha1.Sum(buffer.Bytes())
var ntid uint16
s.mut.Lock()
defer s.mut.Unlock()
if id, ok := s.signatures[hash]; ok {
ntid = id
} else {
ntid = s.nextID
s.signatures[hash] = ntid
s.specifiers[ntid] = tr.FieldSpecifiers
s.nextID++
if s.nextID == 65535 {
panic("IPFIX has run out of virtual template ids!")
}
s.minRecord[ntid] = calcMinRecLen(tr.FieldSpecifiers)
}
if _, ok := s.aliases[tr.TemplateID]; !ok {
s.aliases[tr.TemplateID] = ntid
}
return ntid
}
func (s *Session) withdrawAliasedTemplateRecord(tr TemplateRecord) {
s.mut.Lock()
defer s.mut.Unlock()
delete(s.aliases, tr.TemplateID)
}
func calcMinRecLen(tpl []TemplateFieldSpecifier) uint16 {
var minLen uint16
for i := range tpl {
if tpl[i].Length == 65535 {
minLen++
} else {
minLen += tpl[i].Length
}
}
return minLen
}
func (s *Session) lookupTemplateFieldSpecifiers(tid uint16) []TemplateFieldSpecifier {
var tpl []TemplateFieldSpecifier
if s.withIDAliasing {
tpl = s.lookupAliasedTemplateFieldSpecifiers(tid)
} else {
tpl = s.lookupUnaliasedTemplateFieldSpecifiers(tid)
}
return tpl
}
func (s *Session) lookupUnaliasedTemplateFieldSpecifiers(tid uint16) []TemplateFieldSpecifier {
var tpl []TemplateFieldSpecifier
s.mut.RLock()
defer s.mut.RUnlock()
if id, ok := s.specifiers[tid]; ok {
tpl = id
}
return tpl
}
func (s *Session) lookupAliasedTemplateFieldSpecifiers(tid uint16) []TemplateFieldSpecifier {
var tpl []TemplateFieldSpecifier
s.mut.RLock()
if id, ok := s.aliases[tid]; ok {
tpl = s.specifiers[id]
}
s.mut.RUnlock()
return tpl
}
func (s *Session) getMinRecLen(tid uint16) uint16 {
var minLen uint16
s.mut.RLock()
defer s.mut.RUnlock()
if s.withIDAliasing {
minLen = s.minRecord[s.aliases[tid]]
} else {
minLen = s.minRecord[tid]
}
return minLen
}
func (s *Session) readVariableLength(sl *slice) (val []byte, err error) {
var l int
l0 := sl.Uint8()
if l0 < 255 {
l = int(l0)
} else {
l = int(sl.Uint16())
}
return sl.Cut(l), sl.Error()
}
func (s *Session) ExportTemplateRecords() []TemplateRecord {
trecs := make([]TemplateRecord, 0, len(s.specifiers))
s.mut.RLock()
defer s.mut.RUnlock()
if s.withIDAliasing {
for t, a := range s.aliases {
tr := TemplateRecord{
TemplateID: t,
FieldSpecifiers: s.specifiers[a],
}
trecs = append(trecs, tr)
}
} else {
for t, fs := range s.specifiers {
tr := TemplateRecord{
TemplateID: t,
FieldSpecifiers: fs,
}
trecs = append(trecs, tr)
}
}
return trecs
}
func (s *Session) LoadTemplateRecords(trecs []TemplateRecord) {
for _, tr := range trecs {
s.registerTemplateRecord(&tr)
}
}