-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
plugin_tcp.go
460 lines (395 loc) · 10.8 KB
/
plugin_tcp.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
package memcache
// Memcache TCP Protocol Plugin implementation
import (
"time"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/packetbeat/procs"
"github.com/elastic/beats/packetbeat/protos"
"github.com/elastic/beats/packetbeat/protos/applayer"
"github.com/elastic/beats/packetbeat/protos/tcp"
)
type tcpMemcache struct {
tcpConfig
}
type tcpConfig struct {
tcpTransTimeout time.Duration
}
type tcpConnectionData struct {
Streams [2]*stream
connection *connection
}
// memcache application layer streams
type stream struct {
applayer.Stream
parser parser
}
type connection struct {
timer *time.Timer
requests messageList
responses messageList
}
type messageList struct {
head *message
tail *message
}
const defaultTCPTransDuration uint = 200
func ensureMemcacheConnection(private protos.ProtocolData) *tcpConnectionData {
if private == nil {
return &tcpConnectionData{}
}
priv, ok := private.(*tcpConnectionData)
if !ok {
logp.Warn("memcache connection data type error, create new one")
return &tcpConnectionData{}
}
if priv == nil {
logp.Warn("Unexpected: memcache TCP connection data not set, create new one")
return &tcpConnectionData{}
}
return priv
}
func isMemcacheConnection(private protos.ProtocolData) bool {
if private == nil {
return false
}
_, ok := private.(*tcpConnectionData)
return ok
}
func (mc *Memcache) ConnectionTimeout() time.Duration {
return mc.tcpTransTimeout
}
// Parse is called from TCP layer when payload data is available for parsing.
func (mc *Memcache) Parse(
pkt *protos.Packet,
tcptuple *common.TcpTuple,
dir uint8,
private protos.ProtocolData,
) protos.ProtocolData {
defer logp.Recover("ParseMemcache(TCP) exception")
tcpConn := ensureMemcacheConnection(private)
debug("memcache connection %p", tcpConn)
tcpConn = mc.memcacheParseTCP(tcpConn, pkt, tcptuple, dir)
if tcpConn == nil {
// explicitely return nil if tcpConn equals nil so ProtocolData really is nil
return nil
}
return tcpConn
}
func (mc *Memcache) newStream(tcptuple *common.TcpTuple) *stream {
s := &stream{}
s.parser.init(&mc.config)
s.Stream.Init(tcp.TCP_MAX_DATA_IN_STREAM)
return s
}
func (mc *Memcache) memcacheParseTCP(
tcpConn *tcpConnectionData,
pkt *protos.Packet,
tcptuple *common.TcpTuple,
dir uint8,
) *tcpConnectionData {
// assume we are in sync
stream := tcpConn.Streams[dir]
if stream == nil {
stream = mc.newStream(tcptuple)
tcpConn.Streams[dir] = stream
}
debug("add payload to stream(%p): %v", stream, dir)
if err := stream.Append(pkt.Payload); err != nil {
debug("%v, dropping TCP streams", err)
mc.pushAllTCPTrans(tcpConn.connection)
tcpConn.drop(dir)
return nil
}
if tcpConn.connection == nil {
tcpConn.connection = &connection{}
} else {
stopped := tcpConn.connection.timer.Stop()
if !stopped {
// timer was stopped by someone else, create new connection
tcpConn.connection = &connection{}
}
}
conn := tcpConn.connection
for stream.Buf.Total() > 0 {
debug("stream(%p) try to content", stream)
msg, err := stream.parse(pkt.Ts)
if err != nil {
// parsing error, drop tcp stream and retry with next segement
debug("Ignore Memcache message, drop tcp stream: %v", err)
mc.pushAllTCPTrans(conn)
tcpConn.drop(dir)
return nil
}
if msg == nil {
// wait for more data
break
}
stream.reset()
tuple := tcptuple.IpPort()
err = mc.onTCPMessage(conn, tuple, dir, msg)
if err != nil {
logp.Warn("error processing memcache message: %s", err)
}
}
conn.timer = time.AfterFunc(mc.tcpTransTimeout, func() {
debug("connection=%p timed out", conn)
mc.pushAllTCPTrans(conn)
})
return tcpConn
}
func (mc *Memcache) onTCPMessage(
conn *connection,
tuple *common.IpPortTuple,
dir uint8,
msg *message,
) error {
msg.Tuple = *tuple
msg.Transport = applayer.TransportTcp
msg.CmdlineTuple = procs.ProcWatcher.FindProcessesTuple(tuple)
if msg.IsRequest {
return mc.onTCPRequest(conn, tuple, dir, msg)
} else {
return mc.onTCPResponse(conn, tuple, dir, msg)
}
}
func (mc *Memcache) onTCPRequest(
conn *connection,
tuple *common.IpPortTuple,
dir uint8,
msg *message,
) error {
requestSeenFirst := dir == tcp.TcpDirectionOriginal
if requestSeenFirst {
msg.Direction = applayer.NetOriginalDirection
} else {
msg.Direction = applayer.NetReverseDirection
}
debug("received memcached(tcp) request message=%p, tuple=%s",
msg, msg.IsRequest, msg.Tuple)
msg.isComplete = true
waitResponse := msg.noreply ||
(!msg.isBinary && msg.command.code != MemcacheCmdQuit) ||
(msg.isBinary && msg.opcode != opcodeQuitQ)
if waitResponse {
conn.requests.append(msg)
} else {
mc.onTCPTrans(msg, nil)
}
return nil
}
func (mc *Memcache) onTCPResponse(
conn *connection,
tuple *common.IpPortTuple,
dir uint8,
msg *message,
) error {
requestSeenFirst := dir == tcp.TcpDirectionReverse
if requestSeenFirst {
msg.Direction = applayer.NetOriginalDirection
} else {
msg.Direction = applayer.NetReverseDirection
}
debug("received memcached(tcp) response message=%p, tuple=%s",
msg, msg.IsRequest, msg.Tuple)
// try to merge response with last received response
// (values and stats responses can be merged)
prev := conn.responses.last()
merged, err := tryMergeResponses(mc, prev, msg)
if err != nil {
return err
}
if merged {
debug("response message got merged")
msg = prev
} else {
conn.responses.append(msg)
}
if !msg.isComplete {
return nil
}
debug("response message complete")
return mc.correlateTCP(conn)
}
func (mc *Memcache) correlateTCP(conn *connection) error {
// merge requests with responses into transactions
for !conn.responses.empty() {
var requ *message
resp := conn.responses.pop()
for !conn.requests.empty() {
requ = conn.requests.pop()
if requ.isBinary != resp.isBinary {
err := ErrMixOfBinaryAndText
logp.Warn("%v", err)
return err
}
// If requ and response belong to the same transaction, continue
// merging them into one transaction
sameTransaction := !requ.isBinary ||
(requ.opaque == resp.opaque &&
requ.opcode == resp.opcode)
if sameTransaction {
break
}
// check if we are missing a response or quiet message.
// Quiet message only MAY get a response -> so we need
// to clear message list from all quiet messages not having
// received a response
if requ.isBinary && !requ.isQuiet {
note := NoteNonQuietResponseOnly
logp.Warn("%s", note)
requ.AddNotes(note)
}
// send request
debug("send single request=%p", requ)
err := mc.onTCPTrans(requ, nil)
if err != nil {
logp.Warn("error processing memcache transaction: %s", err)
}
requ = nil
}
// Check if response without request. This should only happen when a TCP
// stream is found (or after message gap) when we receive a response
// without having seen a request.
if requ == nil {
debug("found orphan memcached response=%p", resp)
resp.AddNotes(NoteTransactionNoRequ)
}
debug("merge request=%p and response=%p", requ, resp)
err := mc.onTCPTrans(requ, resp)
if err != nil {
logp.Warn("error processing memcache transaction: %s", err)
}
// continue processing more transactions (reporting error only)
}
return nil
}
func (mc *Memcache) onTCPTrans(requ, resp *message) error {
debug("received memcache(tcp) transaction")
trans := newTransaction(requ, resp)
return mc.finishTransaction(trans)
}
// GapInStream is called by TCP layer when a packets are missing from the tcp
// stream.
func (mc *Memcache) GapInStream(
tcptuple *common.TcpTuple,
dir uint8, nbytes int,
private protos.ProtocolData,
) (priv protos.ProtocolData, drop bool) {
debug("memcache(tcp) stream gap detected")
defer logp.Recover("GapInStream(memcache) exception")
if !isMemcacheConnection(private) {
return private, false
}
conn := private.(*tcpConnectionData)
stream := conn.Streams[dir]
parser := stream.parser
msg := parser.message
if msg != nil {
if msg.IsRequest {
msg.AddNotes(NoteRequestPacketLoss)
} else {
msg.AddNotes(NoteResponsePacketLoss)
}
}
// If we are about to read binary data (length) encoded, but missing gab
// does fully cover data area, we might be able to continue processing the
// stream + transactions
inData := parser.state == parseStateDataBinary ||
parser.state == parseStateIncompleteDataBinary ||
parser.state == parseStateData ||
parser.state == parseStateIncompleteData
if inData {
if msg == nil {
logp.WTF("parser message is nil on data load")
return private, true
}
alreadyRead := stream.Buf.Len() - int(msg.bytesLost)
dataRequired := int(msg.bytes) - alreadyRead
if nbytes <= dataRequired {
// yay, all bytes included in message binary data part.
// just drop binary data part and recover parsing.
if msg.isBinary {
parser.state = parseStateIncompleteDataBinary
} else {
parser.state = parseStateIncompleteData
}
msg.bytesLost += uint(nbytes)
return private, false
}
}
// need to drop TCP stream. But try to publish all cached trancsactions first
mc.pushAllTCPTrans(conn.connection)
return private, true
}
// ReceivedFin is called by tcp layer when the FIN flag is seen in the TCP stream.
func (mc *Memcache) ReceivedFin(
tcptuple *common.TcpTuple,
dir uint8,
private protos.ProtocolData,
) protos.ProtocolData {
// We rely on transaction timeout to publish all unfinished transactions.
return private
}
func (mc *Memcache) pushAllTCPTrans(conn *connection) {
if conn == nil {
return
}
// first let's try to send finished transactions
// (unlikely we have some, though)
mc.correlateTCP(conn)
// only requests in map:
debug("publish incomplete transactions")
for !conn.requests.empty() {
msg := conn.requests.pop()
if !msg.isQuiet && !msg.noreply {
msg.AddNotes(NoteTransUnfinished)
}
debug("push incomplete request=%p", msg)
err := mc.onTCPTrans(msg, nil)
if err != nil {
logp.Warn("failed to publish unfinished transaction with %v", err)
}
// continue processing more transactions (reporting error only)
}
}
func (private *tcpConnectionData) drop(dir uint8) {
private.Streams[dir] = nil
private.Streams[1-dir] = nil
}
func (stream *stream) reset() {
parser := &stream.parser
debug("consumed %v bytes", stream.Buf.BufferConsumed())
stream.Stream.Reset()
parser.reset()
}
func (stream *stream) parse(ts time.Time) (*message, error) {
return stream.parser.parse(&stream.Buf, ts)
}
func (ml *messageList) append(msg *message) {
if ml.tail == nil {
ml.head = msg
} else {
ml.tail.next = msg
}
msg.next = nil
ml.tail = msg
}
func (ml *messageList) empty() bool {
return ml.head == nil
}
func (ml *messageList) pop() *message {
if ml.head == nil {
return nil
}
msg := ml.head
ml.head = ml.head.next
if ml.head == nil {
ml.tail = nil
}
debug("new head=%p", ml.head)
return msg
}
func (ml *messageList) last() *message {
return ml.tail
}