tcp_frames_test.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. package bwtest
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "encoding/binary"
  7. "encoding/json"
  8. "net"
  9. "sync"
  10. "testing"
  11. "time"
  12. )
  13. func TestConcurrentTCPFramesRemainDistinct(t *testing.T) {
  14. a, b := net.Pipe()
  15. defer a.Close()
  16. defer b.Close()
  17. w := tcpFrameWriter{conn: a}
  18. var wg sync.WaitGroup
  19. for _, kind := range []byte{tcpFrameData, tcpFrameControl} {
  20. wg.Add(1)
  21. go func(kind byte) {
  22. defer wg.Done()
  23. for range 20 {
  24. if _, err := w.write(kind, bytes.Repeat([]byte{kind}, 1024)); err != nil {
  25. return
  26. }
  27. }
  28. }(kind)
  29. }
  30. counts := map[byte]int{}
  31. buf := make([]byte, tcpFrameMax)
  32. _ = b.SetReadDeadline(time.Now().Add(3 * time.Second))
  33. for range 40 {
  34. kind, payload, err := readTCPFrame(b, buf)
  35. if err != nil {
  36. t.Fatal(err)
  37. }
  38. if !bytes.Equal(payload, bytes.Repeat([]byte{kind}, 1024)) {
  39. t.Fatal("interleaved control and data")
  40. }
  41. counts[kind]++
  42. }
  43. wg.Wait()
  44. if counts[tcpFrameData] != 20 || counts[tcpFrameControl] != 20 {
  45. t.Fatal(counts)
  46. }
  47. }
  48. func TestTCPFrameBounds(t *testing.T) {
  49. for _, n := range []uint32{0, tcpFrameMax + 1} {
  50. h := make([]byte, 5)
  51. h[0] = tcpFrameData
  52. binary.BigEndian.PutUint32(h[1:], n)
  53. if _, _, err := readTCPFrame(bytes.NewReader(h), make([]byte, tcpFrameMax)); err == nil {
  54. t.Fatal("invalid frame length accepted")
  55. }
  56. }
  57. }
  58. func testServer(t *testing.T) *BwTestServer {
  59. t.Helper()
  60. ln, err := net.Listen("tcp", "127.0.0.1:0")
  61. if err != nil {
  62. t.Fatal(err)
  63. }
  64. port := ln.Addr().(*net.TCPAddr).Port
  65. ln.Close()
  66. s := NewServer(ServerConfig{Enabled: true, ListenAddr: "127.0.0.1", Port: port})
  67. if err = s.Start(); err != nil {
  68. t.Fatal(err)
  69. }
  70. t.Cleanup(s.Stop)
  71. return s
  72. }
  73. func TestBandwidthTCPAllDirections(t *testing.T) {
  74. s := testServer(t)
  75. for _, direction := range []string{"tx", "rx", "both"} {
  76. t.Run(direction, func(t *testing.T) {
  77. c := NewClient()
  78. t.Cleanup(c.Stop)
  79. err := c.Run(context.Background(), SessionRequest{Target: "127.0.0.1", Port: s.config.Port, Protocol: "tcp", Direction: direction, BandwidthLimit: 2_000_000, Duration: 2})
  80. if err != nil {
  81. t.Fatal(err)
  82. }
  83. deadline := time.Now().Add(5 * time.Second)
  84. for c.GetStatus().Running && time.Now().Before(deadline) {
  85. time.Sleep(10 * time.Millisecond)
  86. }
  87. st := c.GetStatus()
  88. if st.Running || st.Error != "" || st.Summary == nil {
  89. t.Fatalf("test did not finish: %+v", st)
  90. }
  91. if direction != "rx" && st.Summary.TotalTxBytes < 65536 {
  92. t.Fatalf("no transmitted data: %+v", st.Summary)
  93. }
  94. if direction != "tx" && st.Summary.TotalRxBytes < 65536 {
  95. t.Fatalf("no received data/reports: %+v", st.Summary)
  96. }
  97. })
  98. }
  99. }
  100. func TestBandwidthStopInterruptsThrottledWriter(t *testing.T) {
  101. s := testServer(t)
  102. c := NewClient()
  103. if err := c.Run(context.Background(), SessionRequest{Target: "127.0.0.1", Port: s.config.Port, Protocol: "tcp", Direction: "both", BandwidthLimit: 1000, Duration: 30}); err != nil {
  104. t.Fatal(err)
  105. }
  106. time.Sleep(150 * time.Millisecond)
  107. c.Stop()
  108. deadline := time.Now().Add(time.Second)
  109. for c.GetStatus().Running && time.Now().Before(deadline) {
  110. time.Sleep(10 * time.Millisecond)
  111. }
  112. if c.GetStatus().Running {
  113. t.Fatal("Stop blocked behind rate limiter")
  114. }
  115. }
  116. func TestBandwidthRejectsUnframedTCP(t *testing.T) {
  117. s := testServer(t)
  118. conn, err := net.Dial("tcp", s.tcpListener.Addr().String())
  119. if err != nil {
  120. t.Fatal(err)
  121. }
  122. defer conn.Close()
  123. _ = conn.SetDeadline(time.Now().Add(time.Second))
  124. b, _ := json.Marshal(SessionHandshake{Type: "request", Protocol: "tcp"})
  125. conn.Write(append(b, '\n'))
  126. line, err := bufio.NewReader(conn).ReadBytes('\n')
  127. if err != nil {
  128. t.Fatal(err)
  129. }
  130. var response SessionHandshake
  131. if err = json.Unmarshal(line, &response); err != nil || response.Type != "reject" {
  132. t.Fatalf("legacy TCP silently accepted: %s %v", line, err)
  133. }
  134. }
  135. func TestRateLimiterCanSendFrameLargerThanBucket(t *testing.T) {
  136. limiter := NewRateLimiter(4_000_000)
  137. ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
  138. defer cancel()
  139. if !limiter.WaitContext(ctx, 65536) {
  140. t.Fatal("64KB frame can never fit nominal 50KB bucket")
  141. }
  142. ctx2, cancel2 := context.WithCancel(context.Background())
  143. cancel2()
  144. if limiter.WaitContext(ctx2, 65536) {
  145. t.Fatal("ignored cancellation")
  146. }
  147. }