Compare commits

..

48 Commits

Author SHA1 Message Date
V2 Ray
d4dcbbc734 Workaround travis brekage
See: https://github.com/travis-ci/travis-ci/issues/5145
2015-11-23 12:08:10 +01:00
V2Ray
869cd46450 Rename to routing 2015-11-23 00:19:23 +01:00
V2Ray
790f6c038c Fix field rule 2015-11-22 22:14:27 +01:00
V2Ray
1cdd3e6647 test case for ip rule 2015-11-22 21:16:28 +01:00
V2Ray
fb1dda5a19 Update config files 2015-11-22 21:05:16 +01:00
V2Ray
46b81b7e98 Update version for next release 2015-11-22 17:45:42 +01:00
V2Ray
12e72509a5 code ready for selective routing 2015-11-22 17:41:52 +01:00
V2Ray
f4ec19625e Implementation of rules router 2015-11-22 12:05:21 +01:00
V2Ray
d48ac4418f config for rule based router 2015-11-21 21:43:40 +01:00
V2Ray
794b5081e3 Simplify swap 2015-11-17 14:26:13 +01:00
V2Ray
1b8e100879 validation reader for vmess 2015-11-15 21:54:28 +01:00
V2Ray
57dc6c69f1 Router config 2015-11-14 14:24:56 +01:00
V2Ray
1d4b98ab9a Outbound detour config 2015-11-13 23:43:58 +01:00
V2Ray
8597642002 UDP support for dokodemo door 2015-11-11 00:08:43 +01:00
V2Ray
b6cebd127d fuzz test for socks udp 2015-11-10 18:16:13 +01:00
V2Ray
3a6844f482 reduce number of iterations of vmess fuzzing test. 2015-11-10 12:25:26 +01:00
V2Ray
bd48556b98 Smarter reader generator 2015-11-10 12:13:01 +01:00
V2Ray
2a6f4740c1 fuzzing test for vmess protocol 2015-11-10 00:05:25 +01:00
V2Ray
d34678d9a6 fuzzing test for socks protocol 2015-11-09 23:52:31 +01:00
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
68 changed files with 1851 additions and 526 deletions

View File

@@ -9,13 +9,15 @@ before_install:
- go get github.com/mattn/goveralls
script:
- go test github.com/v2ray/v2ray-core/...
- ./testing/coverage/coverall
- go test github.com/v2ray/v2ray-core/...
- ./testing/coverage/coverall
env:
secure: "nnEiGTuS8SsSFRpxUsPh6hmx/OfPDA6AO3OX7IpjPCbkQnjuFEsm3DfPEZOHTiYra00Ea3bNw9ePLPqyWdLAPmcLoUBhWRyfevt9m3jrbyrT8O9MCXNDY6i1ll3E43nx8kxRDF1QbYaSK4jppa8Vu2vyZH5+GiS0JVcw/7CfX8TyUMbDuyaQXYQ1kwixlThQZH43xxQ7u5CFF1pBFdwpkuDm2/wKUE+0CGZOeWzUYI8h1in4eY0Vse4Zt4GqS2eywf4rw12bBysZ21UnT/xu990m5nzAScbUGjloplJNpdZGtD8SBTGujZBMMUzKi/E0zJkdEf37MZ9rsarfv6v9khdwTp/8VoAiZxpG1IDISIu0TClAjw8NYO5hmuF01/oJexMuxqRhMPwbk1nPsustlBKEG3zjvW5yILMkiaRl67Pj+9h21zMGYmwPGka7Ollh9ki2h17RFNuj9Yxm5XX2xvZDIvtxL1a8S50vv7VZTT9rrrFMhGP7ty9gj2opjJ7QBgwi2W/eVGhfshfnZJjJ7Bqf+gl1MDOYcTlqmFe5JvKdIO9mN7gskJizmeFxh31LrZ2sCY71/iicGj7gZJ4e/u2/dI2OVfFWTTbHoiIyCLvvrA18zBF9Sky1Y3QDj85GdRtC0SI6TXJLAIa7jNgF6Nr2mAg044DaX9VW0VH0VnE="
before_deploy: "./release/release.sh"
before_deploy:
- rvm 1.9.3 do gem install mime-types -v 2.6.2
- "./release/release.sh"
deploy:
provider: releases

View File

