-
Notifications
You must be signed in to change notification settings - Fork 0
/
socks.go
134 lines (118 loc) · 2.11 KB
/
socks.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
package socks
import (
"bytes"
"errors"
"io"
"log"
"net"
"sync"
)
func newConn(conn net.Conn) {
defer conn.Close()
err := consult(conn)
if err != nil {
log.Println(err.Error())
return
}
err = responseWriter(conn)
if err != nil {
log.Println(err.Error())
return
}
}
var ErrUnsupportedVersion = errors.New("unsupported version")
func consult(conn net.Conn) (err error) {
msg := make([]byte, 2)
_, err = conn.Read(msg)
if err != nil {
return err
}
if msg[0] != 5 {
return ErrUnsupportedVersion
}
msg = make([]byte, msg[1])
_, err = conn.Read(msg)
if err != nil {
return err
}
if bytes.IndexByte(msg, 0) < 0 {
_, err = conn.Write([]byte{5, 0xff})
if err != nil {
return err
}
return errors.New("unsupported method")
}
_, err = conn.Write([]byte{5, 0})
return err
}
func responseWriter(sconn net.Conn) error {
req, err := ReadRequest(sconn)
if err != nil {
return err
}
switch req[1] {
case byte(Connect):
dconn, err := net.Dial("tcp", req.Addr())
if err != nil {
return err
}
resp, _ := NewRespone(Succeeded, req.AddrType(), req.Addr())
_, err = sconn.Write(resp)
if err != nil {
return err
}
var wg sync.WaitGroup
wg.Add(2)
go func() {
_, err = io.Copy(dconn, sconn)
if err != nil {
return
}
}()
go func() {
_, err = io.Copy(sconn, dconn)
if err != nil {
return
}
}()
wg.Wait()
return nil
case 2:
return errors.New("bind method not supported")
case 3:
return errors.New("udp method not supported")
default:
return errors.New("unexpected cmd")
}
}
func Serve(l net.Listener) error {
srv := &Server{Addr: l.Addr().String()}
return srv.Serve(l)
}
func ListenAndServe(addr string) error {
srv := &Server{Addr: addr}
return srv.ListenAndServe()
}
type Server struct {
Addr string
}
func (srv *Server) ListenAndServe() error {
addr := srv.Addr
if addr == "" {
addr = ":1080"
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return srv.Serve(ln)
}
func (srv *Server) Serve(l net.Listener) error {
for {
conn, err := l.Accept()
if err != nil {
return err
}
go newConn(conn)
}
}