forked from onrik/SOCKSProxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_socks4.go
108 lines (100 loc) · 2.13 KB
/
client_socks4.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
package proxy
import (
"bufio"
"errors"
"fmt"
"net"
"net/url"
"strings"
)
type socks4Client struct {
proxy *url.URL
conf *SOCKSConf
}
func (c *socks4Client) Dial(network, address string) (remoteConn net.Conn, err error) {
host, port, err := splitHostPort(address)
if err != nil {
return
}
request := &socks4Request{
command:commandConnect,
port: port,
ip: []byte{0, 0, 0, 1},
userId: []byte{},
fqdn: host,
}
if c.isSOCKS4() {
request.ip, err = c.lookupIP(string(request.fqdn))
if err != nil {
return
}
}
remoteConn, err = c.conf.Dial("tcp", c.proxy.Host)
if err != nil {
return
}
if _, err = remoteConn.Write(request.ToPacket()); err != nil {
return
}
switch request.command {
case commandConnect:
err = c.handleConnect(remoteConn)
}
return
}
func (c *socks4Client) handleConnect(remoteConn net.Conn) (err error) {
reader := bufio.NewReader(remoteConn)
version, err := reader.ReadByte()
if err != nil {
return
}
if version != 0 {
err = errVersionError
return
}
code, err := reader.ReadByte()
if err != nil {
return
}
if code != socks4StatusGranted {
switch code {
case socks4StatusRejected:
err = errors.New("Socks connection request rejected or failed.")
case 92:
err = errors.New("Socks connection request rejected becasue SOCKS server cannot connect to identd on the client.")
case 93:
err = errors.New("Socks connection request rejected because the client program and identd report different user-ids.")
default:
err = errors.New("Socks connection request failed, unknown error.")
}
return
}
_, err = reader.Discard(2) // dst port
if err != nil {
return
}
_, err = reader.Discard(4) // dst ip
if err != nil {
return
}
return
}
func (c *socks4Client) isSOCKS4() bool {
return strings.ToUpper(c.proxy.Scheme) == "SOCKS4"
}
func (c *socks4Client) lookupIP(host string) (ip net.IP, err error) {
ips, err := net.LookupIP(host)
if err != nil {
return
}
if len(ips) == 0 {
err = fmt.Errorf("Cannot resolve host: %s.", host)
return
}
ip = ips[0]
if len(ip) != net.IPv4len {
err = errors.New("IPv6 is not supported by SOCKS4.")
return
}
return
}