forked from txthinking/socks5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
101 lines (96 loc) · 2.19 KB
/
client.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
package socks5
import (
"errors"
"net"
"time"
)
// Client is socks5 client wrapper
type Client struct {
UserName string
Password string
TCPAddr *net.TCPAddr
TCPConn *net.TCPConn
UDPAddr *net.UDPAddr
TCPDeadline int // not refreshed
TCPTimeout int
UDPDeadline int // refreshed
}
func NewClient(addr, username, password string, tcpTimeout, tcpDeadline, udpDeadline int) (*Client, error) {
taddr, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
return nil, err
}
uaddr, err := net.ResolveUDPAddr("udp", addr)
if err != nil {
return nil, err
}
c := &Client{
UserName: username,
Password: password,
TCPAddr: taddr,
UDPAddr: uaddr,
TCPTimeout: tcpTimeout,
TCPDeadline: tcpDeadline,
UDPDeadline: udpDeadline,
}
return c, nil
}
func (c *Client) Negotiate() error {
con, err := Dial.Dial("tcp", c.TCPAddr.String())
if err != nil {
return err
}
c.TCPConn = con.(*net.TCPConn)
if c.TCPTimeout != 0 {
if err := c.TCPConn.SetKeepAlivePeriod(time.Duration(c.TCPTimeout) * time.Second); err != nil {
return err
}
}
if c.TCPDeadline != 0 {
if err := c.TCPConn.SetDeadline(time.Now().Add(time.Duration(c.TCPTimeout) * time.Second)); err != nil {
return err
}
}
m := MethodNone
if c.UserName != "" && c.Password != "" {
m = MethodUsernamePassword
}
rq := NewNegotiationRequest([]byte{m})
if err := rq.WriteTo(c.TCPConn); err != nil {
return err
}
rp, err := NewNegotiationReplyFrom(c.TCPConn)
if err != nil {
return err
}
if rp.Method != m {
return errors.New("Unsupport method")
}
if m == MethodUsernamePassword {
urq := NewUserPassNegotiationRequest([]byte(c.UserName), []byte(c.Password))
if err := urq.WriteTo(c.TCPConn); err != nil {
return err
}
urp, err := NewUserPassNegotiationReplyFrom(c.TCPConn)
if err != nil {
return err
}
if urp.Status != UserPassStatusSuccess {
return ErrUserPassAuth
}
}
return nil
}
func (c *Client) Request(r *Request) (*Reply, error) {
if err := r.WriteTo(c.TCPConn); err != nil {
return nil, err
}
rp, err := NewReplyFrom(c.TCPConn)
if err != nil {
return nil, err
}
if rp.Rep != RepSuccess {
return nil, errors.New("Host unreachable")
}
return rp, nil
}