forked from quic-go/quic-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpacket_unpacker.go
95 lines (82 loc) · 2.41 KB
/
packet_unpacker.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 quic
import (
"bytes"
"fmt"
"github.com/lucas-clemente/quic-go/internal/protocol"
"github.com/lucas-clemente/quic-go/internal/qerr"
"github.com/lucas-clemente/quic-go/internal/wire"
)
type unpackedPacket struct {
encryptionLevel protocol.EncryptionLevel
frames []wire.Frame
}
type quicAEAD interface {
OpenInitial(dst, src []byte, pn protocol.PacketNumber, ad []byte) ([]byte, error)
OpenHandshake(dst, src []byte, pn protocol.PacketNumber, ad []byte) ([]byte, error)
Open1RTT(dst, src []byte, pn protocol.PacketNumber, ad []byte) ([]byte, error)
}
// The packetUnpacker unpacks QUIC packets.
type packetUnpacker struct {
aead quicAEAD
version protocol.VersionNumber
}
var _ unpacker = &packetUnpacker{}
func newPacketUnpacker(aead quicAEAD, version protocol.VersionNumber) unpacker {
return &packetUnpacker{
aead: aead,
version: version,
}
}
func (u *packetUnpacker) Unpack(headerBinary []byte, hdr *wire.Header, data []byte) (*unpackedPacket, error) {
buf := *getPacketBuffer()
buf = buf[:0]
defer putPacketBuffer(&buf)
var decrypted []byte
var encryptionLevel protocol.EncryptionLevel
var err error
switch hdr.Type {
case protocol.PacketTypeInitial:
decrypted, err = u.aead.OpenInitial(buf, data, hdr.PacketNumber, headerBinary)
encryptionLevel = protocol.EncryptionInitial
case protocol.PacketTypeHandshake:
decrypted, err = u.aead.OpenHandshake(buf, data, hdr.PacketNumber, headerBinary)
encryptionLevel = protocol.EncryptionHandshake
default:
if hdr.IsLongHeader {
return nil, fmt.Errorf("unknown packet type: %s", hdr.Type)
}
decrypted, err = u.aead.Open1RTT(buf, data, hdr.PacketNumber, headerBinary)
encryptionLevel = protocol.Encryption1RTT
}
if err != nil {
// Wrap err in quicError so that public reset is sent by session
return nil, qerr.Error(qerr.DecryptionFailure, err.Error())
}
fs, err := u.parseFrames(decrypted)
if err != nil {
return nil, err
}
return &unpackedPacket{
encryptionLevel: encryptionLevel,
frames: fs,
}, nil
}
func (u *packetUnpacker) parseFrames(decrypted []byte) ([]wire.Frame, error) {
r := bytes.NewReader(decrypted)
if r.Len() == 0 {
return nil, qerr.MissingPayload
}
fs := make([]wire.Frame, 0, 2)
// Read all frames in the packet
for {
frame, err := wire.ParseNextFrame(r, u.version)
if err != nil {
return nil, err
}
if frame == nil {
break
}
fs = append(fs, frame)
}
return fs, nil
}