-
Notifications
You must be signed in to change notification settings - Fork 18
/
netctl.go
591 lines (455 loc) · 11.6 KB
/
netctl.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
package proton
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"net/http"
"sync"
"time"
)
// Listener wraps a net.Listener.
// It can be configured to spawn connections that drop all reads or writes.
type Listener struct {
net.Listener
canRead bool
rlock sync.RWMutex
canWrite bool
wlock sync.RWMutex
conns []net.Conn
connLock sync.RWMutex
done chan struct{}
doneOnce sync.Once
newConn func(net.Conn, *Listener) net.Conn
}
// NewListener returns a new DropListener.
func NewListener(l net.Listener, newConn func(net.Conn, *Listener) net.Conn) *Listener {
return &Listener{
Listener: l,
canRead: true,
canWrite: true,
done: make(chan struct{}),
newConn: newConn,
}
}
func (l *Listener) Accept() (net.Conn, error) {
conn, err := l.Listener.Accept()
if err != nil {
return nil, err
}
l.connLock.Lock()
defer l.connLock.Unlock()
dropConn := l.newConn(conn, l)
l.conns = append(l.conns, dropConn)
return dropConn, nil
}
// SetCanRead sets whether the connections spawned by this listener can read.
func (l *Listener) SetCanRead(canRead bool) {
l.rlock.Lock()
defer l.rlock.Unlock()
l.canRead = canRead
}
// SetCanWrite sets whether the connections spawned by this listener can write.
func (l *Listener) SetCanWrite(canWrite bool) {
l.wlock.Lock()
defer l.wlock.Unlock()
l.canWrite = canWrite
}
// Close closes the listener.
func (l *Listener) Close() error {
defer l.doneOnce.Do(func() {
close(l.done)
})
return l.Listener.Close()
}
// Done returns a channel that is closed when the listener is closed.
func (l *Listener) Done() <-chan struct{} {
return l.done
}
// DropAll closes all connections spawned by this listener.
func (l *Listener) DropAll() {
l.connLock.RLock()
defer l.connLock.RUnlock()
for _, conn := range l.conns {
_ = conn.Close()
}
}
type hangConn struct {
net.Conn
l *Listener
}
func NewHangConn(c net.Conn, l *Listener) net.Conn {
return &hangConn{
Conn: c,
l: l,
}
}
func (c *hangConn) Read(b []byte) (int, error) {
c.l.rlock.RLock()
defer c.l.rlock.RUnlock()
if !c.l.canRead {
c.l.rlock.RUnlock()
<-c.l.Done()
c.l.rlock.RLock()
}
return c.Conn.Read(b)
}
func (c *hangConn) Write(b []byte) (int, error) {
c.l.wlock.RLock()
defer c.l.wlock.RUnlock()
if !c.l.canWrite {
c.l.wlock.RUnlock()
<-c.l.Done()
c.l.wlock.RLock()
}
return c.Conn.Write(b)
}
type dropConn struct {
net.Conn
l *Listener
}
func NewDropConn(c net.Conn, l *Listener) net.Conn {
return &dropConn{
Conn: c,
l: l,
}
}
func (c *dropConn) Read(b []byte) (int, error) {
c.l.rlock.RLock()
defer c.l.rlock.RUnlock()
if c.l.canRead {
return c.Conn.Read(b)
}
// Read half the length of the buffer.
n, err := c.Conn.Read(b[:len(b)/2])
if err != nil {
return n, fmt.Errorf("read: %w", err)
}
if err := c.Close(); err != nil {
return n, fmt.Errorf("close: %w", err)
}
return n, errors.New("read: connection closed")
}
func (c *dropConn) Write(b []byte) (int, error) {
c.l.wlock.RLock()
defer c.l.wlock.RUnlock()
if c.l.canWrite {
return c.Conn.Write(b)
}
// Write half the length of the buffer.
n, err := c.Conn.Write(b[:len(b)/2])
if err != nil {
return n, fmt.Errorf("write: %w", err)
}
if err := c.Close(); err != nil {
return n, fmt.Errorf("close: %w", err)
}
return n, errors.New("write: connection closed")
}
func (c *dropConn) Close() error {
if tcpConn, ok := c.Conn.(*net.TCPConn); ok {
if err := tcpConn.SetLinger(0); err != nil {
return err
}
}
return c.Conn.Close()
}
// InsecureTransport returns an http.Transport with InsecureSkipVerify set to true.
func InsecureTransport() *http.Transport {
return &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
// ctl can be used to control whether a dialer can dial, and whether the resulting
// connection can read or write.
type NetCtl struct {
canDial bool
dialLimit uint64
dialCount uint64
onDial []func(net.Conn)
dlock sync.RWMutex
canRead bool
readLimit uint64
readCount uint64
readSpeed int
onRead []func([]byte)
rlock sync.RWMutex
canWrite bool
writeLimit uint64
writeCount uint64
writeSpeed int
onWrite []func([]byte)
wlock sync.RWMutex
conns []net.Conn
}
// NewNetCtl returns a new ctl with all fields set to true.
func NewNetCtl() *NetCtl {
return &NetCtl{
canDial: true,
canRead: true,
canWrite: true,
}
}
// SetCanDial sets whether the dialer can dial.
func (c *NetCtl) SetCanDial(canDial bool) {
c.dlock.Lock()
defer c.dlock.Unlock()
c.canDial = canDial
}
// SetDialLimit sets the maximum number of times dialers using this controller can dial.
func (c *NetCtl) SetDialLimit(limit uint64) {
c.dlock.Lock()
defer c.dlock.Unlock()
c.dialLimit = limit
}
// SetCanRead sets whether the connection can read.
func (c *NetCtl) SetCanRead(canRead bool) {
c.dlock.Lock()
defer c.dlock.Unlock()
for _, conn := range c.conns {
conn.Close()
}
c.rlock.Lock()
defer c.rlock.Unlock()
c.canRead = canRead
}
// SetReadLimit sets the maximum number of bytes that can be read.
func (c *NetCtl) SetReadLimit(limit uint64) {
c.dlock.Lock()
defer c.dlock.Unlock()
for _, conn := range c.conns {
conn.Close()
}
c.rlock.Lock()
defer c.rlock.Unlock()
c.readLimit = limit
c.readCount = 0
}
// SetReadSpeed sets the maximum number of bytes that can be read per second.
func (c *NetCtl) SetReadSpeed(speed int) {
c.dlock.Lock()
defer c.dlock.Unlock()
for _, conn := range c.conns {
conn.Close()
}
c.rlock.Lock()
defer c.rlock.Unlock()
c.readSpeed = speed
}
// SetCanWrite sets whether the connection can write.
func (c *NetCtl) SetCanWrite(canWrite bool) {
c.dlock.Lock()
defer c.dlock.Unlock()
for _, conn := range c.conns {
conn.Close()
}
c.wlock.Lock()
defer c.wlock.Unlock()
c.canWrite = canWrite
}
// SetWriteLimit sets the maximum number of bytes that can be written.
func (c *NetCtl) SetWriteLimit(limit uint64) {
c.dlock.Lock()
defer c.dlock.Unlock()
for _, conn := range c.conns {
conn.Close()
}
c.wlock.Lock()
defer c.wlock.Unlock()
c.writeLimit = limit
c.writeCount = 0
}
// SetWriteSpeed sets the maximum number of bytes that can be written per second.
func (c *NetCtl) SetWriteSpeed(speed int) {
c.dlock.Lock()
defer c.dlock.Unlock()
for _, conn := range c.conns {
conn.Close()
}
c.wlock.Lock()
defer c.wlock.Unlock()
c.writeSpeed = speed
}
// OnDial adds a callback that is called with the created connection when a dial is successful.
func (c *NetCtl) OnDial(f func(net.Conn)) {
c.dlock.Lock()
defer c.dlock.Unlock()
c.onDial = append(c.onDial, f)
}
// OnRead adds a callback that is called with the read bytes when a read is successful.
func (c *NetCtl) OnRead(fn func([]byte)) {
c.rlock.Lock()
defer c.rlock.Unlock()
c.onRead = append(c.onRead, fn)
}
// OnWrite adds a callback that is called with the written bytes when a write is successful.
func (c *NetCtl) OnWrite(fn func([]byte)) {
c.wlock.Lock()
defer c.wlock.Unlock()
c.onWrite = append(c.onWrite, fn)
}
// Disable is equivalent to disallowing dial, read and write.
func (c *NetCtl) Disable() {
c.SetCanDial(false)
c.SetCanRead(false)
c.SetCanWrite(false)
}
// Enable is equivalent to allowing dial, read and write.
func (c *NetCtl) Enable() {
c.SetCanDial(true)
c.SetCanRead(true)
c.SetCanWrite(true)
}
// NewDialer returns a new dialer controlled by the ctl.
func (c *NetCtl) NewRoundTripper(tlsConfig *tls.Config) http.RoundTripper {
return &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return c.dial(ctx, &net.Dialer{}, network, addr)
},
DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return c.dial(ctx, &tls.Dialer{Config: tlsConfig}, network, addr)
},
TLSClientConfig: tlsConfig,
ResponseHeaderTimeout: time.Second,
ExpectContinueTimeout: time.Second,
}
}
// ctxDialer implements DialContext.
type ctxDialer interface {
DialContext(ctx context.Context, network, addr string) (net.Conn, error)
}
// dial dials using d, but only if the controller allows it.
func (c *NetCtl) dial(ctx context.Context, dialer ctxDialer, network, addr string) (net.Conn, error) {
c.dlock.Lock()
defer c.dlock.Unlock()
if !c.canDial {
return nil, errors.New("dial failed (not allowed)")
}
if c.dialLimit > 0 && c.dialCount >= c.dialLimit {
return nil, errors.New("dial failed (limit reached)")
}
conn, err := dialer.DialContext(ctx, network, addr)
if err != nil {
return nil, err
}
c.dialCount++
for _, fn := range c.onDial {
fn(conn)
}
c.conns = append(c.conns, conn)
return newConn(conn, c), nil
}
// read reads from r, but only if the controller allows it.
func (c *NetCtl) read(r io.Reader, b []byte) (int, error) {
c.rlock.Lock()
defer c.rlock.Unlock()
if !c.canRead {
return 0, errors.New("read failed (not allowed)")
}
if c.readLimit > 0 && c.readCount >= c.readLimit {
return 0, errors.New("read failed (limit reached)")
}
var rem uint64
if c.readLimit > 0 && c.readLimit-c.readCount < uint64(len(b)) {
rem = c.readLimit - c.readCount
} else {
rem = uint64(len(b))
}
c.rlock.Unlock()
n, err := newSlowReader(r, c.readSpeed).Read(b[:rem])
c.rlock.Lock()
c.readCount += uint64(n)
for _, fn := range c.onRead {
fn(b[:n])
}
return n, err
}
// write writes to w, but only if the controller allows it.
func (c *NetCtl) write(w io.Writer, b []byte) (int, error) {
c.wlock.Lock()
defer c.wlock.Unlock()
if !c.canWrite {
return 0, errors.New("write failed (not allowed)")
}
if c.writeLimit > 0 && c.writeCount >= c.writeLimit {
return 0, errors.New("write failed (limit exceeded)")
}
var rem uint64
if c.writeLimit > 0 && c.writeLimit-c.writeCount < uint64(len(b)) {
rem = c.writeLimit - c.writeCount
} else {
rem = uint64(len(b))
}
c.wlock.Unlock()
n, err := newSlowWriter(w, c.writeSpeed).Write(b[:rem])
c.wlock.Lock()
c.writeCount += uint64(n)
for _, fn := range c.onWrite {
fn(b[:n])
}
if uint64(n) < rem {
return n, fmt.Errorf("write incomplete (limit reached)")
}
return n, err
}
// conn is a wrapper around net.conn that can be used to control whether a connection can read or write.
type conn struct {
net.Conn
ctl *NetCtl
}
func newConn(c net.Conn, ctl *NetCtl) *conn {
return &conn{
Conn: c,
ctl: ctl,
}
}
// Read reads from the wrapped connection, but only if the controller allows it.
func (c *conn) Read(b []byte) (int, error) {
return c.ctl.read(c.Conn, b)
}
// Write writes to the wrapped connection, but only if the controller allows it.
func (c *conn) Write(b []byte) (int, error) {
return c.ctl.write(c.Conn, b)
}
// slowReader is an io.Reader that reads at a fixed rate.
type slowReader struct {
r io.Reader
// bytesPerSec is the number of bytes to read per second.
bytesPerSec int
}
func newSlowReader(r io.Reader, bytesPerSec int) *slowReader {
return &slowReader{
r: r,
bytesPerSec: bytesPerSec,
}
}
func (r *slowReader) Read(b []byte) (int, error) {
start := time.Now()
n, err := r.r.Read(b)
if r.bytesPerSec > 0 {
time.Sleep(time.Until(start.Add(time.Duration(n*r.bytesPerSec) * time.Second)))
}
return n, err
}
// slowWriter is an io.Writer that writes at a fixed rate.
type slowWriter struct {
w io.Writer
// bytesPerSec is the number of bytes to write per second.
bytesPerSec int
}
func newSlowWriter(w io.Writer, bytesPerSec int) *slowWriter {
return &slowWriter{
w: w,
bytesPerSec: bytesPerSec,
}
}
func (w *slowWriter) Write(b []byte) (int, error) {
start := time.Now()
n, err := w.w.Write(b)
if w.bytesPerSec > 0 {
time.Sleep(time.Until(start.Add(time.Duration(n*w.bytesPerSec) * time.Second)))
}
return n, err
}