forked from zmap/zgrab2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn_timeout_test.go
422 lines (370 loc) · 11.2 KB
/
conn_timeout_test.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
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
420
421
422
package zgrab2
import (
"bytes"
"context"
"fmt"
"io"
"net"
"strings"
"testing"
"time"
"github.com/sirupsen/logrus"
)
// Config for a single timeout test
type connTimeoutTestConfig struct {
// Name for the test for logging purposes
name string
// Optional explicit endpoint to connect to (if absent, use 127.0.0.1)
endpoint string
// TCP port number to communicate on
port int
// Function used to dial new connections
dialer func() (*TimeoutConnection, error)
// Client timeout values
timeout time.Duration
connectTimeout time.Duration
readTimeout time.Duration
writeTimeout time.Duration
// Time for server to wait after listening before accepting a connection
acceptDelay time.Duration
// Time for server to wait after accepting before writing payload
writeDelay time.Duration
// Time for server to wait before reading payload
readDelay time.Duration
// Payload for server to send client after connecting
serverToClientPayload []byte
// Payload for client to send server after reading the previous payload
clientToServerPayload []byte
// Step when the client is expected to fail
failStep testStep
// If non-empty, the error string returned by the client should contain this
failError string
}
// Standardized time units, separated by factors of 10.
const (
short = 100 * time.Millisecond
medium = 1000 * time.Millisecond
long = 10000 * time.Millisecond
)
// enum type for the various locations where the test can fail
type testStep string
const (
testStepConnect = testStep("connect")
testStepRead = testStep("read")
testStepWrite = testStep("write")
testStepDone = testStep("done")
)
// Encapsulates a source for an error (client/server/???), the step where it occurred, and an
// optional cause.
type timeoutTestError struct {
source string
step testStep
cause error
}
func (err *timeoutTestError) Error() string {
return fmt.Sprintf("%s error at %s: %v", err.source, err.step, err.cause)
}
func serverError(step testStep, err error) *timeoutTestError {
return &timeoutTestError{
source: "server",
step: step,
cause: err,
}
}
func clientError(step testStep, err error) *timeoutTestError {
return &timeoutTestError{
source: "client",
step: step,
cause: err,
}
}
// Helper to ensure all data is written to a socket
func _write(writer io.Writer, data []byte) error {
n, err := writer.Write(data)
if err == nil && n != len(data) {
err = io.ErrShortWrite
}
return err
}
// Run the configured server. As soon as it returns, it is listening.
// Returns a channel that receives a timeoutTestError on error, or is closed on successful completion.
func (cfg *connTimeoutTestConfig) runServer(t *testing.T) (chan *timeoutTestError) {
errorChan := make(chan *timeoutTestError)
if cfg.endpoint != "" {
// Only listen on localhost
return errorChan
}
listener, err := net.Listen("tcp", cfg.getEndpoint())
if err != nil {
logrus.Fatalf("Error listening: %v", err)
}
go func() {
defer listener.Close()
defer close(errorChan)
time.Sleep(cfg.acceptDelay)
sock, err := listener.Accept()
if err != nil {
errorChan <- serverError(testStepConnect, err)
return
}
defer sock.Close()
time.Sleep(cfg.writeDelay)
if err := _write(sock, cfg.serverToClientPayload); err != nil {
errorChan <- serverError(testStepWrite, err)
return
}
time.Sleep(cfg.readDelay)
buf := make([]byte, len(cfg.clientToServerPayload))
n, err := io.ReadFull(sock, buf)
if err != nil && err != io.EOF {
errorChan <- serverError(testStepRead, err)
return
}
if err == io.EOF && n < len(buf) {
errorChan <- serverError(testStepRead, err)
return
}
if !bytes.Equal(buf, cfg.clientToServerPayload) {
t.Errorf("%s: clientToServerPayload mismatch", cfg.name)
}
return
}()
return errorChan
}
// Get the configured endpoint
func (cfg *connTimeoutTestConfig) getEndpoint() string {
if cfg.endpoint != "" {
return cfg.endpoint
}
return fmt.Sprintf("127.0.0.1:%d", cfg.port)
}
// Dial a connection to the configured endpoint using a Dialer
func (cfg *connTimeoutTestConfig) dialerDial() (*TimeoutConnection, error) {
dialer := NewDialer(&Dialer{
Timeout: cfg.timeout,
ConnectTimeout: cfg.connectTimeout,
ReadTimeout: cfg.readTimeout,
WriteTimeout: cfg.writeTimeout,
})
ret, err := dialer.Dial("tcp", cfg.getEndpoint())
if err != nil {
return nil, err
}
return ret.(*TimeoutConnection), err
}
// Dial a connection to the configured endpoint using a DialTimeoutConnectionEx
func (cfg *connTimeoutTestConfig) directDial() (*TimeoutConnection, error) {
ret, err := DialTimeoutConnectionEx("tcp", cfg.getEndpoint(), cfg.connectTimeout, cfg.timeout, cfg.readTimeout, cfg.writeTimeout, 0)
if err != nil {
return nil, err
}
return ret.(*TimeoutConnection), err
}
// Dial a connection to the configured endpoint using Dialer.DialContext
func (cfg *connTimeoutTestConfig) contextDial() (*TimeoutConnection, error) {
dialer := NewDialer(&Dialer{
Timeout: cfg.timeout,
ConnectTimeout: cfg.connectTimeout,
ReadTimeout: cfg.readTimeout,
WriteTimeout: cfg.writeTimeout,
})
ret, err := dialer.DialContext(context.Background(), "tcp", cfg.getEndpoint())
if err != nil {
return nil, err
}
return ret.(*TimeoutConnection), err
}
// Run the client: connect to the server, read the payload, write the payload, disconnect.
func (cfg *connTimeoutTestConfig) runClient(t *testing.T) (testStep, error) {
conn, err := cfg.dialer()
if err != nil {
return testStepConnect, err
}
defer conn.Close()
buf := make([]byte, len(cfg.serverToClientPayload))
_, err = io.ReadFull(conn, buf)
if err != nil {
return testStepRead, err
}
if !bytes.Equal(cfg.serverToClientPayload, buf) {
t.Errorf("%s: serverToClientPayload payload mismatch", cfg.name)
}
if err := _write(conn, cfg.clientToServerPayload); err != nil {
return testStepWrite, err
}
return testStepDone, nil
}
// Run the configured test -- start a server and a client to connect to it.
func (cfg *connTimeoutTestConfig) run(t *testing.T) {
done := make(chan *timeoutTestError)
serverError := cfg.runServer(t)
go func() {
defer func() {
if err := recover(); err != nil {
close(done)
panic(err)
}
}()
step, err := cfg.runClient(t)
done <- clientError(step, err)
}()
go func() {
time.Sleep(long + medium + short)
done <- &timeoutTestError{source: "timeout"}
}()
var ret *timeoutTestError
select {
case err := <-serverError:
t.Fatalf("%s: Server error: %v", cfg.name, err)
case ret = <-done:
if ret == nil {
t.Fatalf("Channel unexpectedly closed")
}
}
if ret.source != "client" {
t.Fatalf("%s: Unexpected error from %s: %v", cfg.name, ret.source, ret.cause)
}
if ret.step != cfg.failStep {
t.Errorf("%s: Failed at step %s, but expected to fail at step %s (error=%v)", cfg.name, ret.step, cfg.failStep, ret.cause)
return
}
if cfg.failError != "" {
errString := "none"
if ret.cause != nil {
errString = ret.cause.Error()
}
if !strings.Contains(errString, cfg.failError) {
t.Errorf("%s: Expected an error (%s) at step %s, got %s", cfg.name, cfg.failError, cfg.failStep, errString)
return
}
} else if ret.cause != nil {
t.Errorf("%s: expected no error at step %s, but got %v", cfg.name, cfg.failStep, ret.cause)
}
}
var connTestConfigs = []connTimeoutTestConfig{
// Long timeouts, short delays -- should succeed
{
name: "happy",
port: 0x5613,
timeout: long,
connectTimeout: medium,
readTimeout: medium,
writeTimeout: medium,
acceptDelay: short,
writeDelay: short,
readDelay: short,
serverToClientPayload: []byte("abc"),
clientToServerPayload: []byte("defghi"),
failStep: testStepDone,
},
// long session timeout, short connectTimeout. Use a non-local, nonexistent endpoint (localhost
// would return "connection refused" immediately)
{
name: "connect_timeout",
endpoint: "10.0.254.254:41591",
timeout: long,
connectTimeout: short,
readTimeout: medium,
writeTimeout: medium,
acceptDelay: short,
writeDelay: short,
readDelay: short,
serverToClientPayload: []byte("abc"),
clientToServerPayload: []byte("defghi"),
failStep: testStepConnect,
failError: "i/o timeout",
},
// short session timeout, medium connect timeout, with connect to nonexistent endpoint.
{
name: "session_connect_timeout",
endpoint: "10.0.254.254:41591",
timeout: short,
connectTimeout: medium,
readTimeout: medium,
writeTimeout: medium,
acceptDelay: short,
writeDelay: short,
readDelay: short,
serverToClientPayload: []byte("abc"),
clientToServerPayload: []byte("defghi"),
failStep: testStepConnect,
failError: "i/o timeout",
},
// Get an IO timeout on the read.
// sessionTimeout > acceptDelay + writeDelay > writeDelay > readTimeout
{
name: "read_timeout",
port: 0x5614,
timeout: long,
connectTimeout: short,
readTimeout: short,
writeTimeout: short,
acceptDelay: short,
writeDelay: medium,
readDelay: short,
serverToClientPayload: []byte("abc"),
clientToServerPayload: []byte("defghi"),
failStep: testStepRead,
failError: "i/o timeout",
},
// Get a context timeout on a read.
// readTimeout > writeDelay > timeout > acceptDelay
{
name: "session_read_timeout",
port: 0x5615,
timeout: short,
connectTimeout: long,
readTimeout: long,
writeTimeout: long,
acceptDelay: 0,
writeDelay: medium * 2,
readDelay: 0,
serverToClientPayload: []byte("abc"),
clientToServerPayload: []byte("defghi"),
failStep: testStepWrite,
failError: "context deadline exceeded",
},
// Use a session timeout that is longer than any individual action's timeout.
// acceptDelay+writeDelay+readDelay > timeout > acceptDelay >= writeDelay >= readDelay
{
name: "session_timeout",
port: 0x5616,
timeout: medium,
connectTimeout: long,
readTimeout: long,
writeTimeout: long,
acceptDelay: time.Nanosecond * time.Duration(medium.Nanoseconds()/2+short.Nanoseconds()),
writeDelay: time.Nanosecond * time.Duration(medium.Nanoseconds()/2+short.Nanoseconds()),
readDelay: time.Nanosecond * time.Duration(medium.Nanoseconds()/2+short.Nanoseconds()),
serverToClientPayload: []byte("abc"),
clientToServerPayload: []byte("defghi"),
failStep: testStepWrite,
failError: "context deadline exceeded",
},
// TODO: How to test write timeout?
}
// TestTimeoutConnectionTimeouts tests that the TimeoutConnection behaves as expected with respect
// to timeouts.
func TestTimeoutConnectionTimeouts(t *testing.T) {
temp := make([]connTimeoutTestConfig, 0, len(connTestConfigs)*3)
// Make three copies of connTestConfigs, one with each dial method.
for _, cfg := range connTestConfigs {
direct := cfg
dialer := cfg
ctxDialer := cfg
dialer.name = dialer.name + "_dialer"
dialer.port = dialer.port + 100
dialer.dialer = dialer.dialerDial
direct.name = direct.name + "_direct"
direct.port = direct.port + 200
direct.dialer = direct.directDial
ctxDialer.name = ctxDialer.name + "_context"
ctxDialer.port = ctxDialer.port + 300
ctxDialer.dialer = ctxDialer.contextDial
temp = append(temp, direct, dialer, ctxDialer)
}
for _, cfg := range temp {
t.Logf("Running %s", cfg.name)
cfg.run(t)
}
}