-
-
Notifications
You must be signed in to change notification settings - Fork 119
/
record.go
76 lines (61 loc) · 1.59 KB
/
record.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
package faketls
import (
"bytes"
"encoding/binary"
"io"
"golang.org/x/xerrors"
)
const maxTLSRecordDataLength = 16384 + 24
type record struct {
Type RecordType
Version [2]byte
Data []byte
}
func readRecord(r io.Reader) (record, error) {
rec := record{}
buf := make([]byte, 5)
if _, err := io.ReadFull(r, buf); err != nil {
return record{}, err
}
rec.Type = RecordType(buf[0])
versionRaw := buf[1:3]
switch {
case bytes.Equal(versionRaw, Version13Bytes[:]):
rec.Version = Version13Bytes
case bytes.Equal(versionRaw, Version12Bytes[:]):
rec.Version = Version12Bytes
case bytes.Equal(versionRaw, Version11Bytes[:]):
rec.Version = Version11Bytes
case bytes.Equal(versionRaw, Version10Bytes[:]):
rec.Version = Version10Bytes
default:
return record{}, xerrors.Errorf("unknown protocol version %v", versionRaw)
}
length := binary.BigEndian.Uint16(buf[3:])
if length > maxTLSRecordDataLength {
return record{}, xerrors.Errorf("record length is too big")
}
rec.Data = make([]byte, length)
if _, err := io.ReadFull(r, rec.Data); err != nil {
return record{}, err
}
return rec, nil
}
func writeRecord(w io.Writer, r record) (int, error) {
buf := [...]byte{
byte(r.Type),
r.Version[0], r.Version[1],
}
if _, err := w.Write(buf[:]); err != nil {
return 0, xerrors.Errorf("type and version: %w", err)
}
binary.BigEndian.PutUint16(buf[:2], uint16(len(r.Data)))
if _, err := w.Write(buf[:2]); err != nil {
return 0, xerrors.Errorf("data length: %w", err)
}
n, err := w.Write(r.Data)
if err != nil {
return 0, xerrors.Errorf("data: %w", err)
}
return n, nil
}