socks_test.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package protocol
  2. import (
  3. "bytes"
  4. "testing"
  5. "github.com/v2ray/v2ray-core/common/alloc"
  6. "github.com/v2ray/v2ray-core/testing/unit"
  7. )
  8. func TestHasAuthenticationMethod(t *testing.T) {
  9. assert := unit.Assert(t)
  10. request := Socks5AuthenticationRequest{
  11. version: socksVersion,
  12. nMethods: byte(0x02),
  13. authMethods: [256]byte{0x01, 0x02},
  14. }
  15. assert.Bool(request.HasAuthMethod(byte(0x01))).IsTrue()
  16. request.authMethods[0] = byte(0x03)
  17. assert.Bool(request.HasAuthMethod(byte(0x01))).IsFalse()
  18. }
  19. func TestAuthenticationRequestRead(t *testing.T) {
  20. assert := unit.Assert(t)
  21. rawRequest := []byte{
  22. 0x05, // version
  23. 0x01, // nMethods
  24. 0x02, // methods
  25. }
  26. request, _, err := ReadAuthentication(bytes.NewReader(rawRequest))
  27. assert.Error(err).IsNil()
  28. assert.Byte(request.version).Named("Version").Equals(0x05)
  29. assert.Byte(request.nMethods).Named("#Methods").Equals(0x01)
  30. assert.Byte(request.authMethods[0]).Named("Auth Method").Equals(0x02)
  31. }
  32. func TestAuthenticationResponseWrite(t *testing.T) {
  33. assert := unit.Assert(t)
  34. response := NewAuthenticationResponse(byte(0x05))
  35. buffer := bytes.NewBuffer(make([]byte, 0, 10))
  36. WriteAuthentication(buffer, response)
  37. assert.Bytes(buffer.Bytes()).Equals([]byte{socksVersion, byte(0x05)})
  38. }
  39. func TestRequestRead(t *testing.T) {
  40. assert := unit.Assert(t)
  41. rawRequest := []byte{
  42. 0x05, // version
  43. 0x01, // cmd connect
  44. 0x00, // reserved
  45. 0x01, // ipv4 type
  46. 0x72, 0x72, 0x72, 0x72, // 114.114.114.114
  47. 0x00, 0x35, // port 53
  48. }
  49. request, err := ReadRequest(bytes.NewReader(rawRequest))
  50. assert.Error(err).IsNil()
  51. assert.Byte(request.Version).Named("Version").Equals(0x05)
  52. assert.Byte(request.Command).Named("Command").Equals(0x01)
  53. assert.Byte(request.AddrType).Named("Address Type").Equals(0x01)
  54. assert.Bytes(request.IPv4[:]).Named("IPv4").Equals([]byte{0x72, 0x72, 0x72, 0x72})
  55. assert.Uint16(request.Port).Named("Port").Equals(53)
  56. }
  57. func TestResponseWrite(t *testing.T) {
  58. assert := unit.Assert(t)
  59. response := Socks5Response{
  60. socksVersion,
  61. ErrorSuccess,
  62. AddrTypeIPv4,
  63. [4]byte{0x72, 0x72, 0x72, 0x72},
  64. "",
  65. [16]byte{},
  66. uint16(53),
  67. }
  68. buffer := alloc.NewSmallBuffer().Clear()
  69. defer buffer.Release()
  70. response.Write(buffer)
  71. expectedBytes := []byte{
  72. socksVersion,
  73. ErrorSuccess,
  74. byte(0x00),
  75. AddrTypeIPv4,
  76. 0x72, 0x72, 0x72, 0x72,
  77. byte(0x00), byte(0x035),
  78. }
  79. assert.Bytes(buffer.Value).Named("raw response").Equals(expectedBytes)
  80. }