-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpacket.go
107 lines (87 loc) Β· 2.35 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
package socks5
import (
"bytes"
"errors"
"net"
)
type payload []byte
func (p *payload) reset() {
*p = nil
}
func (p payload) len() int64 {
return int64(len(p))
}
type packet struct {
address *address
payload payload
}
func (p *packet) decode(data []byte) error {
buffer := bytes.NewBuffer(data)
// Reserved 2 bytes: 0x00, 0x00
if _, err := buffer.Read(make([]byte, 2)); err != nil {
return errors.New("failed to read reserved bytes")
}
// Current fragment number
frag, err := buffer.ReadByte()
if err != nil {
return errors.New("failed to read current fragment number")
}
// If not support fragmentation must drop any datagram whose FRAG field is other than 0x00
if frag != 0x00 {
return errors.New("not support fragmentation")
}
var address address
address.Type, err = buffer.ReadByte()
if err != nil {
return errors.New("failed to read address type")
}
switch address.Type {
case addressTypeIPv4:
address.IP = make(net.IP, net.IPv4len)
if _, err := buffer.Read(address.IP); err != nil {
return errors.New("failed to read IPv4 address")
}
case addressTypeFQDN:
address.DomainLen, err = buffer.ReadByte()
if err != nil {
return errors.New("failed to read domain length")
}
address.Domain = make([]byte, address.DomainLen)
if _, err := buffer.Read(address.Domain); err != nil {
return errors.New("failed to read domain")
}
case addressTypeIPv6:
address.IP = make(net.IP, net.IPv6len)
if _, err := buffer.Read(address.IP); err != nil {
return errors.New("failed to read IPv6 address")
}
default:
return errors.New("not support address type")
}
address.Port = make([]byte, 2)
if _, err := buffer.Read(address.Port); err != nil {
return errors.New("failed to read port")
}
p.address = &address
p.payload = buffer.Bytes()
return nil
}
func (p *packet) encode(data []byte) {
p.payload = []byte{
0x00, // Reserved byte
0x00, // Reserved byte
0x00, // Current fragment number
p.address.Type,
}
switch p.address.Type {
case addressTypeIPv4:
p.payload = append(p.payload, p.address.IP.To4()...)
case addressTypeFQDN:
p.payload = append(p.payload, p.address.DomainLen)
p.payload = append(p.payload, p.address.Domain...)
case addressTypeIPv6:
p.payload = append(p.payload, p.address.IP.To16()...)
}
p.payload = append(p.payload, p.address.Port...)
p.payload = append(p.payload, data...)
}