1
0

socks5_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package socks5
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "io"
  6. "log"
  7. "net"
  8. "os"
  9. "testing"
  10. "time"
  11. )
  12. func TestSOCKS5_Connect(t *testing.T) {
  13. // Create a local listener
  14. l, err := net.Listen("tcp", "127.0.0.1:0")
  15. if err != nil {
  16. t.Fatalf("err: %v", err)
  17. }
  18. go func() {
  19. conn, err := l.Accept()
  20. if err != nil {
  21. t.Fatalf("err: %v", err)
  22. }
  23. defer conn.Close()
  24. buf := make([]byte, 4)
  25. if _, err := io.ReadAtLeast(conn, buf, 4); err != nil {
  26. t.Fatalf("err: %v", err)
  27. }
  28. if !bytes.Equal(buf, []byte("ping")) {
  29. t.Fatalf("bad: %v", buf)
  30. }
  31. conn.Write([]byte("pong"))
  32. }()
  33. lAddr := l.Addr().(*net.TCPAddr)
  34. // Create a socks server
  35. creds := StaticCredentials{
  36. "foo": "bar",
  37. }
  38. cator := UserPassAuthenticator{Credentials: creds}
  39. conf := &Config{
  40. AuthMethods: []Authenticator{cator},
  41. Logger: log.New(os.Stdout, "", log.LstdFlags),
  42. }
  43. serv, err := New(conf)
  44. if err != nil {
  45. t.Fatalf("err: %v", err)
  46. }
  47. // Start listening
  48. go func() {
  49. if err := serv.ListenAndServe("tcp", "127.0.0.1:12365"); err != nil {
  50. t.Fatalf("err: %v", err)
  51. }
  52. }()
  53. time.Sleep(10 * time.Millisecond)
  54. // Get a local conn
  55. conn, err := net.Dial("tcp", "127.0.0.1:12365")
  56. if err != nil {
  57. t.Fatalf("err: %v", err)
  58. }
  59. // Connect, auth and connec to local
  60. req := bytes.NewBuffer(nil)
  61. req.Write([]byte{5})
  62. req.Write([]byte{2, NoAuth, UserPassAuth})
  63. req.Write([]byte{1, 3, 'f', 'o', 'o', 3, 'b', 'a', 'r'})
  64. req.Write([]byte{5, 1, 0, 1, 127, 0, 0, 1})
  65. port := []byte{0, 0}
  66. binary.BigEndian.PutUint16(port, uint16(lAddr.Port))
  67. req.Write(port)
  68. // Send a ping
  69. req.Write([]byte("ping"))
  70. // Send all the bytes
  71. conn.Write(req.Bytes())
  72. // Verify response
  73. expected := []byte{
  74. socks5Version, UserPassAuth,
  75. 1, authSuccess,
  76. 5,
  77. 0,
  78. 0,
  79. 1,
  80. 127, 0, 0, 1,
  81. 0, 0,
  82. 'p', 'o', 'n', 'g',
  83. }
  84. out := make([]byte, len(expected))
  85. conn.SetDeadline(time.Now().Add(time.Second))
  86. if _, err := io.ReadAtLeast(conn, out, len(out)); err != nil {
  87. t.Fatalf("err: %v", err)
  88. }
  89. // Ignore the port
  90. out[12] = 0
  91. out[13] = 0
  92. if !bytes.Equal(out, expected) {
  93. t.Fatalf("bad: %v", out)
  94. }
  95. }