-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
plugin_udp.go
341 lines (295 loc) · 8.03 KB
/
plugin_udp.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
package memcache
// Memcache UDP Protocol Plugin implementation.
import (
"sync"
"time"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/common/streambuf"
"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"
)
type udpMemcache struct {
udpConfig udpConfig
udpConnections map[common.HashableIPPortTuple]*udpConnection
udpExpTrans udpExpTransList
}
type udpConfig struct {
transTimeout time.Duration
}
type mcUDPHeader struct {
requestID uint16
seqNumber uint16
numDatagrams uint16
}
type udpConnection struct {
tuple common.IPPortTuple
transactions map[uint16]*udpTransaction
memcache *memcache
}
type udpTransaction struct {
requestID uint16
timer *time.Timer
next *udpTransaction
connection *udpConnection
messages [2]*udpMessage
request *message
response *message
}
// udpExpTransList holds a list of expired transactions for cleanup (manual gc)
// The list is filled by timeout handlers and cleaned by processing thread (ParseUdp)
// to deal with possible thread safety issues
//
// Note: only for cleanup. Transaction was published already,
// as publishing is thread safe
type udpExpTransList struct {
sync.Mutex
head *udpTransaction
}
type udpMessage struct {
numDatagrams uint16
count uint16
isComplete bool
datagrams [][]byte
}
func (mc *memcache) ParseUDP(pkt *protos.Packet) {
defer logp.Recover("ParseMemcache(UDP) exception")
buffer := streambuf.NewFixed(pkt.Payload)
header, err := parseUDPHeader(buffer)
if err != nil {
debug("parsing memcache udp header failed")
return
}
debug("new udp datagram requestId=%v, seqNumber=%v, numDatagrams=%v",
header.requestID, header.seqNumber, header.numDatagrams)
// find connection object based on ips and ports (forward->reverse connection)
connection, dir := mc.getUDPConnection(&pkt.Tuple)
debug("udp connection: %p", connection)
// get udp transaction combining forward/reverse direction 'streams'
// for current requestId
trans := connection.udpTransactionForID(header.requestID)
debug("udp transaction (id=%v): %p", header.requestID, trans)
// Clean old transaction. We do the cleaning after potentially adding a new
// transaction to the connection object, so connection object will not be
// cleaned accidentally (not bad, but let's rather reuse it)
expTrans := mc.udpExpTrans.steal()
for expTrans != nil {
tmp := expTrans.next
expTrans.connection.killTransaction(expTrans)
expTrans = tmp
}
// get UDP transaction stream combining datagram packets in transaction
udpMsg := trans.udpMessageForDir(&header, dir)
if udpMsg.numDatagrams != header.numDatagrams {
logp.Warn("number of datagram mismatches in stream")
connection.killTransaction(trans)
return
}
// try to combine datagrams into complete memcached message
payload := udpMsg.addDatagram(&header, buffer.Bytes())
done := false
if payload != nil {
// parse memcached message
msg, err := parseUDP(&mc.config, pkt.Ts, payload)
if err != nil {
logp.Warn("failed to parse memcached(UDP) message: %s", err)
connection.killTransaction(trans)
return
}
// apply memcached to transaction
done, err = mc.onUDPMessage(trans, &pkt.Tuple, dir, msg)
if err != nil {
logp.Warn("error processing memcache message: %s", err)
connection.killTransaction(trans)
done = true
}
}
if !done {
trans.timer = time.AfterFunc(mc.udpConfig.transTimeout, func() {
debug("transaction timeout -> forward")
mc.onUDPTrans(trans)
mc.udpExpTrans.push(trans)
})
}
}
func (mc *memcache) getUDPConnection(
tuple *common.IPPortTuple,
) (*udpConnection, applayer.NetDirection) {
connection := mc.udpConnections[tuple.Hashable()]
if connection != nil {
return connection, applayer.NetOriginalDirection
}
connection = mc.udpConnections[tuple.RevHashable()]
if connection != nil {
return connection, applayer.NetReverseDirection
}
connection = newUDPConnection(mc, tuple)
mc.udpConnections[tuple.Hashable()] = connection
return connection, applayer.NetOriginalDirection
}
func (mc *memcache) onUDPMessage(
trans *udpTransaction,
tuple *common.IPPortTuple,
dir applayer.NetDirection,
msg *message,
) (bool, error) {
debug("received memcached(udp) message")
if msg.IsRequest {
msg.Direction = applayer.NetOriginalDirection
} else {
msg.Direction = applayer.NetReverseDirection
}
msg.Tuple = *tuple
msg.Transport = applayer.TransportUDP
msg.CmdlineTuple = procs.ProcWatcher.FindProcessesTuple(tuple)
done := false
var err error
if msg.IsRequest {
msg.isComplete = true
trans.request = msg
waitResponse := msg.noreply ||
(!msg.isBinary && msg.command.code != memcacheCmdQuit) ||
(msg.isBinary && msg.opcode != opcodeQuitQ)
done = !waitResponse
} else {
msg.isComplete = true
trans.response = msg
}
done = done || (trans.request != nil && trans.response != nil)
if done {
err = mc.onUDPTrans(trans)
trans.connection.killTransaction(trans)
}
return done, err
}
func (mc *memcache) onUDPTrans(udp *udpTransaction) error {
debug("received memcache(udp) transaction")
trans := newTransaction(udp.request, udp.response)
return mc.finishTransaction(trans)
}
func newUDPConnection(mc *memcache, tuple *common.IPPortTuple) *udpConnection {
c := &udpConnection{
tuple: *tuple,
memcache: mc,
transactions: make(map[uint16]*udpTransaction),
}
return c
}
func (c *udpConnection) udpTransactionForID(requestID uint16) *udpTransaction {
trans := c.transactions[requestID]
if trans != nil && trans.timer != nil {
stopped := trans.timer.Stop()
if !stopped {
logp.Warn("timer stopped while processing transaction -> create new transaction")
trans = nil
}
}
if trans == nil {
trans = &udpTransaction{
requestID: requestID,
connection: c,
}
c.transactions[requestID] = trans
} else {
trans.timer = nil
}
return trans
}
func (c *udpConnection) killTransaction(t *udpTransaction) {
if t.timer != nil {
t.timer.Stop()
}
if c.transactions[t.requestID] != t {
// transaction was already replaced
return
}
delete(c.transactions, t.requestID)
if len(c.transactions) == 0 {
delete(c.memcache.udpConnections, c.tuple.Hashable())
}
}
func (lst *udpExpTransList) push(t *udpTransaction) {
lst.Lock()
defer lst.Unlock()
t.next = lst.head
lst.head = t
}
func (lst *udpExpTransList) steal() *udpTransaction {
lst.Lock()
t := lst.head
lst.head = nil
lst.Unlock()
return t
}
func (t *udpTransaction) udpMessageForDir(
header *mcUDPHeader,
dir applayer.NetDirection,
) *udpMessage {
udpMsg := t.messages[dir]
if udpMsg == nil {
udpMsg = newUDPMessage(header)
t.messages[dir] = udpMsg
}
return udpMsg
}
func newUDPMessage(header *mcUDPHeader) *udpMessage {
udpMsg := &udpMessage{
numDatagrams: header.numDatagrams,
count: 0,
}
if header.numDatagrams > 1 {
udpMsg.datagrams = make([][]byte, header.numDatagrams)
}
return udpMsg
}
func (msg *udpMessage) addDatagram(
header *mcUDPHeader,
data []byte,
) *streambuf.Buffer {
if msg.isComplete {
return nil
}
if msg.numDatagrams == 1 {
msg.isComplete = true
return streambuf.NewFixed(data)
}
if msg.count < msg.numDatagrams {
if msg.datagrams[header.seqNumber] != nil {
return nil
}
msg.datagrams[header.seqNumber] = data
msg.count++
}
if msg.count < msg.numDatagrams {
return nil
}
buffer := streambuf.New(nil)
for _, payload := range msg.datagrams {
buffer.Append(payload)
}
msg.isComplete = true
msg.datagrams = nil
buffer.Fix()
return buffer
}
func parseUDPHeader(buf *streambuf.Buffer) (mcUDPHeader, error) {
var h mcUDPHeader
h.requestID, _ = buf.ReadNetUint16()
h.seqNumber, _ = buf.ReadNetUint16()
h.numDatagrams, _ = buf.ReadNetUint16()
buf.Advance(2) // ignore reserved
return h, buf.Err()
}
func parseUDP(
config *parserConfig,
ts time.Time,
buf *streambuf.Buffer,
) (*message, error) {
parser := newParser(config)
msg, err := parser.parse(buf, ts)
if err != nil && msg == nil {
err = errUDPIncompleteMessage
}
return msg, err
}