Ejemplo n.º 1
0
func (this *HttpProxyServer) handleConnection(conn *hub.TCPConn) {
	defer conn.Close()
	reader := bufio.NewReader(conn)

	request, err := http.ReadRequest(reader)
	if err != nil {
		log.Warning("Failed to read http request: ", err)
		return
	}
	log.Info("Request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]")
	defaultPort := v2net.Port(80)
	if strings.ToLower(request.URL.Scheme) == "https" {
		defaultPort = v2net.Port(443)
	}
	host := request.Host
	if len(host) == 0 {
		host = request.URL.Host
	}
	dest, err := parseHost(host, defaultPort)
	if err != nil {
		log.Warning("Malformed proxy host (", host, "): ", err)
		return
	}
	if strings.ToUpper(request.Method) == "CONNECT" {
		this.handleConnect(request, dest, reader, conn)
	} else {
		this.handlePlainHTTP(request, dest, reader, conn)
	}
}
Ejemplo n.º 2
0
func (this *Server) handleConnection(conn internet.Connection) {
	defer conn.Close()
	timedReader := v2net.NewTimeOutReader(this.config.Timeout, conn)
	reader := bufio.NewReaderSize(timedReader, 2048)

	request, err := http.ReadRequest(reader)
	if err != nil {
		if err != io.EOF {
			log.Warning("HTTP: Failed to read http request: ", err)
		}
		return
	}
	log.Info("HTTP: Request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]")
	defaultPort := v2net.Port(80)
	if strings.ToLower(request.URL.Scheme) == "https" {
		defaultPort = v2net.Port(443)
	}
	host := request.Host
	if len(host) == 0 {
		host = request.URL.Host
	}
	dest, err := parseHost(host, defaultPort)
	if err != nil {
		log.Warning("HTTP: Malformed proxy host (", host, "): ", err)
		return
	}
	log.Access(conn.RemoteAddr(), request.URL, log.AccessAccepted, "")
	if strings.ToUpper(request.Method) == "CONNECT" {
		this.handleConnect(request, dest, reader, conn)
	} else {
		this.handlePlainHTTP(request, dest, reader, conn)
	}
}
Ejemplo n.º 3
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()
}
Ejemplo n.º 4
0
func (this *InboundConnectionConfig) UnmarshalJSON(data []byte) error {
	type JsonConfig struct {
		Port          uint16                   `json:"port"`
		Listen        *v2net.AddressJson       `json:"listen"`
		Protocol      string                   `json:"protocol"`
		StreamSetting *internet.StreamSettings `json:"streamSettings"`
		Settings      json.RawMessage          `json:"settings"`
	}

	jsonConfig := new(JsonConfig)
	if err := json.Unmarshal(data, jsonConfig); err != nil {
		return errors.New("Point: Failed to parse inbound config: " + err.Error())
	}
	this.Port = v2net.Port(jsonConfig.Port)
	this.ListenOn = v2net.AnyIP
	if jsonConfig.Listen != nil {
		if jsonConfig.Listen.Address.IsDomain() {
			return errors.New("Point: Unable to listen on domain address: " + jsonConfig.Listen.Address.Domain())
		}
		this.ListenOn = jsonConfig.Listen.Address
	}
	if jsonConfig.StreamSetting != nil {
		this.StreamSettings = jsonConfig.StreamSetting
	}

	this.Protocol = jsonConfig.Protocol
	this.Settings = jsonConfig.Settings
	return nil
}
Ejemplo n.º 5
0
func (this *Config) UnmarshalJSON(data []byte) error {
	type JsonConfig struct {
		Servers []v2net.AddressJson          `json:"servers"`
		Hosts   map[string]v2net.AddressJson `json:"hosts"`
	}
	jsonConfig := new(JsonConfig)
	if err := json.Unmarshal(data, jsonConfig); err != nil {
		return err
	}
	this.NameServers = make([]v2net.Destination, len(jsonConfig.Servers))
	for idx, server := range jsonConfig.Servers {
		this.NameServers[idx] = v2net.UDPDestination(server.Address, v2net.Port(53))
	}

	if jsonConfig.Hosts != nil {
		this.Hosts = make(map[string]net.IP)
		for domain, ip := range jsonConfig.Hosts {
			if ip.Address.IsDomain() {
				return errors.New(ip.Address.String() + " is not an IP.")
			}
			this.Hosts[domain] = ip.Address.IP()
		}
	}

	return nil
}
Ejemplo n.º 6
0
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.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).Equals(expectedBytes)
}
Ejemplo n.º 7
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)
}
Ejemplo n.º 8
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)
}
Ejemplo 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 := 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)
	}
}
Ejemplo 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 := 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)
	}
}
Ejemplo n.º 11
0
func TestServerList(t *testing.T) {
	assert := assert.On(t)

	list := NewServerList()
	list.AddServer(NewServerSpec(v2net.TCPDestination(v2net.LocalHostIP, v2net.Port(1)), AlwaysValid()))
	assert.Uint32(list.Size()).Equals(1)
	list.AddServer(NewServerSpec(v2net.TCPDestination(v2net.LocalHostIP, v2net.Port(2)), BeforeTime(time.Now().Add(time.Second))))
	assert.Uint32(list.Size()).Equals(2)

	server := list.GetServer(1)
	assert.Port(server.Destination().Port()).Equals(2)
	time.Sleep(2 * time.Second)
	server = list.GetServer(1)
	assert.Pointer(server).IsNil()

	server = list.GetServer(0)
	assert.Port(server.Destination().Port()).Equals(1)
}
Ejemplo n.º 12
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()
}
Ejemplo n.º 13
0
func (this *InboundDetourHandlerDynamic) pickUnusedPort() v2net.Port {
	delta := int(this.config.PortRange.To) - int(this.config.PortRange.From) + 1
	for {
		r := dice.Roll(delta)
		port := this.config.PortRange.From + v2net.Port(r)
		_, used := this.portsInUse[port]
		if !used {
			return port
		}
	}
}
Ejemplo n.º 14
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())
}
Ejemplo n.º 15
0
func TestNormalRequestParsing(t *testing.T) {
	assert := assert.On(t)

	buffer := alloc.NewSmallBuffer().Clear()
	buffer.AppendBytes(1, 127, 0, 0, 1, 0, 80)

	request, err := ReadRequest(buffer, nil, false)
	assert.Error(err).IsNil()
	assert.Address(request.Address).Equals(v2net.LocalHostIP)
	assert.Port(request.Port).Equals(v2net.Port(80))
	assert.Bool(request.OTA).IsFalse()
}
Ejemplo n.º 16
0
func TestNormalRequestParsing(t *testing.T) {
	v2testing.Current(t)

	buffer := alloc.NewSmallBuffer().Clear()
	buffer.AppendBytes(1, 127, 0, 0, 1, 0, 80)

	request, err := ReadRequest(buffer, nil, false)
	assert.Error(err).IsNil()
	netassert.Address(request.Address).Equals(v2net.IPAddress([]byte{127, 0, 0, 1}))
	netassert.Port(request.Port).Equals(v2net.Port(80))
	assert.Bool(request.OTA).IsFalse()
}
Ejemplo n.º 17
0
func TestUDPRequestParsing(t *testing.T) {
	v2testing.Current(t)

	buffer := alloc.NewSmallBuffer().Clear()
	buffer.AppendBytes(1, 127, 0, 0, 1, 0, 80, 1, 2, 3, 4, 5, 6)

	request, err := ReadRequest(buffer, nil, true)
	assert.Error(err).IsNil()
	netassert.Address(request.Address).Equals(v2net.IPAddress([]byte{127, 0, 0, 1}))
	netassert.Port(request.Port).Equals(v2net.Port(80))
	assert.Bool(request.OTA).IsFalse()
	assert.Bytes(request.UDPPayload.Value).Equals([]byte{1, 2, 3, 4, 5, 6})
}
Ejemplo n.º 18
0
func (server *Server) Start() (v2net.Destination, error) {
	conn, err := net.ListenUDP("udp", &net.UDPAddr{
		IP:   []byte{0, 0, 0, 0},
		Port: int(server.Port),
		Zone: "",
	})
	if err != nil {
		return nil, err
	}
	go server.handleConnection(conn)
	localAddr := conn.LocalAddr().(*net.UDPAddr)
	return v2net.UDPDestination(v2net.IPAddress(localAddr.IP), v2net.Port(localAddr.Port)), nil
}
Ejemplo n.º 19
0
func (server *Server) Start() (v2net.Destination, error) {
	listener, err := net.ListenTCP("tcp", &net.TCPAddr{
		IP:   []byte{0, 0, 0, 0},
		Port: int(server.Port),
		Zone: "",
	})
	if err != nil {
		return nil, err
	}
	go server.acceptConnections(listener)
	localAddr := listener.Addr().(*net.TCPAddr)
	return v2net.TCPDestination(v2net.IPAddress(localAddr.IP), v2net.Port(localAddr.Port)), nil
}
Ejemplo n.º 20
0
func (this *DokodemoDoor) HandleTCPConnection(conn internet.Connection) {
	defer conn.Close()

	var dest v2net.Destination
	if this.config.FollowRedirect {
		originalDest := GetOriginalDestination(conn)
		if originalDest != nil {
			log.Info("Dokodemo: Following redirect to: ", originalDest)
			dest = originalDest
		}
	}
	if dest == nil && this.address != nil && this.port > v2net.Port(0) {
		dest = v2net.TCPDestination(this.address, this.port)
	}

	if dest == nil {
		log.Info("Dokodemo: Unknown destination, stop forwarding...")
		return
	}
	log.Info("Dokodemo: Handling request to ", dest)

	ray := this.packetDispatcher.DispatchToOutbound(dest)
	defer ray.InboundOutput().Release()

	var inputFinish, outputFinish sync.Mutex
	inputFinish.Lock()
	outputFinish.Lock()

	reader := v2net.NewTimeOutReader(this.config.Timeout, conn)
	defer reader.Release()

	go func() {
		v2reader := v2io.NewAdaptiveReader(reader)
		defer v2reader.Release()

		v2io.Pipe(v2reader, ray.InboundInput())
		inputFinish.Unlock()
		ray.InboundInput().Close()
	}()

	go func() {
		v2writer := v2io.NewAdaptiveWriter(conn)
		defer v2writer.Release()

		v2io.Pipe(ray.InboundOutput(), v2writer)
		outputFinish.Unlock()
	}()

	outputFinish.Lock()
	inputFinish.Lock()
}
Ejemplo n.º 21
0
func (this *UDPHub) start() {
	this.accepting = true
	for this.accepting {
		buffer := alloc.NewBuffer()
		nBytes, addr, err := this.conn.ReadFromUDP(buffer.Value)
		if err != nil {
			buffer.Release()
			continue
		}
		buffer.Slice(0, nBytes)
		dest := v2net.UDPDestination(v2net.IPAddress(addr.IP), v2net.Port(addr.Port))
		go this.callback(buffer, dest)
	}
}
Ejemplo n.º 22
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()
}
Ejemplo n.º 23
0
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))
}
Ejemplo n.º 24
0
func TestServerPicker(t *testing.T) {
	assert := assert.On(t)

	list := NewServerList()
	list.AddServer(NewServerSpec(v2net.TCPDestination(v2net.LocalHostIP, v2net.Port(1)), AlwaysValid()))
	list.AddServer(NewServerSpec(v2net.TCPDestination(v2net.LocalHostIP, v2net.Port(2)), BeforeTime(time.Now().Add(time.Second))))
	list.AddServer(NewServerSpec(v2net.TCPDestination(v2net.LocalHostIP, v2net.Port(3)), BeforeTime(time.Now().Add(time.Second))))

	picker := NewRoundRobinServerPicker(list)
	server := picker.PickServer()
	assert.Port(server.Destination().Port()).Equals(1)
	server = picker.PickServer()
	assert.Port(server.Destination().Port()).Equals(2)
	server = picker.PickServer()
	assert.Port(server.Destination().Port()).Equals(3)
	server = picker.PickServer()
	assert.Port(server.Destination().Port()).Equals(1)

	time.Sleep(2 * time.Second)
	server = picker.PickServer()
	assert.Port(server.Destination().Port()).Equals(1)
	server = picker.PickServer()
	assert.Port(server.Destination().Port()).Equals(1)
}
Ejemplo n.º 25
0
func TestSocks4AuthenticationRequestRead(t *testing.T) {
	assert := assert.On(t)

	rawRequest := []byte{
		0x04, // version
		0x01, // command
		0x00, 0x35,
		0x72, 0x72, 0x72, 0x72,
	}
	_, request4, err := ReadAuthentication(bytes.NewReader(rawRequest))
	assert.Error(err).Equals(Socks4Downgrade)
	assert.Byte(request4.Version).Equals(0x04)
	assert.Byte(request4.Command).Equals(0x01)
	assert.Port(request4.Port).Equals(v2net.Port(53))
	assert.Bytes(request4.IP[:]).Equals([]byte{0x72, 0x72, 0x72, 0x72})
}
Ejemplo n.º 26
0
func TestDomainAddressRequest(t *testing.T) {
	v2testing.Current(t)

	payload := make([]byte, 0, 1024)
	payload = append(payload, 0, 0, 1, AddrTypeDomain, byte(len("v2ray.com")))
	payload = append(payload, []byte("v2ray.com")...)
	payload = append(payload, 0, 80)
	payload = append(payload, []byte("Actual payload")...)

	request, err := ReadUDPRequest(payload)
	assert.Error(err).IsNil()

	assert.Byte(request.Fragment).Equals(1)
	assert.String(request.Address).Equals("v2ray.com")
	netassert.Port(request.Port).Equals(v2net.Port(80))
	assert.Bytes(request.Data.Value).Equals([]byte("Actual payload"))
}
Ejemplo n.º 27
0
func (this *PortRange) UnmarshalJSON(data []byte) error {
	var maybeint int
	err := json.Unmarshal(data, &maybeint)
	if err == nil {
		if maybeint <= 0 || maybeint >= 65535 {
			log.Error("Invalid port [%s]", string(data))
			return InvalidPortRange
		}
		this.from = v2net.Port(maybeint)
		this.to = v2net.Port(maybeint)
		return nil
	}

	var maybestring string
	err = json.Unmarshal(data, &maybestring)
	if err == nil {
		pair := strings.SplitN(maybestring, "-", 2)
		if len(pair) == 1 {
			value, err := strconv.Atoi(pair[0])
			if err != nil || value <= 0 || value >= 65535 {
				log.Error("Invalid from port %s", pair[0])
				return InvalidPortRange
			}
			this.from = v2net.Port(value)
			this.to = v2net.Port(value)
			return nil
		} else if len(pair) == 2 {
			from, err := strconv.Atoi(pair[0])
			if err != nil || from <= 0 || from >= 65535 {
				log.Error("Invalid from port %s", pair[0])
				return InvalidPortRange
			}
			this.from = v2net.Port(from)

			to, err := strconv.Atoi(pair[1])
			if err != nil || to <= 0 || to >= 65535 {
				log.Error("Invalid to port %s", pair[1])
				return InvalidPortRange
			}
			this.to = v2net.Port(to)

			if this.from > this.to {
				log.Error("Invalid port range %d -> %d", this.from, this.to)
				return InvalidPortRange
			}
			return nil
		}
	}

	return InvalidPortRange
}
Ejemplo n.º 28
0
func TestRequestRead(t *testing.T) {
	assert := assert.On(t)

	rawRequest := []byte{
		0x05,                   // version
		0x01,                   // cmd connect
		0x00,                   // reserved
		0x01,                   // ipv4 type
		0x72, 0x72, 0x72, 0x72, // 114.114.114.114
		0x00, 0x35, // port 53
	}
	request, err := ReadRequest(bytes.NewReader(rawRequest))
	assert.Error(err).IsNil()
	assert.Byte(request.Version).Equals(0x05)
	assert.Byte(request.Command).Equals(0x01)
	assert.Byte(request.AddrType).Equals(0x01)
	assert.Bytes(request.IPv4[:]).Equals([]byte{0x72, 0x72, 0x72, 0x72})
	assert.Port(request.Port).Equals(v2net.Port(53))
}
Ejemplo n.º 29
0
func (this *Config) UnmarshalJSON(data []byte) error {
	type JsonConfig struct {
		Port            v2net.Port                `json:"port"` // Port of this Point server.
		LogConfig       *LogConfig                `json:"log"`
		RouterConfig    *router.Config            `json:"routing"`
		DNSConfig       *dns.Config               `json:"dns"`
		InboundConfig   *InboundConnectionConfig  `json:"inbound"`
		OutboundConfig  *OutboundConnectionConfig `json:"outbound"`
		InboundDetours  []*InboundDetourConfig    `json:"inboundDetour"`
		OutboundDetours []*OutboundDetourConfig   `json:"outboundDetour"`
		Transport       *transport.Config         `json:"transport"`
	}
	jsonConfig := new(JsonConfig)
	if err := json.Unmarshal(data, jsonConfig); err != nil {
		return errors.New("Point: Failed to parse config: " + err.Error())
	}
	this.Port = jsonConfig.Port
	this.LogConfig = jsonConfig.LogConfig
	this.RouterConfig = jsonConfig.RouterConfig

	if jsonConfig.InboundConfig == nil {
		return errors.New("Point: Inbound config is not specified.")
	}
	this.InboundConfig = jsonConfig.InboundConfig

	if jsonConfig.OutboundConfig == nil {
		return errors.New("Point: Outbound config is not specified.")
	}
	this.OutboundConfig = jsonConfig.OutboundConfig
	this.InboundDetours = jsonConfig.InboundDetours
	this.OutboundDetours = jsonConfig.OutboundDetours
	if jsonConfig.DNSConfig == nil {
		jsonConfig.DNSConfig = &dns.Config{
			NameServers: []v2net.Destination{
				v2net.UDPDestination(v2net.DomainAddress("localhost"), v2net.Port(53)),
			},
		}
	}
	this.DNSConfig = jsonConfig.DNSConfig
	this.TransportConfig = jsonConfig.Transport
	return nil
}
Ejemplo n.º 30
0
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()
}