/
ds_client.go
389 lines (367 loc) · 10.9 KB
/
ds_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
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
386
387
388
389
package main
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"time"
"github.com/darksocks/darksocks/ds"
)
var clientConf string
var clientConfDir string
var client *ds.Client
var proxyServer *ds.SocksProxy
var managerServer *http.Server
var managerListener net.Listener
var abpPath = filepath.Join(execDir(), "abp.js")
var gfwListPath = filepath.Join(execDir(), "gfwlist.txt")
var userRulesPath = filepath.Join(execDir(), "user_rules.txt")
var gfwListURL = "https://raw.githubusercontent.com/gfwlist/gfwlist/master/gfwlist.txt"
//ClientServerConf is pojo for dark socks server configure
type ClientServerConf struct {
Enable bool `json:"enable"`
Name string `json:"name"`
Address []string `json:"address"`
Username string `json:"username"`
Password string `json:"password"`
LastUsed int `json:"-"`
}
//ClientConf is pojo for dark socks client configure
type ClientConf struct {
Servers []*ClientServerConf `json:"servers"`
SocksAddr string `json:"socks_addr"`
HTTPAddr string `json:"http_addr"`
ManagerAddr string `json:"manager_addr"`
Mode string `json:"mode"`
LogLevel int `json:"log"`
}
//Dial connection by remote
func (c *ClientConf) Dial(remote string) (raw io.ReadWriteCloser, err error) {
for _, conf := range c.Servers {
if conf.Enable && len(conf.Address) > 0 {
address := conf.Address[conf.LastUsed]
conf.LastUsed = (conf.LastUsed + 1) % len(conf.Address)
if len(conf.Username) > 0 && len(conf.Password) > 0 {
if strings.Contains(address, "?") {
address += fmt.Sprintf("&username=%v&password=%v", conf.Username, conf.Password)
} else {
address += fmt.Sprintf("?username=%v&password=%v", conf.Username, conf.Password)
}
}
ds.InfoLog("Client start connect one channel to %v", conf.Name)
raw, err = ds.WebsocketDialer("").Dial(address)
if err == nil {
ds.InfoLog("Client connect one channel to %v success", conf.Name)
conn := ds.NewStringConn(raw)
conn.Name = conf.Name
raw = conn
break
} else {
ds.WarnLog("Client connect one channel fail with %v", err)
}
}
}
if raw == nil {
err = fmt.Errorf("server not found")
}
return
}
//PAC is http handler to get pac js
func (c *ClientConf) PAC(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "application/x-javascript")
//
abpRaw, err := ioutil.ReadFile(abpPath)
if err != nil {
ds.ErrorLog("PAC read apb.js fail with %v", err)
res.WriteHeader(500)
fmt.Fprintf(res, "%v", err)
return
}
abpStr := string(abpRaw)
//
//rules
gfwRules, err := readGfwlist()
if err != nil {
ds.ErrorLog("PAC read gfwlist.txt fail with %v", err)
res.WriteHeader(500)
fmt.Fprintf(res, "%v", err)
return
}
userRules, _ := readUserRules()
gfwRules = append(gfwRules, userRules...)
gfwRulesJS, _ := json.Marshal(gfwRules)
abpStr = strings.Replace(abpStr, "__RULES__", string(gfwRulesJS), 1)
//
//proxy address
if proxyServer == nil || proxyServer.Listener == nil {
ds.ErrorLog("PAC load fail with socks proxy server is not started")
res.WriteHeader(500)
fmt.Fprintf(res, "%v", "socks proxy server is not started")
return
}
//
// socksProxy.
parts := strings.SplitN(proxyServer.Addr().String(), ":", -1)
abpStr = strings.Replace(abpStr, "__SOCKS5ADDR__", "127.0.0.1", -1)
abpStr = strings.Replace(abpStr, "__SOCKS5PORT__", parts[len(parts)-1], -1)
res.Write([]byte(abpStr))
}
//ChangeProxyMode is http handler to change proxy mode
func (c *ClientConf) ChangeProxyMode(w http.ResponseWriter, r *http.Request) {
mode := r.URL.Query().Get("mode")
_, err := changeProxyMode(mode)
if err != nil {
w.WriteHeader(500)
fmt.Fprintf(w, "%v", err)
return
}
c.Mode = mode
err = ds.WriteJSON(clientConf, c)
if err != nil {
w.WriteHeader(500)
fmt.Fprintf(w, "%v", err)
return
}
fmt.Fprintf(w, "%v", "ok")
}
//UpdateGfwlist is http handler to update gfwlist.txt
func (c *ClientConf) UpdateGfwlist(w http.ResponseWriter, r *http.Request) {
err := updateGfwlist()
if err != nil {
w.WriteHeader(500)
fmt.Fprintf(w, "%v", err)
return
}
fmt.Fprintf(w, "%v", "ok")
}
func startClient(c string) (err error) {
conf := &ClientConf{Mode: "auto"}
err = ds.ReadJSON(c, &conf)
if err != nil {
ds.ErrorLog("Client read configure fail with %v", err)
exitf(1)
return
}
if len(conf.SocksAddr) < 1 {
ds.ErrorLog("Client socks_addr is required")
exitf(1)
return
}
clientConf = c
clientConfDir = filepath.Dir(clientConf)
os.MkdirAll(workDir, os.ModePerm)
ds.SetLogLevel(conf.LogLevel)
ds.InfoLog("Client using config from %v", c)
client = ds.NewClient(ds.DefaultBufferSize, conf)
proxyServer = ds.NewSocksProxy()
proxyServer.Dialer = func(target string, raw io.ReadWriteCloser) (sid uint64, err error) {
err = client.ProcConn(raw, target)
return
}
if len(conf.ManagerAddr) > 0 {
mux := http.NewServeMux()
mux.HandleFunc("/pac.js", conf.PAC)
mux.HandleFunc("/changeProxyMode", conf.ChangeProxyMode)
mux.HandleFunc("/updateGfwlist", conf.UpdateGfwlist)
var listener net.Listener
managerServer = &http.Server{Addr: conf.ManagerAddr, Handler: mux}
listener, err = net.Listen("tcp", conf.ManagerAddr)
if err != nil {
ds.ErrorLog("Client start web server fail with %v", err)
exitf(1)
return
}
managerServer.Addr = listener.Addr().String()
managerListener = &ds.TCPKeepAliveListener{TCPListener: listener.(*net.TCPListener)}
}
err = proxyServer.Listen(conf.SocksAddr)
if err != nil {
ds.ErrorLog("Client start proxy server fail with %v", err)
exitf(1)
return
}
changeProxyMode(conf.Mode)
// writeRuntimeVar()
wait := sync.WaitGroup{}
if managerServer != nil {
wait.Add(1)
ds.InfoLog("Client start web server on %v", managerListener.Addr())
go func() {
xerr := managerServer.Serve(managerListener)
ds.WarnLog("Client the web server on %v is stopped by %v", managerListener.Addr(), xerr)
wait.Done()
}()
}
if len(conf.HTTPAddr) > 0 {
wait.Add(1)
go func() {
xerr := runPrivoxy(conf.HTTPAddr)
ds.WarnLog("Client the privoxy on %v is stopped by %v", conf.HTTPAddr, xerr)
wait.Done()
}()
}
go handlerClientKill()
proxyServer.Run()
ds.InfoLog("Client all listener is stopped")
changeProxyMode("manual")
wait.Wait()
return
}
func stopClient() {
ds.InfoLog("Client stopping client listener")
if proxyServer != nil {
proxyServer.Close()
}
if managerServer != nil {
managerServer.Close()
}
if privoxyRunner != nil && privoxyRunner.Process != nil {
privoxyRunner.Process.Kill()
}
if client != nil {
client.Close()
}
}
var clientKillSignal chan os.Signal
func handlerClientKill() {
clientKillSignal = make(chan os.Signal, 1000)
signal.Notify(clientKillSignal, os.Kill, os.Interrupt)
v := <-clientKillSignal
ds.WarnLog("Clien receive kill signal:%v", v)
stopClient()
}
func changeProxyMode(mode string) (message string, err error) {
if proxyServer == nil || proxyServer.Listener == nil || managerServer == nil {
err = fmt.Errorf("proxy server is not started")
return
}
proxyServerParts := strings.Split(proxyServer.Addr().String(), ":")
managerServerParts := strings.Split(managerServer.Addr, ":")
switch mode {
case "auto":
pacURL := fmt.Sprintf("http://127.0.0.1:%v/pac.js?timestamp=%v", managerServerParts[len(managerServerParts)-1], time.Now().Local().UnixNano()/1e6)
ds.InfoLog("start change proxy mode to %v by %v", mode, pacURL)
message, err = changeProxyModeNative("auto", pacURL)
case "global":
ds.InfoLog("start change proxy mode to %v by 127.0.0.1:%v", mode, proxyServerParts[len(proxyServerParts)-1])
message, err = changeProxyModeNative("global", "127.0.0.1", proxyServerParts[len(proxyServerParts)-1])
default:
message, err = changeProxyModeNative("manual")
}
if err != nil {
ds.WarnLog("change proxy mode to %v fail with %v, the log is\n%v\n", mode, err, message)
} else {
ds.InfoLog("change proxy mode to %v is success", mode)
}
return
}
func readGfwlist() (rules []string, err error) {
gfwFile := filepath.Join(workDir, "gfwlist.txt")
gfwRaw, err := ioutil.ReadFile(gfwFile)
if err != nil {
gfwFile = gfwListPath
gfwRaw, err = ioutil.ReadFile(gfwFile)
if err != nil {
err = fmt.Errorf("read gfwlist.txt fail with %v", err)
return
}
}
gfwData, err := base64.StdEncoding.DecodeString(string(gfwRaw))
if err != nil {
err = fmt.Errorf("decode gfwlist.txt fail with %v", err)
return
}
gfwRulesAll := strings.Split(string(gfwData), "\n")
for _, rule := range gfwRulesAll {
if strings.HasPrefix(rule, "[") || strings.HasPrefix(rule, "!") || len(strings.TrimSpace(rule)) < 1 {
continue
}
rules = append(rules, rule)
}
return
}
func readUserRules() (rules []string, err error) {
gfwFile := filepath.Join(workDir, "user_rules.txt")
gfwData, err := ioutil.ReadFile(gfwFile)
if err != nil {
gfwFile = userRulesPath
gfwData, err = ioutil.ReadFile(gfwFile)
if err != nil {
err = fmt.Errorf("read gfwlist.txt fail with %v", err)
return
}
}
gfwRulesAll := strings.Split(string(gfwData), "\n")
for _, rule := range gfwRulesAll {
rule = strings.TrimSpace(rule)
if strings.HasPrefix(rule, "--") || strings.HasPrefix(rule, "!") || len(strings.TrimSpace(rule)) < 1 {
continue
}
rules = append(rules, rule)
}
return
}
func updateGfwlist() (err error) {
if client == nil {
err = fmt.Errorf("proxy server is not started")
return
}
gfwData, err := client.HTTPGet(gfwListURL)
if err != nil {
return
}
os.MkdirAll(workDir, os.ModePerm)
gfwFile := filepath.Join(workDir, "gfwlist.txt")
err = ioutil.WriteFile(gfwFile, gfwData, os.ModePerm)
return
}
const (
//PrivoxyTmpl is privoxy template
PrivoxyTmpl = `
listen-address {http}
toggle 1
enable-remote-toggle 1
enable-remote-http-toggle 1
enable-edit-actions 0
enforce-blocks 0
buffer-limit 4096
forwarded-connect-retries 0
accept-intercepted-requests 0
allow-cgi-request-crunching 0
split-large-forms 0
keep-alive-timeout 5
socket-timeout 60
forward-socks5 / {socks5} .
forward 192.168.*.*/ .
forward 10.*.*.*/ .
forward 127.*.*.*/ .
`
)
func writePrivoxyConf(confFile, httpAddr, socksAddr string) (err error) {
data := PrivoxyTmpl
data = strings.Replace(data, "{http}", httpAddr, 1)
data = strings.Replace(data, "{socks5}", socksAddr, 1)
err = ioutil.WriteFile(confFile, []byte(data), os.ModePerm)
return
}
func runPrivoxy(httpAddr string) (err error) {
proxyServerParts := strings.SplitN(proxyServer.Addr().String(), ":", -1)
socksAddr := fmt.Sprintf("127.0.0.1:%v", proxyServerParts[len(proxyServerParts)-1])
ds.InfoLog("Client start privoxy by listening http proxy on %v and forwarding to %v", httpAddr, socksAddr)
confFile := filepath.Join(workDir, "privoxy.conf")
err = writePrivoxyConf(confFile, httpAddr, socksAddr)
if err != nil {
ds.WarnLog("Client save privoxy config to %v fail with %v", confFile, err)
return
}
err = runPrivoxyNative(confFile)
return
}