forked from wzshiming/socks5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.go
385 lines (349 loc) · 7.96 KB
/
common.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
package socks5
import (
"context"
"encoding/binary"
"errors"
"io"
"math"
"net"
"os"
"reflect"
"runtime"
"strconv"
"strings"
)
var (
errStringTooLong = errors.New("string too long")
errUserAuthFailed = errors.New("user authentication failed")
errNoSupportedAuth = errors.New("no supported authentication mechanism")
errUnrecognizedAddrType = errors.New("unrecognized address type")
)
const (
maxUdpPacket = math.MaxUint16 - 28
)
const (
socks5Version = 0x05
)
const (
ConnectCommand Command = 0x01
BindCommand Command = 0x02
AssociateCommand Command = 0x03
)
// Command is a SOCKS Command.
type Command byte
func (cmd Command) String() string {
switch cmd {
case ConnectCommand:
return "socks connect"
case BindCommand:
return "socks bind"
case AssociateCommand:
return "socks associate"
default:
return "socks " + strconv.Itoa(int(cmd))
}
}
const (
successReply reply = 0x00
serverFailure reply = 0x01
ruleFailure reply = 0x02
networkUnreachable reply = 0x03
hostUnreachable reply = 0x04
connectionRefused reply = 0x05
ttlExpired reply = 0x06
commandNotSupported reply = 0x07
addrTypeNotSupported reply = 0x08
)
func errToReply(err error) reply {
if err == nil {
return successReply
}
msg := err.Error()
resp := hostUnreachable
if strings.Contains(msg, "refused") {
resp = connectionRefused
} else if strings.Contains(msg, "network is unreachable") {
resp = networkUnreachable
}
return resp
}
// reply is a SOCKS Command reply code.
type reply byte
func (code reply) String() string {
switch code {
case successReply:
return "succeeded"
case serverFailure:
return "general SOCKS server failure"
case ruleFailure:
return "connection not allowed by ruleset"
case networkUnreachable:
return "network unreachable"
case hostUnreachable:
return "host unreachable"
case connectionRefused:
return "connection refused"
case ttlExpired:
return "TTL expired"
case commandNotSupported:
return "Command not supported"
case addrTypeNotSupported:
return "address type not supported"
default:
return "unknown code: " + strconv.Itoa(int(code))
}
}
const (
ipv4Address = 0x01
fqdnAddress = 0x03
ipv6Address = 0x04
)
// address is a SOCKS-specific address.
// Either Name or IP is used exclusively.
type address struct {
Name string // fully-qualified domain name
IP net.IP
Port int
}
func (a *address) Network() string { return "socks5" }
func (a *address) String() string {
if a == nil {
return "<nil>"
}
return a.Address()
}
// Address returns a string suitable to dial; prefer returning IP-based
// address, fallback to Name
func (a address) Address() string {
port := strconv.Itoa(a.Port)
if 0 != len(a.IP) {
return net.JoinHostPort(a.IP.String(), port)
}
return net.JoinHostPort(a.Name, port)
}
// authMethod is a SOCKS authentication method.
type authMethod byte
const (
noAuth authMethod = 0x00 // no authentication required
gssapiAuth authMethod = 0x01 // use GSSAPI
userAuth authMethod = 0x02 // use username/password
noAcceptable authMethod = 0xff // no acceptable authentication methods
)
const (
userAuthVersion = 0x01
authSuccess = 0x00
authFailure = 0x01
)
func readBytes(r io.Reader) ([]byte, error) {
var buf [1]byte
_, err := r.Read(buf[:])
if err != nil {
return nil, err
}
bytes := make([]byte, buf[0])
_, err = io.ReadFull(r, bytes)
if err != nil {
return nil, err
}
return bytes, nil
}
func writeBytes(w io.Writer, b []byte) error {
_, err := w.Write([]byte{byte(len(b))})
if err != nil {
return err
}
_, err = w.Write(b)
return err
}
func readByte(r io.Reader) (byte, error) {
var buf [1]byte
_, err := r.Read(buf[:])
if err != nil {
return 0, err
}
return buf[0], nil
}
func readAddr(r io.Reader) (*address, error) {
address := &address{}
var addrType [1]byte
if _, err := r.Read(addrType[:]); err != nil {
return nil, err
}
switch addrType[0] {
case ipv4Address:
addr := make(net.IP, net.IPv4len)
if _, err := io.ReadFull(r, addr); err != nil {
return nil, err
}
address.IP = addr
case ipv6Address:
addr := make(net.IP, net.IPv6len)
if _, err := io.ReadFull(r, addr); err != nil {
return nil, err
}
address.IP = addr
case fqdnAddress:
if _, err := r.Read(addrType[:]); err != nil {
return nil, err
}
addrLen := int(addrType[0])
fqdn := make([]byte, addrLen)
if _, err := io.ReadFull(r, fqdn); err != nil {
return nil, err
}
address.Name = string(fqdn)
default:
return nil, errUnrecognizedAddrType
}
var port [2]byte
if _, err := io.ReadFull(r, port[:]); err != nil {
return nil, err
}
address.Port = int(binary.BigEndian.Uint16(port[:]))
return address, nil
}
func writeAddr(w io.Writer, addr *address) error {
if addr == nil {
_, err := w.Write([]byte{ipv4Address, 0, 0, 0, 0, 0, 0})
if err != nil {
return err
}
return nil
}
if addr.IP != nil {
if ip4 := addr.IP.To4(); ip4 != nil {
_, err := w.Write([]byte{ipv4Address})
if err != nil {
return err
}
_, err = w.Write(ip4)
if err != nil {
return err
}
} else if ip6 := addr.IP.To16(); ip6 != nil {
_, err := w.Write([]byte{ipv6Address})
if err != nil {
return err
}
_, err = w.Write(ip6)
if err != nil {
return err
}
} else {
_, err := w.Write([]byte{ipv4Address, 0, 0, 0, 0})
if err != nil {
return err
}
}
} else if addr.Name != "" {
if len(addr.Name) > 255 {
return errStringTooLong
}
_, err := w.Write([]byte{fqdnAddress, byte(len(addr.Name))})
if err != nil {
return err
}
_, err = w.Write([]byte(addr.Name))
if err != nil {
return err
}
} else {
_, err := w.Write([]byte{ipv4Address, 0, 0, 0, 0})
if err != nil {
return err
}
}
var p [2]byte
binary.BigEndian.PutUint16(p[:], uint16(addr.Port))
_, err := w.Write(p[:])
return err
}
func writeAddrWithStr(w io.Writer, addr string) error {
host, port, err := splitHostPort(addr)
if err != nil {
return err
}
if ip := net.ParseIP(host); ip != nil {
return writeAddr(w, &address{IP: ip, Port: port})
}
return writeAddr(w, &address{Name: host, Port: port})
}
func splitHostPort(address string) (string, int, error) {
host, port, err := net.SplitHostPort(address)
if err != nil {
return "", 0, err
}
portnum, err := strconv.Atoi(port)
if err != nil {
return "", 0, err
}
if 0 > portnum || portnum > 0xffff {
return "", 0, errors.New("port number out of range " + port)
}
return host, portnum, nil
}
// isClosedConnError reports whether err is an error from use of a closed
// network connection.
func isClosedConnError(err error) bool {
if err == nil {
return false
}
str := err.Error()
if strings.Contains(str, "use of closed network connection") {
return true
}
if runtime.GOOS == "windows" {
if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
if se, ok := oe.Err.(*os.SyscallError); ok && se.Syscall == "wsarecv" {
const WSAECONNABORTED = 10053
const WSAECONNRESET = 10054
if n := errno(se.Err); n == WSAECONNRESET || n == WSAECONNABORTED {
return true
}
}
}
}
return false
}
func errno(v error) uintptr {
if rv := reflect.ValueOf(v); rv.Kind() == reflect.Uintptr {
return uintptr(rv.Uint())
}
return 0
}
// tunnel create tunnels for two io.ReadWriteCloser
func tunnel(ctx context.Context, c1, c2 io.ReadWriteCloser, buf1, buf2 []byte) error {
ctx, cancel := context.WithCancel(ctx)
var errs tunnelErr
go func() {
_, errs[0] = io.CopyBuffer(c1, c2, buf1)
cancel()
}()
go func() {
_, errs[1] = io.CopyBuffer(c2, c1, buf2)
cancel()
}()
<-ctx.Done()
errs[2] = c1.Close()
errs[3] = c2.Close()
errs[4] = ctx.Err()
if errs[4] == context.Canceled {
errs[4] = nil
}
return errs.FirstError()
}
type tunnelErr [5]error
func (t tunnelErr) FirstError() error {
for _, err := range t {
if err != nil {
return err
}
}
return nil
}
// BytesPool is an interface for getting and returning temporary
// bytes for use by io.CopyBuffer.
type BytesPool interface {
Get() []byte
Put([]byte)
}