func TestDomainNotMatchingDomain(t *testing.T) {
	v2testing.Current(t)

	rawJson := `{
    "type": "field",
    "domain": ["google.com", "v2ray.com"],
    "tag": "test"
  }`
	rule := parseRule([]byte(rawJson))
	dest := v2net.TCPDestination(v2net.DomainAddress("baidu.com"), 80)
	assert.Bool(rule.Apply(dest)).IsFalse()

	dest = v2net.TCPDestination(v2net.DomainAddress("www.google.com"), 80)
	assert.Bool(rule.Apply(dest)).IsTrue()
}
Esempio n. 2
0
func TestDomainAddressEquals(t *testing.T) {
	assert := assert.On(t)

	addr := v2net.DomainAddress("v2ray.com")
	assert.Bool(addr.Equals(nil)).IsFalse()

	addr2 := v2net.DomainAddress("v2ray.com")
	assert.Bool(addr.Equals(addr2)).IsTrue()

	addr3 := v2net.DomainAddress("www.v2ray.com")
	assert.Bool(addr.Equals(addr3)).IsFalse()

	addr4 := v2net.IPAddress([]byte{1, 3, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6})
	assert.Bool(addr.Equals(addr4)).IsFalse()
}
Esempio n. 3
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)
}
Esempio n. 4
0
func ReadUDPRequest(packet []byte) (request Socks5UDPRequest, err error) {
	// packet[0] and packet[1] are reserved
	request.Fragment = packet[2]

	addrType := packet[3]
	var dataBegin int

	switch addrType {
	case AddrTypeIPv4:
		ip := packet[4:8]
		port := binary.BigEndian.Uint16(packet[8:10])
		request.Address = v2net.IPAddress(ip, port)
		dataBegin = 10
	case AddrTypeIPv6:
		ip := packet[4:20]
		port := binary.BigEndian.Uint16(packet[20:22])
		request.Address = v2net.IPAddress(ip, port)
		dataBegin = 22
	case AddrTypeDomain:
		domainLength := int(packet[4])
		domain := string(packet[5 : 5+domainLength])
		port := binary.BigEndian.Uint16(packet[5+domainLength : 5+domainLength+2])
		request.Address = v2net.DomainAddress(domain, port)
		dataBegin = 5 + domainLength + 2
	default:
		log.Warning("Unknown address type %d", addrType)
		err = ErrorUnknownAddressType
		return
	}

	request.Data = make([]byte, len(packet)-dataBegin)
	copy(request.Data, packet[dataBegin:])

	return
}
Esempio n. 5
0
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)
}
Esempio n. 6
0
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)
}
Esempio n. 7
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)
}
Esempio n. 8
0
func ReadVMessUDP(buffer []byte, userset user.UserSet) (*VMessUDP, error) {
	userHash := buffer[:user.IDBytesLen]
	userId, timeSec, valid := userset.GetUser(userHash)
	if !valid {
		return nil, errors.NewAuthenticationError(userHash)
	}

	buffer = buffer[user.IDBytesLen:]
	aesCipher, err := aes.NewCipher(userId.CmdKey())
	if err != nil {
		return nil, err
	}
	aesStream := cipher.NewCFBDecrypter(aesCipher, user.Int64Hash(timeSec))
	aesStream.XORKeyStream(buffer, buffer)

	fnvHash := binary.BigEndian.Uint32(buffer[:4])
	fnv1a := fnv.New32a()
	fnv1a.Write(buffer[4:])
	fnvHashActual := fnv1a.Sum32()

	if fnvHash != fnvHashActual {
		log.Warning("Unexpected fhv hash %d, should be %d", fnvHashActual, fnvHash)
		return nil, errors.NewCorruptedPacketError()
	}

	buffer = buffer[4:]

	vmess := &VMessUDP{
		user:    *userId,
		version: buffer[0],
		token:   binary.BigEndian.Uint16(buffer[1:3]),
	}

	// buffer[3] is reserved

	port := binary.BigEndian.Uint16(buffer[4:6])
	addrType := buffer[6]
	var address v2net.Address
	switch addrType {
	case addrTypeIPv4:
		address = v2net.IPAddress(buffer[7:11], port)
		buffer = buffer[11:]
	case addrTypeIPv6:
		address = v2net.IPAddress(buffer[7:23], port)
		buffer = buffer[23:]
	case addrTypeDomain:
		domainLength := buffer[7]
		domain := string(buffer[8 : 8+domainLength])
		address = v2net.DomainAddress(domain, port)
		buffer = buffer[8+domainLength:]
	default:
		log.Warning("Unexpected address type %d", addrType)
		return nil, errors.NewCorruptedPacketError()
	}

	vmess.address = address
	vmess.data = buffer

	return vmess, nil
}
Esempio n. 9
0
func BenchmarkVMessRequestWriting(b *testing.B) {
	id, err := uuid.ParseString("2b2966ac-16aa-4fbf-8d81-c5f172a3da51")
	assert.Error(err).IsNil()

	userId := vmess.NewID(id)
	userSet := protocoltesting.MockUserSet{[]*vmess.User{}, make(map[string]int), make(map[string]Timestamp)}

	testUser := &vmess.User{
		ID: userId,
	}
	userSet.AddUser(testUser)

	request := new(VMessRequest)
	request.Version = byte(0x01)
	request.User = testUser

	randBytes := make([]byte, 36)
	rand.Read(randBytes)
	request.RequestIV = randBytes[:16]
	request.RequestKey = randBytes[16:32]
	request.ResponseHeader = randBytes[32:]

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

	for i := 0; i < b.N; i++ {
		request.ToBytes(NewRandomTimestampGenerator(Timestamp(time.Now().Unix()), 30), nil)
	}
}
Esempio n. 10
0
func BenchmarkVMessRequestWriting(b *testing.B) {
	id, err := uuid.ParseString("2b2966ac-16aa-4fbf-8d81-c5f172a3da51")
	assert.Error(err).IsNil()

	userId := vmess.NewID(id)
	userSet := mocks.MockUserSet{[]vmess.User{}, make(map[string]int), make(map[string]int64)}

	testUser := &TestUser{
		id: userId,
	}
	userSet.AddUser(testUser)

	request := new(VMessRequest)
	request.Version = byte(0x01)
	request.User = testUser

	randBytes := make([]byte, 36)
	rand.Read(randBytes)
	request.RequestIV = randBytes[:16]
	request.RequestKey = randBytes[16:32]
	request.ResponseHeader = randBytes[32:]

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

	for i := 0; i < b.N; i++ {
		request.ToBytes(user.NewTimeHash(user.HMACHash{}), user.GenerateRandomInt64InRange, nil)
	}
}
Esempio n. 11
0
func TestOwnHosts(t *testing.T) {
	v2testing.Current(t)

	rawJson := `{
    "ownHosts": [
      "127.0.0.1",
      "google.com"
    ]
  }`

	config := new(Config)
	err := json.Unmarshal([]byte(rawJson), config)
	assert.Error(err).IsNil()
	assert.Bool(config.IsOwnHost(v2net.IPAddress([]byte{127, 0, 0, 1}))).IsTrue()
	assert.Bool(config.IsOwnHost(v2net.DomainAddress("google.com"))).IsTrue()
	assert.Bool(config.IsOwnHost(v2net.DomainAddress("local.v2ray.com"))).IsTrue()
	assert.Bool(config.IsOwnHost(v2net.DomainAddress("v2ray.com"))).IsFalse()
}
Esempio n. 12
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()
}
Esempio n. 13
0
func TestVMessSerialization(t *testing.T) {
	assert := unit.Assert(t)

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

	userSet := mocks.MockUserSet{[]user.ID{}, make(map[string]int), make(map[string]int64)}
	userSet.AddUser(user.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)

	mockTime := int64(1823730)
	buffer, err := request.ToBytes(user.NewTimeHash(user.HMACHash{}), func(base int64, delta int) int64 { return mockTime }, nil)
	if err != nil {
		t.Fatal(err)
	}

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

	requestReader := NewVMessRequestReader(&userSet)
	actualRequest, err := requestReader.Read(bytes.NewReader(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())
}
Esempio n. 14
0
func ReadRequest(reader io.Reader) (*Request, error) {
	buffer := alloc.NewSmallBuffer()
	defer buffer.Release()

	_, err := v2net.ReadAllBytes(reader, buffer.Value[:1])
	if err != nil {
		log.Error("Shadowsocks: Failed to read address type: ", err)
		return nil, transport.CorruptedPacket
	}

	request := new(Request)

	addrType := buffer.Value[0]
	switch addrType {
	case AddrTypeIPv4:
		_, err := v2net.ReadAllBytes(reader, buffer.Value[:4])
		if err != nil {
			log.Error("Shadowsocks: Failed to read IPv4 address: ", err)
			return nil, transport.CorruptedPacket
		}
		request.Address = v2net.IPAddress(buffer.Value[:4])
	case AddrTypeIPv6:
		_, err := v2net.ReadAllBytes(reader, buffer.Value[:16])
		if err != nil {
			log.Error("Shadowsocks: Failed to read IPv6 address: ", err)
			return nil, transport.CorruptedPacket
		}
		request.Address = v2net.IPAddress(buffer.Value[:16])
	case AddrTypeDomain:
		_, err := v2net.ReadAllBytes(reader, buffer.Value[:1])
		if err != nil {
			log.Error("Shadowsocks: Failed to read domain lenth: ", err)
			return nil, transport.CorruptedPacket
		}
		domainLength := int(buffer.Value[0])
		_, err = v2net.ReadAllBytes(reader, buffer.Value[:domainLength])
		if err != nil {
			log.Error("Shadowsocks: Failed to read domain: ", err)
			return nil, transport.CorruptedPacket
		}
		request.Address = v2net.DomainAddress(string(buffer.Value[:domainLength]))
	default:
		log.Error("Shadowsocks: Unknown address type: ", addrType)
		return nil, transport.CorruptedPacket
	}

	_, err = v2net.ReadAllBytes(reader, buffer.Value[:2])
	if err != nil {
		log.Error("Shadowsocks: Failed to read port: ", err)
		return nil, transport.CorruptedPacket
	}

	request.Port = v2net.PortFromBytes(buffer.Value[:2])
	return request, nil
}
Esempio n. 15
0
func ReadUDPRequest(packet []byte) (*Socks5UDPRequest, error) {
	if len(packet) < 5 {
		return nil, transport.CorruptedPacket
	}
	request := new(Socks5UDPRequest)

	// packet[0] and packet[1] are reserved
	request.Fragment = packet[2]

	addrType := packet[3]
	var dataBegin int

	switch addrType {
	case AddrTypeIPv4:
		if len(packet) < 10 {
			return nil, transport.CorruptedPacket
		}
		ip := packet[4:8]
		request.Port = v2net.PortFromBytes(packet[8:10])
		request.Address = v2net.IPAddress(ip)
		dataBegin = 10
	case AddrTypeIPv6:
		if len(packet) < 22 {
			return nil, transport.CorruptedPacket
		}
		ip := packet[4:20]
		request.Port = v2net.PortFromBytes(packet[20:22])
		request.Address = v2net.IPAddress(ip)
		dataBegin = 22
	case AddrTypeDomain:
		domainLength := int(packet[4])
		if len(packet) < 5+domainLength+2 {
			return nil, transport.CorruptedPacket
		}
		domain := string(packet[5 : 5+domainLength])
		request.Port = v2net.PortFromBytes(packet[5+domainLength : 5+domainLength+2])
		maybeIP := net.ParseIP(domain)
		if maybeIP != nil {
			request.Address = v2net.IPAddress(maybeIP)
		} else {
			request.Address = v2net.DomainAddress(domain)
		}
		dataBegin = 5 + domainLength + 2
	default:
		log.Warning("Unknown address type ", addrType)
		return nil, ErrorUnknownAddressType
	}

	if len(packet) > dataBegin {
		request.Data = alloc.NewBuffer().Clear().Append(packet[dataBegin:])
	}

	return request, nil
}
Esempio n. 16
0
func TestVMessSerialization(t *testing.T) {
	v2testing.Current(t)

	id, err := uuid.ParseString("2b2966ac-16aa-4fbf-8d81-c5f172a3da51")
	assert.Error(err).IsNil()

	userId := vmess.NewID(id)

	testUser := &vmess.User{
		ID: userId,
	}

	userSet := protocoltesting.MockUserSet{[]*vmess.User{}, make(map[string]int), make(map[string]Timestamp)}
	userSet.AddUser(testUser)

	request := new(VMessRequest)
	request.Version = byte(0x01)
	request.User = testUser

	randBytes := make([]byte, 36)
	_, err = rand.Read(randBytes)
	assert.Error(err).IsNil()
	request.RequestIV = randBytes[:16]
	request.RequestKey = randBytes[16:32]
	request.ResponseHeader = randBytes[32:]

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

	mockTime := Timestamp(1823730)

	buffer, err := request.ToBytes(&FakeTimestampGenerator{timestamp: mockTime}, nil)
	if err != nil {
		t.Fatal(err)
	}

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

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

	assert.Byte(actualRequest.Version).Named("Version").Equals(byte(0x01))
	assert.String(actualRequest.User.ID).Named("UserId").Equals(request.User.ID.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).Named("Address").Equals(request.Address.String())
}
Esempio n. 17
0
func TestDomainRule(t *testing.T) {
	assert := assert.On(t)

	rule := ParseRule([]byte(`{
    "type": "field",
    "domain": [
      "ooxx.com",
      "oxox.com",
      "regexp:\\.cn$"
    ],
    "network": "tcp",
    "outboundTag": "direct"
  }`))
	assert.Pointer(rule).IsNotNil()
	assert.Bool(rule.Apply(v2net.TCPDestination(v2net.DomainAddress("www.ooxx.com"), 80))).IsTrue()
	assert.Bool(rule.Apply(v2net.TCPDestination(v2net.DomainAddress("www.aabb.com"), 80))).IsFalse()
	assert.Bool(rule.Apply(v2net.TCPDestination(v2net.IPAddress([]byte{127, 0, 0, 1}), 80))).IsFalse()
	assert.Bool(rule.Apply(v2net.TCPDestination(v2net.DomainAddress("www.12306.cn"), 80))).IsTrue()
	assert.Bool(rule.Apply(v2net.TCPDestination(v2net.DomainAddress("www.acn.com"), 80))).IsFalse()
}
Esempio n. 18
0
func (request *Socks5Request) Destination() v2net.Address {
	switch request.AddrType {
	case AddrTypeIPv4:
		return v2net.IPAddress(request.IPv4[:], request.Port)
	case AddrTypeIPv6:
		return v2net.IPAddress(request.IPv6[:], request.Port)
	case AddrTypeDomain:
		return v2net.DomainAddress(request.Domain, request.Port)
	default:
		panic("Unknown address type")
	}
}
Esempio n. 19
0
func TestDomainAddress(t *testing.T) {
	v2testing.Current(t)

	domain := "v2ray.com"
	addr := v2net.DomainAddress(domain)

	v2netassert.Address(addr).IsDomain()
	v2netassert.Address(addr).IsNotIPv6()
	v2netassert.Address(addr).IsNotIPv4()
	assert.StringLiteral(addr.Domain()).Equals(domain)
	assert.String(addr).Equals("v2ray.com")
}
Esempio n. 20
0
func TestPortMatching(t *testing.T) {
	assert := unit.Assert(t)

	rule := &FieldRule{
		Port: &v2nettesting.PortRange{
			FromValue: 0,
			ToValue:   100,
		},
	}
	dest := v2net.NewTCPDestination(v2net.DomainAddress("www.v2ray.com", 80))
	assert.Bool(rule.Apply(dest)).IsTrue()
}
Esempio n. 21
0
func TestDomainAddress(t *testing.T) {
	assert := assert.On(t)

	domain := "v2ray.com"
	addr := v2net.DomainAddress(domain)

	assert.Address(addr).IsDomain()
	assert.Address(addr).IsNotIPv6()
	assert.Address(addr).IsNotIPv4()
	assert.String(addr.Domain()).Equals(domain)
	assert.Address(addr).EqualsString("v2ray.com")
}
Esempio n. 22
0
func NewDokodemoDoor(dispatcher app.PacketDispatcher, config *json.DokodemoConfig) *DokodemoDoor {
	d := &DokodemoDoor{
		config:     config,
		dispatcher: dispatcher,
	}
	ip := net.ParseIP(config.Host)
	if ip != nil {
		d.address = v2net.IPAddress(ip, uint16(config.Port))
	} else {
		d.address = v2net.DomainAddress(config.Host, uint16(config.Port))
	}
	return d
}
Esempio n. 23
0
func TestSimpleRouter(t *testing.T) {
	v2testing.Current(t)

	router := NewRouter().AddRule(
		&Rule{
			Tag:       "test",
			Condition: NewNetworkMatcher(v2net.Network("tcp").AsList()),
		})

	tag, err := router.TakeDetour(v2net.TCPDestination(v2net.DomainAddress("v2ray.com"), 80))
	assert.Error(err).IsNil()
	assert.StringLiteral(tag).Equals("test")
}
Esempio n. 24
0
func TestOTARequest(t *testing.T) {
	v2testing.Current(t)

	buffer := alloc.NewSmallBuffer().Clear()
	buffer.AppendBytes(0x13, 13, 119, 119, 119, 46, 118, 50, 114, 97, 121, 46, 99, 111, 109, 0, 0, 239, 115, 52, 212, 178, 172, 26, 6, 168, 0)

	auth := NewAuthenticator(HeaderKeyGenerator(
		[]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5},
		[]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5}))
	request, err := ReadRequest(buffer, auth, false)
	assert.Error(err).IsNil()
	netassert.Address(request.Address).Equals(v2net.DomainAddress("www.v2ray.com"))
	assert.Bool(request.OTA).IsTrue()
}
Esempio n. 25
0
func (request *Socks5Request) Destination() v2net.Destination {
	var address v2net.Address
	switch request.AddrType {
	case AddrTypeIPv4:
		address = v2net.IPAddress(request.IPv4[:], request.Port)
	case AddrTypeIPv6:
		address = v2net.IPAddress(request.IPv6[:], request.Port)
	case AddrTypeDomain:
		address = v2net.DomainAddress(request.Domain, request.Port)
	default:
		panic("Unknown address type")
	}
	return v2net.NewTCPDestination(address)
}
Esempio n. 26
0
func TestSimpleRouter(t *testing.T) {
	v2testing.Current(t)

	router := NewRouter().AddRule(
		&testinconfig.TestRule{
			TagValue: "test",
			Function: func(dest v2net.Destination) bool {
				return dest.IsTCP()
			},
		})

	tag, err := router.TakeDetour(v2net.TCPDestination(v2net.DomainAddress("v2ray.com"), 80))
	assert.Error(err).IsNil()
	assert.StringLiteral(tag).Equals("test")
}
Esempio n. 27
0
func TestDialDomain(t *testing.T) {
	assert := assert.On(t)

	server := &tcp.Server{
		Port: v2nettesting.PickPort(),
	}
	dest, err := server.Start()
	assert.Error(err).IsNil()
	defer server.Close()

	conn, err := DialToDest(nil, v2net.TCPDestination(v2net.DomainAddress("local.v2ray.com"), dest.Port()))
	assert.Error(err).IsNil()
	assert.String(conn.RemoteAddr().String()).Equals("127.0.0.1:" + dest.Port().String())
	conn.Close()
}
Esempio n. 28
0
func TestUDPDestinationEquals(t *testing.T) {
	assert := assert.On(t)

	dest := v2net.UDPDestination(v2net.IPAddress([]byte{1, 2, 3, 4}), 80)
	assert.Bool(dest.Equals(nil)).IsFalse()

	dest2 := v2net.UDPDestination(v2net.IPAddress([]byte{1, 2, 3, 4}), 80)
	assert.Bool(dest.Equals(dest2)).IsTrue()

	dest3 := v2net.TCPDestination(v2net.IPAddress([]byte{1, 2, 3, 4}), 80)
	assert.Bool(dest.Equals(dest3)).IsFalse()

	dest4 := v2net.UDPDestination(v2net.DomainAddress("v2ray.com"), 80)
	assert.Bool(dest.Equals(dest4)).IsFalse()
}
Esempio n. 29
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)
}
Esempio n. 30
0
func (request *Socks5Request) Destination() v2net.Destination {
	switch request.AddrType {
	case AddrTypeIPv4:
		return v2net.TCPDestination(v2net.IPAddress(request.IPv4[:]), request.Port)
	case AddrTypeIPv6:
		return v2net.TCPDestination(v2net.IPAddress(request.IPv6[:]), request.Port)
	case AddrTypeDomain:
		maybeIP := net.ParseIP(request.Domain)
		if maybeIP != nil {
			return v2net.TCPDestination(v2net.IPAddress(maybeIP), request.Port)
		} else {
			return v2net.TCPDestination(v2net.DomainAddress(request.Domain), request.Port)
		}
	default:
		panic("Unknown address type")
	}
}