-
Notifications
You must be signed in to change notification settings - Fork 17
/
enumeratedblock.go
467 lines (414 loc) · 13 KB
/
enumeratedblock.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
/*************************************************************************
* Copyright 2017 Gravwell, Inc. All rights reserved.
* Contact: <legal@gravwell.io>
*
* This software may be modified and distributed under the terms of the
* BSD 2-clause license. See the LICENSE file for details.
**************************************************************************/
package entry
import (
"encoding/binary"
"errors"
"fmt"
"io"
)
const (
EVBlockHeaderLen = 8
MaxEvBlockCount = 0xffff //bonkers, but we need to be safe
MaxEvBlockSize = 1024 * 1024 * 32 //not too lean, but let's remove opportunity for crazy memory pressure
)
var (
ErrEnumeratedValueBlockInvalidCount = errors.New("enumerated value block has too many evs")
ErrEnumeratedValueBlockInvalidSize = errors.New("enumerated value block is too large")
ErrEnumeratedValueBlockCorrupt = errors.New("enumerated value block buffer is corrupted")
)
// EVBlockHeader type expressed for documentation, defines transport header for evlocks.
type EVBlockHeader struct {
Size uint32 //this is the complete size, including the header
Count uint16
pad uint16 //used as a bit of an encoding sanity check and to get word alignment
}
// EVBlock is a block of enumerated values, this is used to help with transporting enumerated values
// over the wire and to guard against users of the API doing wonky things that become expensive
// to encode/decode.
type EVBlock struct {
// keep the size running as we go so encoding is less expensive to ask for it
// size is the encoded size, it includes the header, we keep this so its easy
// to pre-allocate buffers when needed
size uint64
evs []EnumeratedValue
}
// Add adds an enumerated value to an evbloc, this function keeps a running tally of size for fast query.
func (eb *EVBlock) Add(ev EnumeratedValue) {
if eb.size == 0 {
eb.fastAdd(ev)
} else {
eb.updateEv(ev)
}
}
// fastAdd is a fast path adder where there are no evs attached and we can just add this quickly
func (eb *EVBlock) fastAdd(ev EnumeratedValue) {
eb.size = EVBlockHeaderLen + uint64(ev.Size())
eb.evs = []EnumeratedValue{ev}
}
func (eb *EVBlock) updateEv(ev EnumeratedValue) {
for i, x := range eb.evs {
if x.Name == ev.Name {
//update existing
eb.size -= uint64(x.Size())
eb.evs[i] = ev
eb.size += uint64(ev.Size())
return
}
}
//if we hit here it wasn't found
eb.size += uint64(ev.Size())
eb.evs = append(eb.evs, ev)
}
// AddSet adds a slice of enumerated value to an evbloc, this function keeps a running tally of size for fast query.
func (eb *EVBlock) AddSet(evs []EnumeratedValue) {
if eb.size == 0 {
eb.fastAddSet(evs)
} else {
//do the slow crappy way where we are updating evs
for _, ev := range evs {
eb.updateEv(ev)
}
}
}
// fastAddSet is a fast path operation when there are no EVs and we basically just get to set them
func (eb *EVBlock) fastAddSet(evs []EnumeratedValue) {
eb.size = EVBlockHeaderLen
eb.evs = make([]EnumeratedValue, 0, len(evs))
for _, ev := range evs {
eb.size += uint64(ev.Size())
eb.evs = append(eb.evs, ev)
}
}
// Size is just a helper accessor to help with encoding efficiency.
func (eb EVBlock) Size() uint64 {
return eb.size
}
// Count is just a helper accessor to spit out the number of EVs in the block.
func (eb EVBlock) Count() int {
return len(eb.evs)
}
// Populated is a helper to check if there are any EVs.
func (eb EVBlock) Populated() bool {
return eb.size > 0
}
// Reset resets the entry block, the underlying slice is not freed.
func (eb *EVBlock) Reset() {
eb.size = 0
eb.evs = eb.evs[0:0]
}
// Values is an accessor to actualy get the set of enumerated values out of the evblock
// this returns the slice directly, so callers COULD mess with the slice and break the size
// tracker. Basically don't re-use or assign to this slice, if you do the evblock you pulled it from
// is no longer valid.
func (eb EVBlock) Values() []EnumeratedValue {
if len(eb.evs) > 0 {
return eb.evs
}
return nil
}
// Valid is a helper to determine if an evblock is valid for transport
// this means that the max ev count hasn't been exceeded nor has the max size.
// If an evblock is empty, it IS valid. So transports should check Populated
// in addition to valid, when deciding which Entry encoder to use.
func (eb EVBlock) Valid() error {
if len(eb.evs) > MaxEvBlockCount {
return ErrEnumeratedValueBlockInvalidCount
} else if eb.size > MaxEvBlockSize {
return ErrEnumeratedValueBlockInvalidSize
}
return nil
}
// Get retrieves an enumerated value from the set using a name
// if the name does not exist an empty EnumeratedValue and ok = false will be returned
func (eb EVBlock) Get(name string) (ev EnumeratedValue, ok bool) {
for i := range eb.evs {
if eb.evs[i].Name == name {
ev = eb.evs[i]
ok = true
break
}
}
return
}
// Append appends one evblock to another. This function DOES NOT de-duplicate enumerated values
// if the src block already has foobar and so does the destination it will be duplicated
func (eb *EVBlock) Append(seb EVBlock) {
for _, v := range seb.evs {
if v.Valid() {
eb.Add(v)
}
}
return
}
func (eb EVBlock) GobEncode() ([]byte, error) {
return eb.Encode()
}
// Encode encodes an evblock into a byte buffer.
func (eb EVBlock) Encode() (bts []byte, err error) {
// We need to do this check so the function can serve double-duty as a gob encoder
if !eb.Populated() {
return
}
// check if its valid
if err = eb.Valid(); err != nil {
return
}
bts = make([]byte, eb.size) //make our buffer
//encode the header
binary.LittleEndian.PutUint32(bts, uint32(eb.size))
binary.LittleEndian.PutUint16(bts[4:], uint16(len(eb.evs)))
// just make sure its zero, in case something crazy is happening
bts[6] = 0
bts[7] = 0
// now loop on Evs encoding into the buffer
evb := bts[EVBlockHeaderLen:] // get a handle on a dedicated buffer we can iterate on
for _, ev := range eb.evs {
var n int
if n, err = ev.encode(evb); err != nil {
return nil, err
} else if n > len(evb) {
return nil, ErrCorruptedEnumeratedValue
}
evb = evb[n:]
}
return
}
// EncodeBuffer encodes an evblock into a caller provided byte buffer
// and returns the number of bytes consumed and a potential error.
func (eb EVBlock) EncodeBuffer(bts []byte) (r int, err error) {
// check if its valid
if err = eb.Valid(); err != nil {
return
}
if len(bts) < int(eb.size) {
err = ErrInvalidBufferSize
return
}
//encode the header
binary.LittleEndian.PutUint32(bts, uint32(eb.size))
binary.LittleEndian.PutUint16(bts[4:], uint16(len(eb.evs)))
// just make sure its zero, in case something crazy is happening
bts[6] = 0
bts[7] = 0
r = EVBlockHeaderLen
// now loop on Evs encoding into the buffer
evb := bts[EVBlockHeaderLen:] // get a handle on a dedicated buffer we can iterate on
for _, ev := range eb.evs {
var n int
if n, err = ev.encode(evb); err != nil {
return -1, err
} else if n > len(evb) {
return -1, ErrCorruptedEnumeratedValue
}
r += n
evb = evb[n:]
}
return
}
// EncodeWriter encodes an evblock directly into a writer
// and returns the number of bytes consumed and a potential error.
func (eb EVBlock) EncodeWriter(w io.Writer) (r int, err error) {
// check if its valid
if err = eb.Valid(); err != nil {
return
}
bts := make([]byte, EVBlockHeaderLen)
//encode the header
binary.LittleEndian.PutUint32(bts, uint32(eb.size))
binary.LittleEndian.PutUint16(bts[4:], uint16(len(eb.evs)))
// just make sure its zero, in case something crazy is happening
bts[6] = 0
bts[7] = 0
if err = writeAll(w, bts); err != nil {
return
}
r = EVBlockHeaderLen
//now go write the individual EVs
for _, ev := range eb.evs {
if n, err := ev.EncodeWriter(w); err != nil {
return -1, err
} else {
r += n
}
}
return
}
func (eb *EVBlock) GobDecode(b []byte) error {
_, err := eb.Decode(b)
return err
}
// Decode decodes an evblock directly from a buffer and returns the number of bytes consumed.
// This function will copy all referenced memory so the underlying buffer can be re-used.
func (eb *EVBlock) Decode(b []byte) (int, error) {
eb.size = 0
if eb.evs != nil {
eb.evs = nil
}
// If they have passed us a zero-byte buffer, there just weren't any EVs attached to the entry
// We have to do this check because this function may be called during a gob decode, which
// doesn't check if the entry has EVs or not.
if len(b) == 0 {
return 0, nil
}
//check if the buffer is big enough for the header
if len(b) < EVBlockHeaderLen {
return -1, ErrInvalidBufferSize
}
h, err := DecodeEVBlockHeader(b)
if err != nil {
return -1, err
} else if int(h.Size) > len(b) {
return -1, ErrEnumeratedValueBlockCorrupt
}
//advance past the header on the buffer so we can iterate
total := int(EVBlockHeaderLen)
b = b[EVBlockHeaderLen:]
eb.evs = make([]EnumeratedValue, 0, h.Count)
for i := uint16(0); i < h.Count; i++ {
var ev EnumeratedValue
if n, err := ev.Decode(b); err != nil {
return -1, err
} else if n > len(b) {
return -1, ErrCorruptedEnumeratedValue
} else {
b = b[n:]
total += n
eb.evs = append(eb.evs, ev)
}
}
//now check if we actually consumed what the header said we should, this should all match perfectly
if total != int(h.Size) {
return -1, ErrCorruptedEnumeratedValue
}
eb.size = uint64(total)
return total, nil
}
// DecodeAlt decodes an evblock directly from a buffer and returns the number of bytes consumed.
// All data is directly referenced to the provided buffer, the buffer cannot be re-used while any numerated
// value is still in use.
func (eb *EVBlock) DecodeAlt(b []byte) (int, error) {
eb.size = 0
if eb.evs != nil {
eb.evs = nil
}
//check if the buffer is big enough for the header
if len(b) < EVBlockHeaderLen {
return -1, ErrInvalidBufferSize
}
h, err := DecodeEVBlockHeader(b)
if err != nil {
return -1, err
} else if int(h.Size) > len(b) {
return -1, ErrEnumeratedValueBlockCorrupt
}
//advance past the header on the buffer so we can iterate
total := int(EVBlockHeaderLen)
b = b[EVBlockHeaderLen:]
eb.evs = make([]EnumeratedValue, 0, h.Count)
for i := uint16(0); i < h.Count; i++ {
var ev EnumeratedValue
if n, err := ev.DecodeAlt(b); err != nil {
return -1, err
} else if n > len(b) {
return -1, ErrCorruptedEnumeratedValue
} else {
b = b[n:]
total += n
eb.evs = append(eb.evs, ev)
}
}
//now check if we actually consumed what the header said we should, this should all match perfectly
if total != int(h.Size) {
return -1, ErrCorruptedEnumeratedValue
}
eb.size = uint64(total)
return total, nil
}
// DecodeReader decodes an evblock directly from a buffer and returns the number of bytes read and a potential error.
func (eb *EVBlock) DecodeReader(r io.Reader) (int, error) {
var h EVBlockHeader
var err error
eb.size = 0
if eb.evs != nil {
eb.evs = nil
}
//get the header and check it
buff := make([]byte, EVBlockHeaderLen)
if err = readAll(r, buff); err != nil {
return -1, nil
}
if h, err = DecodeEVBlockHeader(buff); err != nil {
return -1, err
}
total := int(EVBlockHeaderLen)
eb.evs = make([]EnumeratedValue, 0, h.Count)
for i := uint16(0); i < h.Count; i++ {
var ev EnumeratedValue
var n int
if n, err = ev.DecodeReader(r); err != nil {
return -1, err
}
total += n
eb.evs = append(eb.evs, ev)
}
//now check if we actually consumed what the header said we should, this should all match perfectly
if total != int(h.Size) {
return -1, ErrCorruptedEnumeratedValue
}
eb.size = uint64(total)
return total, nil
}
// DecodeEVBlockHeader decodes an EVBlockHeader from a buffer and validates it.
// An empty EVBlockHeader and error is returned if the buffer or resulting EVBlockHeader is invalid.
func DecodeEVBlockHeader(buff []byte) (h EVBlockHeader, err error) {
h.Size = binary.LittleEndian.Uint32(buff)
h.Count = binary.LittleEndian.Uint16(buff[4:])
h.pad = binary.LittleEndian.Uint16(buff[6:])
if h.pad != 0 || h.Count > MaxEvBlockCount || h.Size > MaxEvBlockSize {
err = ErrEnumeratedValueBlockCorrupt
return
}
//ok, POTENTIALLY ok
return
}
// Compare compares two evblocks and returns an error describing the differences if there are any.
func (eb EVBlock) Compare(eb2 EVBlock) error {
if eb.size != eb2.size {
return fmt.Errorf("mismatch size: %d != %d", eb.size, eb2.size)
} else if len(eb.evs) != len(eb.evs) {
return fmt.Errorf("mismatch count: %d != %d", len(eb.evs), len(eb.evs))
}
for i := range eb.evs {
if err := eb.evs[i].Compare(eb2.evs[i]); err != nil {
return fmt.Errorf("EV compare on %d failed: %v", i, err)
}
}
return nil
}
// DeepCopy performs a deep copy of an evblock so that any handles on underlying bytes are discarded.
// This function is expensive, use sparingly.
func (eb EVBlock) DeepCopy() (r EVBlock) {
if eb.size == 0 || len(eb.evs) == 0 {
return
}
r = EVBlock{
size: eb.size,
evs: make([]EnumeratedValue, 0, len(eb.evs)),
}
for _, ev := range eb.evs {
r.evs = append(r.evs, EnumeratedValue{
Name: ev.Name, //strings are immuntable, no need to copy
Value: EnumeratedData{
evtype: ev.Value.evtype,
data: append([]byte(nil), ev.Value.data...),
},
})
}
return
}