-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathproxy.go
More file actions
91 lines (82 loc) · 2.38 KB
/
proxy.go
File metadata and controls
91 lines (82 loc) · 2.38 KB
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
package proxyclient
import (
"context"
"errors"
"net"
"net/url"
"strconv"
"strings"
"sync"
"time"
httpProxy "github.com/chainreactors/proxyclient/http"
socksProxy "github.com/chainreactors/proxyclient/socks"
)
var builtinSchemeInitOnce sync.Once
func init() {
InitBuiltinSchemes()
}
// InitBuiltinSchemes registers the built-in proxy dialer factories.
// It is safe to call multiple times and is useful for runtimes where
// package init ordering/state may be unreliable (e.g. some WASM targets).
func InitBuiltinSchemes() {
builtinSchemeInitOnce.Do(func() {
RegisterScheme("DIRECT", newDirectProxyClient)
RegisterScheme("REJECT", newRejectProxyClient)
RegisterScheme("SOCKS", newSocksProxyClient)
RegisterScheme("SOCKS4", newSocksProxyClient)
RegisterScheme("SOCKS4A", newSocksProxyClient)
RegisterScheme("SOCKS5", newSocksProxyClient)
RegisterScheme("SOCKS5+TLS", newSocksProxyClient)
RegisterScheme("HTTP", newHTTPProxyClient)
RegisterScheme("HTTPS", newHTTPProxyClient)
})
}
func newDirectProxyClient(proxy *url.URL, _ Dial) (dial Dial, err error) {
dial = (&net.Dialer{}).DialContext
if timeout, _ := time.ParseDuration(proxy.Query().Get("timeout")); timeout != 0 {
dial = DialWithTimeout(timeout)
}
return
}
func newRejectProxyClient(proxy *url.URL, _ Dial) (dial Dial, err error) {
dialErr := errors.New("reject dial")
dial = func(ctx context.Context, network, address string) (net.Conn, error) {
return nil, dialErr
}
if try, _ := strconv.ParseInt(proxy.Query().Get("try-to-blackhole"), 10, 8); try > 0 {
attempt := int64(0)
dial = func(ctx context.Context, network, address string) (net.Conn, error) {
attempt++
if attempt > try {
return blackholeConn{}, nil
}
return nil, dialErr
}
}
return
}
func newHTTPProxyClient(proxy *url.URL, upstreamDial Dial) (dial Dial, err error) {
client := httpProxy.Client{
Proxy: *proxy,
TLSConfig: tlsConfigByProxyURL(proxy),
UpstreamDial: upstreamDial,
}
dial = Dial(client.Dial).TCPOnly
return
}
func newSocksProxyClient(proxy *url.URL, upstreamDial Dial) (dial Dial, err error) {
conf := &socksProxy.SOCKSConf{
TLSConfig: tlsConfigByProxyURL(proxy),
Dial: upstreamDial,
}
client, err := socksProxy.NewClient(proxy, conf)
if err != nil {
return
}
dial = Dial(client.Dial)
switch strings.ToUpper(proxy.Scheme) {
case "SOCKS", "SOCKS4", "SOCKS4A":
dial = dial.TCPOnly
}
return
}