-
Notifications
You must be signed in to change notification settings - Fork 20
/
client.go
232 lines (207 loc) · 5.12 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
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
// Copyright 2017 Burak Sezer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"crypto/tls"
"io"
"log"
"net"
"os"
"sync"
"time"
)
type client struct {
cfg config
password []byte
keepAlivePeriod time.Duration
dialTimeout time.Duration
wg sync.WaitGroup
errChan chan error
signal chan os.Signal
done chan struct{}
}
func newClient(cfg config, sigChan chan os.Signal) *client {
return &client{
cfg: cfg,
keepAlivePeriod: time.Duration(cfg.KeepAlivePeriod) * time.Second,
dialTimeout: time.Duration(cfg.DialTimeout) * time.Second,
errChan: make(chan error, 1),
signal: sigChan,
done: make(chan struct{}),
}
}
func (c *client) connCopy(dst, src net.Conn, copyDone chan struct{}) {
defer c.wg.Done()
defer func() {
copyDone <- struct{}{}
}()
_, err := io.Copy(dst, src)
if err != nil {
opErr, ok := err.(*net.OpError)
switch {
case ok && opErr.Op == "readfrom":
return
case ok && opErr.Op == "read":
return
default:
}
log.Println("[ERR] gsocks5: Failed to copy connection from",
src.RemoteAddr(), "to", dst.RemoteAddr(), ":", err)
}
}
func (c *client) proxyClientConn(conn, rConn net.Conn, ch chan struct{}) {
defer c.wg.Done()
// close ch, clientConn waits until it will be closed.
defer close(ch)
copyDone := make(chan struct{}, 2)
c.wg.Add(2)
go c.connCopy(rConn, conn, copyDone)
go c.connCopy(conn, rConn, copyDone)
// rConn and conn will be closed by defer calls in clientConn. There is nothing to do here.
<-copyDone
}
func (c *client) authenticate(conn io.ReadWriter, errChan chan error) {
defer c.wg.Done()
_, err := conn.Write(c.password)
if err != nil {
errChan <- nil
return
}
// Wait for authSuccess
buf := make([]byte, len(authSuccess))
_, err = conn.Read(buf)
if err != nil {
errChan <- err
return
}
if !bytes.Equal(buf, authSuccess) {
errChan <- errAuthenticationFailed
return
}
errChan <- nil
}
func (c *client) clientConn(conn net.Conn) {
defer c.wg.Done()
defer closeConn(conn)
d := &net.Dialer{
Timeout: c.dialTimeout,
}
cfg := &tls.Config{
InsecureSkipVerify: c.cfg.InsecureSkipVerify,
}
rConn, err := tls.DialWithDialer(d, "tcp", c.cfg.ServerAddr, cfg)
if err != nil {
log.Println("[ERR] gsocks5: Failed to dial", c.cfg.ServerAddr, err)
return
}
defer closeConn(rConn)
if c.password != nil {
errChan := make(chan error, 1)
c.wg.Add(1)
go c.authenticate(rConn, errChan)
select {
case <-time.After(5 * time.Second):
log.Println("[ERR] gsocks5: Authentication timeout")
return
case err := <-errChan:
if err != nil {
log.Println("[ERR] gsocks5: Failed to authenticate:", err)
return
}
}
}
ch := make(chan struct{})
c.wg.Add(1)
go c.proxyClientConn(conn, rConn, ch)
select {
case <-c.done:
case <-ch:
}
}
func (c *client) serve(l net.Listener) {
defer c.wg.Done()
for {
conn, err := l.Accept()
if err != nil {
log.Println("[DEBUG] gsocks5: Listener error:", err)
// Shutdown the client immediately.
c.shutdown()
if opErr, ok := err.(*net.OpError); !ok || (ok && opErr.Op != opErrAccept) {
c.errChan <- err
return
}
c.errChan <- nil
return
}
err = conn.(*net.TCPConn).SetKeepAlive(true)
if err != nil {
log.Println("[ERR] gsocks5: Failed to set KeepAlive on TCP connection")
return
}
err = conn.(*net.TCPConn).SetKeepAlivePeriod(c.keepAlivePeriod)
if err != nil {
log.Println("[ERR] gsocks5: Failed to set KeepAlivePeriod on TCP connection")
return
}
c.wg.Add(1)
go c.clientConn(conn)
}
}
func (c *client) shutdown() {
select {
case <-c.done:
return
default:
}
close(c.done)
}
func (c *client) run() error {
if c.cfg.Password != "" {
c.password = []byte(c.cfg.Password)
if len(c.password) > maxPasswordLength {
return errPasswordTooLong
}
}
ln, err := net.Listen("tcp", c.cfg.ClientAddr)
if err != nil {
return err
}
log.Println("[INF] gsocks5: Proxy client runs on", c.cfg.ClientAddr)
c.wg.Add(1)
go c.serve(ln)
select {
// Wait for SIGINT or SIGTERM
case <-c.signal:
// Wait for a listener error
case <-c.done:
}
// Signal all running goroutines to stop.
c.shutdown()
log.Println("[INF] gsocks5: Stopping proxy client", c.cfg.ClientAddr)
if err = ln.Close(); err != nil {
log.Println("[ERR] gsocks5: Failed to close listener", err)
}
ch := make(chan struct{})
go func() {
defer close(ch)
c.wg.Wait()
}()
select {
case <-ch:
case <-time.After(time.Duration(c.cfg.GracefulPeriod) * time.Second):
log.Println("[WARN] Some goroutines will be stopped immediately")
}
return <-c.errChan
}