Compare commits

...

29 Commits
v0.11 ... v0.12

Author SHA1 Message Date
V2Ray
da1b428bb4 Fix default config file 2015-11-09 22:31:19 +01:00
V2Ray
a3a51b7b30 Update coverall 2015-11-06 13:56:33 +01:00
V2Ray
5347673e00 test case for socks udp 2015-11-06 13:45:41 +01:00
V2Ray
6ce1539bca Update coverall script 2015-11-06 13:28:34 +01:00
V2Ray
e60fcba4b3 Test cases for Socks end 2 end. 2015-11-06 13:08:20 +01:00
V2Ray
fdc72ed8c9 Move mocked userset to vmess/protocol/user 2015-11-04 23:04:00 +01:00
V2Ray
1d4b541d2f Move mock config to app/config 2015-11-04 23:01:04 +01:00
V2Ray
346b6125f4 test cases for Destination 2015-11-04 22:48:54 +01:00
V2Ray
31fb65b3d8 Remove VMess UDP 2015-11-04 21:52:48 +01:00
V2Ray
581e6b7104 More test case for building 2015-11-04 21:20:06 +01:00
V2Ray
8204c9923d typo 2015-11-04 17:57:11 +01:00
V2Ray
602afca3e3 Test case for macos building 2015-11-04 17:52:59 +01:00
V2Ray
0a8e283e55 function to create router 2015-11-03 23:24:56 +01:00
V2Ray
0d06561b7e More test case 2015-11-03 22:27:26 +01:00
V2Ray
c144e77eb3 Refactor socks config 2015-11-03 22:23:50 +01:00
V2Ray
654cdf18d9 Refactor socks json config 2015-11-03 22:09:07 +01:00
V2Ray
a46db069fb Refactor AES encryption/decryption 2015-11-03 21:26:16 +01:00
V2Ray
3f884ed924 More test case for stream logger 2015-11-03 20:30:14 +01:00
V2Ray
144141b3c3 test case for stream logger 2015-11-03 20:24:29 +01:00
V2Ray
cb19e4613f Update port range test 2015-11-03 20:07:46 +01:00
V2Ray
6faff6d514 test case for socks udp protocol 2015-11-03 18:33:58 +01:00
V2Ray
d9ebd008d3 Check lenth of the udp packet before parsing 2015-11-03 18:20:28 +01:00
V2Ray
d58384ced0 One more test case for retry 2015-11-03 00:12:25 +01:00
V2Ray
f080f36372 format code 2015-11-03 00:07:19 +01:00
V2Ray
60b116fbde Test case for retry 2015-11-03 00:07:15 +01:00
V2Ray
1edd0e660e Remove redunent code 2015-11-02 23:55:10 +01:00
V2Ray
8fbb9762db typo 2015-11-02 23:54:11 +01:00
V2Ray
1a4405dbe1 Remove redunent code 2015-11-02 23:52:22 +01:00
V2Ray
f2cf4a1f89 Test case for too-short request 2015-11-02 23:48:47 +01:00
39 changed files with 860 additions and 461 deletions

View File

