func TestSwitchAccount(t *testing.T) { v2testing.Current(t) sa := &SwitchAccount{ Port: 1234, ID: uuid.New(), AlterIds: 1024, ValidUntil: time.Now(), } cmd, err := CreateResponseCommand(1) assert.Error(err).IsNil() buffer := bytes.NewBuffer(make([]byte, 0, 1024)) nBytes, err := sa.Marshal(buffer) assert.Error(err).IsNil() assert.Int(nBytes).Equals(buffer.Len()) cmd.Unmarshal(buffer.Bytes()) sa2, ok := cmd.(*SwitchAccount) assert.Bool(ok).IsTrue() netassert.Port(sa.Port).Equals(sa2.Port) assert.String(sa.ID).Equals(sa2.ID.String()) assert.Uint16(sa.AlterIds.Value()).Equals(sa2.AlterIds.Value()) assert.Int64(sa.ValidUntil.Unix()).Equals(sa2.ValidUntil.Unix()) }
func TestIPNet(t *testing.T) { v2testing.Current(t) ipNet := NewIPNet() ipNet.Add(parseCIDR(("0.0.0.0/8"))) ipNet.Add(parseCIDR(("10.0.0.0/8"))) ipNet.Add(parseCIDR(("100.64.0.0/10"))) ipNet.Add(parseCIDR(("127.0.0.0/8"))) ipNet.Add(parseCIDR(("169.254.0.0/16"))) ipNet.Add(parseCIDR(("172.16.0.0/12"))) ipNet.Add(parseCIDR(("192.0.0.0/24"))) ipNet.Add(parseCIDR(("192.0.2.0/24"))) ipNet.Add(parseCIDR(("192.168.0.0/16"))) ipNet.Add(parseCIDR(("198.18.0.0/15"))) ipNet.Add(parseCIDR(("198.51.100.0/24"))) ipNet.Add(parseCIDR(("203.0.113.0/24"))) ipNet.Add(parseCIDR(("8.8.8.8/32"))) assert.Bool(ipNet.Contains(net.ParseIP("192.168.1.1"))).IsTrue() assert.Bool(ipNet.Contains(net.ParseIP("192.0.0.0"))).IsTrue() assert.Bool(ipNet.Contains(net.ParseIP("192.0.1.0"))).IsFalse() assert.Bool(ipNet.Contains(net.ParseIP("0.1.0.0"))).IsTrue() assert.Bool(ipNet.Contains(net.ParseIP("1.0.0.1"))).IsFalse() assert.Bool(ipNet.Contains(net.ParseIP("8.8.8.7"))).IsFalse() assert.Bool(ipNet.Contains(net.ParseIP("8.8.8.8"))).IsTrue() assert.Bool(ipNet.Contains(net.ParseIP("2001:cdba::3257:9652"))).IsFalse() }
func TestSocksUdpSend(t *testing.T) { v2testing.Current(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, } protocol, err := proxytesting.RegisterOutboundConnectionHandlerCreator("mock_och", func(space app.Space, config interface{}) (v2proxy.OutboundConnectionHandler, error) { return och, nil }) assert.Error(err).IsNil() config := &point.Config{ Port: port, InboundConfig: &point.ConnectionConfig{ Protocol: "socks", Settings: []byte(`{"auth": "noauth", "udp": true}`), }, OutboundConfig: &point.ConnectionConfig{ Protocol: protocol, Settings: 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.StringLiteral(och.Destination.String()).Equals("udp:8.8.4.4:53") }
func TestPubsub(t *testing.T) { v2testing.Current(t) messages := make(map[string]app.PubsubMessage) pubsub := New() pubsub.Subscribe(&apptesting.Context{}, "t1", func(message app.PubsubMessage) { messages["t1"] = message }) pubsub.Subscribe(&apptesting.Context{}, "t2", func(message app.PubsubMessage) { messages["t2"] = message }) message := app.PubsubMessage([]byte("This is a pubsub message.")) pubsub.Publish(&apptesting.Context{}, "t2", message) <-time.Tick(time.Second) _, found := messages["t1"] assert.Bool(found).IsFalse() actualMessage, found := messages["t2"] assert.Bool(found).IsTrue() assert.StringLiteral(string(actualMessage)).Equals(string(message)) }
func TestDokodemoUDP(t *testing.T) { v2testing.Current(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: v2netjson.NewIPHost(net.ParseIP("127.0.0.1")), PortValue: port, NetworkList: &networkList, TimeoutValue: 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.StringLiteral("Processed: " + data2Send).Equals(string(response[:nBytes])) }
func TestInvalidNetworkJson(t *testing.T) { v2testing.Current(t) var list NetworkList err := json.Unmarshal([]byte("0"), &list) assert.Error(err).IsNotNil() }
func TestSwitchAccount(t *testing.T) { v2testing.Current(t) sa := &SwitchAccount{ Port: 1234, ID: uuid.New(), AlterIds: 1024, Level: 128, ValidMin: 16, } cmd, err := CreateResponseCommand(1) assert.Error(err).IsNil() buffer := bytes.NewBuffer(make([]byte, 0, 1024)) sa.Marshal(buffer) cmd.Unmarshal(buffer.Bytes()) sa2, ok := cmd.(*SwitchAccount) assert.Bool(ok).IsTrue() assert.Pointer(sa.Host).IsNil() assert.Pointer(sa2.Host).IsNil() netassert.Port(sa.Port).Equals(sa2.Port) assert.String(sa.ID).Equals(sa2.ID.String()) assert.Uint16(sa.AlterIds.Value()).Equals(sa2.AlterIds.Value()) assert.Byte(byte(sa.Level)).Equals(byte(sa2.Level)) assert.Byte(sa.ValidMin).Equals(sa2.ValidMin) }
func TestNext(t *testing.T) { v2testing.Current(t) uuid := New() uuid2 := uuid.Next() assert.Bool(uuid.Equals(uuid2)).IsFalse() }
func TestReadSingleByte(t *testing.T) { v2testing.Current(t) reader := NewVMessRequestReader(nil) _, err := reader.Read(bytes.NewReader(make([]byte, 1))) assert.Error(err).Equals(io.EOF) }
func TestInsufficientPortRequest(t *testing.T) { v2testing.Current(t) buffer := alloc.NewSmallBuffer().Clear().AppendBytes(1, 1, 2, 3, 4, 5) _, err := ReadRequest(buffer, nil, false) assert.Error(err).Equals(transport.ErrorCorruptedPacket) }
func TestSwitchAccount(t *testing.T) { v2testing.Current(t) sa := &protocol.CommandSwitchAccount{ Port: 1234, ID: uuid.New(), AlterIds: 1024, Level: 128, ValidMin: 16, } buffer := alloc.NewBuffer().Clear() err := MarshalCommand(sa, buffer) assert.Error(err).IsNil() cmd, err := UnmarshalCommand(1, buffer.Value[2:]) assert.Error(err).IsNil() sa2, ok := cmd.(*protocol.CommandSwitchAccount) assert.Bool(ok).IsTrue() assert.Pointer(sa.Host).IsNil() assert.Pointer(sa2.Host).IsNil() netassert.Port(sa.Port).Equals(sa2.Port) assert.String(sa.ID).Equals(sa2.ID.String()) assert.Uint16(sa.AlterIds.Value()).Equals(sa2.AlterIds.Value()) assert.Byte(byte(sa.Level)).Equals(byte(sa2.Level)) assert.Byte(sa.ValidMin).Equals(sa2.ValidMin) }
func TestDefaultIPAddress(t *testing.T) { v2testing.Current(t) socksConfig, err := config.CreateInboundConnectionConfig("socks", []byte(`{}`)) assert.Error(err).IsNil() assert.String(socksConfig.(*SocksConfig).IP()).Equals("127.0.0.1") }
func TestHopByHopHeadersStrip(t *testing.T) { v2testing.Current(t) rawRequest := `GET /pkg/net/http/ HTTP/1.1 Host: golang.org Connection: keep-alive,Foo, Bar Foo: foo Bar: bar Proxy-Connection: keep-alive Proxy-Authenticate: abc User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X; de-de) AppleWebKit/523.10.3 (KHTML, like Gecko) Version/3.0.4 Safari/523.10 Accept-Encoding: gzip Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7 Cache-Control: no-cache Accept-Language: de,en;q=0.7,en-us;q=0.3 ` b := bufio.NewReader(strings.NewReader(rawRequest)) req, err := http.ReadRequest(b) assert.Error(err).IsNil() assert.StringLiteral(req.Header.Get("Foo")).Equals("foo") assert.StringLiteral(req.Header.Get("Bar")).Equals("bar") assert.StringLiteral(req.Header.Get("Connection")).Equals("keep-alive,Foo, Bar") assert.StringLiteral(req.Header.Get("Proxy-Connection")).Equals("keep-alive") assert.StringLiteral(req.Header.Get("Proxy-Authenticate")).Equals("abc") StripHopByHopHeaders(req) assert.StringLiteral(req.Header.Get("Connection")).Equals("close") assert.StringLiteral(req.Header.Get("Foo")).Equals("") assert.StringLiteral(req.Header.Get("Bar")).Equals("") assert.StringLiteral(req.Header.Get("Proxy-Connection")).Equals("") assert.StringLiteral(req.Header.Get("Proxy-Authenticate")).Equals("") }
func TestRepoVersion(t *testing.T) { v2testing.Current(t) version, err := RepoVersionHead() assert.Error(err).IsNil() assert.Int(len(version)).GreaterThan(0) }
func TestRevParse(t *testing.T) { v2testing.Current(t) rev, err := RevParse("HEAD") assert.Error(err).IsNil() assert.Int(len(rev)).GreaterThan(0) }
func TestRequestSerialization(t *testing.T) { v2testing.Current(t) user := protocol.NewUser( protocol.NewID(uuid.New()), protocol.UserLevelUntrusted, 0, "*****@*****.**") expectedRequest := &protocol.RequestHeader{ Version: 1, User: user, Command: protocol.RequestCommandTCP, Option: protocol.RequestOption(0), Address: v2net.DomainAddress("www.v2ray.com"), Port: v2net.Port(443), } buffer := alloc.NewBuffer().Clear() client := NewClientSession(protocol.DefaultIDHash) client.EncodeRequestHeader(expectedRequest, buffer) userValidator := protocol.NewTimedUserValidator(protocol.DefaultIDHash) userValidator.Add(user) server := NewServerSession(userValidator) actualRequest, err := server.DecodeRequestHeader(buffer) assert.Error(err).IsNil() assert.Byte(expectedRequest.Version).Equals(actualRequest.Version) assert.Byte(byte(expectedRequest.Command)).Equals(byte(actualRequest.Command)) assert.Byte(byte(expectedRequest.Option)).Equals(byte(actualRequest.Option)) netassert.Address(expectedRequest.Address).Equals(actualRequest.Address) netassert.Port(expectedRequest.Port).Equals(actualRequest.Port) }
func TestWrongProtocolVersion(t *testing.T) { v2testing.Current(t) buffer := alloc.NewBuffer().Clear().AppendBytes(6, 1, 0) _, _, err := ReadAuthentication(buffer) assert.Error(err).Equals(proxy.ErrorInvalidProtocolVersion) }
func TestZeroAuthenticationMethod(t *testing.T) { v2testing.Current(t) buffer := alloc.NewBuffer().Clear().AppendBytes(5, 0) _, _, err := ReadAuthentication(buffer) assert.Error(err).Equals(proxy.ErrorInvalidAuthentication) }
func TestSingleBytePayload(t *testing.T) { v2testing.Current(t) buffer := alloc.NewSmallBuffer().Clear().AppendBytes(1) _, err := ReadRequest(buffer, nil, false) assert.Error(err).Equals(transport.ErrorCorruptedPacket) }
func TestResponseWrite(t *testing.T) { v2testing.Current(t) response := Socks5Response{ socksVersion, ErrorSuccess, AddrTypeIPv4, [4]byte{0x72, 0x72, 0x72, 0x72}, "", [16]byte{}, v2net.Port(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) }
func TestWrongAddressType(t *testing.T) { v2testing.Current(t) buffer := alloc.NewSmallBuffer().Clear().AppendBytes(5) _, err := ReadRequest(buffer, nil, false) assert.Error(err).Equals(transport.ErrorCorruptedPacket) }
func TestBufferedReader(t *testing.T) { v2testing.Current(t) content := alloc.NewLargeBuffer() len := content.Len() reader := NewBufferedReader(content) assert.Bool(reader.Cached()).IsTrue() payload := make([]byte, 16) nBytes, err := reader.Read(payload) assert.Int(nBytes).Equals(16) assert.Error(err).IsNil() len2 := content.Len() assert.Int(len - len2).GreaterThan(16) nBytes, err = reader.Read(payload) assert.Int(nBytes).Equals(16) assert.Error(err).IsNil() assert.Int(content.Len()).Equals(len2) reader.SetCached(false) payload2 := alloc.NewBuffer() reader.Read(payload2.Value) assert.Int(content.Len()).Equals(len2) reader.Read(payload2.Value) assert.Int(content.Len()).LessThan(len2) }
func TestInvalidStringLiteralJson(t *testing.T) { v2testing.Current(t) var s StringLiteral err := json.Unmarshal([]byte("1"), &s) assert.Error(err).IsNotNil() }
func TestInvalidIdJson(t *testing.T) { v2testing.Current(t) user := new(User) err := json.Unmarshal([]byte(`{"id": "1234"}`), user) assert.Error(err).IsNotNil() }
func TestHttpProxy(t *testing.T) { v2testing.Current(t) httpServer := &v2http.Server{ Port: v2net.Port(50042), PathHandler: make(map[string]http.HandlerFunc), } _, err := httpServer.Start() assert.Error(err).IsNil() defer httpServer.Close() assert.Error(InitializeServerSetOnce("test_5")).IsNil() transport := &http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { return url.Parse("http://127.0.0.1:50040/") }, } client := &http.Client{ Transport: transport, } resp, err := client.Get("http://127.0.0.1:50042/") assert.Error(err).IsNil() assert.Int(resp.StatusCode).Equals(200) content, err := ioutil.ReadAll(resp.Body) assert.Error(err).IsNil() assert.StringLiteral(string(content)).Equals("Home") CloseAllServers() }
func TestBuildAndRun(t *testing.T) { v2testing.Current(t) gopath := os.Getenv("GOPATH") goOS := parseOS(runtime.GOOS) goArch := parseArch(runtime.GOARCH) target := filepath.Join(gopath, "src", "v2ray_test") if goOS == Windows { target += ".exe" } 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.StringLiteral(errStr).Equals("") os.Remove(target) }
func TestDokodemoTCP(t *testing.T) { v2testing.Current(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: "dokodemo-door", SettingsValue: []byte(`{ "address": "127.0.0.1", "port": ` + port.String() + `, "network": "tcp", "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() tcpClient, err := net.DialTCP("tcp", nil, &net.TCPAddr{ IP: []byte{127, 0, 0, 1}, Port: int(pointPort), Zone: "", }) assert.Error(err).IsNil() tcpClient.Write([]byte(data2Send)) tcpClient.CloseWrite() response := make([]byte, 1024) nBytes, err := tcpClient.Read(response) assert.Error(err).IsNil() tcpClient.Close() assert.StringLiteral("Processed: " + data2Send).Equals(string(response[:nBytes])) }
func TestSinglePacket(t *testing.T) { v2testing.Current(t) port := v2nettesting.PickPort() 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() freedom := &FreedomConnection{} traffic := ray.NewRay() data2Send := "Data to be sent to remote" payload := alloc.NewSmallBuffer().Clear().Append([]byte(data2Send)) packet := v2net.NewPacket(v2net.TCPDestination(v2net.IPAddress([]byte{127, 0, 0, 1}), port), payload, false) err = freedom.Dispatch(packet, traffic) assert.Error(err).IsNil() close(traffic.InboundInput()) respPayload := <-traffic.InboundOutput() defer respPayload.Release() assert.Bytes(respPayload.Value).Equals([]byte("Processed: Data to be sent to remote")) _, open := <-traffic.InboundOutput() assert.Bool(open).IsFalse() tcpServer.Close() }
func TestBuildMacOS(t *testing.T) { v2testing.Current(t) binPath = filepath.Join(os.Getenv("GOPATH"), "testing") cleanBinPath() build("macos", "amd64", true, "test", "metadata.txt") 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", "metadata.txt") 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", "metadata.txt") 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 TestSocksUdpSend(t *testing.T) { v2testing.Current(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", UDP: 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.StringLiteral(och.Destination.String()).Equals("udp:8.8.4.4:53") }