-
Notifications
You must be signed in to change notification settings - Fork 4
/
tor.go
115 lines (103 loc) · 2.59 KB
/
tor.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
package is
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"os"
"os/exec"
"runtime"
"time"
"github.com/cretz/bine/tor"
"github.com/wabarc/logger"
"golang.org/x/net/proxy"
)
func newTorClient(ctx context.Context) (client *http.Client, t *tor.Tor, err error) {
var dialer proxy.ContextDialer
addr, isUseProxy := useProxy()
if isUseProxy {
// Create a socks5 dialer
pxy, err := proxy.SOCKS5("tcp", addr, nil, proxy.Direct)
if err != nil {
return nil, t, fmt.Errorf("Can't connect to the proxy: %w", err)
}
dialer = pxy.(interface {
DialContext(ctx context.Context, network, addr string) (net.Conn, error)
})
} else {
// Lookup tor executable file
if _, err := exec.LookPath("tor"); err != nil {
return nil, t, fmt.Errorf("%w", err)
}
// Start tor with default config
startConf := &tor.StartConf{
TempDataDirBase: os.TempDir(),
RetainTempDataDir: false,
EnableNetwork: true,
NoHush: false,
}
t, err = tor.Start(ctx, startConf)
if err != nil {
return nil, t, fmt.Errorf("Make connection failed: %w", err)
}
// defer t.Close()
t.DeleteDataDirOnClose = true
t.StopProcessOnClose = true
// Wait at most a minute to start network and get
dialCtx, dialCancel := context.WithTimeout(ctx, time.Minute)
defer dialCancel()
t.ProcessCancelFunc = dialCancel
// Make connection
dialer, err = t.Dialer(dialCtx, nil)
if err != nil {
t.Close()
return nil, t, fmt.Errorf("Make connection failed: %w", err)
}
}
return &http.Client{
Timeout: timeout,
CheckRedirect: noRedirect,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: dialer.DialContext,
MaxIdleConns: 10,
IdleConnTimeout: 60 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: false,
MinVersion: tls.VersionTLS12,
},
},
}, t, nil
}
func closeTor(t *tor.Tor) error {
if t != nil {
return t.Close()
}
return nil
}
func useProxy() (addr string, ok bool) {
host := os.Getenv("TOR_HOST")
port := os.Getenv("TOR_SOCKS_PORT")
if host == "" {
host = "127.0.0.1"
}
if port == "" {
port = "9050"
}
addr = net.JoinHostPort(host, port)
conn, err := net.DialTimeout("tcp", addr, time.Second)
if err != nil {
logger.Debug("Try to connect tor proxy failed: %v", err)
return addr, false
}
if conn != nil {
conn.Close()
logger.Debug("Connected: %v", addr)
return addr, true
}
return addr, false
}