@@ -1,11 +1,11 @@
package config
type RouterConfig interface {
Strategy() string
Settings() interface{}
}
import (
routerconfig "github.com/v2ray/v2ray-core/app/router/config"
v2net "github.com/v2ray/v2ray-core/common/net"
)
type ConnectionTag string
type DetourTag string
type ConnectionConfig interface {
Protocol() string
@@ -16,21 +16,24 @@ type LogConfig interface {
AccessLog() string
}
type PortRange interface {
From() uint16
To() uint16
}
type InboundDetourConfig interface {
Protocol() string
PortRange() PortRange
PortRange() v2net.PortRange
Settings() interface{}
}
type OutboundDetourConfig interface {
Protocol() string
Tag() DetourTag
Settings() interface{}
}
type PointConfig interface {
Port() uint16
LogConfig() LogConfig
RouterConfig() routerconfig.RouterConfig
InboundConfig() ConnectionConfig
OutboundConfig() ConnectionConfig
InboundDetours() []InboundDetourConfig
OutboundDetours() []OutboundDetourConfig
}

View File

@@ -3,21 +3,22 @@ package json
import (
"encoding/json"
"github.com/v2ray/v2ray-core/app/point/config"
v2net "github.com/v2ray/v2ray-core/common/net"
v2netjson "github.com/v2ray/v2ray-core/common/net/json"
proxyconfig "github.com/v2ray/v2ray-core/proxy/common/config"
)
type InboundDetourConfig struct {
ProtocolValue string `json:"protocol"`
PortRangeValue *PortRange `json:"port"`
SettingsValue json.RawMessage `json:"settings"`
ProtocolValue string `json:"protocol"`
PortRangeValue *v2netjson.PortRange `json:"port"`
SettingsValue json.RawMessage `json:"settings"`
}
func (this *InboundDetourConfig) Protocol() string {
return this.ProtocolValue
}
func (this *InboundDetourConfig) PortRange() config.PortRange {
func (this *InboundDetourConfig) PortRange() v2net.PortRange {
return this.PortRangeValue
}

View File

@@ -6,17 +6,21 @@ import (
"os"
"github.com/v2ray/v2ray-core/app/point/config"
routerconfig "github.com/v2ray/v2ray-core/app/router/config"
routerconfigjson "github.com/v2ray/v2ray-core/app/router/config/json"
"github.com/v2ray/v2ray-core/common/log"
proxyconfig "github.com/v2ray/v2ray-core/proxy/common/config"
)
// Config is the config for Point server.
type Config struct {
PortValue uint16 `json:"port"` // Port of this Point server.
LogConfigValue *LogConfig `json:"log"`
InboundConfigValue *ConnectionConfig `json:"inbound"`
OutboundConfigValue *ConnectionConfig `json:"outbound"`
InboundDetoursValue []*InboundDetourConfig `json:"inboundDetour"`
PortValue uint16 `json:"port"` // Port of this Point server.
LogConfigValue *LogConfig `json:"log"`
RouterConfigValue *routerconfigjson.RouterConfig `json:"routing"`
InboundConfigValue *ConnectionConfig `json:"inbound"`
OutboundConfigValue *ConnectionConfig `json:"outbound"`
InboundDetoursValue []*InboundDetourConfig `json:"inboundDetour"`
OutboundDetoursValue []*OutboundDetourConfig `json:"outboundDetour"`
}
func (config *Config) Port() uint16 {
@@ -30,6 +34,13 @@ func (config *Config) LogConfig() config.LogConfig {
return config.LogConfigValue
}
func (this *Config) RouterConfig() routerconfig.RouterConfig {
if this.RouterConfigValue == nil {
return nil
}
return this.RouterConfigValue
}
func (config *Config) InboundConfig() config.ConnectionConfig {
if config.InboundConfigValue == nil {
return nil
@@ -52,6 +63,14 @@ func (this *Config) InboundDetours() []config.InboundDetourConfig {
return detours
}
func (this *Config) OutboundDetours() []config.OutboundDetourConfig {
detours := make([]config.OutboundDetourConfig, len(this.OutboundDetoursValue))
for idx, detour := range this.OutboundDetoursValue {
detours[idx] = detour
}
return detours
}
func LoadConfig(file string) (*Config, error) {
fixedFile := os.ExpandEnv(file)
rawConfig, err := ioutil.ReadFile(fixedFile)

View File

@@ -0,0 +1,26 @@
package json
import (
"encoding/json"
"github.com/v2ray/v2ray-core/app/point/config"
proxyconfig "github.com/v2ray/v2ray-core/proxy/common/config"
)
type OutboundDetourConfig struct {
ProtocolValue string `json:"protocol"`
TagValue string `json:"tag"`
SettingsValue json.RawMessage `json:"settings"`
}
func (this *OutboundDetourConfig) Protocol() string {
return this.ProtocolValue
}
func (this *OutboundDetourConfig) Tag() config.DetourTag {
return config.DetourTag(this.TagValue)
}
func (this *OutboundDetourConfig) Settings() interface{} {
return loadConnectionConfig(this.SettingsValue, this.ProtocolValue, proxyconfig.TypeOutbound)
}

View File

@@ -2,6 +2,8 @@ package mocks
import (
"github.com/v2ray/v2ray-core/app/point/config"
routerconfig "github.com/v2ray/v2ray-core/app/router/config"
v2net "github.com/v2ray/v2ray-core/common/net"
)
type ConnectionConfig struct {
@@ -39,20 +41,31 @@ type InboundDetourConfig struct {
PortRangeValue *PortRange
}
func (this *InboundDetourConfig) PortRange() config.PortRange {
func (this *InboundDetourConfig) PortRange() v2net.PortRange {
return this.PortRangeValue
}
type OutboundDetourConfig struct {
ConnectionConfig
TagValue config.DetourTag
}
func (this *OutboundDetourConfig) Tag() config.DetourTag {
return this.TagValue
}
func (config *LogConfig) AccessLog() string {
return config.AccessLogValue
}
type Config struct {
PortValue uint16
LogConfigValue *LogConfig
InboundConfigValue *ConnectionConfig
OutboundConfigValue *ConnectionConfig
InboundDetoursValue []*InboundDetourConfig
PortValue uint16
LogConfigValue *LogConfig
RouterConfigValue routerconfig.RouterConfig
InboundConfigValue *ConnectionConfig
OutboundConfigValue *ConnectionConfig
InboundDetoursValue []*InboundDetourConfig
OutboundDetoursValue []*OutboundDetourConfig
}
func (config *Config) Port() uint16 {
@@ -63,6 +76,10 @@ func (config *Config) LogConfig() config.LogConfig {
return config.LogConfigValue
}
func (this *Config) RouterConfig() routerconfig.RouterConfig {
return this.RouterConfigValue
}
func (config *Config) InboundConfig() config.ConnectionConfig {
return config.InboundConfigValue
}
@@ -78,3 +95,11 @@ func (this *Config) InboundDetours() []config.InboundDetourConfig {
}
return detours
}
func (this *Config) OutboundDetours() []config.OutboundDetourConfig {
detours := make([]config.OutboundDetourConfig, len(this.OutboundDetoursValue))
for idx, detour := range this.OutboundDetoursValue {
detours[idx] = detour
}
return detours
}

View File

@@ -2,6 +2,7 @@ package point
import (
"github.com/v2ray/v2ray-core/app/point/config"
"github.com/v2ray/v2ray-core/app/router"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/common/retry"
@@ -11,10 +12,12 @@ import (
// Point is an single server in V2Ray system.
type Point struct {
port uint16
ich connhandler.InboundConnectionHandler
och connhandler.OutboundConnectionHandler
idh []*InboundDetourHandler
port uint16
ich connhandler.InboundConnectionHandler
och connhandler.OutboundConnectionHandler
idh []*InboundDetourHandler
odh map[config.DetourTag]connhandler.OutboundConnectionHandler
router router.Router
}
// NewPoint returns a new Point server based on given configuration.
@@ -65,6 +68,34 @@ func NewPoint(pConfig config.PointConfig) (*Point, error) {
}
}
outboundDetours := pConfig.OutboundDetours()
if len(outboundDetours) > 0 {
vpoint.odh = make(map[config.DetourTag]connhandler.OutboundConnectionHandler)
for _, detourConfig := range outboundDetours {
detourFactory := connhandler.GetOutboundConnectionHandlerFactory(detourConfig.Protocol())
if detourFactory == nil {
log.Error("Unknown detour outbound connection handler factory %s", detourConfig.Protocol())
return nil, config.BadConfiguration
}
detourHandler, err := detourFactory.Create(detourConfig.Settings())
if err != nil {
log.Error("Failed to create detour outbound connection handler: %v", err)
return nil, err
}
vpoint.odh[detourConfig.Tag()] = detourHandler
}
}
routerConfig := pConfig.RouterConfig()
if routerConfig != nil {
r, err := router.CreateRouter(routerConfig.Strategy(), routerConfig.Settings())
if err != nil {
log.Error("Failed to create router: %v", err)
return nil, config.BadConfiguration
}
vpoint.router = r
}
return vpoint, nil
}
@@ -100,6 +131,19 @@ func (vp *Point) Start() error {
func (p *Point) DispatchToOutbound(packet v2net.Packet) ray.InboundRay {
direct := ray.NewRay()
dest := packet.Destination()
if p.router != nil {
tag, err := p.router.TakeDetour(dest)
if err == nil {
handler, found := p.odh[tag]
if found {
go handler.Dispatch(packet, direct)
return direct
}
}
}
go p.och.Dispatch(packet, direct)
return direct
}

View File

@@ -0,0 +1,6 @@
package config
type RouterConfig interface {
Strategy() string
Settings() interface{}
}

View File

@@ -0,0 +1,25 @@
package json
type ConfigObjectCreator func() interface{}
var (
configCache map[string]ConfigObjectCreator
)
func RegisterRouterConfig(strategy string, creator ConfigObjectCreator) error {
// TODO: check strategy
configCache[strategy] = creator
return nil
}
func CreateRouterConfig(strategy string) interface{} {
creator, found := configCache[strategy]
if !found {
return nil
}
return creator()
}
func init() {
configCache = make(map[string]ConfigObjectCreator)
}

View File

@@ -0,0 +1,26 @@
package json
import (
"encoding/json"
"github.com/v2ray/v2ray-core/common/log"
)
type RouterConfig struct {
StrategyValue string `json:"strategy"`
SettingsValue json.RawMessage `json:"settings"`
}
func (this *RouterConfig) Strategy() string {
return this.StrategyValue
}
func (this *RouterConfig) Settings() interface{} {
settings := CreateRouterConfig(this.Strategy())
err := json.Unmarshal(this.SettingsValue, settings)
if err != nil {
log.Error("Failed to load router settings: %v", err)
return nil
}
return settings
}

View File

@@ -1,12 +1,18 @@
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)
TakeDetour(v2net.Destination) (config.DetourTag, error)
}
type RouterFactory interface {
@@ -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
}

View File

@@ -0,0 +1,93 @@
package json
import (
"encoding/json"
"errors"
"net"
"strings"
v2net "github.com/v2ray/v2ray-core/common/net"
v2netjson "github.com/v2ray/v2ray-core/common/net/json"
)
type FieldRule struct {
Rule
Domain string
IP *net.IPNet
Port v2net.PortRange
Network v2net.NetworkList
}
func (this *FieldRule) Apply(dest v2net.Destination) bool {
address := dest.Address()
if len(this.Domain) > 0 {
if !address.IsDomain() || !strings.Contains(address.Domain(), this.Domain) {
return false
}
}
if this.IP != nil {
if !(address.IsIPv4() || address.IsIPv6()) || !this.IP.Contains(address.IP()) {
return false
}
}
if this.Port != nil {
port := address.Port()
if port < this.Port.From() || port > this.Port.To() {
return false
}
}
if this.Network != nil {
if !this.Network.HasNetwork(v2net.Network(dest.Network())) {
return false
}
}
return true
}
func (this *FieldRule) UnmarshalJSON(data []byte) error {
type RawFieldRule struct {
Rule
Domain string `json:"domain"`
IP string `json:"ip"`
Port *v2netjson.PortRange `json:"port"`
Network *v2netjson.NetworkList `json:"network"`
}
rawFieldRule := RawFieldRule{}
err := json.Unmarshal(data, &rawFieldRule)
if err != nil {
return err
}
this.Type = rawFieldRule.Type
this.OutboundTag = rawFieldRule.OutboundTag
hasField := false
if len(rawFieldRule.Domain) > 0 {
this.Domain = rawFieldRule.Domain
hasField = true
}
if len(rawFieldRule.IP) > 0 {
_, ipNet, err := net.ParseCIDR(rawFieldRule.IP)
if err != nil {
return errors.New("Invalid IP range in router rule: " + err.Error())
}
this.IP = ipNet
hasField = true
}
if rawFieldRule.Port != nil {
this.Port = rawFieldRule.Port
hasField = true
}
if rawFieldRule.Network != nil {
this.Network = rawFieldRule.Network
hasField = true
}
if !hasField {
return errors.New("This rule has no effective fields.")
}
return nil
}

View File

@@ -0,0 +1,71 @@
package json
import (
"testing"
v2net "github.com/v2ray/v2ray-core/common/net"
v2nettesting "github.com/v2ray/v2ray-core/common/net/testing"
"github.com/v2ray/v2ray-core/testing/unit"
)
func TestDomainMatching(t *testing.T) {
assert := unit.Assert(t)
rule := &FieldRule{
Domain: "v2ray.com",
}
dest := v2net.NewTCPDestination(v2net.DomainAddress("www.v2ray.com", 80))
assert.Bool(rule.Apply(dest)).IsTrue()
}
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()
}
func TestIPMatching(t *testing.T) {
assert := unit.Assert(t)
rawJson := `{
"type": "field",
"ip": "10.0.0.0/8",
"tag": "test"
}`
rule := parseRule([]byte(rawJson))
dest := v2net.NewTCPDestination(v2net.IPAddress([]byte{10, 0, 0, 1}, 80))
assert.Bool(rule.Apply(dest)).IsTrue()
}
func TestPortNotMatching(t *testing.T) {
assert := unit.Assert(t)
rawJson := `{
"type": "field",
"port": "80-100",
"tag": "test"
}`
rule := parseRule([]byte(rawJson))
dest := v2net.NewTCPDestination(v2net.IPAddress([]byte{10, 0, 0, 1}, 79))
assert.Bool(rule.Apply(dest)).IsFalse()
}
func TestDomainNotMatching(t *testing.T) {
assert := unit.Assert(t)
rawJson := `{
"type": "field",
"domain": "google.com",
"tag": "test"
}`
rule := parseRule([]byte(rawJson))
dest := v2net.NewTCPDestination(v2net.IPAddress([]byte{10, 0, 0, 1}, 79))
assert.Bool(rule.Apply(dest)).IsFalse()
}

View File

@@ -0,0 +1,47 @@
package json
import (
"encoding/json"
v2routerconfigjson "github.com/v2ray/v2ray-core/app/router/config/json"
"github.com/v2ray/v2ray-core/app/router/rules/config"
"github.com/v2ray/v2ray-core/common/log"
)
type RouterRuleConfig struct {
RuleList []json.RawMessage `json:"rules"`
}
func parseRule(msg json.RawMessage) config.Rule {
rule := new(Rule)
err := json.Unmarshal(msg, rule)
if err != nil {
log.Error("Invalid router rule: %v", err)
return nil
}
if rule.Type == "field" {
fieldrule := new(FieldRule)
err = json.Unmarshal(msg, fieldrule)
if err != nil {
log.Error("Invalid field rule: %v", err)
return nil
}
return fieldrule
}
log.Error("Unknown router rule type: %s", rule.Type)
return nil
}
func (this *RouterRuleConfig) Rules() []config.Rule {
rules := make([]config.Rule, len(this.RuleList))
for idx, rawRule := range this.RuleList {
rules[idx] = parseRule(rawRule)
}
return rules
}
func init() {
v2routerconfigjson.RegisterRouterConfig("rules", func() interface{} {
return new(RouterRuleConfig)
})
}

View File

@@ -0,0 +1,19 @@
package json
import (
"github.com/v2ray/v2ray-core/app/point/config"
v2net "github.com/v2ray/v2ray-core/common/net"
)
type Rule struct {
Type string `json:"type"`
OutboundTag string `json:"outboundTag"`
}
func (this *Rule) Tag() config.DetourTag {
return config.DetourTag(this.OutboundTag)
}
func (this *Rule) Apply(dest v2net.Destination) bool {
return false
}

View File

@@ -0,0 +1,5 @@
package config
type RouterRuleConfig interface {
Rules() []Rule
}

View File

@@ -0,0 +1,11 @@
package config
import (
"github.com/v2ray/v2ray-core/app/point/config"
v2net "github.com/v2ray/v2ray-core/common/net"
)
type Rule interface {
Tag() config.DetourTag
Apply(dest v2net.Destination) bool
}

View File

@@ -0,0 +1,51 @@
package rules
import (
"errors"
pointconfig "github.com/v2ray/v2ray-core/app/point/config"
"github.com/v2ray/v2ray-core/app/router"
"github.com/v2ray/v2ray-core/app/router/rules/config"
"github.com/v2ray/v2ray-core/app/router/rules/config/json"
v2net "github.com/v2ray/v2ray-core/common/net"
)
var (
InvalidRule = errors.New("Invalid Rule")
NoRuleApplicable = errors.New("No rule applicable")
EmptyTag = pointconfig.DetourTag("")
)
type Router struct {
rules []config.Rule
}
func (this *Router) TakeDetour(dest v2net.Destination) (pointconfig.DetourTag, error) {
for _, rule := range this.rules {
if rule.Apply(dest) {
return rule.Tag(), nil
}
}
return EmptyTag, NoRuleApplicable
}
type RouterFactory struct {
}
func (this *RouterFactory) Create(rawConfig interface{}) (router.Router, error) {
config := rawConfig.(*json.RouterRuleConfig)
rules := config.Rules()
for _, rule := range rules {
if rule == nil {
return nil, InvalidRule
}
}
return &Router{
rules: rules,
}, nil
}
func init() {
router.RegisterRouter("rules", &RouterFactory{})
}

View File

@@ -1,25 +0,0 @@
package wildcard_router
import (
"github.com/v2ray/v2ray-core/app/point/config"
"github.com/v2ray/v2ray-core/app/router"
v2net "github.com/v2ray/v2ray-core/common/net"
)
type WildcardRouter struct {
}
func (router *WildcardRouter) TakeDetour(packet v2net.Packet) (config.ConnectionTag, error) {
return "", nil
}
type WildcardRouterFactory struct {
}
func (factory *WildcardRouterFactory) Create(rawConfig interface{}) (router.Router, error) {
return &WildcardRouter{}, nil
}
func init() {
router.RegisterRouter("wildcard", &WildcardRouterFactory{})
}

View File

@@ -22,9 +22,7 @@ func (queue timedQueueImpl) Less(i, j int) bool {
}
func (queue timedQueueImpl) Swap(i, j int) {
tmp := queue[i]
queue[i] = queue[j]
queue[j] = tmp
queue[i], queue[j] = queue[j], queue[i]
}
func (queue *timedQueueImpl) Push(value interface{}) {

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

@@ -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)

6
common/net/portrange.go Normal file
View File

@@ -0,0 +1,6 @@
package net
type PortRange interface {
From() uint16
To() uint16
}

View File

@@ -0,0 +1,14 @@
package testing
type PortRange struct {
FromValue uint16
ToValue uint16
}
func (this *PortRange) From() uint16 {
return this.FromValue
}
func (this *PortRange) To() uint16 {
return this.ToValue
}

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

@@ -8,7 +8,7 @@ import (
)
var (
version = "0.11"
version = "0.14"
build = "Custom"
codename = "Post Apocalypse"
intro = "A stable and unbreakable connection for everyone."

View File

@@ -35,15 +35,59 @@ func NewDokodemoDoor(dispatcher app.PacketDispatcher, config *json.DokodemoConfi
}
func (this *DokodemoDoor) Listen(port uint16) error {
this.accepting = true
if this.config.Network.HasNetwork(v2net.TCPNetwork) {
err := this.ListenTCP(port)
if err != nil {
return err
}
}
if this.config.Network.HasNetwork(v2net.UDPNetwork) {
err := this.ListenUDP(port)
if err != nil {
return err
}
}
return nil
}
func (this *DokodemoDoor) ListenUDP(port uint16) error {
udpConn, err := net.ListenUDP("udp", &net.UDPAddr{
IP: []byte{0, 0, 0, 0},
Port: int(port),
Zone: "",
})
if err != nil {
log.Error("Dokodemo failed to listen on port %d: %v", port, err)
return err
}
go this.handleUDPPackets(udpConn)
return nil
}
func (this *DokodemoDoor) handleUDPPackets(udpConn *net.UDPConn) {
defer udpConn.Close()
for this.accepting {
buffer := alloc.NewBuffer()
nBytes, addr, err := udpConn.ReadFromUDP(buffer.Value)
buffer.Slice(0, nBytes)
if err != nil {
buffer.Release()
log.Error("Dokodemo failed to read from UDP: %v", err)
return
}
packet := v2net.NewPacket(v2net.NewUDPDestination(this.address), buffer, false)
ray := this.dispatcher.DispatchToOutbound(packet)
close(ray.InboundInput())
for payload := range ray.InboundOutput() {
udpConn.WriteToUDP(payload.Value, addr)
}
}
}
func (this *DokodemoDoor) ListenTCP(port uint16) error {
tcpListener, err := net.ListenTCP("tcp", &net.TCPAddr{
IP: []byte{0, 0, 0, 0},
@@ -54,7 +98,6 @@ func (this *DokodemoDoor) ListenTCP(port uint16) error {
log.Error("Dokodemo failed to listen on port %d: %v", port, err)
return err
}
this.accepting = true
go this.AcceptTCPConnections(tcpListener)
return nil
}

View File

@@ -5,12 +5,13 @@ 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/servers/udp"
"github.com/v2ray/v2ray-core/testing/unit"
)
@@ -75,3 +76,64 @@ func TestDokodemoTCP(t *testing.T) {
assert.String("Processed: " + data2Send).Equals(string(response[:nBytes]))
}
func TestDokodemoUDP(t *testing.T) {
assert := unit.Assert(t)
port := v2nettesting.PickPort()
data2Send := "Data to be sent to remote."
udpServer := &udp.Server{
Port: port,
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()
pointPort := v2nettesting.PickPort()
networkList := v2netjson.NetworkList([]string{"udp"})
config := mocks.Config{
PortValue: pointPort,
InboundConfigValue: &mocks.ConnectionConfig{
ProtocolValue: "dokodemo-door",
SettingsValue: &json.DokodemoConfig{
Host: "127.0.0.1",
Port: int(port),
Network: &networkList,
Timeout: 0,
},
},
OutboundConfigValue: &mocks.ConnectionConfig{
ProtocolValue: "freedom",
SettingsValue: nil,
},
}
point, err := point.NewPoint(&config)
assert.Error(err).IsNil()
err = point.Start()
assert.Error(err).IsNil()
udpClient, err := net.DialUDP("udp", nil, &net.UDPAddr{
IP: []byte{127, 0, 0, 1},
Port: int(pointPort),
Zone: "",
})
assert.Error(err).IsNil()
udpClient.Write([]byte(data2Send))
response := make([]byte, 1024)
nBytes, err := udpClient.Read(response)
assert.Error(err).IsNil()
udpClient.Close()
assert.String("Processed: " + data2Send).Equals(string(response[:nBytes]))
}

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

@@ -0,0 +1,35 @@
package protocol
import (
"testing"
"github.com/v2ray/v2ray-core/testing/fuzzing"
)
const (
Iterations = int(500000)
)
func TestReadAuthentication(t *testing.T) {
for i := 0; i < Iterations; i++ {
ReadAuthentication(fuzzing.RandomReader())
}
}
func TestReadUserPassRequest(t *testing.T) {
for i := 0; i < Iterations; i++ {
ReadUserPassRequest(fuzzing.RandomReader())
}
}
func TestReadRequest(t *testing.T) {
for i := 0; i < Iterations; i++ {
ReadRequest(fuzzing.RandomReader())
}
}
func TestReadUDPRequest(t *testing.T) {
for i := 0; i < Iterations; i++ {
ReadUDPRequest(fuzzing.RandomBytes())
}
}

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

@@ -0,0 +1,75 @@
package io
import (
"errors"
"hash/fnv"
"io"
"github.com/v2ray/v2ray-core/common/alloc"
"github.com/v2ray/v2ray-core/transport"
)
var (
TruncatedPayload = errors.New("Truncated payload.")
)
type ValidationReader struct {
reader io.Reader
buffer *alloc.Buffer
}
func NewValidationReader(reader io.Reader) *ValidationReader {
return &ValidationReader{
reader: reader,
buffer: alloc.NewLargeBuffer().Clear(),
}
}
func (this *ValidationReader) Read(data []byte) (int, error) {
nBytes, err := this.reader.Read(data)
if err != nil {
return nBytes, err
}
nBytesActual := 0
dataActual := data[:]
for {
payload, rest, err := parsePayload(data)
if err != nil {
return nBytesActual, err
}
copy(dataActual, payload)
nBytesActual += len(payload)
dataActual = dataActual[nBytesActual:]
if len(rest) == 0 {
break
}
data = rest
}
return nBytesActual, nil
}
func parsePayload(data []byte) (payload []byte, rest []byte, err error) {
dataLen := len(data)
if dataLen < 6 {
err = TruncatedPayload
return
}
payloadLen := int(data[0])<<8 + int(data[1])
if dataLen < payloadLen+6 {
err = TruncatedPayload
return
}
payload = data[6 : 6+payloadLen]
rest = data[6+payloadLen:]
fnv1a := fnv.New32a()
fnv1a.Write(payload)
actualHash := fnv1a.Sum32()
expectedHash := uint32(data[2])<<24 + uint32(data[3])<<16 + uint32(data[4])<<8 + uint32(data[5])
if actualHash != expectedHash {
err = transport.CorruptedPacket
return
}
return
}

View File

@@ -0,0 +1,29 @@
package mocks
import (
"github.com/v2ray/v2ray-core/proxy/vmess/config"
)
type StaticUser struct {
id *config.ID
}
func (this *StaticUser) ID() *config.ID {
return this.id
}
func (this *StaticUser) Level() config.UserLevel {
return config.UserLevelUntrusted
}
type StaticUserSet struct {
}
func (us *StaticUserSet) AddUser(user config.User) error {
return nil
}
func (us *StaticUserSet) GetUser(userhash []byte) (config.User, int64, bool) {
id, _ := config.NewID("703e9102-eb57-499c-8b59-faf4f371bb21")
return &StaticUser{id: id}, 0, true
}

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

@@ -0,0 +1,15 @@
package protocol
import (
"testing"
"github.com/v2ray/v2ray-core/proxy/vmess/protocol/user/testing/mocks"
"github.com/v2ray/v2ray-core/testing/fuzzing"
)
func TestVMessRequestReader(t *testing.T) {
reader := NewVMessRequestReader(&mocks.StaticUserSet{})
for i := 0; i < 1000000; i++ {
reader.Read(fuzzing.RandomReader())
}
}

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,98 @@
"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"}
]
}
]
}
},
"outboundDetour": [
{
"protocol": "freedom",
"settings": {},
"tag": "direct"
}
],
"routing": {
"strategy": "rules",
"settings": {
"rules": [
{
"type": "field",
"ip": "0.0.0.0/8",
"outboundTag": "direct"
},
{
"type": "field",
"ip": "10.0.0.0/8",
"outboundTag": "direct"
},
{
"type": "field",
"ip": "100.64.0.0/10",
"outboundTag": "direct"
},
{
"type": "field",
"ip": "127.0.0.0/8",
"outboundTag": "direct"
},
{
"type": "field",
"ip": "169.254.0.0/16",
"outboundTag": "direct"
},
{
"type": "field",
"ip": "172.16.0.0/12",
"outboundTag": "direct"
},
{
"type": "field",
"ip": "192.0.0.0/24",
"outboundTag": "direct"
},
{
"type": "field",
"ip": "192.0.2.0/24",
"outboundTag": "direct"
},
{
"type": "field",
"ip": "192.168.0.0/16",
"outboundTag": "direct"
},
{
"type": "field",
"ip": "198.18.0.0/15",
"outboundTag": "direct"
},
{
"type": "field",
"ip": "198.51.100.0/24",
"outboundTag": "direct"
},
{
"type": "field",
"ip": "203.0.113.0/24",
"outboundTag": "direct"
},
{
"type": "field",
"ip": "::1/128",
"outboundTag": "direct"
},
{
"type": "field",
"ip": "fc00::/7",
"outboundTag": "direct"
},
{
"type": "field",
"ip": "fe80::/10",
"outboundTag": "direct"
}
]
}

View File

@@ -15,12 +15,100 @@
"id": "3b129dec-72a3-4d28-aeee-028a0fe86e22",
"level": 1
}
],
"udp": false
]
}
},
"outbound": {
"protocol": "freedom",
"settings": {}
},
"outboundDetour": [
{
"protocol": "blackhole",
"settings": {},
"tag": "blocked"
}
],
"routing": {
"strategy": "rules",
"settings": {
"rules": [
{
"type": "field",
"ip": "0.0.0.0/8",
"outboundTag": "blocked"
},
{
"type": "field",
"ip": "10.0.0.0/8",
"outboundTag": "blocked"
},
{
"type": "field",
"ip": "100.64.0.0/10",
"outboundTag": "blocked"
},
{
"type": "field",
"ip": "127.0.0.0/8",
"outboundTag": "blocked"
},
{
"type": "field",
"ip": "169.254.0.0/16",
"outboundTag": "blocked"
},
{
"type": "field",
"ip": "172.16.0.0/12",
"outboundTag": "blocked"
},
{
"type": "field",
"ip": "192.0.0.0/24",
"outboundTag": "blocked"
},
{
"type": "field",
"ip": "192.0.2.0/24",
"outboundTag": "blocked"
},
{
"type": "field",
"ip": "192.168.0.0/16",
"outboundTag": "blocked"
},
{
"type": "field",
"ip": "198.18.0.0/15",
"outboundTag": "blocked"
},
{
"type": "field",
"ip": "198.51.100.0/24",
"outboundTag": "blocked"
},
{
"type": "field",
"ip": "203.0.113.0/24",
"outboundTag": "blocked"
},
{
"type": "field",
"ip": "::1/128",
"outboundTag": "blocked"
},
{
"type": "field",
"ip": "fc00::/7",
"outboundTag": "blocked"
},
{
"type": "field",
"ip": "fe80::/10",
"outboundTag": "blocked"
}
]
}
}
}

