-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathpacket.go
119 lines (93 loc) · 1.85 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
package a2s
import (
"bytes"
"encoding/binary"
"errors"
"net"
)
const MaxPacketSize = 1400
var (
ErrOutOfBounds = errors.New("Read out of bounds")
)
type PacketBuilder struct {
bytes.Buffer
}
func (b *PacketBuilder) WriteCString(s string) {
b.WriteString(s)
b.WriteByte(0)
}
func (b *PacketBuilder) WriteBytes(bytes []byte) {
b.Write(bytes)
}
type PacketReader struct {
buffer []byte
pos int
}
func NewPacketReader(b []byte) *PacketReader {
return &PacketReader{
buffer: b,
pos: 0,
}
}
func (r *PacketReader) CanRead(size int) error {
if r.pos+size > len(r.buffer) {
return ErrOutOfBounds
}
return nil
}
func (r *PacketReader) Pos() int {
return r.pos
}
func (r *PacketReader) ReadIPv4() (net.IP, error) {
if err := r.CanRead(net.IPv4len); err != nil {
return nil, err
}
ip := net.IP(r.buffer[r.pos : r.pos+net.IPv4len])
r.pos += net.IPv4len
return ip, nil
}
func (r *PacketReader) ReadPort() (uint16, error) {
if err := r.CanRead(2); err != nil {
return 0, err
}
port := binary.BigEndian.Uint16(r.buffer[r.pos:])
r.pos += 2
return port, nil
}
func (r *PacketReader) ReadUint8() uint8 {
b := r.buffer[r.pos]
r.pos++
return b
}
func (r *PacketReader) ReadUint16() uint16 {
u16 := binary.LittleEndian.Uint16(r.buffer[r.pos:])
r.pos += 2
return u16
}
func (r *PacketReader) ReadUint32() uint32 {
u32 := binary.LittleEndian.Uint32(r.buffer[r.pos:])
r.pos += 4
return u32
}
func (r *PacketReader) ReadInt32() int32 {
return int32(r.ReadUint32())
}
func (r *PacketReader) ReadUint64() uint64 {
u64 := binary.LittleEndian.Uint64(r.buffer[r.pos:])
r.pos += 8
return u64
}
func (r *PacketReader) ReadString() string {
start := r.pos
for {
if r.buffer[r.pos] == 0 {
r.pos++
break
}
r.pos++
}
return string(r.buffer[start : r.pos-1])
}
func (r *PacketReader) More() bool {
return r.pos < len(r.buffer)
}