-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
stdout.go
249 lines (210 loc) · 5.87 KB
/
stdout.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
package loggers
import (
"bytes"
"encoding/json"
"io"
"log"
"os"
"strings"
"time"
"github.com/dmachard/go-dnscollector/dnsutils"
"github.com/dmachard/go-dnscollector/transformers"
"github.com/dmachard/go-logger"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcapgo"
)
func IsStdoutValidMode(mode string) bool {
switch mode {
case
dnsutils.MODE_TEXT,
dnsutils.MODE_JSON,
dnsutils.MODE_FLATJSON,
dnsutils.MODE_PCAP:
return true
}
return false
}
type StdOut struct {
stopProcess chan bool
doneProcess chan bool
stopRun chan bool
doneRun chan bool
inputChan chan dnsutils.DnsMessage
outputChan chan dnsutils.DnsMessage
textFormat []string
config *dnsutils.Config
configChan chan *dnsutils.Config
logger *logger.Logger
writerText *log.Logger
writerPcap *pcapgo.Writer
name string
}
func NewStdOut(config *dnsutils.Config, console *logger.Logger, name string) *StdOut {
console.Info("[%s] logger=stdout - enabled", name)
o := &StdOut{
stopProcess: make(chan bool),
doneProcess: make(chan bool),
stopRun: make(chan bool),
doneRun: make(chan bool),
inputChan: make(chan dnsutils.DnsMessage, config.Loggers.Stdout.ChannelBufferSize),
outputChan: make(chan dnsutils.DnsMessage, config.Loggers.Stdout.ChannelBufferSize),
logger: console,
config: config,
configChan: make(chan *dnsutils.Config),
writerText: log.New(os.Stdout, "", 0),
name: name,
}
o.ReadConfig()
return o
}
func (c *StdOut) GetName() string { return c.name }
func (c *StdOut) SetLoggers(loggers []dnsutils.Worker) {}
func (c *StdOut) ReadConfig() {
if !IsStdoutValidMode(c.config.Loggers.Stdout.Mode) {
c.logger.Fatal("["+c.name+"] logger=stdout - invalid mode: ", c.config.Loggers.Stdout.Mode)
}
if len(c.config.Loggers.Stdout.TextFormat) > 0 {
c.textFormat = strings.Fields(c.config.Loggers.Stdout.TextFormat)
} else {
c.textFormat = strings.Fields(c.config.Global.TextFormat)
}
}
func (o *StdOut) ReloadConfig(config *dnsutils.Config) {
o.LogInfo("reload configuration!")
o.configChan <- config
}
func (c *StdOut) LogInfo(msg string, v ...interface{}) {
c.logger.Info("["+c.name+"] logger=stdout - "+msg, v...)
}
func (c *StdOut) LogError(msg string, v ...interface{}) {
c.logger.Error("["+c.name+"] logger=stdout - "+msg, v...)
}
func (o *StdOut) SetTextWriter(b *bytes.Buffer) {
o.writerText = log.New(os.Stdout, "", 0)
o.writerText.SetOutput(b)
}
func (o *StdOut) SetPcapWriter(w io.Writer) {
o.LogInfo("init pcap writer")
o.writerPcap = pcapgo.NewWriter(w)
if err := o.writerPcap.WriteFileHeader(65536, layers.LinkTypeEthernet); err != nil {
o.logger.Fatal("["+o.name+"] logger=stdout - pcap init error: %e", err)
}
}
func (o *StdOut) Channel() chan dnsutils.DnsMessage {
return o.inputChan
}
func (o *StdOut) Stop() {
o.LogInfo("stopping to run...")
o.stopRun <- true
<-o.doneRun
o.LogInfo("stopping to process...")
o.stopProcess <- true
<-o.doneProcess
}
func (o *StdOut) Run() {
o.LogInfo("running in background...")
// prepare transforms
listChannel := []chan dnsutils.DnsMessage{}
listChannel = append(listChannel, o.outputChan)
subprocessors := transformers.NewTransforms(&o.config.OutgoingTransformers, o.logger, o.name, listChannel, 0)
// goroutine to process transformed dns messages
go o.Process()
// loop to process incoming messages
RUN_LOOP:
for {
select {
case <-o.stopRun:
// cleanup transformers
subprocessors.Reset()
o.doneRun <- true
break RUN_LOOP
// new config provided?
case cfg, opened := <-o.configChan:
if !opened {
return
}
o.config = cfg
o.ReadConfig()
subprocessors.ReloadConfig(&cfg.OutgoingTransformers)
case dm, opened := <-o.inputChan:
if !opened {
o.LogInfo("run: input channel closed!")
return
}
// apply tranforms, init dns message with additionnals parts if necessary
subprocessors.InitDnsMessageFormat(&dm)
if subprocessors.ProcessMessage(&dm) == transformers.RETURN_DROP {
continue
}
// send to output channel
o.outputChan <- dm
}
}
o.LogInfo("run terminated")
}
func (o *StdOut) Process() {
// standard output buffer
buffer := new(bytes.Buffer)
if o.config.Loggers.Stdout.Mode == dnsutils.MODE_PCAP && o.writerPcap == nil {
o.SetPcapWriter(os.Stdout)
}
o.LogInfo("ready to process")
PROCESS_LOOP:
for {
select {
case <-o.stopProcess:
o.doneProcess <- true
break PROCESS_LOOP
case dm, opened := <-o.outputChan:
if !opened {
o.LogInfo("process: output channel closed!")
return
}
switch o.config.Loggers.Stdout.Mode {
case dnsutils.MODE_PCAP:
if len(dm.DNS.Payload) == 0 {
o.LogError("process: no dns payload to encode, drop it")
continue
}
pkt, err := dm.ToPacketLayer()
if err != nil {
o.LogError("unable to pack layer: %s", err)
continue
}
buf := gopacket.NewSerializeBuffer()
opts := gopacket.SerializeOptions{
FixLengths: true,
ComputeChecksums: true,
}
for _, l := range pkt {
l.SerializeTo(buf, opts)
}
bufSize := len(buf.Bytes())
ci := gopacket.CaptureInfo{
Timestamp: time.Unix(int64(dm.DnsTap.TimeSec), int64(dm.DnsTap.TimeNsec)),
CaptureLength: bufSize,
Length: bufSize,
}
o.writerPcap.WritePacket(ci, buf.Bytes())
case dnsutils.MODE_TEXT:
o.writerText.Print(dm.String(o.textFormat,
o.config.Global.TextFormatDelimiter,
o.config.Global.TextFormatBoundary))
case dnsutils.MODE_JSON:
json.NewEncoder(buffer).Encode(dm)
o.writerText.Print(buffer.String())
buffer.Reset()
case dnsutils.MODE_FLATJSON:
flat, err := dm.Flatten()
if err != nil {
o.LogError("process: flattening DNS message failed: %e", err)
}
json.NewEncoder(buffer).Encode(flat)
o.writerText.Print(buffer.String())
buffer.Reset()
}
}
}
o.LogInfo("processing terminated")
}