View File

@@ -9,9 +9,14 @@ import (
"github.com/v2ray/v2ray-core"
"github.com/v2ray/v2ray-core/app/point"
jsonconf "github.com/v2ray/v2ray-core/app/point/config/json"
_ "github.com/v2ray/v2ray-core/app/router/config/json"
_ "github.com/v2ray/v2ray-core/app/router/rules"
_ "github.com/v2ray/v2ray-core/app/router/rules/config/json"
"github.com/v2ray/v2ray-core/common/log"
// The following are neccesary as they register handlers in their init functions.
_ "github.com/v2ray/v2ray-core/proxy/blackhole"
_ "github.com/v2ray/v2ray-core/proxy/blackhole/config/json"
_ "github.com/v2ray/v2ray-core/proxy/dokodemo"
_ "github.com/v2ray/v2ray-core/proxy/dokodemo/config/json"
_ "github.com/v2ray/v2ray-core/proxy/freedom"

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,17 @@
package fuzzing
import (
"bytes"
"crypto/rand"
"io"
)
func RandomBytes() []byte {
buffer := make([]byte, 256)
rand.Read(buffer)
return buffer[1 : 1+int(buffer[0])]
}
func RandomReader() io.Reader {
return bytes.NewReader(RandomBytes())
}

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()
}