box_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package main
  2. import (
  3. "context"
  4. "net"
  5. "testing"
  6. "github.com/sagernet/sing-box"
  7. "github.com/sagernet/sing-box/option"
  8. M "github.com/sagernet/sing/common/metadata"
  9. N "github.com/sagernet/sing/common/network"
  10. "github.com/sagernet/sing/protocol/socks"
  11. "github.com/stretchr/testify/require"
  12. )
  13. func mkPort(t *testing.T) uint16 {
  14. for {
  15. tcpListener, err := net.ListenTCP("tcp", nil)
  16. require.NoError(t, err)
  17. listenPort := M.SocksaddrFromNet(tcpListener.Addr()).Port
  18. tcpListener.Close()
  19. udpListener, err := net.ListenUDP("udp", &net.UDPAddr{Port: int(listenPort)})
  20. if err != nil {
  21. continue
  22. }
  23. udpListener.Close()
  24. return listenPort
  25. }
  26. }
  27. func startInstance(t *testing.T, options option.Options) {
  28. instance, err := box.New(context.Background(), options)
  29. require.NoError(t, err)
  30. require.NoError(t, instance.Start())
  31. t.Cleanup(func() {
  32. instance.Close()
  33. })
  34. }
  35. func testSuit(t *testing.T, clientPort uint16, testPort uint16) {
  36. dialer := socks.NewClient(N.SystemDialer, M.ParseSocksaddrHostPort("127.0.0.1", clientPort), socks.Version5, "", "")
  37. dialTCP := func() (net.Conn, error) {
  38. return dialer.DialContext(context.Background(), "tcp", M.ParseSocksaddrHostPort("127.0.0.1", testPort))
  39. }
  40. dialUDP := func() (net.PacketConn, error) {
  41. return dialer.ListenPacket(context.Background(), M.ParseSocksaddrHostPort("127.0.0.1", testPort))
  42. }
  43. require.NoError(t, testPingPongWithConn(t, testPort, dialTCP))
  44. require.NoError(t, testLargeDataWithConn(t, testPort, dialTCP))
  45. require.NoError(t, testPingPongWithPacketConn(t, testPort, dialUDP))
  46. require.NoError(t, testLargeDataWithPacketConn(t, testPort, dialUDP))
  47. require.NoError(t, testPacketConnTimeout(t, dialUDP))
  48. }