-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfragment_buffer.go
95 lines (76 loc) · 2.58 KB
/
fragment_buffer.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
package dtls
type fragment struct {
recordLayerHeader recordLayerHeader
handshakeHeader handshakeHeader
data []byte
}
type fragmentBuffer struct {
// map of MessageSequenceNumbers that hold slices of fragments
cache map[uint16][]*fragment
currentMessageSequenceNumber uint16
}
func newFragmentBuffer() *fragmentBuffer {
return &fragmentBuffer{cache: map[uint16][]*fragment{}}
}
// Attempts to push a DTLS packet to the fragmentBuffer
// when it returns true it means the fragmentBuffer has inserted and the buffer shouldn't be handled
// when an error returns it is fatal, and the DTLS connection should be stopped
func (f *fragmentBuffer) push(buf []byte) (bool, error) {
frag := new(fragment)
if err := frag.recordLayerHeader.Unmarshal(buf); err != nil {
return false, err
}
// fragment isn't a handshake, we don't need to handle it
if frag.recordLayerHeader.contentType != contentTypeHandshake {
return false, nil
}
if err := frag.handshakeHeader.Unmarshal(buf[recordLayerHeaderSize:]); err != nil {
return false, err
}
if _, ok := f.cache[frag.handshakeHeader.messageSequence]; !ok {
f.cache[frag.handshakeHeader.messageSequence] = []*fragment{}
}
// Discard all headers, when rebuilding the packet we will re-build
frag.data = append([]byte{}, buf[recordLayerHeaderSize+handshakeHeaderLength:]...)
f.cache[frag.handshakeHeader.messageSequence] = append(f.cache[frag.handshakeHeader.messageSequence], frag)
return true, nil
}
func (f *fragmentBuffer) pop() (content []byte, epoch uint16) {
frags, ok := f.cache[f.currentMessageSequenceNumber]
if !ok {
return nil, 0
}
// Go doesn't support recursive lambdas
var appendMessage func(targetOffset uint32) bool
rawMessage := []byte{}
appendMessage = func(targetOffset uint32) bool {
for _, f := range frags {
if f.handshakeHeader.fragmentOffset == targetOffset {
fragmentEnd := (f.handshakeHeader.fragmentOffset + f.handshakeHeader.fragmentLength)
if fragmentEnd != f.handshakeHeader.length {
if !appendMessage(fragmentEnd) {
return false
}
}
rawMessage = append(f.data, rawMessage...)
return true
}
}
return false
}
// Recursively collect up
if !appendMessage(0) {
return nil, 0
}
firstHeader := frags[0].handshakeHeader
firstHeader.fragmentOffset = 0
firstHeader.fragmentLength = firstHeader.length
rawHeader, err := firstHeader.Marshal()
if err != nil {
return nil, 0
}
messageEpoch := frags[0].recordLayerHeader.epoch
delete(f.cache, f.currentMessageSequenceNumber)
f.currentMessageSequenceNumber++
return append(rawHeader, rawMessage...), messageEpoch
}