/
udp_stream.go
383 lines (339 loc) · 11.1 KB
/
udp_stream.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
package packetstream
import (
"context"
"fmt"
"os"
"strconv"
"sync"
"time"
log "github.com/golang/glog"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/jipanyang/hpinggo/options"
)
func logUDPReply(packet gopacket.Packet, key string) {
fmt.Fprintf(os.Stdout, "[%v] got UDP reply\n", key)
log.V(2).Infof("%v", packet)
}
// udpStream
type udpStream struct {
key key // This is supposed to be client 2 server key, egress in our case.
bytesEgress, bytesIngress, bytes int64 // Total bytes seen on this stream.
ciEgress, ciIngress *gopacket.CaptureInfo // To store the CaptureInfo seen on first packet of each direction
lastPacketSeen time.Time // last time we saw a packet from either stream.
done bool // if true, we've seen the last packet we're going to for this stream.
}
// maybeFinish print out stats.
// TODO: do something more meaningful.
func (s *udpStream) maybeFinish() {
switch {
case s.ciEgress == nil:
log.Fatalf("Egress missing: [%v]", s)
case s.ciIngress == nil:
log.V(5).Infof("Ingress missing: [%v]", s)
case !s.done:
log.V(5).Infof("still waiting on stream: [%v] ", s)
default:
log.V(5).Infof("[%v] FINISHED, bytes: %d tx, %d rx", s.key, s.bytesEgress, s.bytesIngress)
}
}
// udpStreamFactory implements reassembly.StreamFactory
// It also implement StreamProtocolLayer interface
type udpStreamFactory struct {
ctx context.Context
streams map[key]*udpStream
localEnpoint gopacket.Endpoint
// the RWMutex is for protecting recvCount (for now) which may be updated in waitPackets
// and read in sendPackets
mu sync.RWMutex
// Number of packets sent
sentPackets int64
// Number of packets received.
recvCount int64
rttMin, rttMax, rttAvg int64
// options specified at user command line
cmdOpts options.Options
// convenient variables derived from options
baseDestPort uint16
incDestPort bool
forceIncDestPort bool
// The dynamic port number which may be derived in real time
dstPort uint16
srcPort uint16
srcTTL uint8 // TTL
}
// Create a new stream factory for UDP transport layer
func newUdpStreamFactory(ctx context.Context, opt options.Options) *udpStreamFactory {
f := &udpStreamFactory{
ctx: ctx,
streams: make(map[key]*udpStream),
recvCount: 0,
cmdOpts: opt,
}
// Make the option setting available more conveniently
f.parseOptions()
// Set the starting point for dest and srouce ports
f.dstPort = f.baseDestPort
f.srcPort = uint16(opt.BaseSourcePort)
if opt.TTL > 0 {
f.srcTTL = uint8(opt.TTL)
} else if opt.TraceRoute {
f.srcTTL = 1
} else {
f.srcTTL = 64
if opt.IPv6 {
f.srcTTL = 255
}
}
return f
}
func (f *udpStreamFactory) delete(s *udpStream) {
delete(f.streams, s.key) // remove it from our map.
}
func (f *udpStreamFactory) parseOptions() {
destPortStr := f.cmdOpts.DestPort
if destPortStr[:1] == "+" {
f.incDestPort = true
destPortStr = destPortStr[1:]
}
if destPortStr[:1] == "+" {
f.forceIncDestPort = true
destPortStr = destPortStr[1:]
}
port, err := strconv.Atoi(destPortStr)
if err != nil {
log.Exitf("Invalid dest port: %v, %v\n", f.cmdOpts.DestPort, err)
}
f.baseDestPort = uint16(port)
}
func (f *udpStreamFactory) PrepareProtocalLayers(netLayer gopacket.NetworkLayer) []gopacket.Layer {
// Prepare for next call, this makes udpStreamFactory stateful
if f.forceIncDestPort {
f.dstPort = f.baseDestPort + uint16(f.sentPackets)
} else if f.incDestPort {
// recvCount may be updated in another routine, protect it with read lock
f.mu.RLock()
f.dstPort = f.baseDestPort + uint16(f.recvCount)
f.mu.RUnlock()
}
// Update source port number unless asked to stay const
if !f.cmdOpts.KeepConstSourcePort {
f.srcPort = uint16(f.cmdOpts.BaseSourcePort) + uint16(f.sentPackets)
}
// TODO: populating the whole udp layer every time, improve it?
udp := &layers.UDP{
SrcPort: layers.UDPPort(f.srcPort),
DstPort: layers.UDPPort(f.dstPort),
}
udp.SetNetworkLayerForChecksum(netLayer)
switch v := netLayer.(type) {
case *layers.IPv4:
v.Protocol = layers.IPProtocolUDP
v.TTL = f.srcTTL
case *layers.IPv6:
v.NextHeader = layers.IPProtocolUDP
v.HopLimit = f.srcTTL
default:
panic("Unsupported network layer value")
}
return []gopacket.Layer{udp}
}
func (f *udpStreamFactory) OnSend(netLayer gopacket.NetworkLayer, transportLayers []gopacket.Layer, payload []byte) {
f.mu.Lock()
defer f.mu.Unlock()
f.sentPackets += 1
if !f.cmdOpts.TraceRouteKeepTTL {
f.srcTTL++
}
netFlow := netLayer.NetworkFlow()
// TODO: check length of slice
transportLayer := transportLayers[0]
// Need the workaroud "udp.SetInternalPortsForTesting()" to get correct transport flow key
udp := transportLayer.(*layers.UDP)
udp.SetInternalPortsForTesting()
udpFlow := udp.TransportFlow()
k := key{netFlow, udpFlow}
if f.streams[k] != nil {
log.Infof("[%v] found existing stream", k)
f.streams[k].lastPacketSeen = time.Now()
return
}
// Fake CaptureInfo since we don't capture on egress
ci := gopacket.CaptureInfo{
Timestamp: time.Now(),
CaptureLength: (len(payload)) + 8, // is 8 the header length?
Length: (len(payload)) + 8,
}
s := &udpStream{key: k, ciEgress: &ci, lastPacketSeen: ci.Timestamp}
f.streams[k] = s
log.V(5).Infof("[%v] created UDP session", k)
}
// TODO: check sequence number of each packet sent or received.
func (f *udpStreamFactory) OnReceive(packet gopacket.Packet) {
log.V(7).Infof("%v", packet)
f.mu.Lock()
defer f.mu.Unlock()
// TODO: handle icmp reply for the packet.
if packet.NetworkLayer() == nil {
log.Errorf("Unusable packet: %v", packet)
return
}
netflow := packet.NetworkLayer().NetworkFlow()
// Deal with packets targeting local endpoint for stream processing. May need change for other features.
if f.localEnpoint != netflow.Dst() {
log.V(5).Infof("Skip non-ingress packets: %v", packet)
return
}
var s *udpStream = nil
// record the icmp reply for udp stream
if !f.cmdOpts.IPv6 {
icmp, ok := packet.Layer(layers.LayerTypeICMPv4).(*layers.ICMPv4)
if ok {
typeCode := icmp.TypeCode
if typeCode.Type() == layers.ICMPv4TypeDestinationUnreachable ||
typeCode.Type() == layers.ICMPv4TypeTimeExceeded {
payload, ok := packet.Layer(gopacket.LayerTypePayload).(*gopacket.Payload)
if ok {
FlowKey, err := parseIcmpErrorMessage(payload.LayerContents(), layers.LayerTypeIPv4)
if err != nil {
log.Infof("Parse ICMP message error: %v\n", err)
} else {
egressFlowKey := FlowKey.(key)
log.V(2).Infof("ICMP payload egress key : %+v", egressFlowKey)
s = f.streams[egressFlowKey]
if s != nil {
if f.cmdOpts.TraceRoute {
ttl := f.srcTTL
if !f.cmdOpts.TraceRouteKeepTTL {
ttl -= 1
}
logTraceRouteIPv4(ttl, s.ciEgress, typeCode, packet)
// fmt.Fprintf(os.Stdout, "hop=%v original flow %v\n", f.srcTTL, egressFlowKey)
} else {
logICMPv4(typeCode, egressFlowKey.String(), s.ciEgress, packet)
}
} else {
log.V(1).Infof("no matching for %v. Timed out?", egressFlowKey)
}
}
} else {
log.V(1).Infof("No payload in icmp : %+v", icmp)
}
} else {
log.V(1).Infof("Unusable icmp typeCode: %+v", icmp.TypeCode)
}
// This is an ICMP message but no matching udp content found there.
if s == nil {
log.V(5).Infof("Unusable packet: %v", packet)
return
}
}
} else {
icmp, ok := packet.Layer(layers.LayerTypeICMPv6).(*layers.ICMPv6)
if ok {
typeCode := icmp.TypeCode
if typeCode.Type() == layers.ICMPv6TypeDestinationUnreachable ||
typeCode.Type() == layers.ICMPv6TypeTimeExceeded {
payload, ok := packet.Layer(gopacket.LayerTypePayload).(*gopacket.Payload)
if ok {
// The first 4 bytes is Unused for the two types of icmpv6 message
// https://tools.ietf.org/html/rfc4443#section-3.1
p := gopacket.NewPacket(payload.LayerContents()[4:], layers.LayerTypeIPv6, gopacket.Default)
if p.TransportLayer() != nil && p.TransportLayer().LayerType() == layers.LayerTypeUDP {
kEgress := key{p.NetworkLayer().NetworkFlow(), p.TransportLayer().TransportFlow()}
s = f.streams[kEgress]
if s != nil {
if f.cmdOpts.TraceRoute {
ttl := f.srcTTL
if !f.cmdOpts.TraceRouteKeepTTL {
ttl -= 1
}
logTraceRouteIPv6(ttl, s.ciEgress, typeCode, packet)
} else {
logICMPv6(typeCode, kEgress.String(), s.ciEgress, packet)
}
} else {
log.Infof(" %v timed out?", kEgress)
}
}
}
}
// This is an ICMPv6 message but no matching udp content found there.
if s == nil {
log.Infof("Unusable packet: %v", packet)
return
}
}
}
if s == nil {
if packet.TransportLayer() == nil ||
packet.TransportLayer().LayerType() != layers.LayerTypeUDP {
log.Errorf("Unusable packet: %v", packet)
return
}
kIngress := key{packet.NetworkLayer().NetworkFlow(), packet.TransportLayer().TransportFlow()}
if f.streams[kIngress] != nil {
// There was bidirection flows for this key.
// TODO: warning depending on test caases.
log.Infof("[%v] found existing stream", kIngress)
}
kEgress := key{kIngress.net.Reverse(), kIngress.transport.Reverse()}
s = f.streams[kEgress]
if s != nil {
logUDPReply(packet, kEgress.String())
} else {
log.V(5).Infof("[%s] not found", kEgress)
}
}
// Found ingress flow for the corresponding egress flow.
if s != nil {
log.V(5).Infof("[%v]: The opposite ingress packet arrived", s.key)
meta := packet.Metadata()
s.bytesIngress += int64(meta.CaptureLength)
s.ciIngress = &meta.CaptureInfo
if s.lastPacketSeen.Before(s.ciIngress.Timestamp) {
s.lastPacketSeen = s.ciIngress.Timestamp
}
f.updateStreamRecvStats(s.ciIngress, s.ciEgress)
s.done = true
s.maybeFinish()
f.delete(s)
}
}
func (f *udpStreamFactory) SetLocalEnpoint(endpoint gopacket.Endpoint) {
f.localEnpoint = endpoint
}
// CollectOldStreams finds any streams that haven't received a packet within
// 'timeout'
func (f *udpStreamFactory) CollectOldStreams(timeout time.Duration) {
cutoff := time.Now().Add(-timeout)
f.mu.Lock()
defer f.mu.Unlock()
for k, s := range f.streams {
if s.lastPacketSeen.Before(cutoff) {
log.V(5).Infof("[%v] timing out old session", s.key)
delete(f.streams, k) // remove it from our map.
s.maybeFinish() // Do something...?
}
}
}
func (f *udpStreamFactory) updateStreamRecvStats(ciIngress *gopacket.CaptureInfo, ciEgress *gopacket.CaptureInfo) {
f.recvCount += 1
delay := int64(ciIngress.Timestamp.Sub(ciEgress.Timestamp) / time.Nanosecond)
if f.rttMin > delay {
f.rttMin = delay
}
if f.rttMax < delay {
f.rttMax = delay
}
f.rttAvg = (f.rttAvg*(f.recvCount-1) + delay) / f.recvCount
}
func (f *udpStreamFactory) ShowStats() {
fmt.Fprintf(os.Stdout, "\n--- hpinggo statistic ---\n")
fmt.Fprintf(os.Stdout, "%v packets tramitted, %v packets received\n",
f.sentPackets, f.recvCount)
fmt.Fprintf(os.Stdout, "round-trip min/avg/max = %v/%v/%v\n",
time.Duration(f.rttMin)*time.Nanosecond,
time.Duration(f.rttAvg)*time.Nanosecond,
time.Duration(f.rttMax)*time.Nanosecond)
}