-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
225 lines (197 loc) · 4.17 KB
/
connection.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
package connection
import (
"bytes"
"context"
"errors"
"io/ioutil"
"net/http"
"sync"
"time"
"github.com/schollz/bine/tor"
log "github.com/schollz/logger"
)
// Connection defines a connection
type Connection struct {
// config paramters
debug bool
name string
usetor bool
connecting bool
ready bool
readyLock sync.Mutex
ipAddress string
tor *tor.Tor
client *http.Client
timeout time.Duration
headers map[string]string
}
var NotReadyError = errors.New("not ready")
// Option is the type all options need to adhere to
type Option func(c *Connection)
// OptionDebug turns on debugging
func OptionDebug(debug bool) Option {
return func(c *Connection) {
c.debug = debug
}
}
// OptionUseTor turns on debugging
func OptionUseTor(usetor bool) Option {
return func(c *Connection) {
c.usetor = usetor
}
}
// OptionTimeout sets timeout
func OptionTimeout(timeout time.Duration) Option {
return func(c *Connection) {
c.timeout = timeout
}
}
// OptionDebug turns on debugging
func OptionHeaders(headers map[string]string) Option {
return func(c *Connection) {
c.headers = make(map[string]string)
for h := range headers {
c.headers[h] = headers[h]
}
}
}
// OptionName turns on debugging
func OptionName(name string) Option {
return func(c *Connection) {
c.name = name
}
}
// New constructs a new instance of HTTPPool
func New(options ...Option) *Connection {
c := Connection{
debug: false,
usetor: true,
timeout: 180 * time.Second,
name: "", // TOOD: use UUID?
headers: make(map[string]string),
}
for _, o := range options {
o(&c)
}
return &c
}
// Close will close connections
func (c *Connection) Close() (err error) {
defer func() {
if r := recover(); r != nil {
log.Trace("Recovered in Close", r)
}
}()
c.ready = false
if c.client != nil {
c.client.CloseIdleConnections()
}
if c.tor != nil {
err = c.tor.Close()
}
return
}
// Connect will connect
func (c *Connection) Connect() (err error) {
defer func() {
if r := recover(); r != nil {
log.Trace("Recovered in Connect", r)
}
}()
if c.connecting {
return
}
c.connecting = true
c.ready = false
// close any current connections
c.Close()
log.Tracef("%s setting up client", c.name)
c.client = &http.Client{
Transport: &http.Transport{
MaxIdleConnsPerHost: 30,
},
Timeout: c.timeout,
}
// keep trying until it gets on
for {
if !c.usetor {
break
}
log.Debug("connecting to tor...")
c.tor, err = tor.Start(nil, nil)
if err != nil {
log.Error(err)
continue
}
// Wait at most a minute to start network and get
dialCtx, dialCancel := context.WithTimeout(context.Background(), 15*time.Second)
defer dialCancel()
// Make connection
dialer, err := c.tor.Dialer(dialCtx, nil)
if err != nil {
log.Debug(err)
continue
}
c.client.Transport = &http.Transport{
DialContext: dialer.DialContext,
MaxIdleConnsPerHost: 20,
}
err = c.getPublicIP()
if err != nil {
continue
}
log.Tracef("new IP address: %s", c.ipAddress)
break
}
c.ready = true
c.connecting = false
return
}
// PublicIP returns the current public IP address, getting it if hasn't been set
func (c *Connection) PublicIP() string {
if c.ipAddress == "" {
c.getPublicIP()
}
return c.ipAddress
}
func (c *Connection) getPublicIP() (err error) {
resp, err := c.client.Get("http://icanhazip.com/")
if err != nil {
log.Debug(err)
return
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
log.Debug(err)
return
}
c.ipAddress = string(bytes.TrimSpace(body))
return
}
// Get will get a URL
func (c *Connection) Get(urlToGet string) (resp *http.Response, err error) {
if !c.ready {
err = NotReadyError
return
}
log.Debugf("[%s] getting %s", c.name, urlToGet)
req, err := http.NewRequest("GET", urlToGet, nil)
if err != nil {
return
}
for h := range c.headers {
req.Header.Set(h, c.headers[h])
}
resp, err = c.client.Do(req)
if err != nil || resp.StatusCode != 200 {
if err != nil {
log.Tracef("[%s] got error: %s", c.name, err.Error())
} else {
log.Tracef("[%s] got status code: %d", c.name, resp.StatusCode)
// bad code received, reload
go c.Connect()
}
}
return
}