forked from heistp/irtt
-
Notifications
You must be signed in to change notification settings - Fork 1
/
packet.go
524 lines (435 loc) · 11.7 KB
/
packet.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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
package nlmt
import (
"crypto/hmac"
"crypto/md5"
"encoding/binary"
"hash"
"io"
"math"
"net"
"time"
)
// -------------------------------------------------------------------------------
// | Oct | 0 | 1 | 2 | 3 |
// -------------------------------------------------------------------------------
// | | 0 1 2 3 4 5 6 7 | 0 1 2 3 4 5 6 7 | 0 1 2 3 4 5 6 7 | 0 1 2 3 4 5 6 7 |
// |------------------------------------------------------------------------------
// | 0 | Magic | Flags |
// |------------------------------------------------------------------------------
// | 4 | Conn Token |
// |------------------------------------------------------------------------------
// | 8 | Conn Token |
// |------------------------------------------------------------------------------
// | 12 | Seqno |
// |------------------------------------------------------------------------------
// | 16 | HMAC (if HMAC flag set) |
// |------------------------------------------------------------------------------
// | 20 | HMAC (if HMAC flag set) |
// |------------------------------------------------------------------------------
// | 24 | HMAC (if HMAC flag set) |
// |------------------------------------------------------------------------------
// | 28 | HMAC (if HMAC flag set) |
// |------------------------------------------------------------------------------
// | 32..| Optional Fields and Payload |
// |------------------------------------------------------------------------------
// little endian used for multi-byte ints
var endian = binary.LittleEndian
// Seqno is a sequence number.
type Seqno uint32
// InvalidSeqno indicates a sequence number that is not valid.
const InvalidSeqno = Seqno(math.MaxUint32)
// ReceivedCount is the received packet count.
type ReceivedCount uint32
// ReceivedWindow is the received packet window.
type ReceivedWindow uint64
// ctoken is a conn token
type ctoken uint64
// magic bytes
var magic = []byte{0x14, 0xa7, 0x5b}
// packet flags
type flags byte
func (f flags) set(fset flags) flags {
return f | fset
}
func (f flags) clear(fcl flags) flags {
return f &^ fcl
}
func (f flags) isset(fl flags) bool {
return f&fl != 0
}
const (
// flOpen is set when opening a new conn, both in the initial request from
// the client to the server, and in the reply from the server.
flOpen flags = 1 << iota
// flReply is set in all packets from the server to the client, and unset in
// all packets from the client to the server.
flReply
// flClose is set when closing a conn, both in the final request from the
// client to the server, and in the reply from the server.
flClose
// flHMAC is set if an HMAC hash is included (so we can tell the
// difference between a missing and invalid HMAC).
flHMAC
)
const flAll = flOpen | flReply | flClose | flHMAC
// field indexes
const (
fMagic fidx = iota
fFlags
fHMAC
fConnToken
fSeqno
fRCount
fRWindow
fRWall
fRMono
fMWall
fMMono
fSWall
fSMono
)
const fcount = fSMono + 1
const foptidx = fHMAC
// field capacities (sync with field constants)
var fcaps = []int{3, 1, md5.Size, 8, 4, 4, 8, 8, 8, 8, 8, 8, 8}
// field index definitions
var finit = []fidx{fMagic, fFlags}
var finitHMAC = []fidx{fMagic, fFlags, fHMAC}
var fopenReply = []fidx{fMagic, fFlags, fConnToken}
var fRequest = []fidx{fMagic, fFlags, fConnToken}
var fcloseRequest = []fidx{fMagic, fFlags, fConnToken}
var fechoRequest = []fidx{fMagic, fFlags, fConnToken, fSeqno}
var fechoReply = []fidx{fMagic, fFlags, fConnToken, fSeqno}
// minHeaderLen is the minimum header length (set in init).
var minHeaderLen int
// maxHeaderLen is the maximum header length (set in init).
var maxHeaderLen int
func init() {
for i := fidx(0); i < fcount; i++ {
if i < foptidx {
minHeaderLen += fcaps[i]
}
maxHeaderLen += fcaps[i]
}
}
func newFields() []field {
f := make([]field, fcount)
for i := fidx(0); i < fcount; i++ {
f[i].cap = fcaps[i]
}
return f
}
// Decorations for Time
func (t *Time) setWallFromBytes(b []byte) {
t.Wall = int64(endian.Uint64(b[:]))
}
func (t *Time) setMonoFromBytes(b []byte) {
t.Mono = time.Duration(endian.Uint64(b[:]))
}
func (t *Time) wallToBytes(b []byte) {
endian.PutUint64(b[:], uint64(t.Wall))
}
func (t *Time) monoToBytes(b []byte) {
endian.PutUint64(b[:], uint64(t.Mono))
}
// Packet struct and construction/set methods
type packet struct {
*fbuf
md5Hash hash.Hash
hmacKey []byte
raddr *net.UDPAddr
tsent Time
trcvd Time
srcIP net.IP
dstIP net.IP
dscp int
ecn int
}
func newPacket(tlen int, cap int, hmacKey []byte) *packet {
if cap < maxHeaderLen {
cap = maxHeaderLen
}
p := &packet{fbuf: newFbuf(newFields(), tlen, cap)}
if len(hmacKey) > 0 {
p.setFields(finitHMAC, true)
p.md5Hash = hmac.New(md5.New, hmacKey)
p.hmacKey = hmacKey
} else {
p.setFields(finit, true)
}
p.set(fMagic, magic)
return p
}
func (p *packet) readReset(n int) error {
if p.md5Hash != nil {
p.setFields(finitHMAC, false)
} else {
p.setFields(finit, false)
}
p.buf = p.buf[:n]
p.tlen = n
if err := p.fbuf.validate(); err != nil {
return err
}
return p.validate()
}
func (p *packet) readTo() []byte {
p.buf = p.buf[:cap(p.buf)]
return p.buf
}
func (p *packet) validate() error {
// magic
if !bytesEqual(p.get(fMagic), magic) {
return Errorf(BadMagic, "bad magic: %x != %x", p.get(fMagic), magic)
}
// flags
if p.flags() > flAll {
return Errorf(InvalidFlagBitsSet, "invalid flag bits set (%x)", p.flags())
}
// if there's a midpoint timestamp, there should be nothing else
if p.hasMidpointStamp() && (p.hasReceiveStamp() || p.hasSendStamp()) {
return Errorf(NonexclusiveMidpointTStamp, "non-exclusive midpoint timestamp")
}
// clock mode should be consistent for both stamps
if p.hasReceiveStamp() && p.hasSendStamp() {
rclock := clockFromBools(p.isset(fRWall), p.isset(fRMono))
sclock := clockFromBools(p.isset(fSWall), p.isset(fSMono))
if sclock != rclock {
return Errorf(InconsistentClocks,
"inconsistent clock mode between send and receive timestamps, %s != %s",
sclock, rclock)
}
}
// validate HMAC
if p.md5Hash != nil {
if p.flags()&flHMAC == 0 {
return Errorf(NoHMAC, "no HMAC present")
}
p.addFields([]fidx{fHMAC}, false)
y := make([]byte, md5.Size)
copy(y[:], p.get(fHMAC))
p.zero(fHMAC)
p.md5Hash.Reset()
p.md5Hash.Write(p.bytes())
x := p.md5Hash.Sum(nil)
if !hmac.Equal(y, x) {
return Errorf(BadHMAC, "invalid HMAC: %x != %x", y, x)
}
} else if p.flags()&flHMAC != 0 {
return Errorf(UnexpectedHMAC, "unexpected HMAC present")
}
return nil
}
// flags
func (p *packet) flags() flags {
return flags(p.getb(fFlags))
}
func (p *packet) setFlagBits(f flags) {
p.setb(fFlags, byte(p.flags().set(f)))
}
func (p *packet) clearFlagBits(f flags) {
p.setb(fFlags, byte(p.flags().clear(f)))
}
// Reply
func (p *packet) reply() bool {
return p.flags()&flReply != 0
}
func (p *packet) setReply(r bool) {
if r {
p.setFlagBits(flReply)
} else {
p.clearFlagBits(flReply)
}
}
// Token
func (p *packet) ctoken() ctoken {
return ctoken(endian.Uint64(p.get(fConnToken)))
}
func (p *packet) setConnToken(ctoken ctoken) {
endian.PutUint64(p.setTo(fConnToken), uint64(ctoken))
}
// Sequence Number
func (p *packet) seqno() Seqno {
return Seqno(endian.Uint32(p.get(fSeqno)))
}
func (p *packet) setSeqno(seqno Seqno) {
endian.PutUint32(p.setTo(fSeqno), uint32(seqno))
}
// Received packet stats
func (p *packet) receivedCount() ReceivedCount {
return ReceivedCount(endian.Uint32(p.get(fRCount)))
}
func (p *packet) setReceivedCount(n ReceivedCount) {
endian.PutUint32(p.setTo(fRCount), uint32(n))
}
func (p *packet) receivedWindow() ReceivedWindow {
return ReceivedWindow(endian.Uint64(p.get(fRWindow)))
}
func (p *packet) setReceivedWindow(w ReceivedWindow) {
endian.PutUint64(p.setTo(fRWindow), uint64(w))
}
func (p *packet) hasReceivedCount() bool {
return p.isset(fRCount)
}
func (p *packet) hasReceivedWindow() bool {
return p.isset(fRWindow)
}
func (p *packet) zeroReceivedStats(rs ReceivedStats) {
if rs&ReceivedStatsCount != 0 {
p.zero(fRCount)
} else {
p.remove(fRCount)
}
if rs&ReceivedStatsWindow != 0 {
p.zero(fRWindow)
} else {
p.remove(fRWindow)
}
}
func (p *packet) addReceivedStatsFields(rs ReceivedStats) {
rfs := make([]fidx, 0, 2)
if rs&ReceivedStatsCount != 0 {
rfs = append(rfs, fRCount)
}
if rs&ReceivedStatsWindow != 0 {
rfs = append(rfs, fRWindow)
}
p.addFields(rfs, false)
}
// Timestamps
func (p *packet) tget(wf fidx, mf fidx, t *Time) {
wb := p.get(wf)
if len(wb) > 0 {
t.setWallFromBytes(wb)
}
mb := p.get(mf)
if len(mb) > 0 {
t.setMonoFromBytes(mb)
}
}
func (p *packet) timestamp() (ts Timestamp) {
p.tget(fRWall, fRMono, &ts.Receive)
p.tget(fMWall, fMMono, &ts.Receive)
p.tget(fMWall, fMMono, &ts.Send)
p.tget(fSWall, fSMono, &ts.Send)
return
}
func (p *packet) tset(t *Time, wf fidx, mf fidx) {
if t.Wall != 0 {
t.wallToBytes(p.setTo(wf))
}
if t.Mono != 0 {
t.monoToBytes(p.setTo(mf))
}
}
func (p *packet) setTimestamp(at StampAt, ts Timestamp) {
if at == AtMidpoint {
p.tset(&ts.Receive, fMWall, fMMono)
return
}
if at&AtReceive != 0 {
p.tset(&ts.Receive, fRWall, fRMono)
}
if at&AtSend != 0 {
p.tset(&ts.Send, fSWall, fSMono)
}
}
func (p *packet) hasReceiveStamp() bool {
return p.isset(fRWall) || p.isset(fRMono)
}
func (p *packet) hasMidpointStamp() bool {
return p.isset(fMWall) || p.isset(fMMono)
}
func (p *packet) hasSendStamp() bool {
return p.isset(fSWall) || p.isset(fSMono)
}
func (p *packet) clock() Clock {
c := Clock(0)
if p.isset(fRWall) || p.isset(fSWall) || p.isset(fMWall) {
c |= Wall
}
if p.isset(fRMono) || p.isset(fSMono) || p.isset(fMMono) {
c |= Monotonic
}
return c
}
func (p *packet) stampAt() (a StampAt) {
if p.isset(fMWall) || p.isset(fMMono) {
a = AtMidpoint
return
}
if p.isset(fRWall) || p.isset(fRMono) {
a |= AtReceive
}
if p.isset(fSWall) || p.isset(fSMono) {
a |= AtSend
}
return
}
func (p *packet) stampZeroes(at StampAt, c Clock) {
zts := func(a StampAt, wf fidx, mf fidx) {
if at&a != 0 {
if c&Wall != 0 {
p.zero(wf)
}
if c&Monotonic != 0 {
p.zero(mf)
}
} else {
p.remove(wf)
p.remove(mf)
}
}
zts(AtReceive, fRWall, fRMono)
zts(AtMidpoint, fMWall, fMMono)
zts(AtSend, fSWall, fSMono)
}
func (p *packet) addTimestampFields(at StampAt, c Clock) {
tfs := make([]fidx, 0, 4)
atf := func(a StampAt, wf fidx, mf fidx) {
if at&a != 0 {
if c&Wall != 0 {
tfs = append(tfs, wf)
}
if c&Monotonic != 0 {
tfs = append(tfs, mf)
}
}
}
atf(AtReceive, fRWall, fRMono)
atf(AtMidpoint, fMWall, fMMono)
atf(AtSend, fSWall, fSMono)
p.addFields(tfs, false)
}
func (p *packet) removeTimestamps() {
p.remove(fRWall)
p.remove(fRMono)
p.remove(fMWall)
p.remove(fMMono)
p.remove(fSWall)
p.remove(fSMono)
}
// HMAC
func (p *packet) updateHMAC() {
if p.md5Hash != nil {
// calculate and set hmac, with zeroed hmac field
p.setFlagBits(flHMAC)
p.zero(fHMAC)
p.md5Hash.Reset()
p.md5Hash.Write(p.buf)
mac := p.md5Hash.Sum(nil)
p.set(fHMAC, mac)
} else if p.isset(fHMAC) {
// clear field and flags
p.clearFlagBits(flHMAC)
p.remove(fHMAC)
}
}
// Payload
func (p *packet) readPayload(r io.Reader) (err error) {
payload := p.payload()
if len(payload) > 0 {
_, err = io.ReadFull(r, p.payload())
}
return err
}