-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcontainer.go
365 lines (313 loc) · 8.77 KB
/
container.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
/*
* Copyright (c) 2017,2018 by Farsight Security, Inc.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package nmsg
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"math/rand"
"google.golang.org/protobuf/proto"
)
const (
nmsgVersion = 2
nmsgFlagZlib = 1
nmsgFlagFragment = 2
headerSize = 10
)
var (
nmsgMagic = [4]byte{'N', 'M', 'S', 'G'}
errBadMagic = errors.New("Bad NMSG Magic Number")
containerOverhead = 10
fragmentOverhead = 10 + 4 + 24
)
type containerHeader struct {
Magic [4]byte
Flags, Version byte
Length uint32
}
// isCompressed() and isFragmented() are helper functions for readability.
func (h *containerHeader) isCompressed() bool {
return h.Flags&nmsgFlagZlib != 0
}
func (h *containerHeader) isFragmented() bool {
return h.Flags&nmsgFlagFragment != 0
}
// A Container encapsulates an Nmsg envelope, and maintains metadata for
// sizing containers as payloads are added.
type Container struct {
// Maximum size of a container. AddPayload attempts to keep the container
// under this size.
maxSize int
// Maximum size of fragment or container. Any containers larger than this
// will be fragmented by WriteTo.
writeSize int
// If true, compress container contents before writing.
compress bool
// If true, container was populated from compressed data
// This is primarily used in fragment reassembly to detect whether the
// fragmented data was compressed prior to fragmentation.
isCompressed bool
// If nonzero, an estimate of the effectiveness of compression, expressed
// as compressedSize / uncompressedSize. Default: 0.5
compressionRatio float32
// The current estimated size of the serialized data, before compression
size int
Nmsg
*NmsgFragment
}
// NewContainer creates a new empty NMSG container.
func NewContainer() *Container {
c := &Container{size: containerOverhead}
c.SetMaxSize(0, 0)
return c
}
// SetMaxSize sets the maximum size (including Marshaling overhead,
// container header, and anticipated compression ratio) of a container.
// AddPayload attempts to keep the container within this size.
//
// writeSize specifies the maximum size of containers or fragments.
// Containers larger than writeSize will be written as fragments instead
// of single containers.
//
// A writeSize value of 0 is treated as equal to size.
func (c *Container) SetMaxSize(size, writeSize int) {
if size < MinContainerSize {
size = MinContainerSize
}
if size > MaxContainerSize {
size = MaxContainerSize
}
if writeSize < size {
writeSize = size
}
c.maxSize = size
c.writeSize = writeSize
}
// SetCompression instructs WriteTo to write containers with compressed
// (if true) or uncompressed (if false) contents.
func (c *Container) SetCompression(compress bool) {
c.compress = compress
}
// SetCompressionRatio sets an estimated compression ratio for the data.
// The default value is 2.0
func (c *Container) SetCompressionRatio(ratio float32) {
c.compressionRatio = ratio
}
// SetSequenced sets or unsets sequencing on the container stream.
// The sequence number is updated every time WriteTo() is called.
func (c *Container) SetSequenced(sequenced bool) {
if sequenced {
seqid := uint64(rand.Uint32()) << 32
seqid |= uint64(rand.Uint32())
c.Nmsg.SequenceId = proto.Uint64(seqid)
c.Nmsg.Sequence = proto.Uint32(0)
} else {
c.Nmsg.SequenceId = nil
c.Nmsg.Sequence = nil
}
}
// AddPayload adds the supplied NmsgPayload to the Container if possible.
//
// The return value 'full' is true if the container is full and needs to
// be emptied with WriteTo().
//
// The return value 'ok' is true if the payload was successfully added to
// the container, otherwise, AddPayload() must be called again after WriteTo().
//
// Both ok and full may be true if the payload is larger than the container's
// MaxSize, or if the container is full after adding the payload.
func (c *Container) AddPayload(p *NmsgPayload) (ok, full bool) {
seqSize := 0
if c.Nmsg.Sequence != nil && c.Nmsg.SequenceId != nil {
seqSize = 18 // 6 + 12 bytes for protobuf-encoded sequence and sequenceId values
}
limit := c.maxSize
if c.compress {
if c.compressionRatio > 0 {
limit = int(float32(limit) * c.compressionRatio)
} else {
limit *= 2
}
}
ps := p.payloadSize()
if c.size+ps+seqSize > limit {
full = true
if c.size != containerOverhead {
return
}
}
ok = true
c.size += ps
c.Nmsg.Payloads = append(c.Nmsg.Payloads, p)
c.Nmsg.PayloadCrcs = append(c.Nmsg.PayloadCrcs, nmsgCRC(p.Payload))
return
}
// Reset discards payloads and crcs from the Container
func (c *Container) Reset() {
c.Nmsg.Payloads = c.Nmsg.Payloads[:0]
c.Nmsg.PayloadCrcs = c.Nmsg.PayloadCrcs[:0]
c.NmsgFragment = nil
}
// WriteTo writes the Container to Writer w. If the
// container requires fragmentation, it will call
// w.Write() multiple times.
func (c *Container) WriteTo(w io.Writer) (int64, error) {
var buf bytes.Buffer
header := containerHeader{
Magic: nmsgMagic,
Version: nmsgVersion,
}
defer c.Reset()
b, err := proto.Marshal(&c.Nmsg)
if err != nil {
return 0, err
}
if c.compress {
b, err = zbufDeflate(b)
if err != nil {
return 0, err
}
header.Flags |= nmsgFlagZlib
}
header.Length = uint32(len(b))
if c.Nmsg.Sequence != nil {
*c.Nmsg.Sequence++
}
c.size = containerOverhead
if len(b)+containerOverhead > c.writeSize {
return c.writeFragments(w, b)
}
if err = binary.Write(&buf, binary.BigEndian, &header); err != nil {
return 0, err
}
if _, err = buf.Write(b); err != nil {
return 0, err
}
return buf.WriteTo(w)
}
func (c *Container) writeFragments(w io.Writer, b []byte) (int64, error) {
header := containerHeader{
Magic: nmsgMagic,
Version: nmsgVersion,
Flags: nmsgFlagFragment,
}
if c.compress {
header.Flags |= nmsgFlagZlib
}
fragSize := c.writeSize - fragmentOverhead
lastFrag := len(b) / fragSize
fragID := rand.Uint32()
nf := NmsgFragment{
Id: proto.Uint32(fragID),
Current: proto.Uint32(uint32(0)),
Last: proto.Uint32(uint32(lastFrag)),
Crc: proto.Uint32(nmsgCRC(b)),
}
var written int64
for i := 0; i <= lastFrag; i++ {
var buf bytes.Buffer
fblen := len(b)
if fblen > fragSize {
fblen = fragSize
}
*nf.Current = uint32(i)
nf.Fragment = b[:fblen]
b = b[fblen:]
fbytes, err := proto.Marshal(&nf)
if err != nil {
return written, err
}
header.Length = uint32(len(fbytes))
if err = binary.Write(&buf, binary.BigEndian, header); err != nil {
return written, err
}
if _, err = buf.Write(fbytes); err != nil {
return written, err
}
n, err := buf.WriteTo(w)
if err != nil {
return written, err
}
written += n
}
return written, nil
}
// ReadFrom Reads a Container from the given io.Reader. It returns the
// number of container bytes read on success.
func (c *Container) ReadFrom(r io.Reader) (n int64, err error) {
/*
* The bytes.Buffer Grow() method may panic with ErrTooLarge.
* We catch this panic (and any other error panic()s and return
* an error.
*/
defer func() {
if r := recover(); r != nil {
var ok bool
if err, ok = r.(error); !ok {
err = fmt.Errorf("nmsg.Container ReadFrom: panic %v", r)
}
}
}()
var buf bytes.Buffer
var h containerHeader
if n, err = io.CopyN(&buf, r, headerSize); err != nil {
return n, err
}
err = binary.Read(&buf, binary.BigEndian, &h)
if err != nil {
return n, &dataError{err}
}
if h.Magic != nmsgMagic {
return 0, &dataError{errBadMagic}
}
buf.Grow(int(h.Length))
if n, err = io.CopyN(&buf, r, int64(h.Length)); err != nil {
return int64(buf.Len()), err
}
// err = c.fromBytesHeader(buf.Bytes(), &h)
err = c.fromNmsgBytes(buf.Bytes(), h.isCompressed(), h.isFragmented())
if err != nil {
err = &dataError{err}
}
return int64(buf.Len()), err
}
// FromBytes parses the given buffer as an NMSG container and stores
// the result in the receiver *Container.
func (c *Container) FromBytes(b []byte) error {
var h containerHeader
buf := bytes.NewBuffer(b)
err := binary.Read(buf, binary.BigEndian, &h)
if err != nil {
return err
}
if h.Magic != nmsgMagic {
return errBadMagic
}
return c.fromNmsgBytes(buf.Bytes(), h.isCompressed(), h.isFragmented())
}
// fromNmsgBytes parses the contents (b) of an NMSG container, according to
// whether the container contents are compressed, fragmented, or both.
func (c *Container) fromNmsgBytes(b []byte, compressed, fragmented bool) error {
var err error
cbytes := b
c.isCompressed = compressed
if compressed {
cbytes, err = zbufInflate(b)
if err != nil {
return err
}
}
if fragmented {
c.NmsgFragment = &NmsgFragment{}
return proto.Unmarshal(cbytes, c.NmsgFragment)
}
c.NmsgFragment = nil
return proto.Unmarshal(cbytes, &c.Nmsg)
}