@@ -55,7 +55,7 @@ func TestOverRangeStringPort(t *testing.T) {
assert := unit.Assert(t)
var portRange PortRange
err := json.Unmarshal([]byte("\"-1\""), &portRange)
err := json.Unmarshal([]byte("\"65536\""), &portRange)
assert.Error(err).Equals(InvalidPortRange)
err = json.Unmarshal([]byte("\"70000-80000\""), &portRange)

View File

@@ -1,10 +1,16 @@
package router
import (
"errors"
"github.com/v2ray/v2ray-core/app/point/config"
v2net "github.com/v2ray/v2ray-core/common/net"
)
var (
RouterNotFound = errors.New("Router not found.")
)
type Router interface {
TakeDetour(v2net.Packet) (config.ConnectionTag, error)
}
@@ -22,3 +28,10 @@ func RegisterRouter(name string, factory RouterFactory) error {
routerCache[name] = factory
return nil
}
func CreateRouter(name string, rawConfig interface{}) (Router, error) {
if factory, found := routerCache[name]; found {
return factory.Create(rawConfig)
}
return nil, RouterNotFound
}

62
common/crypto/aes.go Normal file
View File

@@ -0,0 +1,62 @@
package crypto
import (
"crypto/aes"
"crypto/cipher"
"io"
)
func NewAesDecryptionStream(key []byte, iv []byte) (cipher.Stream, error) {
aesBlock, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
return cipher.NewCFBDecrypter(aesBlock, iv), nil
}
func NewAesEncryptionStream(key []byte, iv []byte) (cipher.Stream, error) {
aesBlock, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
return cipher.NewCFBEncrypter(aesBlock, iv), nil
}
type cryptionReader struct {
stream cipher.Stream
reader io.Reader
}
func NewCryptionReader(stream cipher.Stream, reader io.Reader) io.Reader {
return &cryptionReader{
stream: stream,
reader: reader,
}
}
func (this *cryptionReader) Read(data []byte) (int, error) {
nBytes, err := this.reader.Read(data)
if nBytes > 0 {
this.stream.XORKeyStream(data[:nBytes], data[:nBytes])
}
return nBytes, err
}
type cryptionWriter struct {
stream cipher.Stream
writer io.Writer
}
func NewCryptionWriter(stream cipher.Stream, writer io.Writer) io.Writer {
return &cryptionWriter{
stream: stream,
writer: writer,
}
}
func (this *cryptionWriter) Write(data []byte) (int, error) {
this.stream.XORKeyStream(data, data)
return this.writer.Write(data)
}

View File

@@ -1,27 +0,0 @@
package io
import (
"crypto/aes"
"crypto/cipher"
"io"
)
func NewAesDecryptReader(key []byte, iv []byte, reader io.Reader) (*CryptionReader, error) {
aesBlock, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesStream := cipher.NewCFBDecrypter(aesBlock, iv)
return NewCryptionReader(aesStream, reader), nil
}
func NewAesEncryptWriter(key []byte, iv []byte, writer io.Writer) (*CryptionWriter, error) {
aesBlock, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesStream := cipher.NewCFBEncrypter(aesBlock, iv)
return NewCryptionWriter(aesStream, writer), nil
}

View File

@@ -1,54 +0,0 @@
package io
import (
"crypto/cipher"
"io"
)
// CryptionReader is a general purpose reader that applies a stream cipher on top of a regular reader.
type CryptionReader struct {
stream cipher.Stream
reader io.Reader
}
// NewCryptionReader creates a new CryptionReader instance from given stream cipher and reader.
func NewCryptionReader(stream cipher.Stream, reader io.Reader) *CryptionReader {
return &CryptionReader{
stream: stream,
reader: reader,
}
}
// Read reads blocks from underlying reader, and crypt it. The content of blocks is modified in place.
func (reader CryptionReader) Read(blocks []byte) (int, error) {
nBytes, err := reader.reader.Read(blocks)
if nBytes > 0 {
reader.stream.XORKeyStream(blocks[:nBytes], blocks[:nBytes])
}
return nBytes, err
}
// Cryption writer is a general purpose of byte stream writer that applies a stream cipher on top of a regular writer.
type CryptionWriter struct {
stream cipher.Stream
writer io.Writer
}
// NewCryptionWriter creates a new CryptionWriter from given stream cipher and writer.
func NewCryptionWriter(stream cipher.Stream, writer io.Writer) *CryptionWriter {
return &CryptionWriter{
stream: stream,
writer: writer,
}
}
// Crypt crypts the content of blocks without writing them into the underlying writer.
func (writer CryptionWriter) Crypt(blocks []byte) {
writer.stream.XORKeyStream(blocks, blocks)
}
// Write crypts the content of blocks in place, and then writes the give blocks to underlying writer.
func (writer CryptionWriter) Write(blocks []byte) (int, error) {
writer.Crypt(blocks)
return writer.writer.Write(blocks)
}

View File

@@ -1,6 +1,7 @@
package log
import (
"bytes"
"testing"
"github.com/v2ray/v2ray-core/testing/unit"
@@ -17,3 +18,18 @@ func TestLogLevelSetting(t *testing.T) {
assert.Pointer(debugLogger).Equals(noOpLoggerInstance)
assert.Pointer(infoLogger).Equals(streamLoggerInstance)
}
func TestStreamLogger(t *testing.T) {
assert := unit.Assert(t)
buffer := bytes.NewBuffer(make([]byte, 0, 1024))
logger := &streamLogger{
writer: buffer,
}
logger.WriteLog("TestPrefix: ", "Test %s Format", "Stream Logger")
assert.Bytes(buffer.Bytes()).Equals([]byte("TestPrefix: Test Stream Logger Format\n"))
buffer.Reset()
logger.WriteLog("TestPrefix: ", "Test No Format")
assert.Bytes(buffer.Bytes()).Equals([]byte("TestPrefix: Test No Format\n"))
}

View File

@@ -0,0 +1,25 @@
package net
import (
"testing"
"github.com/v2ray/v2ray-core/testing/unit"
)
func TestTCPDestination(t *testing.T) {
assert := unit.Assert(t)
dest := NewTCPDestination(IPAddress([]byte{1, 2, 3, 4}, 80))
assert.Bool(dest.IsTCP()).IsTrue()
assert.Bool(dest.IsUDP()).IsFalse()
assert.String(dest.String()).Equals("tcp:1.2.3.4:80")
}
func TestUDPDestination(t *testing.T) {
assert := unit.Assert(t)
dest := NewUDPDestination(IPAddress([]byte{0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88}, 53))
assert.Bool(dest.IsTCP()).IsFalse()
assert.Bool(dest.IsUDP()).IsTrue()
assert.String(dest.String()).Equals("udp:[2001:4860:4860::8888]:53")
}

View File

@@ -0,0 +1,80 @@
package retry
import (
"errors"
"testing"
"time"
"github.com/v2ray/v2ray-core/testing/unit"
)
var (
TestError = errors.New("This is a fake error.")
)
func TestNoRetry(t *testing.T) {
assert := unit.Assert(t)
startTime := time.Now().Unix()
err := Timed(10, 100000).On(func() error {
return nil
})
endTime := time.Now().Unix()
assert.Error(err).IsNil()
assert.Int64(endTime - startTime).AtLeast(0)
}
func TestRetryOnce(t *testing.T) {
assert := unit.Assert(t)
startTime := time.Now()
called := 0
err := Timed(10, 1000).On(func() error {
if called == 0 {
called++
return TestError
}
return nil
})
duration := time.Since(startTime)
assert.Error(err).IsNil()
assert.Int64(int64(duration / time.Millisecond)).AtLeast(900)
}
func TestRetryMultiple(t *testing.T) {
assert := unit.Assert(t)
startTime := time.Now()
called := 0
err := Timed(10, 1000).On(func() error {
if called < 5 {
called++
return TestError
}
return nil
})
duration := time.Since(startTime)
assert.Error(err).IsNil()
assert.Int64(int64(duration / time.Millisecond)).AtLeast(4900)
}
func TestRetryExhausted(t *testing.T) {
assert := unit.Assert(t)
startTime := time.Now()
called := 0
err := Timed(2, 1000).On(func() error {
if called < 5 {
called++
return TestError
}
return nil
})
duration := time.Since(startTime)
assert.Error(err).Equals(RetryFailed)
assert.Int64(int64(duration / time.Millisecond)).AtLeast(1900)
}

View File

@@ -5,11 +5,11 @@ import (
"testing"
"github.com/v2ray/v2ray-core/app/point"
"github.com/v2ray/v2ray-core/app/point/config/testing/mocks"
v2netjson "github.com/v2ray/v2ray-core/common/net/json"
v2nettesting "github.com/v2ray/v2ray-core/common/net/testing"
"github.com/v2ray/v2ray-core/proxy/dokodemo/config/json"
_ "github.com/v2ray/v2ray-core/proxy/freedom"
"github.com/v2ray/v2ray-core/testing/mocks"
"github.com/v2ray/v2ray-core/testing/servers/tcp"
"github.com/v2ray/v2ray-core/testing/unit"
)

View File

@@ -10,6 +10,7 @@ import (
"golang.org/x/net/proxy"
"github.com/v2ray/v2ray-core/app/point"
"github.com/v2ray/v2ray-core/app/point/config/testing/mocks"
"github.com/v2ray/v2ray-core/common/alloc"
v2net "github.com/v2ray/v2ray-core/common/net"
v2nettesting "github.com/v2ray/v2ray-core/common/net/testing"
@@ -17,7 +18,6 @@ import (
_ "github.com/v2ray/v2ray-core/proxy/socks"
"github.com/v2ray/v2ray-core/proxy/socks/config/json"
proxymocks "github.com/v2ray/v2ray-core/proxy/testing/mocks"
"github.com/v2ray/v2ray-core/testing/mocks"
"github.com/v2ray/v2ray-core/testing/servers/tcp"
"github.com/v2ray/v2ray-core/testing/servers/udp"
"github.com/v2ray/v2ray-core/testing/unit"

View File

@@ -1,9 +1,11 @@
package json
import (
"encoding/json"
"errors"
"net"
"github.com/v2ray/v2ray-core/proxy/common/config/json"
jsonconfig "github.com/v2ray/v2ray-core/proxy/common/config/json"
)
const (
@@ -16,28 +18,49 @@ type SocksAccount struct {
Password string `json:"pass"`
}
type SocksConfig struct {
AuthMethod string `json:"auth"`
Accounts []SocksAccount `json:"accounts"`
UDPEnabled bool `json:"udp"`
HostIP string `json:"ip"`
type SocksAccountMap map[string]string
accountMap map[string]string
ip net.IP
func (this *SocksAccountMap) UnmarshalJSON(data []byte) error {
var accounts []SocksAccount
err := json.Unmarshal(data, &accounts)
if err != nil {
return err
}
*this = make(map[string]string)
for _, account := range accounts {
(*this)[account.Username] = account.Password
}
return nil
}
func (sc *SocksConfig) Initialize() {
sc.accountMap = make(map[string]string)
for _, account := range sc.Accounts {
sc.accountMap[account.Username] = account.Password
func (this *SocksAccountMap) HasAccount(user, pass string) bool {
if actualPass, found := (*this)[user]; found {
return actualPass == pass
}
return false
}
if len(sc.HostIP) > 0 {
sc.ip = net.ParseIP(sc.HostIP)
if sc.ip == nil {
sc.ip = net.IPv4(127, 0, 0, 1)
}
type IPAddress net.IP
func (this *IPAddress) UnmarshalJSON(data []byte) error {
var ipStr string
err := json.Unmarshal(data, &ipStr)
if err != nil {
return err
}
ip := net.ParseIP(ipStr)
if ip == nil {
return errors.New("Unknown IP format: " + ipStr)
}
*this = IPAddress(ip)
return nil
}
type SocksConfig struct {
AuthMethod string `json:"auth"`
Accounts SocksAccountMap `json:"accounts"`
UDPEnabled bool `json:"udp"`
HostIP IPAddress `json:"ip"`
}
func (sc *SocksConfig) IsNoAuth() bool {
@@ -49,18 +72,17 @@ func (sc *SocksConfig) IsPassword() bool {
}
func (sc *SocksConfig) HasAccount(user, pass string) bool {
if actualPass, found := sc.accountMap[user]; found {
return actualPass == pass
}
return false
return sc.Accounts.HasAccount(user, pass)
}
func (sc *SocksConfig) IP() net.IP {
return sc.ip
return net.IP(sc.HostIP)
}
func init() {
json.RegisterInboundConnectionConfig("socks", func() interface{} {
return new(SocksConfig)
jsonconfig.RegisterInboundConnectionConfig("socks", func() interface{} {
return &SocksConfig{
HostIP: IPAddress(net.IPv4(127, 0, 0, 1)),
}
})
}

View File

@@ -0,0 +1,64 @@
package json
import (
"encoding/json"
"net"
"testing"
"github.com/v2ray/v2ray-core/proxy/common/config"
jsonconfig "github.com/v2ray/v2ray-core/proxy/common/config/json"
"github.com/v2ray/v2ray-core/testing/unit"
)
func TestAccountMapParsing(t *testing.T) {
assert := unit.Assert(t)
var accountMap SocksAccountMap
err := json.Unmarshal([]byte("[{\"user\": \"a\", \"pass\":\"b\"}, {\"user\": \"c\", \"pass\":\"d\"}]"), &accountMap)
assert.Error(err).IsNil()
assert.Bool(accountMap.HasAccount("a", "b")).IsTrue()
assert.Bool(accountMap.HasAccount("a", "c")).IsFalse()
assert.Bool(accountMap.HasAccount("c", "d")).IsTrue()
assert.Bool(accountMap.HasAccount("e", "d")).IsFalse()
}
func TestDefaultIPAddress(t *testing.T) {
assert := unit.Assert(t)
socksConfig := jsonconfig.CreateConfig("socks", config.TypeInbound).(*SocksConfig)
assert.String(socksConfig.IP().String()).Equals("127.0.0.1")
}
func TestIPAddressParsing(t *testing.T) {
assert := unit.Assert(t)
var ipAddress IPAddress
err := json.Unmarshal([]byte("\"1.2.3.4\""), &ipAddress)
assert.Error(err).IsNil()
assert.String(net.IP(ipAddress).String()).Equals("1.2.3.4")
}
func TestNoAuthConfig(t *testing.T) {
assert := unit.Assert(t)
var config SocksConfig
err := json.Unmarshal([]byte("{\"auth\":\"noauth\", \"ip\":\"8.8.8.8\"}"), &config)
assert.Error(err).IsNil()
assert.Bool(config.IsNoAuth()).IsTrue()
assert.Bool(config.IsPassword()).IsFalse()
assert.String(config.IP().String()).Equals("8.8.8.8")
assert.Bool(config.UDPEnabled).IsFalse()
}
func TestUserPassConfig(t *testing.T) {
assert := unit.Assert(t)
var config SocksConfig
err := json.Unmarshal([]byte("{\"auth\":\"password\", \"accounts\":[{\"user\":\"x\", \"pass\":\"y\"}], \"udp\":true}"), &config)
assert.Error(err).IsNil()
assert.Bool(config.IsNoAuth()).IsFalse()
assert.Bool(config.IsPassword()).IsTrue()
assert.Bool(config.HasAccount("x", "y")).IsTrue()
assert.Bool(config.UDPEnabled).IsTrue()
}

View File

@@ -28,11 +28,7 @@ func TestSocks4AuthenticationRequestRead(t *testing.T) {
func TestSocks4AuthenticationResponseToBytes(t *testing.T) {
assert := unit.Assert(t)
response := &Socks4AuthenticationResponse{
result: byte(0x10),
port: 443,
ip: []byte{1, 2, 3, 4},
}
response := NewSocks4AuthenticationResponse(byte(0x10), 443, []byte{1, 2, 3, 4})
buffer := alloc.NewSmallBuffer().Clear()
defer buffer.Release()

View File

@@ -2,10 +2,12 @@ package protocol
import (
"bytes"
"io"
"testing"
"github.com/v2ray/v2ray-core/common/alloc"
"github.com/v2ray/v2ray-core/testing/unit"
"github.com/v2ray/v2ray-core/transport"
)
func TestHasAuthenticationMethod(t *testing.T) {
@@ -94,3 +96,17 @@ func TestResponseWrite(t *testing.T) {
}
assert.Bytes(buffer.Value).Named("raw response").Equals(expectedBytes)
}
func TestEOF(t *testing.T) {
assert := unit.Assert(t)
_, _, err := ReadAuthentication(bytes.NewReader(make([]byte, 0)))
assert.Error(err).Equals(io.EOF)
}
func TestSignleByte(t *testing.T) {
assert := unit.Assert(t)
_, _, err := ReadAuthentication(bytes.NewReader(make([]byte, 1)))
assert.Error(err).Equals(transport.CorruptedPacket)
}

View File

@@ -7,6 +7,7 @@ import (
"github.com/v2ray/v2ray-core/common/alloc"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/transport"
)
var (
@@ -37,7 +38,12 @@ func (request *Socks5UDPRequest) Write(buffer *alloc.Buffer) {
buffer.Append(request.Data.Value)
}
func ReadUDPRequest(packet []byte) (request Socks5UDPRequest, err error) {
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]
@@ -46,28 +52,38 @@ func ReadUDPRequest(packet []byte) (request Socks5UDPRequest, err error) {
switch addrType {
case AddrTypeIPv4:
if len(packet) < 10 {
return nil, transport.CorruptedPacket
}
ip := packet[4:8]
port := binary.BigEndian.Uint16(packet[8:10])
request.Address = v2net.IPAddress(ip, port)
dataBegin = 10
case AddrTypeIPv6:
if len(packet) < 22 {
return nil, transport.CorruptedPacket
}
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])
if len(packet) < 5+domainLength+2 {
return nil, transport.CorruptedPacket
}
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
return nil, ErrorUnknownAddressType
}
request.Data = alloc.NewBuffer().Clear().Append(packet[dataBegin:])
if len(packet) > dataBegin {
request.Data = alloc.NewBuffer().Clear().Append(packet[dataBegin:])
}
return
return request, nil
}

View File

@@ -0,0 +1,35 @@
package protocol
import (
"testing"
"github.com/v2ray/v2ray-core/testing/unit"
"github.com/v2ray/v2ray-core/transport"
)
func TestSingleByteRequest(t *testing.T) {
assert := unit.Assert(t)
request, err := ReadUDPRequest(make([]byte, 1))
if request != nil {
t.Fail()
}
assert.Error(err).Equals(transport.CorruptedPacket)
}
func TestDomainAddressRequest(t *testing.T) {
assert := unit.Assert(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.String()).Equals("v2ray.com:80")
assert.Bytes(request.Data.Value).Equals([]byte("Actual payload"))
}

View File

@@ -145,6 +145,8 @@ func (server *SocksServer) handleSocks5(reader *v2net.TimeOutReader, writer io.W
if request.Command == protocol.CmdBind || request.Command == protocol.CmdUdpAssociate {
response := protocol.NewSocks5Response()
response.Error = protocol.ErrorCommandNotSupported
response.Port = uint16(0)
response.SetIPv4([]byte{0, 0, 0, 0})
responseBuffer := alloc.NewSmallBuffer().Clear()
response.Write(responseBuffer)
@@ -163,11 +165,7 @@ func (server *SocksServer) handleSocks5(reader *v2net.TimeOutReader, writer io.W
// Some SOCKS software requires a value other than dest. Let's fake one:
response.Port = uint16(1717)
response.AddrType = protocol.AddrTypeIPv4
response.IPv4[0] = 0
response.IPv4[1] = 0
response.IPv4[2] = 0
response.IPv4[3] = 0
response.SetIPv4([]byte{0, 0, 0, 0})
responseBuffer := alloc.NewSmallBuffer().Clear()
response.Write(responseBuffer)
@@ -198,14 +196,11 @@ func (server *SocksServer) handleUDP(reader *v2net.TimeOutReader, writer io.Writ
response.Port = udpAddr.Port()
switch {
case udpAddr.IsIPv4():
response.AddrType = protocol.AddrTypeIPv4
copy(response.IPv4[:], udpAddr.IP())
response.SetIPv4(udpAddr.IP())
case udpAddr.IsIPv6():
response.AddrType = protocol.AddrTypeIPv6
copy(response.IPv6[:], udpAddr.IP())
response.SetIPv6(udpAddr.IP())
case udpAddr.IsDomain():
response.AddrType = protocol.AddrTypeDomain
response.Domain = udpAddr.Domain()
response.SetDomain(udpAddr.Domain())
}
responseBuffer := alloc.NewSmallBuffer().Clear()

View File

@@ -10,11 +10,11 @@ import (
"golang.org/x/net/proxy"
"github.com/v2ray/v2ray-core/app/point"
"github.com/v2ray/v2ray-core/app/point/config/testing/mocks"
v2nettesting "github.com/v2ray/v2ray-core/common/net/testing"
"github.com/v2ray/v2ray-core/proxy/common/connhandler"
"github.com/v2ray/v2ray-core/proxy/socks/config/json"
proxymocks "github.com/v2ray/v2ray-core/proxy/testing/mocks"
"github.com/v2ray/v2ray-core/testing/mocks"
"github.com/v2ray/v2ray-core/testing/unit"
)
@@ -92,11 +92,8 @@ func TestSocksTcpConnectWithUserPass(t *testing.T) {
ProtocolValue: "socks",
SettingsValue: &json.SocksConfig{
AuthMethod: "password",
Accounts: []json.SocksAccount{
json.SocksAccount{
Username: "userx",
Password: "passy",
},
Accounts: json.SocksAccountMap{
"userx": "passy",
},
},
},
@@ -153,11 +150,8 @@ func TestSocksTcpConnectWithWrongUserPass(t *testing.T) {
ProtocolValue: "socks",
SettingsValue: &json.SocksConfig{
AuthMethod: "password",
Accounts: []json.SocksAccount{
json.SocksAccount{
Username: "userx",
Password: "passy",
},
Accounts: json.SocksAccountMap{
"userx": "passy",
},
},
},
@@ -200,11 +194,8 @@ func TestSocksTcpConnectWithWrongAuthMethod(t *testing.T) {
ProtocolValue: "socks",
SettingsValue: &json.SocksConfig{
AuthMethod: "password",
Accounts: []json.SocksAccount{
json.SocksAccount{
Username: "userx",
Password: "passy",
},
Accounts: json.SocksAccountMap{
"userx": "passy",
},
},
},

View File

@@ -10,9 +10,7 @@ type SocksServerFactory struct {
}
func (factory SocksServerFactory) Create(dispatcher app.PacketDispatcher, rawConfig interface{}) (connhandler.InboundConnectionHandler, error) {
config := rawConfig.(*json.SocksConfig)
config.Initialize()
return NewSocksServer(dispatcher, config), nil
return NewSocksServer(dispatcher, rawConfig.(*json.SocksConfig)), nil
}
func init() {

View File

@@ -46,7 +46,9 @@ func (server *SocksServer) AcceptPackets(conn *net.UDPConn) error {
buffer.Release()
if err != nil {
log.Error("Socks failed to parse UDP request: %v", err)
request.Data.Release()
continue
}
if request.Data == nil || request.Data.Len() == 0 {
continue
}
if request.Fragment != 0 {

View File

@@ -2,5 +2,4 @@ package config
type Inbound interface {
AllowedUsers() []User
UDPEnabled() bool
}

View File

@@ -7,7 +7,6 @@ import (
type Inbound struct {
AllowedClients []*ConfigUser `json:"clients"`
UDP bool `json:"udp"`
}
func (c *Inbound) AllowedUsers() []vmessconfig.User {
@@ -18,10 +17,6 @@ func (c *Inbound) AllowedUsers() []vmessconfig.User {
return users
}
func (c *Inbound) UDPEnabled() bool {
return c.UDP
}
func init() {
json.RegisterInboundConnectionConfig("vmess", func() interface{} {
return new(Inbound)

View File

@@ -3,7 +3,6 @@ package json
import (
"encoding/json"
"net"
"strings"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
@@ -16,18 +15,11 @@ type RawConfigTarget struct {
Address string `json:"address"`
Port uint16 `json:"port"`
Users []*ConfigUser `json:"users"`
Network string `json:"network"`
}
func (config RawConfigTarget) HasNetwork(network string) bool {
return strings.Contains(config.Network, network)
}
type ConfigTarget struct {
Address v2net.Address
Users []*ConfigUser
TCPEnabled bool
UDPEnabled bool
Address v2net.Address
Users []*ConfigUser
}
func (t *ConfigTarget) UnmarshalJSON(data []byte) error {
@@ -42,12 +34,6 @@ func (t *ConfigTarget) UnmarshalJSON(data []byte) error {
return proxyconfig.BadConfiguration
}
t.Address = v2net.IPAddress(ip, rawConfig.Port)
if rawConfig.HasNetwork("tcp") {
t.TCPEnabled = true
}
if rawConfig.HasNetwork("udp") {
t.UDPEnabled = true
}
return nil
}
@@ -62,18 +48,10 @@ func (o *Outbound) Targets() []*vmessconfig.OutboundTarget {
for _, rawUser := range rawTarget.Users {
users = append(users, rawUser)
}
if rawTarget.TCPEnabled {
targets = append(targets, &vmessconfig.OutboundTarget{
Destination: v2net.NewTCPDestination(rawTarget.Address),
Accounts: users,
})
}
if rawTarget.UDPEnabled {
targets = append(targets, &vmessconfig.OutboundTarget{
Destination: v2net.NewUDPDestination(rawTarget.Address),
Accounts: users,
})
}
targets = append(targets, &vmessconfig.OutboundTarget{
Destination: v2net.NewTCPDestination(rawTarget.Address),
Accounts: users,
})
}
return targets
}

View File

@@ -2,15 +2,13 @@
package protocol
import (
"crypto/aes"
"crypto/cipher"
"encoding/binary"
"hash/fnv"
"io"
"time"
"github.com/v2ray/v2ray-core/common/alloc"
v2io "github.com/v2ray/v2ray-core/common/io"
v2crypto "github.com/v2ray/v2ray-core/common/crypto"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
proxyerrors "github.com/v2ray/v2ray-core/proxy/common/errors"
@@ -80,16 +78,12 @@ func (r *VMessRequestReader) Read(reader io.Reader) (*VMessRequest, error) {
return nil, proxyerrors.InvalidAuthentication
}
aesCipher, err := aes.NewCipher(userObj.ID().CmdKey())
aesStream, err := v2crypto.NewAesDecryptionStream(userObj.ID().CmdKey(), user.Int64Hash(timeSec))
if err != nil {
return nil, err
}
aesStream := cipher.NewCFBDecrypter(aesCipher, user.Int64Hash(timeSec))
decryptor := v2io.NewCryptionReader(aesStream, reader)
if err != nil {
return nil, err
}
decryptor := v2crypto.NewCryptionReader(aesStream, reader)
nBytes, err = v2net.ReadAllBytes(decryptor, buffer.Value[:41])
if err != nil {
@@ -201,11 +195,10 @@ func (request *VMessRequest) ToBytes(idHash user.CounterHash, randomRangeInt64 u
buffer.AppendBytes(byte(fnvHash>>24), byte(fnvHash>>16), byte(fnvHash>>8), byte(fnvHash))
encryptionEnd += 4
aesCipher, err := aes.NewCipher(request.User.ID().CmdKey())
aesStream, err := v2crypto.NewAesEncryptionStream(request.User.ID().CmdKey(), user.Int64Hash(counter))
if err != nil {
return nil, err
}
aesStream := cipher.NewCFBEncrypter(aesCipher, user.Int64Hash(counter))
aesStream.XORKeyStream(buffer.Value[encryptionBegin:encryptionEnd], buffer.Value[encryptionBegin:encryptionEnd])
return buffer, nil

View File

@@ -3,12 +3,13 @@ package protocol
import (
"bytes"
"crypto/rand"
"io"
"testing"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/proxy/vmess/config"
"github.com/v2ray/v2ray-core/proxy/vmess/protocol/user"
"github.com/v2ray/v2ray-core/testing/mocks"
"github.com/v2ray/v2ray-core/proxy/vmess/protocol/user/testing/mocks"
"github.com/v2ray/v2ray-core/testing/unit"
)
@@ -79,6 +80,14 @@ func TestVMessSerialization(t *testing.T) {
assert.String(actualRequest.Address.String()).Named("Address").Equals(request.Address.String())
}
func TestReadSingleByte(t *testing.T) {
assert := unit.Assert(t)
reader := NewVMessRequestReader(nil)
_, err := reader.Read(bytes.NewReader(make([]byte, 1)))
assert.Error(err).Equals(io.EOF)
}
func BenchmarkVMessRequestWriting(b *testing.B) {
userId, _ := config.NewID("2b2966ac-16aa-4fbf-8d81-c5f172a3da51")
userSet := mocks.MockUserSet{[]config.User{}, make(map[string]int), make(map[string]int64)}

View File

@@ -5,14 +5,13 @@ import (
"testing"
"github.com/v2ray/v2ray-core/app/point"
"github.com/v2ray/v2ray-core/common/alloc"
"github.com/v2ray/v2ray-core/app/point/config/testing/mocks"
v2net "github.com/v2ray/v2ray-core/common/net"
v2nettesting "github.com/v2ray/v2ray-core/common/net/testing"
"github.com/v2ray/v2ray-core/proxy/common/connhandler"
proxymocks "github.com/v2ray/v2ray-core/proxy/testing/mocks"
"github.com/v2ray/v2ray-core/proxy/vmess/config"
"github.com/v2ray/v2ray-core/proxy/vmess/config/json"
"github.com/v2ray/v2ray-core/testing/mocks"
"github.com/v2ray/v2ray-core/testing/unit"
)
@@ -45,8 +44,7 @@ func TestVMessInAndOut(t *testing.T) {
SettingsValue: &json.Outbound{
[]*json.ConfigTarget{
&json.ConfigTarget{
Address: v2net.IPAddress([]byte{127, 0, 0, 1}, portB),
TCPEnabled: true,
Address: v2net.IPAddress([]byte{127, 0, 0, 1}, portB),
Users: []*json.ConfigUser{
&json.ConfigUser{Id: testAccount},
},
@@ -98,92 +96,3 @@ func TestVMessInAndOut(t *testing.T) {
assert.Bytes(ichConnInput).Equals(ochConnOutput.Bytes())
assert.Bytes(ichConnOutput.Bytes()).Equals(ochConnInput)
}
func TestVMessInAndOutUDP(t *testing.T) {
assert := unit.Assert(t)
data2Send := "The data to be send to outbound server."
testAccount, err := config.NewID("ad937d9d-6e23-4a5a-ba23-bce5092a7c51")
assert.Error(err).IsNil()
portA := v2nettesting.PickPort()
portB := v2nettesting.PickPort()
ichConnInput := []byte("The data to be send to outbound server.")
ichConnOutput := bytes.NewBuffer(make([]byte, 0, 1024))
ich := &proxymocks.InboundConnectionHandler{
ConnInput: bytes.NewReader(ichConnInput),
ConnOutput: ichConnOutput,
}
connhandler.RegisterInboundConnectionHandlerFactory("mock_ich", ich)
configA := mocks.Config{
PortValue: portA,
InboundConfigValue: &mocks.ConnectionConfig{
ProtocolValue: "mock_ich",
SettingsValue: nil,
},
OutboundConfigValue: &mocks.ConnectionConfig{
ProtocolValue: "vmess",
SettingsValue: &json.Outbound{
[]*json.ConfigTarget{
&json.ConfigTarget{
Address: v2net.IPAddress([]byte{127, 0, 0, 1}, portB),
UDPEnabled: true,
Users: []*json.ConfigUser{
&json.ConfigUser{Id: testAccount},
},
},
},
},
},
}
pointA, err := point.NewPoint(&configA)
assert.Error(err).IsNil()
err = pointA.Start()
assert.Error(err).IsNil()
ochConnInput := []byte("The data to be returned to inbound server.")
ochConnOutput := bytes.NewBuffer(make([]byte, 0, 1024))
och := &proxymocks.OutboundConnectionHandler{
ConnInput: bytes.NewReader(ochConnInput),
ConnOutput: ochConnOutput,
}
connhandler.RegisterOutboundConnectionHandlerFactory("mock_och", och)
configB := mocks.Config{
PortValue: portB,
InboundConfigValue: &mocks.ConnectionConfig{
ProtocolValue: "vmess",
SettingsValue: &json.Inbound{
AllowedClients: []*json.ConfigUser{
&json.ConfigUser{Id: testAccount},
},
UDP: true,
},
},
OutboundConfigValue: &mocks.ConnectionConfig{
ProtocolValue: "mock_och",
SettingsValue: nil,
},
}
pointB, err := point.NewPoint(&configB)
assert.Error(err).IsNil()
err = pointB.Start()
assert.Error(err).IsNil()
data2SendBuffer := alloc.NewBuffer()
data2SendBuffer.Clear()
data2SendBuffer.Append([]byte(data2Send))
dest := v2net.NewUDPDestination(v2net.IPAddress([]byte{1, 2, 3, 4}, 80))
ich.Communicate(v2net.NewPacket(dest, data2SendBuffer, false))
assert.Bytes(ichConnInput).Equals(ochConnOutput.Bytes())
assert.Bytes(ichConnOutput.Bytes()).Equals(ochConnInput)
}

View File

@@ -8,7 +8,7 @@ import (
"github.com/v2ray/v2ray-core/app"
"github.com/v2ray/v2ray-core/common/alloc"
v2io "github.com/v2ray/v2ray-core/common/io"
v2crypto "github.com/v2ray/v2ray-core/common/crypto"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/common/retry"
@@ -22,14 +22,12 @@ type VMessInboundHandler struct {
dispatcher app.PacketDispatcher
clients user.UserSet
accepting bool
udpEnabled bool
}
func NewVMessInboundHandler(dispatcher app.PacketDispatcher, clients user.UserSet, udpEnabled bool) *VMessInboundHandler {
func NewVMessInboundHandler(dispatcher app.PacketDispatcher, clients user.UserSet) *VMessInboundHandler {
return &VMessInboundHandler{
dispatcher: dispatcher,
clients: clients,
udpEnabled: udpEnabled,
}
}
@@ -45,11 +43,6 @@ func (handler *VMessInboundHandler) Listen(port uint16) error {
}
handler.accepting = true
go handler.AcceptConnections(listener)
if handler.udpEnabled {
handler.ListenUDP(port)
}
return nil
}
@@ -98,12 +91,14 @@ func (handler *VMessInboundHandler) HandleConnection(connection *net.TCPConn) er
responseKey := md5.Sum(request.RequestKey)
responseIV := md5.Sum(request.RequestIV)
responseWriter, err := v2io.NewAesEncryptWriter(responseKey[:], responseIV[:], connection)
aesStream, err := v2crypto.NewAesEncryptionStream(responseKey[:], responseIV[:])
if err != nil {
log.Error("VMessIn: Failed to create encrypt writer: %v", err)
log.Error("VMessIn: Failed to create AES decryption stream: %v", err)
return err
}
responseWriter := v2crypto.NewCryptionWriter(aesStream, connection)
// Optimize for small response packet
buffer := alloc.NewLargeBuffer().Clear()
buffer.Append(request.ResponseHeader)
@@ -127,12 +122,12 @@ func handleInput(request *protocol.VMessRequest, reader io.Reader, input chan<-
defer close(input)
defer finish.Unlock()
requestReader, err := v2io.NewAesDecryptReader(request.RequestKey, request.RequestIV, reader)
aesStream, err := v2crypto.NewAesDecryptionStream(request.RequestKey, request.RequestIV)
if err != nil {
log.Error("VMessIn: Failed to create decrypt reader: %v", err)
log.Error("VMessIn: Failed to create AES decryption stream: %v", err)
return
}
requestReader := v2crypto.NewCryptionReader(aesStream, reader)
v2net.ReaderToChan(input, requestReader)
}
@@ -152,7 +147,7 @@ func (factory *VMessInboundHandlerFactory) Create(dispatcher app.PacketDispatche
allowedClients.AddUser(user)
}
return NewVMessInboundHandler(dispatcher, allowedClients, config.UDPEnabled()), nil
return NewVMessInboundHandler(dispatcher, allowedClients), nil
}
func init() {

View File

@@ -1,108 +0,0 @@
package vmess
import (
"bytes"
"crypto/md5"
"net"
"github.com/v2ray/v2ray-core/common/alloc"
v2io "github.com/v2ray/v2ray-core/common/io"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/proxy/vmess/protocol"
)
const (
bufferSize = 2 * 1024
)
func (handler *VMessInboundHandler) ListenUDP(port uint16) error {
addr := &net.UDPAddr{
IP: net.IP{0, 0, 0, 0},
Port: int(port),
Zone: "",
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
log.Error("VMessIn failed to listen UDP on port %d: %v", port, err)
return err
}
go handler.AcceptPackets(conn)
return nil
}
func (handler *VMessInboundHandler) AcceptPackets(conn *net.UDPConn) {
for {
buffer := alloc.NewBuffer()
nBytes, addr, err := conn.ReadFromUDP(buffer.Value)
if err != nil {
log.Error("VMessIn failed to read UDP packets: %v", err)
buffer.Release()
continue
}
reader := bytes.NewReader(buffer.Value[:nBytes])
requestReader := protocol.NewVMessRequestReader(handler.clients)
request, err := requestReader.Read(reader)
if err != nil {
log.Access(addr.String(), "", log.AccessRejected, err.Error())
log.Warning("VMessIn: Invalid request from (%s): %v", addr.String(), err)
buffer.Release()
continue
}
log.Access(addr.String(), request.Address.String(), log.AccessAccepted, "")
cryptReader, err := v2io.NewAesDecryptReader(request.RequestKey, request.RequestIV, reader)
if err != nil {
log.Error("VMessIn: Failed to create decrypt reader: %v", err)
buffer.Release()
continue
}
data := alloc.NewBuffer()
nBytes, err = cryptReader.Read(data.Value)
buffer.Release()
if err != nil {
log.Warning("VMessIn: Unable to decrypt data: %v", err)
data.Release()
continue
}
data.Slice(0, nBytes)
packet := v2net.NewPacket(request.Destination(), data, false)
go handler.handlePacket(conn, request, packet, addr)
}
}
func (handler *VMessInboundHandler) handlePacket(conn *net.UDPConn, request *protocol.VMessRequest, packet v2net.Packet, clientAddr *net.UDPAddr) {
ray := handler.dispatcher.DispatchToOutbound(packet)
close(ray.InboundInput())
responseKey := md5.Sum(request.RequestKey)
responseIV := md5.Sum(request.RequestIV)
buffer := alloc.NewBuffer().Clear()
defer buffer.Release()
responseWriter, err := v2io.NewAesEncryptWriter(responseKey[:], responseIV[:], buffer)
if err != nil {
log.Error("VMessIn: Failed to create encrypt writer: %v", err)
return
}
responseWriter.Write(request.ResponseHeader)
hasData := false
if data, ok := <-ray.InboundOutput(); ok {
hasData = true
responseWriter.Write(data.Value)
data.Release()
}
if hasData {
conn.WriteToUDP(buffer.Value, clientAddr)
log.Info("VMessIn sending %d bytes to %s", buffer.Len(), clientAddr.String())
}
}

View File

@@ -9,7 +9,7 @@ import (
"sync"
"github.com/v2ray/v2ray-core/common/alloc"
v2io "github.com/v2ray/v2ray-core/common/io"
v2crypto "github.com/v2ray/v2ray-core/common/crypto"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/proxy/common/connhandler"
@@ -20,14 +20,12 @@ import (
)
type VMessOutboundHandler struct {
vNextList []*config.OutboundTarget
vNextListUDP []*config.OutboundTarget
vNextList []*config.OutboundTarget
}
func NewVMessOutboundHandler(vNextList, vNextListUDP []*config.OutboundTarget) *VMessOutboundHandler {
func NewVMessOutboundHandler(vNextList []*config.OutboundTarget) *VMessOutboundHandler {
return &VMessOutboundHandler{
vNextList: vNextList,
vNextListUDP: vNextListUDP,
vNextList: vNextList,
}
}
@@ -56,9 +54,6 @@ func pickVNext(serverList []*config.OutboundTarget) (v2net.Destination, config.U
func (handler *VMessOutboundHandler) Dispatch(firstPacket v2net.Packet, ray ray.OutboundRay) error {
vNextList := handler.vNextList
if firstPacket.Destination().IsUDP() {
vNextList = handler.vNextListUDP
}
vNextAddress, vNextUser := pickVNext(vNextList)
command := protocol.CmdTCP
@@ -114,11 +109,12 @@ func startCommunicate(request *protocol.VMessRequest, dest v2net.Destination, ra
func handleRequest(conn net.Conn, request *protocol.VMessRequest, firstPacket v2net.Packet, input <-chan *alloc.Buffer, finish *sync.Mutex) {
defer finish.Unlock()
encryptRequestWriter, err := v2io.NewAesEncryptWriter(request.RequestKey[:], request.RequestIV[:], conn)
aesStream, err := v2crypto.NewAesEncryptionStream(request.RequestKey[:], request.RequestIV[:])
if err != nil {
log.Error("VMessOut: Failed to create encrypt writer: %v", err)
log.Error("VMessOut: Failed to create AES encryption stream: %v", err)
return
}
encryptRequestWriter := v2crypto.NewCryptionWriter(aesStream, conn)
buffer := alloc.NewBuffer().Clear()
buffer, err = request.ToBytes(user.NewTimeHash(user.HMACHash{}), user.GenerateRandomInt64InRange, buffer)
@@ -136,7 +132,7 @@ func handleRequest(conn net.Conn, request *protocol.VMessRequest, firstPacket v2
}
if firstChunk != nil {
encryptRequestWriter.Crypt(firstChunk.Value)
aesStream.XORKeyStream(firstChunk.Value, firstChunk.Value)
buffer.Append(firstChunk.Value)
firstChunk.Release()
@@ -160,11 +156,12 @@ func handleResponse(conn net.Conn, request *protocol.VMessRequest, output chan<-
responseKey := md5.Sum(request.RequestKey[:])
responseIV := md5.Sum(request.RequestIV[:])
decryptResponseReader, err := v2io.NewAesDecryptReader(responseKey[:], responseIV[:], conn)
aesStream, err := v2crypto.NewAesDecryptionStream(responseKey[:], responseIV[:])
if err != nil {
log.Error("VMessOut: Failed to create decrypt reader: %v", err)
log.Error("VMessOut: Failed to create AES encryption stream: %v", err)
return
}
decryptResponseReader := v2crypto.NewCryptionReader(aesStream, conn)
buffer, err := v2net.ReadFrom(decryptResponseReader, nil)
if err != nil {
@@ -192,17 +189,7 @@ type VMessOutboundHandlerFactory struct {
func (factory *VMessOutboundHandlerFactory) Create(rawConfig interface{}) (connhandler.OutboundConnectionHandler, error) {
vOutConfig := rawConfig.(config.Outbound)
servers := make([]*config.OutboundTarget, 0, 16)
udpServers := make([]*config.OutboundTarget, 0, 16)
for _, target := range vOutConfig.Targets() {
if target.Destination.IsTCP() {
servers = append(servers, target)
}
if target.Destination.IsUDP() {
udpServers = append(udpServers, target)
}
}
return NewVMessOutboundHandler(servers, udpServers), nil
return NewVMessOutboundHandler(vOutConfig.Targets()), nil
}
func init() {

View File

@@ -20,8 +20,7 @@
"port": 37192,
"users": [
{"id": "27848739-7e62-4138-9fd3-098a63964b6b"}
],
"network": "tcp"
]
}
]
}

View File

@@ -19,9 +19,9 @@
"address": "127.0.0.1",
"port": 37192,
"users": [
{"id": "ad937d9d-6e23-4a5a-ba23-bce5092a7c51"}
],
"network": "tcp"
{"id": "27848739-7e62-4138-9fd3-098a63964b6b"},
{"id": "3b129dec-72a3-4d28-aeee-028a0fe86e22"}
]
}
]
}

View File

@@ -15,8 +15,7 @@
"id": "3b129dec-72a3-4d28-aeee-028a0fe86e22",
"level": 1
}
],
"udp": false
]
}
},
"outbound": {

View File

@@ -27,7 +27,7 @@ for DIR in $(find * -type d -not -path "*.git*"); do
fi
done
cat coverall.out | sort -t: -k1 > coverallsorted.out
cat coverall.out | sort -t: -k1 | grep -vw "testing" > coverallsorted.out
echo "mode: set" | cat - coverallsorted.out > coverall.out
rm coverallsorted.out

View File

@@ -0,0 +1,132 @@
package scenarios
import (
"net"
"github.com/v2ray/v2ray-core/app/point"
"github.com/v2ray/v2ray-core/app/point/config/testing/mocks"
v2net "github.com/v2ray/v2ray-core/common/net"
v2nettesting "github.com/v2ray/v2ray-core/common/net/testing"
_ "github.com/v2ray/v2ray-core/proxy/freedom"
_ "github.com/v2ray/v2ray-core/proxy/socks"
socksjson "github.com/v2ray/v2ray-core/proxy/socks/config/json"
_ "github.com/v2ray/v2ray-core/proxy/vmess"
"github.com/v2ray/v2ray-core/proxy/vmess/config"
vmessjson "github.com/v2ray/v2ray-core/proxy/vmess/config/json"
)
const (
socks5Version = byte(0x05)
)
func socks5AuthMethodRequest(methods ...byte) []byte {
request := []byte{socks5Version, byte(len(methods))}
request = append(request, methods...)
return request
}
func appendAddress(request []byte, address v2net.Address) []byte {
switch {
case address.IsIPv4():
request = append(request, byte(0x01))
request = append(request, address.IP()...)
case address.IsIPv6():
request = append(request, byte(0x04))
request = append(request, address.IP()...)
case address.IsDomain():
request = append(request, byte(0x03), byte(len(address.Domain())))
request = append(request, []byte(address.Domain())...)
}
request = append(request, address.PortBytes()...)
return request
}
func socks5Request(command byte, address v2net.Address) []byte {
request := []byte{socks5Version, command, 0}
request = appendAddress(request, address)
return request
}
func socks5UDPRequest(address v2net.Address, payload []byte) []byte {
request := make([]byte, 0, 1024)
request = append(request, 0, 0, 0)
request = appendAddress(request, address)
request = append(request, payload...)
return request
}
func setUpV2Ray() (uint16, error) {
id1, err := config.NewID("ad937d9d-6e23-4a5a-ba23-bce5092a7c51")
if err != nil {
return 0, err
}
id2, err := config.NewID("93ccfc71-b136-4015-ac85-e037bd1ead9e")
if err != nil {
return 0, err
}
users := []*vmessjson.ConfigUser{
&vmessjson.ConfigUser{Id: id1},
&vmessjson.ConfigUser{Id: id2},
}
portB := v2nettesting.PickPort()
configB := mocks.Config{
PortValue: portB,
InboundConfigValue: &mocks.ConnectionConfig{
ProtocolValue: "vmess",
SettingsValue: &vmessjson.Inbound{
AllowedClients: users,
},
},
OutboundConfigValue: &mocks.ConnectionConfig{
ProtocolValue: "freedom",
SettingsValue: nil,
},
}
pointB, err := point.NewPoint(&configB)
if err != nil {
return 0, err
}
err = pointB.Start()
if err != nil {
return 0, err
}
portA := v2nettesting.PickPort()
configA := mocks.Config{
PortValue: portA,
InboundConfigValue: &mocks.ConnectionConfig{
ProtocolValue: "socks",
SettingsValue: &socksjson.SocksConfig{
AuthMethod: "noauth",
UDPEnabled: true,
HostIP: socksjson.IPAddress(net.IPv4(127, 0, 0, 1)),
},
},
OutboundConfigValue: &mocks.ConnectionConfig{
ProtocolValue: "vmess",
SettingsValue: &vmessjson.Outbound{
[]*vmessjson.ConfigTarget{
&vmessjson.ConfigTarget{
Address: v2net.IPAddress([]byte{127, 0, 0, 1}, portB),
Users: users,
},
},
},
},
}
pointA, err := point.NewPoint(&configA)
if err != nil {
return 0, err
}
err = pointA.Start()
if err != nil {
return 0, err
}
return portA, nil
}

View File

@@ -0,0 +1,192 @@
package scenarios
import (
"net"
"testing"
v2net "github.com/v2ray/v2ray-core/common/net"
v2nettesting "github.com/v2ray/v2ray-core/common/net/testing"
"github.com/v2ray/v2ray-core/testing/servers/tcp"
"github.com/v2ray/v2ray-core/testing/servers/udp"
"github.com/v2ray/v2ray-core/testing/unit"
)
func TestTCPConnection(t *testing.T) {
assert := unit.Assert(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()
v2rayPort, err := setUpV2Ray()
assert.Error(err).IsNil()
for i := 0; i < 100; i++ {
conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{
IP: []byte{127, 0, 0, 1},
Port: int(v2rayPort),
})
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(1), 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, 0, 0, 1, 0, 0, 0, 0, 6, 181})
actualRequest := []byte("Request to target server.")
nBytes, err = conn.Write(actualRequest)
assert.Error(err).IsNil()
assert.Int(nBytes).Equals(len(actualRequest))
actualRequest = []byte("Request to target server again.")
nBytes, err = conn.Write(actualRequest)
assert.Error(err).IsNil()
assert.Int(nBytes).Equals(len(actualRequest))
conn.CloseWrite()
actualResponse := make([]byte, 1024)
nBytes, err = conn.Read(actualResponse)
assert.Error(err).IsNil()
assert.String(string(actualResponse[:nBytes])).Equals("Processed: Request to target server.Request to target server again.")
conn.Close()
}
}
func TestTCPBind(t *testing.T) {
assert := unit.Assert(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()
v2rayPort, err := setUpV2Ray()
assert.Error(err).IsNil()
conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{
IP: []byte{127, 0, 0, 1},
Port: int(v2rayPort),
})
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.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()
}
func TestUDPAssociate(t *testing.T) {
assert := unit.Assert(t)
targetPort := v2nettesting.PickPort()
udpServer := &udp.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 := udpServer.Start()
assert.Error(err).IsNil()
v2rayPort, err := setUpV2Ray()
assert.Error(err).IsNil()
conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{
IP: []byte{127, 0, 0, 1},
Port: int(v2rayPort),
})
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(3), 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, 0, 0, 1, 127, 0, 0, 1, byte(v2rayPort >> 8), byte(v2rayPort)})
udpConn, err := net.DialUDP("udp", nil, &net.UDPAddr{
IP: []byte{127, 0, 0, 1},
Port: int(v2rayPort),
})
assert.Error(err).IsNil()
udpPayload := "UDP request to udp server."
udpRequest := socks5UDPRequest(v2net.IPAddress([]byte{127, 0, 0, 1}, targetPort), []byte(udpPayload))
nBytes, err = udpConn.Write(udpRequest)
assert.Int(nBytes).Equals(len(udpRequest))
assert.Error(err).IsNil()
udpResponse := make([]byte, 1024)
nBytes, err = udpConn.Read(udpResponse)
assert.Error(err).IsNil()
assert.Bytes(udpResponse[:nBytes]).Equals(
socks5UDPRequest(v2net.IPAddress([]byte{127, 0, 0, 1}, targetPort), []byte("Processed: UDP request to udp server.")))
udpConn.Close()
conn.Close()
}

View File

@@ -11,16 +11,17 @@ import (
)
var (
targetOS = flag.String("os", runtime.GOOS, "Target OS of this build.")
targetArch = flag.String("arch", runtime.GOARCH, "Target CPU arch of this build.")
archive = flag.Bool("zip", false, "Whether to make an archive of files or not.")
flagTargetOS = flag.String("os", runtime.GOOS, "Target OS of this build.")
flagTargetArch = flag.String("arch", runtime.GOARCH, "Target CPU arch of this build.")
flagArchive = flag.Bool("zip", false, "Whether to make an archive of files or not.")
binPath string
)
func createTargetDirectory(version string, goOS GoOS, goArch GoArch) (string, error) {
suffix := getSuffix(goOS, goArch)
GOPATH := os.Getenv("GOPATH")
targetDir := filepath.Join(GOPATH, "bin", "v2ray-"+version+suffix)
targetDir := filepath.Join(binPath, "v2ray-"+version+suffix)
if version != "custom" {
os.RemoveAll(targetDir)
}
@@ -36,19 +37,31 @@ func getTargetFile(goOS GoOS) string {
return "v2ray" + suffix
}
func getBinPath() string {
GOPATH := os.Getenv("GOPATH")
return filepath.Join(GOPATH, "bin")
}
func main() {
flag.Parse()
binPath = getBinPath()
build(*flagTargetOS, *flagTargetArch, *flagArchive, "")
}
v2rayOS := parseOS(*targetOS)
v2rayArch := parseArch(*targetArch)
func build(targetOS, targetArch string, archive bool, version string) {
v2rayOS := parseOS(targetOS)
v2rayArch := parseArch(targetArch)
version, err := git.RepoVersionHead()
if version == git.VersionUndefined {
version = "custom"
}
if err != nil {
fmt.Println("Unable to detect V2Ray version: " + err.Error())
return
if len(version) == 0 {
v, err := git.RepoVersionHead()
if v == git.VersionUndefined {
v = "custom"
}
if err != nil {
fmt.Println("Unable to detect V2Ray version: " + err.Error())
return
}
version = v
}
fmt.Printf("Building V2Ray (%s) for %s %s\n", version, v2rayOS, v2rayArch)
@@ -68,9 +81,7 @@ func main() {
fmt.Println("Unable to copy config files: " + err.Error())
}
if *archive {
GOPATH := os.Getenv("GOPATH")
binPath := filepath.Join(GOPATH, "bin")
if archive {
err := os.Chdir(binPath)
if err != nil {
fmt.Printf("Unable to switch to directory (%s): %v\n", binPath, err)

59
tools/build/build_test.go Normal file
View File

@@ -0,0 +1,59 @@
package main
import (
"fmt"
"os"
"path/filepath"
"testing"
"github.com/v2ray/v2ray-core/testing/unit"
)
func cleanBinPath() {
os.RemoveAll(binPath)
os.Mkdir(binPath, os.ModeDir|0777)
}
func fileExists(file string) bool {
_, err := os.Stat(file)
return err == nil
}
func allFilesExists(files ...string) bool {
for _, file := range files {
fullPath := filepath.Join(binPath, file)
if !fileExists(fullPath) {
fmt.Println(fullPath + " doesn't exist.")
return false
}
}
return true
}
func TestBuildMacOS(t *testing.T) {
assert := unit.Assert(t)
binPath = filepath.Join(os.Getenv("GOPATH"), "testing")
cleanBinPath()
build("macos", "amd64", true, "test")
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")
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")
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()
}