forked from coredns/coredns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dnstap_encoder.go
92 lines (81 loc) · 1.79 KB
/
dnstap_encoder.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
package dnstapio
import (
"encoding/binary"
"fmt"
"io"
tap "github.com/dnstap/golang-dnstap"
fs "github.com/farsightsec/golang-framestream"
"github.com/golang/protobuf/proto"
)
const (
frameLenSize = 4
protobufSize = 1024 * 1024
)
type dnstapEncoder struct {
fse *fs.Encoder
opts *fs.EncoderOptions
writer io.Writer
buffer *proto.Buffer
}
func newDnstapEncoder(o *fs.EncoderOptions) *dnstapEncoder {
return &dnstapEncoder{
opts: o,
buffer: proto.NewBuffer(make([]byte, 0, protobufSize)),
}
}
func (enc *dnstapEncoder) resetWriter(w io.Writer) error {
fse, err := fs.NewEncoder(w, enc.opts)
if err != nil {
return err
}
if err = fse.Flush(); err != nil {
return err
}
enc.fse = fse
enc.writer = w
return nil
}
func (enc *dnstapEncoder) writeMsg(msg *tap.Dnstap) error {
if len(enc.buffer.Bytes()) >= protobufSize {
if err := enc.flushBuffer(); err != nil {
return err
}
}
bufLen := len(enc.buffer.Bytes())
// add placeholder for frame length
if err := enc.buffer.EncodeFixed32(0); err != nil {
enc.buffer.SetBuf(enc.buffer.Bytes()[:bufLen])
return err
}
if err := enc.buffer.Marshal(msg); err != nil {
enc.buffer.SetBuf(enc.buffer.Bytes()[:bufLen])
return err
}
enc.encodeFrameLen(enc.buffer.Bytes()[bufLen:])
return nil
}
func (enc *dnstapEncoder) flushBuffer() error {
if enc.fse == nil || enc.writer == nil {
return fmt.Errorf("no writer")
}
buf := enc.buffer.Bytes()
written := 0
for written < len(buf) {
n, err := enc.writer.Write(buf[written:])
written += n
if err != nil {
return err
}
}
enc.buffer.Reset()
return nil
}
func (enc *dnstapEncoder) encodeFrameLen(buf []byte) {
binary.BigEndian.PutUint32(buf, uint32(len(buf)-4))
}
func (enc *dnstapEncoder) close() error {
if enc.fse != nil {
return enc.fse.Close()
}
return nil
}