-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathconn_test.go
More file actions
419 lines (353 loc) · 10 KB
/
conn_test.go
File metadata and controls
419 lines (353 loc) · 10 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
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package enproxy
import (
"bufio"
"bytes"
"crypto/tls"
"io"
"net"
"net/http"
"sync"
"testing"
"time"
"github.com/getlantern/fdcount"
"github.com/getlantern/keyman"
"github.com/getlantern/testify/assert"
. "github.com/getlantern/waitforserver"
)
const (
TEXT = "Hello byte counting world"
HR = "----------------------------"
)
var (
pk *keyman.PrivateKey
cert *keyman.Certificate
proxyAddr = ""
httpAddr = ""
httpsAddr = ""
bytesReceived = int64(0)
bytesSent = int64(0)
destsReceived = make(map[string]bool)
destsSent = make(map[string]bool)
statMutex sync.Mutex
)
func TestPlainTextStreamingNoHostFn(t *testing.T) {
doTestPlainText(false, false, t)
}
func TestPlainTextBufferedNoHostFn(t *testing.T) {
doTestPlainText(true, false, t)
}
func TestPlainTextStreamingHostFn(t *testing.T) {
doTestPlainText(false, true, t)
}
func TestPlainTextBufferedHostFn(t *testing.T) {
doTestPlainText(true, true, t)
}
func TestTLSStreaming(t *testing.T) {
doTestTLS(false, t)
}
func TestTLSBuffered(t *testing.T) {
doTestTLS(true, t)
}
func TestBadStreaming(t *testing.T) {
doTestBad(false, t)
}
func TestBadBuffered(t *testing.T) {
doTestBad(true, t)
}
func TestIdle(t *testing.T) {
idleTimeout := 100 * time.Millisecond
_, counter, err := fdcount.Matching("TCP")
if err != nil {
t.Fatalf("Unable to get fdcount: %v", err)
}
_, err = Dial(httpAddr, &Config{
DialProxy: func(addr string) (net.Conn, error) {
return net.Dial("tcp", proxyAddr)
},
NewRequest: newRequest,
IdleTimeout: idleTimeout,
})
if assert.NoError(t, err, "Dialing should have succeeded") {
time.Sleep(idleTimeout * 2)
assert.NoError(t, counter.AssertDelta(2), "All file descriptors except the connection from proxy to destination site should have been closed")
}
}
// This test stimulates a connection leak as seen in
// https://github.com/getlantern/lantern/issues/2174.
func TestHTTPRedirect(t *testing.T) {
startProxy(t, false)
client := &http.Client{
Transport: &http.Transport{
Dial: func(network, addr string) (net.Conn, error) {
return Dial(addr, &Config{
DialProxy: func(addr string) (net.Conn, error) {
return net.Dial("tcp", proxyAddr)
},
NewRequest: newRequest,
})
},
DisableKeepAlives: true,
},
}
_, counter, err := fdcount.Matching("TCP")
if err != nil {
t.Fatalf("Unable to get fdcount: %v", err)
}
resp, err := client.Head("http://www.facebook.com")
if assert.NoError(t, err, "Head request to facebook should have succeeded") {
if err := resp.Body.Close(); err != nil {
log.Debugf("Unable to close response body: %v", err)
}
}
assert.NoError(t, counter.AssertDelta(2), "All file descriptors except the connection from proxy to destination site should have been closed")
}
func doTestPlainText(buffered bool, useHostFn bool, t *testing.T) {
var counter *fdcount.Counter
var err error
startServers(t, useHostFn)
err = fdcount.WaitUntilNoneMatch("CLOSE_WAIT", 5*time.Second)
if err != nil {
t.Fatalf("Unable to wait until no more connections are in CLOSE_WAIT: %v", err)
}
_, counter, err = fdcount.Matching("TCP")
if err != nil {
t.Fatalf("Unable to get fdcount: %v", err)
}
var reportedHost string
var reportedHostMutex sync.Mutex
onResponse := func(resp *http.Response) {
reportedHostMutex.Lock()
reportedHost = resp.Header.Get(X_ENPROXY_PROXY_HOST)
reportedHostMutex.Unlock()
}
conn, err := prepareConn(httpAddr, buffered, false, t, onResponse)
if err != nil {
t.Fatalf("Unable to prepareConn: %s", err)
}
defer func() {
err := conn.Close()
assert.Nil(t, err, "Closing conn should succeed")
if !assert.NoError(t, counter.AssertDelta(2), "All file descriptors except the connection from proxy to destination site should have been closed") {
DumpConnTrace()
}
}()
doRequests(conn, t)
assert.Equal(t, 208, bytesReceived, "Wrong number of bytes received")
assert.Equal(t, 284, bytesSent, "Wrong number of bytes sent")
assert.True(t, destsSent[httpAddr], "http address wasn't recorded as sent destination")
assert.True(t, destsReceived[httpAddr], "http address wasn't recorded as received destination")
reportedHostMutex.Lock()
rh := reportedHost
reportedHostMutex.Unlock()
assert.Equal(t, "localhost", rh, "Didn't get correct reported host")
}
func doTestTLS(buffered bool, t *testing.T) {
startServers(t, false)
_, counter, err := fdcount.Matching("TCP")
if err != nil {
t.Fatalf("Unable to get fdcount: %v", err)
}
conn, err := prepareConn(httpsAddr, buffered, false, t, nil)
if err != nil {
t.Fatalf("Unable to prepareConn: %s", err)
}
tlsConn := tls.Client(conn, &tls.Config{
ServerName: "localhost",
RootCAs: cert.PoolContainingCert(),
})
defer func() {
err := conn.Close()
assert.Nil(t, err, "Closing conn should succeed")
if !assert.NoError(t, counter.AssertDelta(2), "All file descriptors except the connection from proxy to destination site should have been closed") {
DumpConnTrace()
}
}()
err = tlsConn.Handshake()
if err != nil {
t.Fatalf("Unable to handshake: %s", err)
}
doRequests(tlsConn, t)
assert.True(t, destsSent[httpsAddr], "https address wasn't recorded as sent destination")
assert.True(t, destsReceived[httpsAddr], "https address wasn't recorded as received destination")
}
func doTestBad(buffered bool, t *testing.T) {
startServers(t, false)
conn, err := prepareConn(httpAddr, buffered, true, t, nil)
if err == nil {
defer func() {
if err := conn.Close(); err != nil {
log.Debugf("Unable to close connection: %v", err)
}
}()
t.Error("Bad conn should have returned error on Connect()")
}
}
func prepareConn(addr string, buffered bool, fail bool, t *testing.T, onResponse func(resp *http.Response)) (conn net.Conn, err error) {
return Dial(addr,
&Config{
DialProxy: func(addr string) (net.Conn, error) {
proto := "tcp"
if fail {
proto = "fakebad"
}
return net.Dial(proto, proxyAddr)
},
NewRequest: newRequest,
BufferRequests: buffered,
OnFirstResponse: onResponse,
})
}
func newRequest(host, path, method string, body io.Reader) (req *http.Request, err error) {
return http.NewRequest(method, "http://"+proxyAddr+"/"+path+"/", body)
}
func doRequests(conn net.Conn, t *testing.T) {
// Single request/response pair
req := makeRequest(conn, t)
readResponse(conn, req, t)
// Consecutive request/response pairs
req = makeRequest(conn, t)
readResponse(conn, req, t)
}
func makeRequest(conn net.Conn, t *testing.T) *http.Request {
req, err := http.NewRequest("GET", "http://www.google.com/humans.txt", nil)
req.Header.Add("Testcdn", "Of course!")
if err != nil {
t.Fatalf("Unable to create request: %s", err)
}
go func() {
err = req.Write(conn)
if err != nil {
t.Fatalf("Unable to write request: %s", err)
}
}()
return req
}
func readResponse(conn net.Conn, req *http.Request, t *testing.T) {
buffIn := bufio.NewReader(conn)
resp, err := http.ReadResponse(buffIn, req)
if err != nil {
t.Fatalf("Unable to read response: %s", err)
}
buff := bytes.NewBuffer(nil)
_, err = io.Copy(buff, resp.Body)
if err != nil {
t.Fatalf("Unable to read response body: %s", err)
}
text := string(buff.Bytes())
assert.Contains(t, text, TEXT, "Wrong text returned from server")
}
func startServers(t *testing.T, useHostFn bool) {
startHttpServer(t)
startHttpsServer(t)
startProxy(t, useHostFn)
}
func startProxy(t *testing.T, useHostFn bool) {
if proxyAddr != "" {
statMutex.Lock()
bytesReceived = 0
bytesSent = 0
destsReceived = make(map[string]bool)
destsReceived = make(map[string]bool)
statMutex.Unlock()
return
}
l, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("Proxy unable to listen: %v", err)
}
proxyAddr = l.Addr().String()
var host string
var hostFn func(*http.Request) string
if useHostFn {
hostFn = func(req *http.Request) string {
if _, found := req.Header["Testcdn"]; found {
return "localhost"
} else {
return ""
}
}
} else {
host = "localhost"
}
go func() {
proxy := &Proxy{
OnBytesReceived: func(clientIp string, destAddr string, req *http.Request, bytes int64) {
statMutex.Lock()
bytesReceived += bytes
destsReceived[destAddr] = true
statMutex.Unlock()
},
OnBytesSent: func(clientIp string, destAddr string, req *http.Request, bytes int64) {
statMutex.Lock()
bytesSent += bytes
destsSent[destAddr] = true
statMutex.Unlock()
},
Host: host,
HostFn: hostFn,
}
err := proxy.Serve(l)
if err != nil {
t.Fatalf("Proxy unable to serve: %s", err)
}
}()
if err := WaitForServer("tcp", proxyAddr, 1*time.Second); err != nil {
t.Fatal(err)
}
}
func startHttpServer(t *testing.T) {
if httpAddr != "" {
return
}
l, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("HTTP unable to listen: %v", err)
}
httpAddr = l.Addr().String()
doStartServer(t, l)
}
func startHttpsServer(t *testing.T) {
if httpsAddr != "" {
return
}
var err error
pk, err = keyman.GeneratePK(2048)
if err != nil {
t.Fatalf("Unable to generate key: %s", err)
}
// Generate self-signed certificate
cert, err = pk.TLSCertificateFor(time.Now().Add(1*time.Hour), true, nil, "tlsdialer", "localhost")
if err != nil {
t.Fatalf("Unable to generate cert: %s", err)
}
keypair, err := tls.X509KeyPair(cert.PEMEncoded(), pk.PEMEncoded())
if err != nil {
t.Fatalf("Unable to generate x509 key pair: %s", err)
}
l, err := tls.Listen("tcp", "localhost:0", &tls.Config{
Certificates: []tls.Certificate{keypair},
})
if err != nil {
t.Fatalf("HTTP unable to listen: %v", err)
}
httpsAddr = l.Addr().String()
doStartServer(t, l)
}
func doStartServer(t *testing.T, l net.Listener) {
go func() {
httpServer := &http.Server{
Handler: http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
if _, err := resp.Write([]byte(TEXT)); err != nil {
log.Debugf("Unable to write response: %v", err)
}
}),
}
err := httpServer.Serve(l)
if err != nil {
t.Fatalf("Unable to start http server: %s", err)
}
}()
if err := WaitForServer("tcp", l.Addr().String(), 1*time.Second); err != nil {
t.Fatal(err)
}
}