func TestHubSocksOption(t *testing.T) { assert := assert.On(t) if os.Geteuid() != 0 { // This test case requires root permission. return } hub, err := ListenUDP(v2net.LocalHostIP, v2net.Port(0), ListenOption{ Callback: func(*buf.Buffer, *proxy.SessionInfo) {}, ReceiveOriginalDest: true, }) assert.Error(err).IsNil() conn := hub.Connection() fd, err := internal.GetSysFd(conn) assert.Error(err).IsNil() val, err := syscall.GetsockoptInt(fd, syscall.SOL_IP, syscall.IP_TRANSPARENT) assert.Error(err).IsNil() assert.Int(val).Equals(1) val, err = syscall.GetsockoptInt(fd, syscall.SOL_IP, syscall.IP_RECVORIGDSTADDR) assert.Error(err).IsNil() assert.Int(val).Equals(1) }
func TestSwitchAccount(t *testing.T) { assert := assert.On(t) sa := &protocol.CommandSwitchAccount{ Port: 1234, ID: uuid.New(), AlterIds: 1024, Level: 128, ValidMin: 16, } buffer := buf.New() err := MarshalCommand(sa, buffer) assert.Error(err).IsNil() cmd, err := UnmarshalCommand(1, buffer.BytesFrom(2)) assert.Error(err).IsNil() sa2, ok := cmd.(*protocol.CommandSwitchAccount) assert.Bool(ok).IsTrue() assert.Pointer(sa.Host).IsNil() assert.Pointer(sa2.Host).IsNil() assert.Port(sa.Port).Equals(sa2.Port) assert.String(sa.ID.String()).Equals(sa2.ID.String()) assert.Uint16(sa.AlterIds).Equals(sa2.AlterIds) assert.Byte(byte(sa.Level)).Equals(byte(sa2.Level)) assert.Byte(sa.ValidMin).Equals(sa2.ValidMin) }
func TestSocksInboundConfig(t *testing.T) { assert := assert.On(t) rawJson := `{ "auth": "password", "accounts": [ { "user": "******", "pass": "******" } ], "udp": false, "ip": "127.0.0.1", "timeout": 5 }` config := new(SocksServerConfig) err := json.Unmarshal([]byte(rawJson), &config) assert.Error(err).IsNil() message, err := config.Build() assert.Error(err).IsNil() iConfig, err := message.GetInstance() assert.Error(err).IsNil() socksConfig := iConfig.(*socks.ServerConfig) assert.Bool(socksConfig.AuthType == socks.AuthType_PASSWORD).IsTrue() assert.Int(len(socksConfig.Accounts)).Equals(1) assert.String(socksConfig.Accounts["my-username"]).Equals("my-password") assert.Bool(socksConfig.UdpEnabled).IsFalse() assert.Address(socksConfig.Address.AsAddress()).Equals(net.LocalHostIP) assert.Uint32(socksConfig.Timeout).Equals(5) }
func TestInvalidUserJson(t *testing.T) { assert := assert.On(t) user := new(User) err := json.Unmarshal([]byte(`{"email": 1234}`), user) assert.Error(err).IsNotNil() }
func TestWrongProtocolVersion(t *testing.T) { assert := assert.On(t) buffer := alloc.NewBuffer().Clear().AppendBytes(6, 1, 0) _, _, err := ReadAuthentication(buffer) assert.Error(err).Equals(proxy.ErrInvalidProtocolVersion) }
func TestRevParse(t *testing.T) { assert := assert.On(t) rev, err := RevParse("HEAD") assert.Error(err).IsNil() assert.Int(len(rev)).GreaterThan(0) }
func TestIPResolution(t *testing.T) { assert := assert.On(t) space := app.NewSpace() space.BindApp(proxyman.APP_ID_OUTBOUND_MANAGER, outbound.New()) space.BindApp(dispatcher.APP_ID, dispatchers.NewDefaultDispatcher(space)) r := router.NewRouter(&router.Config{}, space) space.BindApp(router.APP_ID, r) dnsServer := dnsserver.NewCacheServer(space, &dns.Config{ Hosts: map[string]*v2net.IPOrDomain{ "v2ray.com": v2net.NewIPOrDomain(v2net.LocalHostIP), }, }) space.BindApp(dns.APP_ID, dnsServer) freedom := NewFreedomConnection( &Config{DomainStrategy: Config_USE_IP}, space, &proxy.OutboundHandlerMeta{ Address: v2net.AnyIP, StreamSettings: &internet.StreamConfig{ Network: v2net.Network_RawTCP, }, }) space.Initialize() ipDest := freedom.ResolveIP(v2net.TCPDestination(v2net.DomainAddress("v2ray.com"), v2net.Port(80))) assert.Destination(ipDest).IsTCP() assert.Address(ipDest.Address).Equals(v2net.LocalHostIP) }
func TestACKSegment(t *testing.T) { assert := assert.On(t) seg := &AckSegment{ Conv: 1, ReceivingWindow: 2, ReceivingNext: 3, Timestamp: 10, NumberList: []uint32{1, 3, 5, 7, 9}, } nBytes := seg.ByteSize() bytes := make([]byte, nBytes) seg.Bytes()(bytes) assert.Int(len(bytes)).Equals(nBytes) iseg, _ := ReadSegment(bytes) seg2 := iseg.(*AckSegment) assert.Uint16(seg2.Conv).Equals(seg.Conv) assert.Uint32(seg2.ReceivingWindow).Equals(seg.ReceivingWindow) assert.Uint32(seg2.ReceivingNext).Equals(seg.ReceivingNext) assert.Int(len(seg2.NumberList)).Equals(len(seg.NumberList)) assert.Uint32(seg2.Timestamp).Equals(seg.Timestamp) for i, number := range seg2.NumberList { assert.Uint32(number).Equals(seg.NumberList[i]) } }
func TestDnsAdd(t *testing.T) { assert := assert.On(t) space := app.NewSpace() outboundHandlerManager := proxyman.NewDefaultOutboundHandlerManager() outboundHandlerManager.SetDefaultHandler( freedom.NewFreedomConnection( &freedom.Config{}, space, &proxy.OutboundHandlerMeta{ Address: v2net.AnyIP, StreamSettings: &internet.StreamSettings{ Type: internet.StreamConnectionTypeRawTCP, }, })) space.BindApp(proxyman.APP_ID_OUTBOUND_MANAGER, outboundHandlerManager) space.BindApp(dispatcher.APP_ID, dispatchers.NewDefaultDispatcher(space)) domain := "local.v2ray.com" server := NewCacheServer(space, &Config{ NameServers: []v2net.Destination{ v2net.UDPDestination(v2net.IPAddress([]byte{8, 8, 8, 8}), v2net.Port(53)), }, }) space.BindApp(APP_ID, server) space.Initialize() ips := server.Get(domain) assert.Int(len(ips)).Equals(1) assert.IP(ips[0].To4()).Equals(net.IP([]byte{127, 0, 0, 1})) }
func TestBlockHTTP(t *testing.T) { assert := assert.On(t) httpServer := &v2http.Server{ Port: net.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:50049/") assert.Error(err).IsNil() assert.Int(resp.StatusCode).Equals(403) CloseAllServers() }
func TestIPResolution(t *testing.T) { assert := assert.On(t) space := app.NewSpace() space.BindApp(proxyman.APP_ID_OUTBOUND_MANAGER, proxyman.NewDefaultOutboundHandlerManager()) space.BindApp(dispatcher.APP_ID, dispatchers.NewDefaultDispatcher(space)) r, _ := router.CreateRouter("rules", &rules.RouterRuleConfig{}, space) space.BindApp(router.APP_ID, r) dnsServer := dns.NewCacheServer(space, &dns.Config{ Hosts: map[string]net.IP{ "v2ray.com": net.IP([]byte{127, 0, 0, 1}), }, }) space.BindApp(dns.APP_ID, dnsServer) freedom := NewFreedomConnection( &Config{DomainStrategy: DomainStrategyUseIP}, space, &proxy.OutboundHandlerMeta{ Address: v2net.AnyIP, StreamSettings: &internet.StreamSettings{ Type: internet.StreamConnectionTypeRawTCP, }, }) space.Initialize() ipDest := freedom.ResolveIP(v2net.TCPDestination(v2net.DomainAddress("v2ray.com"), v2net.Port(80))) assert.Destination(ipDest).IsTCP() assert.Address(ipDest.Address()).Equals(v2net.LocalHostIP) }
func TestTCPRequest(t *testing.T) { assert := assert.On(t) request := &protocol.RequestHeader{ Version: Version, Command: protocol.RequestCommandTCP, Address: v2net.LocalHostIP, Option: RequestOptionOneTimeAuth, Port: 1234, User: &protocol.User{ Email: "*****@*****.**", Account: loader.NewTypedSettings(&Account{ Password: "******", CipherType: CipherType_CHACHA20, }), }, } data := alloc.NewLocalBuffer(256).Clear().AppendString("test string") cache := alloc.NewBuffer().Clear() writer, err := WriteTCPRequest(request, cache) assert.Error(err).IsNil() writer.Write(data) decodedRequest, reader, err := ReadTCPSession(request.User, cache) assert.Error(err).IsNil() assert.Address(decodedRequest.Address).Equals(request.Address) assert.Port(decodedRequest.Port).Equals(request.Port) decodedData, err := reader.Read() assert.Error(err).IsNil() assert.Bytes(decodedData.Value).Equals([]byte("test string")) }
func TestUDPEncoding(t *testing.T) { assert := assert.On(t) request := &protocol.RequestHeader{ Version: Version, Command: protocol.RequestCommandUDP, Address: v2net.LocalHostIP, Port: 1234, User: &protocol.User{ Email: "*****@*****.**", Account: loader.NewTypedSettings(&Account{ Password: "******", CipherType: CipherType_AES_128_CFB, Ota: Account_Disabled, }), }, } data := alloc.NewLocalBuffer(256).Clear().AppendString("test string") encodedData, err := EncodeUDPPacket(request, data) assert.Error(err).IsNil() decodedRequest, decodedData, err := DecodeUDPPacket(request.User, encodedData) assert.Error(err).IsNil() assert.Bytes(decodedData.Value).Equals(data.Value) assert.Address(decodedRequest.Address).Equals(request.Address) assert.Port(decodedRequest.Port).Equals(request.Port) }
func TestNext(t *testing.T) { assert := assert.On(t) uuid := New() uuid2 := uuid.Next() assert.Bool(uuid.Equals(uuid2)).IsFalse() }
func TestBuildMacOS(t *testing.T) { assert := assert.On(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 TestCmdSegment(t *testing.T) { assert := assert.On(t) seg := &CmdOnlySegment{ Conv: 1, Cmd: CommandPing, Option: SegmentOptionClose, SendingNext: 11, ReceivinNext: 13, PeerRTO: 15, } nBytes := seg.ByteSize() bytes := make([]byte, nBytes) seg.Bytes()(bytes) assert.Int(len(bytes)).Equals(nBytes) iseg, _ := ReadSegment(bytes) seg2 := iseg.(*CmdOnlySegment) assert.Uint16(seg2.Conv).Equals(seg.Conv) assert.Byte(byte(seg2.Command())).Equals(byte(seg.Command())) assert.Byte(byte(seg2.Option)).Equals(byte(seg.Option)) assert.Uint32(seg2.SendingNext).Equals(seg.SendingNext) assert.Uint32(seg2.ReceivinNext).Equals(seg.ReceivinNext) assert.Uint32(seg2.PeerRTO).Equals(seg.PeerRTO) }
func Test1ByteDataSegment(t *testing.T) { assert := assert.On(t) b := buf.NewLocal(512) b.AppendBytes('a') seg := &DataSegment{ Conv: 1, Timestamp: 3, Number: 4, SendingNext: 5, Data: b, } nBytes := seg.ByteSize() bytes := make([]byte, nBytes) seg.Bytes()(bytes) assert.Int(len(bytes)).Equals(nBytes) iseg, _ := ReadSegment(bytes) seg2 := iseg.(*DataSegment) assert.Uint16(seg2.Conv).Equals(seg.Conv) assert.Uint32(seg2.Timestamp).Equals(seg.Timestamp) assert.Uint32(seg2.SendingNext).Equals(seg.SendingNext) assert.Uint32(seg2.Number).Equals(seg.Number) assert.Bytes(seg2.Data.Bytes()).Equals(seg.Data.Bytes()) }
func TestHopByHopHeadersStrip(t *testing.T) { assert := assert.On(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.String(req.Header.Get("Foo")).Equals("foo") assert.String(req.Header.Get("Bar")).Equals("bar") assert.String(req.Header.Get("Connection")).Equals("keep-alive,Foo, Bar") assert.String(req.Header.Get("Proxy-Connection")).Equals("keep-alive") assert.String(req.Header.Get("Proxy-Authenticate")).Equals("abc") StripHopByHopHeaders(req) assert.String(req.Header.Get("Connection")).Equals("close") assert.String(req.Header.Get("Foo")).Equals("") assert.String(req.Header.Get("Bar")).Equals("") assert.String(req.Header.Get("Proxy-Connection")).Equals("") assert.String(req.Header.Get("Proxy-Authenticate")).Equals("") }
func TestUDPEncoding(t *testing.T) { assert := assert.On(t) request := &protocol.RequestHeader{ Version: Version, Command: protocol.RequestCommandUDP, Address: v2net.LocalHostIP, Port: 1234, User: &protocol.User{ Email: "*****@*****.**", Account: serial.ToTypedMessage(&Account{ Password: "******", CipherType: CipherType_AES_128_CFB, Ota: Account_Disabled, }), }, } data := buf.NewLocal(256) data.AppendSupplier(serial.WriteString("test string")) encodedData, err := EncodeUDPPacket(request, data) assert.Error(err).IsNil() decodedRequest, decodedData, err := DecodeUDPPacket(request.User, encodedData) assert.Error(err).IsNil() assert.Bytes(decodedData.Bytes()).Equals(data.Bytes()) assert.Address(decodedRequest.Address).Equals(request.Address) assert.Port(decodedRequest.Port).Equals(request.Port) }
func Test_Connect_wss_guess_reuse(t *testing.T) { assert := assert.On(t) (&Config{Pto: "", Path: "", ConnectionReuse: true}).Apply() i := 3 for i != 0 { conn, err := Dial(v2net.AnyIP, v2net.TCPDestination(v2net.DomainAddress("echo.websocket.org"), 443)) assert.Error(err).IsNil() conn.Write([]byte("echo")) s := make(chan int) go func() { buf := make([]byte, 4) conn.Read(buf) str := string(buf) if str != "echo" { assert.Fail("Data mismatch") } s <- 0 }() <-s if i == 0 { conn.SetDeadline(time.Now()) conn.SetReadDeadline(time.Now()) conn.SetWriteDeadline(time.Now()) conn.SetReusable(false) } conn.Close() i-- } }
func TestRepoVersion(t *testing.T) { assert := assert.On(t) version, err := RepoVersionHead() assert.Error(err).IsNil() assert.Int(len(version)).GreaterThan(0) }
func Test_listenWSAndDial(t *testing.T) { assert := assert.On(t) (&Config{Pto: "ws", Path: "ws"}).Apply() listen, err := ListenWS(v2net.DomainAddress("localhost"), 13142) assert.Error(err).IsNil() go func() { conn, err := listen.Accept() assert.Error(err).IsNil() conn.Close() conn, err = listen.Accept() assert.Error(err).IsNil() conn.Close() conn, err = listen.Accept() assert.Error(err).IsNil() conn.Close() listen.Close() }() conn, err := Dial(v2net.AnyIP, v2net.TCPDestination(v2net.DomainAddress("localhost"), 13142)) assert.Error(err).IsNil() conn.Close() <-time.After(time.Second * 5) conn, err = Dial(v2net.AnyIP, v2net.TCPDestination(v2net.DomainAddress("localhost"), 13142)) assert.Error(err).IsNil() conn.Close() <-time.After(time.Second * 15) conn, err = Dial(v2net.AnyIP, v2net.TCPDestination(v2net.DomainAddress("localhost"), 13142)) assert.Error(err).IsNil() conn.Close() }
func TestZeroAuthenticationMethod(t *testing.T) { assert := assert.On(t) buffer := alloc.NewBuffer().Clear().AppendBytes(5, 0) _, _, err := ReadAuthentication(buffer) assert.Error(err).Equals(proxy.ErrInvalidAuthentication) }
func TestBuildAndRun(t *testing.T) { assert := assert.On(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", "tools", "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.String(errStr).Equals("") os.Remove(target) }
func TestResponseWrite(t *testing.T) { assert := assert.On(t) response := Socks5Response{ socksVersion, ErrorSuccess, AddrTypeIPv4, [4]byte{0x72, 0x72, 0x72, 0x72}, "", [16]byte{}, v2net.Port(53), } buffer := alloc.NewLocalBuffer(2048).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).Equals(expectedBytes) }
func TestSimpleRouter(t *testing.T) { assert := assert.On(t) config := &Config{ Rule: []*RoutingRule{ { Tag: "test", NetworkList: &net.NetworkList{ Network: []net.Network{net.Network_TCP}, }, }, }, } space := app.NewSpace() ctx := app.ContextWithSpace(context.Background(), space) assert.Error(app.AddApplicationToSpace(ctx, new(dns.Config))).IsNil() assert.Error(app.AddApplicationToSpace(ctx, new(dispatcher.Config))).IsNil() assert.Error(app.AddApplicationToSpace(ctx, new(proxyman.OutboundConfig))).IsNil() assert.Error(app.AddApplicationToSpace(ctx, config)).IsNil() assert.Error(space.Initialize()).IsNil() r := FromSpace(space) ctx = proxy.ContextWithDestination(ctx, net.TCPDestination(net.DomainAddress("v2ray.com"), 80)) tag, err := r.TakeDetour(ctx) assert.Error(err).IsNil() assert.String(tag).Equals("test") }
func TestInvalidNetworkJson(t *testing.T) { assert := assert.On(t) var list NetworkList err := json.Unmarshal([]byte("0"), &list) assert.Error(err).IsNotNil() }
func TestBadSegment(t *testing.T) { assert := assert.On(t) seg, buf := ReadSegment(nil) assert.Pointer(seg).IsNil() assert.Int(len(buf)).Equals(0) }
func TestIPNet(t *testing.T) { assert := assert.On(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 TestNormalGetRequest(t *testing.T) { assert := assert.On(t) testPacketDispatcher := testdispatcher.NewTestPacketDispatcher(nil) port := v2net.Port(dice.Roll(20000) + 10000) httpProxy := NewServer( &Config{}, testPacketDispatcher, &proxy.InboundHandlerMeta{ Address: v2net.LocalHostIP, Port: port, StreamSettings: &internet.StreamSettings{ Type: internet.StreamConnectionTypeRawTCP, }}) defer httpProxy.Close() err := httpProxy.Start() assert.Error(err).IsNil() assert.Port(port).Equals(httpProxy.Port()) httpClient := &http.Client{} resp, err := httpClient.Get("http://127.0.0.1:" + port.String() + "/") assert.Error(err).IsNil() assert.Int(resp.StatusCode).Equals(400) }