Debian Codegraph @

netctl.go

raw ◀ ▶
1 Debian patch touch this file
1 package proton
2
3 import (
4 "context"
5 "crypto/tls"
6 "errors"
7 "fmt"
8 "io"
9 "net"
10 "net/http"
11 "sync"
12 "time"
13 )
14
15 // Listener wraps a net.Listener.
16 // It can be configured to spawn connections that drop all reads or writes.
17 type Listener struct {
18 net.Listener
19
20 canRead bool
21 rlock sync.RWMutex
22
23 canWrite bool
24 wlock sync.RWMutex
25
26 conns []net.Conn
27 connLock sync.RWMutex
28
29 done chan struct{}
30 doneOnce sync.Once
31
32 newConn func(net.Conn, *Listener) net.Conn
33 }
34
35 // NewListener returns a new DropListener.
36 func NewListener(l net.Listener, newConn func(net.Conn, *Listener) net.Conn) *Listener {
37 return &Listener{
38 Listener: l,
39 canRead: true,
40 canWrite: true,
41 done: make(chan struct{}),
42 newConn: newConn,
43 }
44 }
45
46 func (l *Listener) Accept() (net.Conn, error) {
47 conn, err := l.Listener.Accept()
48 if err != nil {
49 return nil, err
50 }
51
52 l.connLock.Lock()
53 defer l.connLock.Unlock()
54
55 dropConn := l.newConn(conn, l)
56
57 l.conns = append(l.conns, dropConn)
58
59 return dropConn, nil
60 }
61
62 // SetCanRead sets whether the connections spawned by this listener can read.
63 func (l *Listener) SetCanRead(canRead bool) {
64 l.rlock.Lock()
65 defer l.rlock.Unlock()
66
67 l.canRead = canRead
68 }
69
70 // SetCanWrite sets whether the connections spawned by this listener can write.
71 func (l *Listener) SetCanWrite(canWrite bool) {
72 l.wlock.Lock()
73 defer l.wlock.Unlock()
74
75 l.canWrite = canWrite
76 }
77
78 // Close closes the listener.
79 func (l *Listener) Close() error {
80 defer l.doneOnce.Do(func() {
81 close(l.done)
82 })
83
84 return l.Listener.Close()
85 }
86
87 // Done returns a channel that is closed when the listener is closed.
88 func (l *Listener) Done() <-chan struct{} {
89 return l.done
90 }
91
92 // DropAll closes all connections spawned by this listener.
93 func (l *Listener) DropAll() {
94 l.connLock.RLock()
95 defer l.connLock.RUnlock()
96
97 for _, conn := range l.conns {
98 _ = conn.Close()
99 }
100 }
101
102 type hangConn struct {
103 net.Conn
104
105 l *Listener
106 }
107
108 func NewHangConn(c net.Conn, l *Listener) net.Conn {
109 return &hangConn{
110 Conn: c,
111 l: l,
112 }
113 }
114
115 func (c *hangConn) Read(b []byte) (int, error) {
116 c.l.rlock.RLock()
117 defer c.l.rlock.RUnlock()
118
119 if !c.l.canRead {
120 c.l.rlock.RUnlock()
121 <-c.l.Done()
122 c.l.rlock.RLock()
123 }
124
125 return c.Conn.Read(b)
126 }
127
128 func (c *hangConn) Write(b []byte) (int, error) {
129 c.l.wlock.RLock()
130 defer c.l.wlock.RUnlock()
131
132 if !c.l.canWrite {
133 c.l.wlock.RUnlock()
134 <-c.l.Done()
135 c.l.wlock.RLock()
136 }
137
138 return c.Conn.Write(b)
139 }
140
141 type dropConn struct {
142 net.Conn
143
144 l *Listener
145 }
146
147 func NewDropConn(c net.Conn, l *Listener) net.Conn {
148 return &dropConn{
149 Conn: c,
150 l: l,
151 }
152 }
153
154 func (c *dropConn) Read(b []byte) (int, error) {
155 c.l.rlock.RLock()
156 defer c.l.rlock.RUnlock()
157
158 if c.l.canRead {
159 return c.Conn.Read(b)
160 }
161
162 // Read half the length of the buffer.
163 n, err := c.Conn.Read(b[:len(b)/2])
164 if err != nil {
165 return n, fmt.Errorf("read: %w", err)
166 }
167
168 if err := c.Close(); err != nil {
169 return n, fmt.Errorf("close: %w", err)
170 }
171
172 return n, errors.New("read: connection closed")
173 }
174
175 func (c *dropConn) Write(b []byte) (int, error) {
176 c.l.wlock.RLock()
177 defer c.l.wlock.RUnlock()
178
179 if c.l.canWrite {
180 return c.Conn.Write(b)
181 }
182
183 // Write half the length of the buffer.
184 n, err := c.Conn.Write(b[:len(b)/2])
185 if err != nil {
186 return n, fmt.Errorf("write: %w", err)
187 }
188
189 if err := c.Close(); err != nil {
190 return n, fmt.Errorf("close: %w", err)
191 }
192
193 return n, errors.New("write: connection closed")
194 }
195
196 func (c *dropConn) Close() error {
197 if tcpConn, ok := c.Conn.(*net.TCPConn); ok {
198 if err := tcpConn.SetLinger(0); err != nil {
199 return err
200 }
201 }
202
203 return c.Conn.Close()
204 }
205
206 // InsecureTransport returns an http.Transport with InsecureSkipVerify set to true.
207 func InsecureTransport() *http.Transport {
208 return &http.Transport{
209 TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
210 }
211 }
212
213 // ctl can be used to control whether a dialer can dial, and whether the resulting
214 // connection can read or write.
215 type NetCtl struct {
216 canDial bool
217 dialLimit uint64
218 dialCount uint64
219 onDial []func(net.Conn)
220 dlock sync.RWMutex
221
222 canRead bool
223 readLimit uint64
224 readCount uint64
225 readSpeed int
226 onRead []func([]byte)
227 rlock sync.RWMutex
228
229 canWrite bool
230 writeLimit uint64
231 writeCount uint64
232 writeSpeed int
233 onWrite []func([]byte)
234 wlock sync.RWMutex
235
236 conns []net.Conn
237 }
238
239 // NewNetCtl returns a new ctl with all fields set to true.
240 func NewNetCtl() *NetCtl {
241 return &NetCtl{
242 canDial: true,
243 canRead: true,
244 canWrite: true,
245 }
246 }
247
248 // SetCanDial sets whether the dialer can dial.
249 func (c *NetCtl) SetCanDial(canDial bool) {
250 c.dlock.Lock()
251 defer c.dlock.Unlock()
252
253 c.canDial = canDial
254 }
255
256 // SetDialLimit sets the maximum number of times dialers using this controller can dial.
257 func (c *NetCtl) SetDialLimit(limit uint64) {
258 c.dlock.Lock()
259 defer c.dlock.Unlock()
260
261 c.dialLimit = limit
262 }
263
264 // SetCanRead sets whether the connection can read.
265 func (c *NetCtl) SetCanRead(canRead bool) {
266 c.dlock.Lock()
267 defer c.dlock.Unlock()
268
269 for _, conn := range c.conns {
270 conn.Close()
271 }
272
273 c.rlock.Lock()
274 defer c.rlock.Unlock()
275
276 c.canRead = canRead
277 }
278
279 // SetReadLimit sets the maximum number of bytes that can be read.
280 func (c *NetCtl) SetReadLimit(limit uint64) {
281 c.dlock.Lock()
282 defer c.dlock.Unlock()
283
284 for _, conn := range c.conns {
285 conn.Close()
286 }
287
288 c.rlock.Lock()
289 defer c.rlock.Unlock()
290
291 c.readLimit = limit
292 c.readCount = 0
293 }
294
295 // SetReadSpeed sets the maximum number of bytes that can be read per second.
296 func (c *NetCtl) SetReadSpeed(speed int) {
297 c.dlock.Lock()
298 defer c.dlock.Unlock()
299
300 for _, conn := range c.conns {
301 conn.Close()
302 }
303
304 c.rlock.Lock()
305 defer c.rlock.Unlock()
306
307 c.readSpeed = speed
308 }
309
310 // SetCanWrite sets whether the connection can write.
311 func (c *NetCtl) SetCanWrite(canWrite bool) {
312 c.dlock.Lock()
313 defer c.dlock.Unlock()
314
315 for _, conn := range c.conns {
316 conn.Close()
317 }
318
319 c.wlock.Lock()
320 defer c.wlock.Unlock()
321
322 c.canWrite = canWrite
323 }
324
325 // SetWriteLimit sets the maximum number of bytes that can be written.
326 func (c *NetCtl) SetWriteLimit(limit uint64) {
327 c.dlock.Lock()
328 defer c.dlock.Unlock()
329
330 for _, conn := range c.conns {
331 conn.Close()
332 }
333
334 c.wlock.Lock()
335 defer c.wlock.Unlock()
336
337 c.writeLimit = limit
338 c.writeCount = 0
339 }
340
341 // SetWriteSpeed sets the maximum number of bytes that can be written per second.
342 func (c *NetCtl) SetWriteSpeed(speed int) {
343 c.dlock.Lock()
344 defer c.dlock.Unlock()
345
346 for _, conn := range c.conns {
347 conn.Close()
348 }
349
350 c.wlock.Lock()
351 defer c.wlock.Unlock()
352
353 c.writeSpeed = speed
354 }
355
356 // OnDial adds a callback that is called with the created connection when a dial is successful.
357 func (c *NetCtl) OnDial(f func(net.Conn)) {
358 c.dlock.Lock()
359 defer c.dlock.Unlock()
360
361 c.onDial = append(c.onDial, f)
362 }
363
364 // OnRead adds a callback that is called with the read bytes when a read is successful.
365 func (c *NetCtl) OnRead(fn func([]byte)) {
366 c.rlock.Lock()
367 defer c.rlock.Unlock()
368
369 c.onRead = append(c.onRead, fn)
370 }
371
372 // OnWrite adds a callback that is called with the written bytes when a write is successful.
373 func (c *NetCtl) OnWrite(fn func([]byte)) {
374 c.wlock.Lock()
375 defer c.wlock.Unlock()
376
377 c.onWrite = append(c.onWrite, fn)
378 }
379
380 // Disable is equivalent to disallowing dial, read and write.
381 func (c *NetCtl) Disable() {
382 c.SetCanDial(false)
383 c.SetCanRead(false)
384 c.SetCanWrite(false)
385 }
386
387 // Enable is equivalent to allowing dial, read and write.
388 func (c *NetCtl) Enable() {
389 c.SetCanDial(true)
390 c.SetCanRead(true)
391 c.SetCanWrite(true)
392 }
393
394 // NewDialer returns a new dialer controlled by the ctl.
395 func (c *NetCtl) NewRoundTripper(tlsConfig *tls.Config) http.RoundTripper {
396 return &http.Transport{
397 DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
398 return c.dial(ctx, &net.Dialer{}, network, addr)
399 },
400 DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
401 return c.dial(ctx, &tls.Dialer{Config: tlsConfig}, network, addr)
402 },
403 TLSClientConfig: tlsConfig,
•404 ResponseHeaderTimeout: 10 * time.Second,
405 ExpectContinueTimeout: time.Second,
406 }
407 }
408
409 // ctxDialer implements DialContext.
410 type ctxDialer interface {
411 DialContext(ctx context.Context, network, addr string) (net.Conn, error)
412 }
413
414 // dial dials using d, but only if the controller allows it.
415 func (c *NetCtl) dial(ctx context.Context, dialer ctxDialer, network, addr string) (net.Conn, error) {
416 c.dlock.Lock()
417 defer c.dlock.Unlock()
418
419 if !c.canDial {
420 return nil, errors.New("dial failed (not allowed)")
421 }
422
423 if c.dialLimit > 0 && c.dialCount >= c.dialLimit {
424 return nil, errors.New("dial failed (limit reached)")
425 }
426
427 conn, err := dialer.DialContext(ctx, network, addr)
428 if err != nil {
429 return nil, err
430 }
431
432 c.dialCount++
433
434 for _, fn := range c.onDial {
435 fn(conn)
436 }
437
438 c.conns = append(c.conns, conn)
439
440 return newConn(conn, c), nil
441 }
442
443 // read reads from r, but only if the controller allows it.
444 func (c *NetCtl) read(r io.Reader, b []byte) (int, error) {
445 c.rlock.Lock()
446 defer c.rlock.Unlock()
447
448 if !c.canRead {
449 return 0, errors.New("read failed (not allowed)")
450 }
451
452 if c.readLimit > 0 && c.readCount >= c.readLimit {
453 return 0, errors.New("read failed (limit reached)")
454 }
455
456 var rem uint64
457
458 if c.readLimit > 0 && c.readLimit-c.readCount < uint64(len(b)) {
459 rem = c.readLimit - c.readCount
460 } else {
461 rem = uint64(len(b))
462 }
463
464 c.rlock.Unlock()
465 n, err := newSlowReader(r, c.readSpeed).Read(b[:rem])
466 c.rlock.Lock()
467
468 c.readCount += uint64(n)
469
470 for _, fn := range c.onRead {
471 fn(b[:n])
472 }
473
474 return n, err
475 }
476
477 // write writes to w, but only if the controller allows it.
478 func (c *NetCtl) write(w io.Writer, b []byte) (int, error) {
479 c.wlock.Lock()
480 defer c.wlock.Unlock()
481
482 if !c.canWrite {
483 return 0, errors.New("write failed (not allowed)")
484 }
485
486 if c.writeLimit > 0 && c.writeCount >= c.writeLimit {
487 return 0, errors.New("write failed (limit exceeded)")
488 }
489
490 var rem uint64
491
492 if c.writeLimit > 0 && c.writeLimit-c.writeCount < uint64(len(b)) {
493 rem = c.writeLimit - c.writeCount
494 } else {
495 rem = uint64(len(b))
496 }
497
498 c.wlock.Unlock()
499 n, err := newSlowWriter(w, c.writeSpeed).Write(b[:rem])
500 c.wlock.Lock()
501
502 c.writeCount += uint64(n)
503
504 for _, fn := range c.onWrite {
505 fn(b[:n])
506 }
507
508 if uint64(n) < rem {
509 return n, fmt.Errorf("write incomplete (limit reached)")
510 }
511
512 return n, err
513 }
514
515 // conn is a wrapper around net.conn that can be used to control whether a connection can read or write.
516 type conn struct {
517 net.Conn
518
519 ctl *NetCtl
520 }
521
522 func newConn(c net.Conn, ctl *NetCtl) *conn {
523 return &conn{
524 Conn: c,
525 ctl: ctl,
526 }
527 }
528
529 // Read reads from the wrapped connection, but only if the controller allows it.
530 func (c *conn) Read(b []byte) (int, error) {
531 return c.ctl.read(c.Conn, b)
532 }
533
534 // Write writes to the wrapped connection, but only if the controller allows it.
535 func (c *conn) Write(b []byte) (int, error) {
536 return c.ctl.write(c.Conn, b)
537 }
538
539 // slowReader is an io.Reader that reads at a fixed rate.
540 type slowReader struct {
541 r io.Reader
542
543 // bytesPerSec is the number of bytes to read per second.
544 bytesPerSec int
545 }
546
547 func newSlowReader(r io.Reader, bytesPerSec int) *slowReader {
548 return &slowReader{
549 r: r,
550 bytesPerSec: bytesPerSec,
551 }
552 }
553
554 func (r *slowReader) Read(b []byte) (int, error) {
555 start := time.Now()
556
557 n, err := r.r.Read(b)
558
559 if r.bytesPerSec > 0 {
560 time.Sleep(time.Until(start.Add(time.Duration(n*r.bytesPerSec) * time.Second)))
561 }
562
563 return n, err
564 }
565
566 // slowWriter is an io.Writer that writes at a fixed rate.
567 type slowWriter struct {
568 w io.Writer
569
570 // bytesPerSec is the number of bytes to write per second.
571 bytesPerSec int
572 }
573
574 func newSlowWriter(w io.Writer, bytesPerSec int) *slowWriter {
575 return &slowWriter{
576 w: w,
577 bytesPerSec: bytesPerSec,
578 }
579 }
580
581 func (w *slowWriter) Write(b []byte) (int, error) {
582 start := time.Now()
583
584 n, err := w.w.Write(b)
585
586 if w.bytesPerSec > 0 {
587 time.Sleep(time.Until(start.Add(time.Duration(n*w.bytesPerSec) * time.Second)))
588 }
589
590 return n, err
591 }