Repository navigation
Expand file tree
/
Copy pathh_stack_system_accept_test.go
More file actions
80 lines (74 loc) · 1.86 KB
/
Copy pathh_stack_system_accept_test.go
File metadata and controls
80 lines (74 loc) · 1.86 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
package tun
import (
"context"
"net"
"net/netip"
"strconv"
"testing"
"time"
"github.com/sagernet/sing/common/logger"
)
func hTCPSystem(t *testing.T) *System {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
s := &System{
ctx: ctx,
logger: logger.NOP(),
inet4Address: netip.MustParseAddr("127.0.0.1"),
inet4NextAddress: netip.MustParseAddr("127.0.0.2"),
}
s.tcpNat4 = NewNat(ctx, time.Minute)
if err := s.startTCPListener(false); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
s.closing.Store(true)
s.listenerAccess.Lock()
s.tcpListener.Close()
s.listenerAccess.Unlock()
})
return s
}
func hDialable(port uint16) bool {
conn, err := net.DialTimeout("tcp4", "127.0.0.1:"+strconv.Itoa(int(port)), 200*time.Millisecond)
if err != nil {
return false
}
conn.Close()
return true
}
// A listener closed behind the stack's back is recreated, and new TCP gets through again.
func TestH_SystemAcceptLoopRecreatesListener(t *testing.T) {
s := hTCPSystem(t)
oldPort := s.currentTCPPort(false)
s.listenerAccess.Lock()
s.tcpListener.Close()
s.listenerAccess.Unlock()
deadline := time.Now().Add(5 * time.Second)
for {
port := s.currentTCPPort(false)
if port != oldPort && hDialable(port) {
break
}
if time.Now().After(deadline) {
t.Fatalf("the listener was not recreated (port %d)", port)
}
time.Sleep(20 * time.Millisecond)
}
if s.tcpRecoveries.Load() != 1 {
t.Fatalf("recoveries: %d", s.tcpRecoveries.Load())
}
}
// Closing the stack ends the loop without recreating anything.
func TestH_SystemAcceptLoopQuietOnClose(t *testing.T) {
s := hTCPSystem(t)
s.closing.Store(true)
s.listenerAccess.Lock()
s.tcpListener.Close()
s.listenerAccess.Unlock()
time.Sleep(300 * time.Millisecond)
if s.tcpRecoveries.Load() != 0 {
t.Fatalf("a closing stack recreated its listener")
}
}