func TestReceiverUser(t *testing.T) {
	assert := assert.On(t)

	id := protocol.NewID(uuid.New())
	alters := protocol.NewAlterIDs(id, 100)
	account := &protocol.VMessAccount{
		ID:       id,
		AlterIDs: alters,
	}
	user := protocol.NewUser(account, protocol.UserLevel(0), "")
	rec := NewReceiver(v2net.TCPDestination(v2net.DomainAddress("v2ray.com"), 80), user)
	assert.Bool(rec.HasUser(user)).IsTrue()
	assert.Int(len(rec.Accounts)).Equals(1)

	id2 := protocol.NewID(uuid.New())
	alters2 := protocol.NewAlterIDs(id2, 100)
	account2 := &protocol.VMessAccount{
		ID:       id2,
		AlterIDs: alters2,
	}
	user2 := protocol.NewUser(account2, protocol.UserLevel(0), "")
	assert.Bool(rec.HasUser(user2)).IsFalse()

	rec.AddUser(user2)
	assert.Bool(rec.HasUser(user2)).IsTrue()
	assert.Int(len(rec.Accounts)).Equals(2)
}
func TestTimeOutSettings(t *testing.T) {
	assert := assert.On(t)

	reader := NewTimeOutReader(8, nil)
	assert.Int(reader.GetTimeOut()).Equals(8)
	reader.SetTimeOut(8) // no op
	assert.Int(reader.GetTimeOut()).Equals(8)
	reader.SetTimeOut(9)
	assert.Int(reader.GetTimeOut()).Equals(9)
}
func TestBufferClear(t *testing.T) {
	v2testing.Current(t)

	buffer := NewBuffer().Clear()
	defer buffer.Release()

	payload := "Bytes"
	buffer.Append([]byte(payload))
	assert.Int(buffer.Len()).Equals(len(payload))

	buffer.Clear()
	assert.Int(buffer.Len()).Equals(0)
}
func TestTCPBind(t *testing.T) {
	v2testing.Current(t)

	targetPort := v2nettesting.PickPort()
	tcpServer := &tcp.Server{
		Port: targetPort,
		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()
	defer tcpServer.Close()

	assert.Error(InitializeServerSetOnce("test_1")).IsNil()

	socksPort := v2net.Port(50000)

	conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{
		IP:   []byte{127, 0, 0, 1},
		Port: int(socksPort),
	})

	authRequest := socks5AuthMethodRequest(byte(0))
	nBytes, err := conn.Write(authRequest)
	assert.Int(nBytes).Equals(len(authRequest))
	assert.Error(err).IsNil()

	authResponse := make([]byte, 1024)
	nBytes, err = conn.Read(authResponse)
	assert.Error(err).IsNil()
	assert.Bytes(authResponse[:nBytes]).Equals([]byte{socks5Version, 0})

	connectRequest := socks5Request(byte(2), v2net.TCPDestination(v2net.IPAddress([]byte{127, 0, 0, 1}), targetPort))
	nBytes, err = conn.Write(connectRequest)
	assert.Int(nBytes).Equals(len(connectRequest))
	assert.Error(err).IsNil()

	connectResponse := make([]byte, 1024)
	nBytes, err = conn.Read(connectResponse)
	assert.Error(err).IsNil()
	assert.Bytes(connectResponse[:nBytes]).Equals([]byte{socks5Version, 7, 0, 1, 0, 0, 0, 0, 0, 0})

	conn.Close()

	CloseAllServers()
}
Exemple #5
0
func TestRepoVersion(t *testing.T) {
	v2testing.Current(t)

	version, err := RepoVersionHead()
	assert.Error(err).IsNil()
	assert.Int(len(version)).GreaterThan(0)
}
Exemple #6
0
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()
}
Exemple #7
0
func TestBadSegment(t *testing.T) {
	assert := assert.On(t)

	seg, buf := ReadSegment(nil)
	assert.Pointer(seg).IsNil()
	assert.Int(len(buf)).Equals(0)
}
Exemple #8
0
func TestACKSegment(t *testing.T) {
	assert := assert.On(t)

	seg := &AckSegment{
		Conv:            1,
		ReceivingWindow: 2,
		ReceivingNext:   3,
		Count:           5,
		NumberList:      []uint32{1, 3, 5, 7, 9},
		TimestampList:   []uint32{2, 4, 6, 8, 10},
	}

	nBytes := seg.ByteSize()
	bytes := seg.Bytes(nil)

	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.Byte(seg2.Count).Equals(seg.Count)
	for i := byte(0); i < seg2.Count; i++ {
		assert.Uint32(seg2.TimestampList[i]).Equals(seg.TimestampList[i])
		assert.Uint32(seg2.NumberList[i]).Equals(seg.NumberList[i])
	}
}
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())
}
Exemple #10
0
func TestNormalGetRequest(t *testing.T) {
	assert := assert.On(t)

	testPacketDispatcher := testdispatcher.NewTestPacketDispatcher(nil)

	port := v2nettesting.PickPort()
	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)
}
Exemple #11
0
func TestRevParse(t *testing.T) {
	v2testing.Current(t)

	rev, err := RevParse("HEAD")
	assert.Error(err).IsNil()
	assert.Int(len(rev)).GreaterThan(0)
}
Exemple #12
0
func TestSendingQueue(t *testing.T) {
	assert := assert.On(t)

	queue := NewSendingQueue(3)

	seg0 := alloc.NewBuffer()
	seg1 := alloc.NewBuffer()
	seg2 := alloc.NewBuffer()
	seg3 := alloc.NewBuffer()

	assert.Bool(queue.IsEmpty()).IsTrue()
	assert.Bool(queue.IsFull()).IsFalse()

	queue.Push(seg0)
	assert.Bool(queue.IsEmpty()).IsFalse()

	queue.Push(seg1)
	queue.Push(seg2)

	assert.Bool(queue.IsFull()).IsTrue()

	assert.Pointer(queue.Pop()).Equals(seg0)

	queue.Push(seg3)
	assert.Bool(queue.IsFull()).IsTrue()

	assert.Pointer(queue.Pop()).Equals(seg1)
	assert.Pointer(queue.Pop()).Equals(seg2)
	assert.Pointer(queue.Pop()).Equals(seg3)
	assert.Int(int(queue.Len())).Equals(0)
}
func TestSizedQueue(t *testing.T) {
	v2testing.Current(t)

	queue := collect.NewSizedQueue(2)
	assert.Pointer(queue.Put(1)).IsNil()
	assert.Pointer(queue.Put(2)).IsNil()
	assert.Int(queue.Put(3).(int)).Equals(1)
}
Exemple #14
0
func TestReceiverUser(t *testing.T) {
	v2testing.Current(t)

	id := proto.NewID(uuid.New())
	user := proto.NewUser(id, proto.UserLevel(0), 100, "")
	rec := NewReceiver(v2net.TCPDestination(v2net.DomainAddress("v2ray.com"), 80), user)
	assert.Bool(rec.HasUser(user)).IsTrue()
	assert.Int(len(rec.Accounts)).Equals(1)

	id2 := proto.NewID(uuid.New())
	user2 := proto.NewUser(id2, proto.UserLevel(0), 100, "")
	assert.Bool(rec.HasUser(user2)).IsFalse()

	rec.AddUser(user2)
	assert.Bool(rec.HasUser(user2)).IsTrue()
	assert.Int(len(rec.Accounts)).Equals(2)
}
func TestRecivingQueue(t *testing.T) {
	assert := assert.On(t)

	queue := NewReceivingQueue(2)
	queue.Put(alloc.NewSmallBuffer().Clear().AppendString("abcd"))
	queue.Put(alloc.NewSmallBuffer().Clear().AppendString("efg"))
	assert.Bool(queue.IsFull()).IsTrue()

	b := make([]byte, 1024)
	nBytes := queue.Read(b)
	assert.Int(nBytes).Equals(7)
	assert.String(string(b[:nBytes])).Equals("abcdefg")

	queue.Put(alloc.NewSmallBuffer().Clear().AppendString("1"))
	queue.Close()
	nBytes = queue.Read(b)
	assert.Int(nBytes).Equals(0)
}
func TestStringListParsingList(t *testing.T) {
	v2testing.Current(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)
}
func TestStringListParsingString(t *testing.T) {
	v2testing.Current(t)

	rawJson := `"abcd"`
	var strList StringList
	err := json.Unmarshal([]byte(rawJson), &strList)
	assert.Error(err).IsNil()
	assert.Int(strList.Len()).Equals(1)
}
func TestDefaultValueOfRandomAllocation(t *testing.T) {
	v2testing.Current(t)

	rawJson := `{
    "protocol": "vmess",
    "port": 1,
    "settings": {},
    "allocate": {
      "strategy": "random"
    }
  }`

	inboundDetourConfig := new(InboundDetourConfig)
	err := json.Unmarshal([]byte(rawJson), inboundDetourConfig)
	assert.Error(err).IsNil()
	assert.StringLiteral(inboundDetourConfig.Allocation.Strategy).Equals(AllocationStrategyRandom)
	assert.Int(inboundDetourConfig.Allocation.Concurrency).Equals(3)
	assert.Int(inboundDetourConfig.Allocation.Refresh).Equals(5)
}
func TestBufferedWriter(t *testing.T) {
	v2testing.Current(t)

	content := alloc.NewLargeBuffer().Clear()

	writer := NewBufferedWriter(content)
	assert.Bool(writer.Cached()).IsTrue()

	payload := make([]byte, 16)

	nBytes, err := writer.Write(payload)
	assert.Int(nBytes).Equals(16)
	assert.Error(err).IsNil()

	assert.Bool(content.IsEmpty()).IsTrue()

	writer.SetCached(false)
	assert.Int(content.Len()).Equals(16)
}
func TestConnectionReadTimeout(t *testing.T) {
	assert := assert.On(t)

	conn := NewConnection(1, &NoOpWriteCloser{}, nil, nil, NewSimpleAuthenticator())
	conn.SetReadDeadline(time.Now().Add(time.Second))

	b := make([]byte, 1024)
	nBytes, err := conn.Read(b)
	assert.Int(nBytes).Equals(0)
	assert.Error(err).IsNotNil()
}
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 TestConfigParsing(t *testing.T) {
	v2testing.Current(t)

	rawJson := `{
    "method": "aes-128-cfb",
    "password": "******"
  }`

	config := new(Config)
	err := json.Unmarshal([]byte(rawJson), config)
	assert.Error(err).IsNil()

	assert.Int(config.Cipher.KeySize()).Equals(16)
	assert.Bytes(config.Key).Equals([]byte{160, 224, 26, 2, 22, 110, 9, 80, 65, 52, 80, 20, 38, 243, 224, 241})
}
func TestConfigParsing(t *testing.T) {
	assert := assert.On(t)

	rawJson := `{
    "servers": ["8.8.8.8"]
  }`

	config := new(Config)
	err := json.Unmarshal([]byte(rawJson), config)
	assert.Error(err).IsNil()
	assert.Int(len(config.NameServers)).Equals(1)
	assert.Destination(config.NameServers[0]).IsUDP()
	assert.Address(config.NameServers[0].Address()).Equals(v2net.IPAddress([]byte{8, 8, 8, 8}))
	assert.Port(config.NameServers[0].Port()).Equals(v2net.Port(53))
}
func TestBufferPrepend(t *testing.T) {
	v2testing.Current(t)

	buffer := NewBuffer().Clear()
	defer buffer.Release()

	buffer.Append([]byte{'a', 'b', 'c'})
	buffer.Prepend([]byte{'x', 'y', 'z'})

	assert.Int(buffer.Len()).Equals(6)
	assert.Bytes(buffer.Value).Equals([]byte("xyzabc"))

	buffer.Prepend([]byte{'u', 'v', 'w'})
	assert.Bytes(buffer.Value).Equals([]byte("uvwxyzabc"))
}
Exemple #25
0
func TestSendingWindow(t *testing.T) {
	assert := assert.On(t)

	window := NewSendingWindow(5, nil, nil)
	window.Push(&DataSegment{
		Number: 0,
	})
	window.Push(&DataSegment{
		Number: 1,
	})
	window.Push(&DataSegment{
		Number: 2,
	})
	assert.Int(window.Len()).Equals(3)

	window.Remove(1)
	assert.Int(window.Len()).Equals(3)
	assert.Uint32(window.First().Number).Equals(0)

	window.Remove(0)
	assert.Int(window.Len()).Equals(1)
	assert.Uint32(window.First().Number).Equals(2)

	window.Remove(0)
	assert.Int(window.Len()).Equals(0)

	window.Push(&DataSegment{
		Number: 4,
	})
	assert.Int(window.Len()).Equals(1)
	assert.Uint32(window.First().Number).Equals(4)

	window.Push(&DataSegment{
		Number: 5,
	})
	assert.Int(window.Len()).Equals(2)

	window.Remove(1)
	assert.Int(window.Len()).Equals(2)

	window.Remove(0)
	assert.Int(window.Len()).Equals(0)
}
Exemple #26
0
func TestNormalGetRequest(t *testing.T) {
	v2testing.Current(t)

	testPacketDispatcher := testdispatcher.NewTestPacketDispatcher(nil)

	httpProxy := NewHttpProxyServer(&Config{}, testPacketDispatcher)
	defer httpProxy.Close()

	port := v2nettesting.PickPort()
	err := httpProxy.Listen(port)
	assert.Error(err).IsNil()
	netassert.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)
}
Exemple #27
0
func TestCacheDnsIPv4(t *testing.T) {
	v2testing.Current(t)

	cd := &CacheDns{
		Address: v2net.IPAddress([]byte{1, 2, 3, 4}),
	}

	buffer := alloc.NewBuffer().Clear()
	defer buffer.Release()

	nBytes, err := cd.Marshal(buffer)
	assert.Error(err).IsNil()
	assert.Int(nBytes).Equals(buffer.Len())

	cd2 := &CacheDns{}
	err = cd2.Unmarshal(buffer.Value)
	assert.Error(err).IsNil()
	netassert.Address(cd.Address).Equals(cd2.Address)
}
Exemple #28
0
func TestDokodemoTCP(t *testing.T) {
	v2testing.Current(t)

	tcpServer := &tcp.Server{
		Port: v2net.Port(50016),
		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()
	defer tcpServer.Close()

	assert.Error(InitializeServerSetOnce("test_2")).IsNil()

	dokodemoPortStart := v2net.Port(50011)
	dokodemoPortEnd := v2net.Port(50015)

	for port := dokodemoPortStart; port <= dokodemoPortEnd; port++ {
		conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{
			IP:   []byte{127, 0, 0, 1},
			Port: int(port),
		})

		payload := "dokodemo request."
		nBytes, err := conn.Write([]byte(payload))
		assert.Error(err).IsNil()
		assert.Int(nBytes).Equals(len(payload))

		conn.CloseWrite()

		response := make([]byte, 1024)
		nBytes, err = conn.Read(response)
		assert.Error(err).IsNil()
		assert.StringLiteral("Processed: " + payload).Equals(string(response[:nBytes]))
		conn.Close()
	}

	CloseAllServers()
}
func TestDynamicVMess(t *testing.T) {
	assert := assert.On(t)

	tcpServer := &tcp.Server{
		Port: v2net.Port(50032),
		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()
	defer tcpServer.Close()

	assert.Error(InitializeServerSetOnce("test_4")).IsNil()

	for i := 0; i < 100; i++ {
		conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{
			IP:   []byte{127, 0, 0, 1},
			Port: 50030,
		})
		assert.Error(err).IsNil()

		payload := "dokodemo request."
		nBytes, err := conn.Write([]byte(payload))
		assert.Error(err).IsNil()
		assert.Int(nBytes).Equals(len(payload))

		conn.CloseWrite()

		response := bytes.NewBuffer(nil)
		_, err = io.Copy(response, conn)
		assert.Error(err).IsNil()
		assert.String("Processed: " + payload).Equals(string(response.Bytes()))

		conn.Close()
	}

	CloseAllServers()
}
func TestShadowsocksTCP(t *testing.T) {
	v2testing.Current(t)

	tcpServer := &tcp.Server{
		Port: v2net.Port(50052),
		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()
	defer tcpServer.Close()

	assert.Error(InitializeServerServer("test_6")).IsNil()

	cipher, err := ssclient.NewCipher("aes-256-cfb", "v2ray-password")
	assert.Error(err).IsNil()

	rawAddr := []byte{1, 127, 0, 0, 1, 0xc3, 0x84} // 127.0.0.1:50052
	conn, err := ssclient.DialWithRawAddr(rawAddr, "127.0.0.1:50051", cipher)
	assert.Error(err).IsNil()

	payload := "shadowsocks request."
	nBytes, err := conn.Write([]byte(payload))
	assert.Error(err).IsNil()
	assert.Int(nBytes).Equals(len(payload))

	conn.Conn.(*net.TCPConn).CloseWrite()

	response := make([]byte, 1024)
	nBytes, err = conn.Read(response)
	assert.Error(err).IsNil()
	assert.StringLiteral("Processed: " + payload).Equals(string(response[:nBytes]))
	conn.Close()

	CloseAllServers()
}