Example #1
0
func TestReadSingleByte(t *testing.T) {
	assert := unit.Assert(t)

	reader := NewVMessRequestReader(nil)
	_, err := reader.Read(bytes.NewReader(make([]byte, 1)))
	assert.Error(err).Equals(io.EOF)
}
Example #2
0
func TestBuildMacOS(t *testing.T) {
	assert := unit.Assert(t)
	binPath = filepath.Join(os.Getenv("GOPATH"), "testing")
	cleanBinPath()

	build("macos", "amd64", true, "test")
	assert.Bool(allFilesExists(
		"v2ray-macos.zip",
		"v2ray-test-macos",
		filepath.Join("v2ray-test-macos", "config.json"),
		filepath.Join("v2ray-test-macos", "v2ray"))).IsTrue()

	build("windows", "amd64", true, "test")
	assert.Bool(allFilesExists(
		"v2ray-windows-64.zip",
		"v2ray-test-windows-64",
		filepath.Join("v2ray-test-windows-64", "config.json"),
		filepath.Join("v2ray-test-windows-64", "v2ray.exe"))).IsTrue()

	build("linux", "amd64", true, "test")
	assert.Bool(allFilesExists(
		"v2ray-linux-64.zip",
		"v2ray-test-linux-64",
		filepath.Join("v2ray-test-linux-64", "vpoint_socks_vmess.json"),
		filepath.Join("v2ray-test-linux-64", "vpoint_vmess_freedom.json"),
		filepath.Join("v2ray-test-linux-64", "v2ray"))).IsTrue()
}
func randomBytes(p []byte, t *testing.T) {
	assert := unit.Assert(t)

	nBytes, err := rand.Read(p)
	assert.Error(err).IsNil()
	assert.Int(nBytes).Named("# bytes of random buffer").Equals(len(p))
}
Example #4
0
func TestResponseWrite(t *testing.T) {
	assert := unit.Assert(t)

	response := Socks5Response{
		socksVersion,
		ErrorSuccess,
		AddrTypeIPv4,
		[4]byte{0x72, 0x72, 0x72, 0x72},
		"",
		[16]byte{},
		uint16(53),
	}
	buffer := alloc.NewSmallBuffer().Clear()
	defer buffer.Release()

	response.Write(buffer)
	expectedBytes := []byte{
		socksVersion,
		ErrorSuccess,
		byte(0x00),
		AddrTypeIPv4,
		0x72, 0x72, 0x72, 0x72,
		byte(0x00), byte(0x035),
	}
	assert.Bytes(buffer.Value).Named("raw response").Equals(expectedBytes)
}
Example #5
0
func TestSocksTcpConnect(t *testing.T) {
	t.Skip("Not ready yet.")

	assert := unit.Assert(t)

	port := uint16(12384)

	uuid := "2418d087-648d-4990-86e8-19dca1d006d3"
	vid, err := core.UUIDToVID(uuid)
	assert.Error(err).IsNil()

	config := core.VConfig{
		port,
		[]core.VUser{core.VUser{vid}},
		"",
		[]core.VNext{}}

	och := new(mocks.FakeOutboundConnectionHandler)
	och.Data2Send = bytes.NewBuffer(make([]byte, 1024))
	och.Data2Return = []byte("The data to be returned to socks server.")

	vpoint, err := core.NewVPoint(&config, SocksServerFactory{}, och)
	assert.Error(err).IsNil()

	err = vpoint.Start()
	assert.Error(err).IsNil()

}
Example #6
0
func TestRevParse(t *testing.T) {
	assert := unit.Assert(t)

	rev, err := RevParse("HEAD")
	assert.Error(err).IsNil()
	assert.Int(len(rev)).GreaterThan(0)
}
Example #7
0
func TestDokodemoUDP(t *testing.T) {
	assert := unit.Assert(t)

	port := v2nettesting.PickPort()

	data2Send := "Data to be sent to remote."

	udpServer := &udp.Server{
		Port: port,
		MsgProcessor: func(data []byte) []byte {
			buffer := make([]byte, 0, 2048)
			buffer = append(buffer, []byte("Processed: ")...)
			buffer = append(buffer, data...)
			return buffer
		},
	}
	_, err := udpServer.Start()
	assert.Error(err).IsNil()

	pointPort := v2nettesting.PickPort()
	networkList := v2netjson.NetworkList([]string{"udp"})
	config := mocks.Config{
		PortValue: pointPort,
		InboundConfigValue: &mocks.ConnectionConfig{
			ProtocolValue: "dokodemo-door",
			SettingsValue: &json.DokodemoConfig{
				Host:    "127.0.0.1",
				Port:    int(port),
				Network: &networkList,
				Timeout: 0,
			},
		},
		OutboundConfigValue: &mocks.ConnectionConfig{
			ProtocolValue: "freedom",
			SettingsValue: nil,
		},
	}

	point, err := point.NewPoint(&config)
	assert.Error(err).IsNil()

	err = point.Start()
	assert.Error(err).IsNil()

	udpClient, err := net.DialUDP("udp", nil, &net.UDPAddr{
		IP:   []byte{127, 0, 0, 1},
		Port: int(pointPort),
		Zone: "",
	})
	assert.Error(err).IsNil()

	udpClient.Write([]byte(data2Send))

	response := make([]byte, 1024)
	nBytes, err := udpClient.Read(response)
	assert.Error(err).IsNil()
	udpClient.Close()

	assert.String("Processed: " + data2Send).Equals(string(response[:nBytes]))
}
Example #8
0
func TestSocksTcpConnectWithUserPass(t *testing.T) {
	assert := unit.Assert(t)
	port := v2nettesting.PickPort()

	connInput := []byte("The data to be returned to socks server.")
	connOutput := bytes.NewBuffer(make([]byte, 0, 1024))
	och := &proxymocks.OutboundConnectionHandler{
		ConnInput:  bytes.NewReader(connInput),
		ConnOutput: connOutput,
	}

	connhandler.RegisterOutboundConnectionHandlerFactory("mock_och", och)

	config := mocks.Config{
		PortValue: port,
		InboundConfigValue: &mocks.ConnectionConfig{
			ProtocolValue: "socks",
			SettingsValue: &json.SocksConfig{
				AuthMethod: "password",
				Accounts: []json.SocksAccount{
					json.SocksAccount{
						Username: "******",
						Password: "******",
					},
				},
			},
		},
		OutboundConfigValue: &mocks.ConnectionConfig{
			ProtocolValue: "mock_och",
			SettingsValue: nil,
		},
	}

	point, err := point.NewPoint(&config)
	assert.Error(err).IsNil()

	err = point.Start()
	assert.Error(err).IsNil()

	socks5Client, err := proxy.SOCKS5("tcp", fmt.Sprintf("127.0.0.1:%d", port), &proxy.Auth{"userx", "passy"}, proxy.Direct)
	assert.Error(err).IsNil()

	targetServer := "1.2.3.4:443"
	conn, err := socks5Client.Dial("tcp", targetServer)
	assert.Error(err).IsNil()

	data2Send := "The data to be sent to remote server."
	conn.Write([]byte(data2Send))
	if tcpConn, ok := conn.(*net.TCPConn); ok {
		tcpConn.CloseWrite()
	}

	dataReturned, err := ioutil.ReadAll(conn)
	assert.Error(err).IsNil()
	conn.Close()

	assert.Bytes([]byte(data2Send)).Equals(connOutput.Bytes())
	assert.Bytes(dataReturned).Equals(connInput)
	assert.String(targetServer).Equals(och.Destination.Address().String())
}
Example #9
0
func TestRepoVersion(t *testing.T) {
	assert := unit.Assert(t)

	version, err := RepoVersionHead()
	assert.Error(err).IsNil()
	assert.Int(len(version)).GreaterThan(0)
}
Example #10
0
func TestBuildAndRun(t *testing.T) {
	assert := unit.Assert(t)

	gopath := os.Getenv("GOPATH")
	target := filepath.Join(gopath, "src", "v2ray_test")
	fmt.Println(target)
	goOS := parseOS(runtime.GOOS)
	goArch := parseArch(runtime.GOARCH)
	err := buildV2Ray(target, "v1.0", goOS, goArch)
	assert.Error(err).IsNil()

	outBuffer := bytes.NewBuffer(make([]byte, 0, 1024))
	errBuffer := bytes.NewBuffer(make([]byte, 0, 1024))
	configFile := filepath.Join(gopath, "src", "github.com", "v2ray", "v2ray-core", "release", "config", "vpoint_socks_vmess.json")
	cmd := exec.Command(target, "--config="+configFile)
	cmd.Stdout = outBuffer
	cmd.Stderr = errBuffer
	cmd.Start()

	<-time.After(1 * time.Second)
	cmd.Process.Kill()

	outStr := string(outBuffer.Bytes())
	errStr := string(errBuffer.Bytes())

	assert.Bool(strings.Contains(outStr, "v1.0")).IsTrue()
	assert.Int(len(errStr)).Equals(0)

	os.Remove(target)
}
Example #11
0
func TestVMessUDPReadWrite(t *testing.T) {
	assert := unit.Assert(t)

	userId, err := user.NewID("2b2966ac-16aa-4fbf-8d81-c5f172a3da51")
	assert.Error(err).IsNil()

	userSet := mocks.MockUserSet{[]user.ID{}, make(map[string]int), make(map[string]int64)}
	userSet.AddUser(user.User{userId})

	message := &VMessUDP{
		user:    userId,
		version: byte(0x01),
		token:   1234,
		address: v2net.DomainAddress("v2ray.com", 8372),
		data:    []byte("An UDP message."),
	}

	mockTime := int64(1823730)
	buffer := message.ToBytes(user.NewTimeHash(user.HMACHash{}), func(base int64, delta int) int64 { return mockTime }, nil)

	userSet.UserHashes[string(buffer[:16])] = 0
	userSet.Timestamps[string(buffer[:16])] = mockTime

	messageRestored, err := ReadVMessUDP(buffer, &userSet)
	assert.Error(err).IsNil()

	assert.String(messageRestored.user.String).Equals(message.user.String)
	assert.Byte(messageRestored.version).Equals(message.version)
	assert.Uint16(messageRestored.token).Equals(message.token)
	assert.String(messageRestored.address.String()).Equals(message.address.String())
	assert.Bytes(messageRestored.data).Equals(message.data)
}
Example #12
0
func TestSocksUdpSend(t *testing.T) {
	assert := unit.Assert(t)
	port := v2nettesting.PickPort()

	connInput := []byte("The data to be returned to socks server.")
	connOutput := bytes.NewBuffer(make([]byte, 0, 1024))
	och := &proxymocks.OutboundConnectionHandler{
		ConnInput:  bytes.NewReader(connInput),
		ConnOutput: connOutput,
	}

	connhandler.RegisterOutboundConnectionHandlerFactory("mock_och", och)

	config := mocks.Config{
		PortValue: port,
		InboundConfigValue: &mocks.ConnectionConfig{
			ProtocolValue: "socks",
			SettingsValue: &json.SocksConfig{
				AuthMethod: "noauth",
				UDPEnabled: true,
			},
		},
		OutboundConfigValue: &mocks.ConnectionConfig{
			ProtocolValue: "mock_och",
			SettingsValue: nil,
		},
	}

	point, err := point.NewPoint(&config)
	assert.Error(err).IsNil()

	err = point.Start()
	assert.Error(err).IsNil()

	conn, err := net.DialUDP("udp", nil, &net.UDPAddr{
		IP:   []byte{127, 0, 0, 1},
		Port: int(port),
		Zone: "",
	})

	assert.Error(err).IsNil()

	data2Send := []byte("Fake DNS request")

	buffer := make([]byte, 0, 1024)
	buffer = append(buffer, 0, 0, 0)
	buffer = append(buffer, 1, 8, 8, 4, 4, 0, 53)
	buffer = append(buffer, data2Send...)

	conn.Write(buffer)

	response := make([]byte, 1024)
	nBytes, err := conn.Read(response)

	assert.Error(err).IsNil()
	assert.Bytes(response[10:nBytes]).Equals(connInput)
	assert.Bytes(data2Send).Equals(connOutput.Bytes())
	assert.String(och.Destination.String()).Equals("udp:8.8.4.4:53")
}
Example #13
0
func TestIPAddressParsing(t *testing.T) {
	assert := unit.Assert(t)

	var ipAddress IPAddress
	err := json.Unmarshal([]byte("\"1.2.3.4\""), &ipAddress)
	assert.Error(err).IsNil()
	assert.String(net.IP(ipAddress).String()).Equals("1.2.3.4")
}
Example #14
0
func TestParseOS(t *testing.T) {
	assert := unit.Assert(t)

	assert.Pointer(parseOS("windows")).Equals(Windows)
	assert.Pointer(parseOS("macos")).Equals(MacOS)
	assert.Pointer(parseOS("linux")).Equals(Linux)
	assert.Pointer(parseOS("test")).Equals(UnknownOS)
}
Example #15
0
func TestUDPDestination(t *testing.T) {
	assert := unit.Assert(t)

	dest := NewUDPDestination(IPAddress([]byte{0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88}, 53))
	assert.Bool(dest.IsTCP()).IsFalse()
	assert.Bool(dest.IsUDP()).IsTrue()
	assert.String(dest.String()).Equals("udp:[2001:4860:4860::8888]:53")
}
Example #16
0
func TestTCPDestination(t *testing.T) {
	assert := unit.Assert(t)

	dest := NewTCPDestination(IPAddress([]byte{1, 2, 3, 4}, 80))
	assert.Bool(dest.IsTCP()).IsTrue()
	assert.Bool(dest.IsUDP()).IsFalse()
	assert.String(dest.String()).Equals("tcp:1.2.3.4:80")
}
Example #17
0
func TestVMessSerialization(t *testing.T) {
	assert := unit.Assert(t)

	userId, err := core.NewID("2b2966ac-16aa-4fbf-8d81-c5f172a3da51")
	if err != nil {
		t.Fatal(err)
	}

	userSet := mocks.MockUserSet{[]core.ID{}, make(map[string]int), make(map[string]int64)}
	userSet.AddUser(core.User{userId})

	request := new(VMessRequest)
	request.Version = byte(0x01)
	request.UserId = userId

	_, err = rand.Read(request.RequestIV[:])
	if err != nil {
		t.Fatal(err)
	}

	_, err = rand.Read(request.RequestKey[:])
	if err != nil {
		t.Fatal(err)
	}

	_, err = rand.Read(request.ResponseHeader[:])
	if err != nil {
		t.Fatal(err)
	}

	request.Command = byte(0x01)
	request.Address = v2net.DomainAddress("v2ray.com", 80)

	buffer := bytes.NewBuffer(make([]byte, 0, 300))
	mockTime := int64(1823730)
	requestWriter := NewVMessRequestWriter(v2hash.NewTimeHash(v2hash.HMACHash{}), func(base int64, delta int) int64 { return mockTime })
	err = requestWriter.Write(buffer, request)
	if err != nil {
		t.Fatal(err)
	}

	userSet.UserHashes[string(buffer.Bytes()[:16])] = 0
	userSet.Timestamps[string(buffer.Bytes()[:16])] = mockTime

	requestReader := NewVMessRequestReader(&userSet)
	actualRequest, err := requestReader.Read(buffer)
	if err != nil {
		t.Fatal(err)
	}

	assert.Byte(actualRequest.Version).Named("Version").Equals(byte(0x01))
	assert.String(actualRequest.UserId.String).Named("UserId").Equals(request.UserId.String)
	assert.Bytes(actualRequest.RequestIV[:]).Named("RequestIV").Equals(request.RequestIV[:])
	assert.Bytes(actualRequest.RequestKey[:]).Named("RequestKey").Equals(request.RequestKey[:])
	assert.Bytes(actualRequest.ResponseHeader[:]).Named("ResponseHeader").Equals(request.ResponseHeader[:])
	assert.Byte(actualRequest.Command).Named("Command").Equals(request.Command)
	assert.String(actualRequest.Address.String()).Named("Address").Equals(request.Address.String())
}
Example #18
0
func TestParseArch(t *testing.T) {
	assert := unit.Assert(t)

	assert.Pointer(parseArch("x86")).Equals(X86)
	assert.Pointer(parseArch("x64")).Equals(Amd64)
	assert.Pointer(parseArch("arm")).Equals(Arm)
	assert.Pointer(parseArch("arm64")).Equals(Arm64)
	assert.Pointer(parseArch("test")).Equals(UnknownArch)
}
Example #19
0
func TestAuthenticationResponseWrite(t *testing.T) {
	assert := unit.Assert(t)

	response := NewAuthenticationResponse(byte(0x05))

	buffer := bytes.NewBuffer(make([]byte, 0, 10))
	WriteAuthentication(buffer, response)
	assert.Bytes(buffer.Bytes()).Equals([]byte{socksVersion, byte(0x05)})
}
Example #20
0
func TestStringListParsingList(t *testing.T) {
	assert := unit.Assert(t)

	rawJson := `["a", "b", "c", "d"]`
	var strList StringList
	err := json.Unmarshal([]byte(rawJson), &strList)
	assert.Error(err).IsNil()
	assert.Int(strList.Len()).Equals(4)
}
Example #21
0
func TestDomainMatching(t *testing.T) {
	assert := unit.Assert(t)

	rule := &FieldRule{
		Domain: NewStringList("v2ray.com"),
	}
	dest := v2net.NewTCPDestination(v2net.DomainAddress("www.v2ray.com", 80))
	assert.Bool(rule.Apply(dest)).IsTrue()
}
Example #22
0
func TestArrayNetworkList(t *testing.T) {
	assert := unit.Assert(t)

	var list NetworkList
	err := json.Unmarshal([]byte("[\"Tcp\"]"), &list)
	assert.Error(err).IsNil()
	assert.Bool(list.HasNetwork("tcp")).IsTrue()
	assert.Bool(list.HasNetwork("udp")).IsFalse()
}
Example #23
0
func TestNetIPv4Address(t *testing.T) {
	assert := unit.Assert(t)

	ip := net.IPv4(1, 2, 3, 4)
	port := uint16(80)
	addr := IPAddress(ip, port)
	assert.Bool(addr.IsIPv4()).IsTrue()
	assert.String(addr.String()).Equals("1.2.3.4:80")
}
Example #24
0
func TestStringListParsingString(t *testing.T) {
	assert := unit.Assert(t)

	rawJson := `"abcd"`
	var strList StringList
	err := json.Unmarshal([]byte(rawJson), &strList)
	assert.Error(err).IsNil()
	assert.Int(strList.Len()).Equals(1)
}
Example #25
0
func TestSingleByteRequest(t *testing.T) {
	assert := unit.Assert(t)

	request, err := ReadUDPRequest(make([]byte, 1))
	if request != nil {
		t.Fail()
	}
	assert.Error(err).Equals(transport.CorruptedPacket)
}
Example #26
0
func TestUUIDToID(t *testing.T) {
	assert := unit.Assert(t)

	uuid := "2418d087-648d-4990-86e8-19dca1d006d3"
	expectedBytes := []byte{0x24, 0x18, 0xd0, 0x87, 0x64, 0x8d, 0x49, 0x90, 0x86, 0xe8, 0x19, 0xdc, 0xa1, 0xd0, 0x06, 0xd3}

	actualBytes, _ := NewID(uuid)
	assert.Bytes(actualBytes.Bytes[:]).Named("UUID").Equals(expectedBytes)
}
Example #27
0
func TestSocksTcpConnect(t *testing.T) {
	assert := unit.Assert(t)
	port := v2nettesting.PickPort()

	data2Send := "Data to be sent to remote"

	tcpServer := &tcp.Server{
		Port: port,
		MsgProcessor: func(data []byte) []byte {
			buffer := make([]byte, 0, 2048)
			buffer = append(buffer, []byte("Processed: ")...)
			buffer = append(buffer, data...)
			return buffer
		},
	}
	_, err := tcpServer.Start()
	assert.Error(err).IsNil()

	pointPort := v2nettesting.PickPort()
	config := mocks.Config{
		PortValue: pointPort,
		InboundConfigValue: &mocks.ConnectionConfig{
			ProtocolValue: "socks",
			SettingsValue: &json.SocksConfig{
				AuthMethod: "auth",
			},
		},
		OutboundConfigValue: &mocks.ConnectionConfig{
			ProtocolValue: "freedom",
			SettingsValue: nil,
		},
	}

	point, err := point.NewPoint(&config)
	assert.Error(err).IsNil()

	err = point.Start()
	assert.Error(err).IsNil()

	socks5Client, err := proxy.SOCKS5("tcp", fmt.Sprintf("127.0.0.1:%d", pointPort), nil, proxy.Direct)
	assert.Error(err).IsNil()

	targetServer := fmt.Sprintf("127.0.0.1:%d", port)
	conn, err := socks5Client.Dial("tcp", targetServer)
	assert.Error(err).IsNil()

	conn.Write([]byte(data2Send))
	if tcpConn, ok := conn.(*net.TCPConn); ok {
		tcpConn.CloseWrite()
	}

	dataReturned, err := ioutil.ReadAll(conn)
	assert.Error(err).IsNil()
	conn.Close()

	assert.Bytes(dataReturned).Equals([]byte("Processed: Data to be sent to remote"))
}
Example #28
0
func TestOverRangeIntPort(t *testing.T) {
	assert := unit.Assert(t)

	var portRange PortRange
	err := json.Unmarshal([]byte("70000"), &portRange)
	assert.Error(err).Equals(InvalidPortRange)

	err = json.Unmarshal([]byte("-1"), &portRange)
	assert.Error(err).Equals(InvalidPortRange)
}
Example #29
0
func TestIntPort(t *testing.T) {
	assert := unit.Assert(t)

	var portRange PortRange
	err := json.Unmarshal([]byte("1234"), &portRange)
	assert.Error(err).IsNil()

	assert.Uint16(portRange.from).Equals(uint16(1234))
	assert.Uint16(portRange.to).Equals(uint16(1234))
}
Example #30
0
func TestGenerateRandomInt64InRange(t *testing.T) {
	assert := unit.Assert(t)
	base := time.Now().Unix()
	delta := 100

	for i := 0; i < 100; i++ {
		v := GenerateRandomInt64InRange(base, delta)
		assert.Int64(v).AtMost(base + int64(delta))
		assert.Int64(v).AtLeast(base - int64(delta))
	}
}