Compare commits

..

142 Commits

Author SHA1 Message Date
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
V2Ray
dcdce6696b Update version for next release 2015-11-02 00:07:28 +01:00
V2Ray
e70c02f768 Fix test break 2015-11-02 00:06:56 +01:00
V2Ray
bbac647656 Update user id 2015-11-02 00:05:32 +01:00
V2Ray
590699fc7b Update ports 2015-11-02 00:04:11 +01:00
V2Ray
fae78683f9 Update DNS port 2015-11-02 00:02:46 +01:00
V2Ray
1cec5ac643 Test case for inbound detour network 2015-11-01 23:01:15 +01:00
V2Ray
1c6b66eacf Test case for dokodemo 2015-11-01 22:17:49 +01:00
V2Ray
03b8c8f9e8 Port picker 2015-11-01 21:32:08 +01:00
V2Ray
192960b711 Move mocked connection handlers to proxy/testing/mocks 2015-11-01 21:15:08 +01:00
V2Ray
f983d285b8 detour handler 2015-11-01 00:11:41 +01:00
V2Ray
3c43268898 inbound detour 2015-10-31 22:22:43 +01:00
V2Ray
1708c48f5b Port range 2015-10-31 21:43:26 +01:00
V2Ray
1c09b70931 format code 2015-10-31 14:08:13 +01:00
V2Ray
3765826602 Test case for config cache. 2015-10-31 14:08:09 +01:00
V2Ray
46c0d457d9 User settings for trusted user 2015-10-31 09:39:45 +01:00
V2Ray
b44098d752 Introduce user level 2015-10-31 00:38:31 +01:00
V2Ray
d585ec0593 Move config to app/point 2015-10-30 22:50:45 +01:00
V2Ray
2b45e63607 Move config cache to proxy/common 2015-10-30 22:42:24 +01:00
V2Ray
c56e17fff9 Dokodemo proxy 2015-10-30 15:56:46 +01:00
V2Ray
f93b29993b Move connection handler interfaces to proxy/common/connhandler 2015-10-30 00:11:29 +01:00
V2Ray
361a22d74d Move proxy errors to proxy/common/errors 2015-10-29 23:59:57 +01:00
V2Ray
ce07ea9769 Split json config files 2015-10-29 23:41:37 +01:00
V2Ray
6e8425b23a Remove config type in connection settings() 2015-10-29 23:35:54 +01:00
V2Ray
fdb41bbd50 Remove call to UTC() which is not necessary. 2015-10-29 12:04:14 +01:00
V2Ray
d0ae47e2ce Router interface 2015-10-28 23:18:07 +01:00
V2Ray
9b8632d01a BlackHole proxy 2015-10-28 17:41:14 +01:00
V2Ray
fdb952fb01 Merge branch 'master' of https://github.com/v2ray/v2ray-core 2015-10-28 12:13:43 +01:00
V2Ray
08328d23fa beginning of http proxy 2015-10-28 12:13:27 +01:00
V2 Ray
65bc306ba7 Update README.md 2015-10-27 12:50:25 +01:00
V2Ray
294376edc0 Remove unused const 2015-10-25 21:44:08 +01:00
V2Ray
2f721c4006 Bump version for 0.10 release 2015-10-25 21:39:44 +01:00
V2Ray
58dcfd5e84 Reduce timeout for reading VMess header 2015-10-21 23:10:03 +02:00
V2Ray
bbc41c5e63 Increase small buffer pool 2015-10-21 22:39:36 +02:00
V2Ray
f474fc32a7 Remove all []byte allocation 2015-10-21 22:38:53 +02:00
V2Ray
96c5d32d59 Remove []byte allocation in vmess 2015-10-21 22:28:26 +02:00
V2Ray
2c710d6b1c Protect from DoS attack 2015-10-21 21:53:55 +02:00
V2Ray
280c138cb4 Remove Milestone description as plan changes 2015-10-19 15:30:10 +02:00
V2Ray
462aa6f041 Remove failing tests 2015-10-19 13:17:18 +02:00
V2Ray
cf0e0b579b Add IP section in socks doc 2015-10-19 10:33:11 +02:00
V2 Ray
481c367154 Merge pull request #46 from v2ray/revert-45-patch-2
Revert "Update guide.md"
2015-10-19 10:31:15 +02:00
V2 Ray
401d61cb5f Revert "Update guide.md" 2015-10-19 10:30:58 +02:00
V2Ray
6fefaaaf5a Merge branch 'master' of https://github.com/v2ray/v2ray-core 2015-10-19 10:30:15 +02:00
V2 Ray
30d7b39410 Merge pull request #45 from kxjhlele/patch-2
Update guide.md
2015-10-19 10:25:37 +02:00
kxjhlele
f44d270c88 Update guide.md
更新配置文件 vpoint_vmess_freedom.json
2015-10-19 15:01:30 +08:00
V2Ray
c4ab202c11 Update version structure 2015-10-18 20:52:38 +02:00
V2Ray
9cd78bee07 Update travis script 2015-10-18 20:45:04 +02:00
V2Ray
288f469c36 Update design 2015-10-18 16:06:55 +02:00
V2Ray
a5888eea73 Merge ID into VMess intro 2015-10-18 15:13:04 +02:00
V2Ray
0ae69720fa Remove 'Point' in guide 2015-10-18 14:49:25 +02:00
V2Ray
a5af51c42c Update install guide 2015-10-18 14:39:59 +02:00
V2Ray
9803bfc3a9 Smart config file 2015-10-18 13:14:34 +02:00
V2Ray
b6a0d0aba9 Bump version for v0.9 release 2015-10-18 13:14:23 +02:00
V2Ray
0703c4469b Update install script 2015-10-18 11:57:43 +02:00
V2Ray
58b88a70ab Remove debug info in build.go 2015-10-18 11:51:21 +02:00
V2Ray
d221147eb4 Update release script 2015-10-18 11:51:02 +02:00
V2Ray
74cba8b177 Able to zip folder when building 2015-10-18 11:42:00 +02:00
V2Ray
0de60adf3c Refactoring build script 2015-10-18 00:50:51 +02:00
V2Ray
acdada81ed Helper functions for git 2015-10-17 22:08:28 +02:00
V2Ray
dcb84b19bd Universal build script 2015-10-17 21:32:48 +02:00
V2Ray
af8c8f16e5 Update donation list 2015-10-17 20:27:53 +02:00
V2Ray
a81327c5b9 Fix zero users bug 2015-10-16 14:15:28 +02:00
Claire Raymond
5c7eb63bea import vmess json config 2015-10-16 10:05:59 +00:00
Claire Raymond
0ebc60febe Fix PrintVersion 2015-10-16 10:05:43 +00:00
Claire Raymond
771d0225c7 Refactor vmess config 2015-10-16 10:03:22 +00:00
Claire Raymond
f10f08c87d add retry on socks and vmess inbound 2015-10-15 11:42:43 +00:00
Claire Raymond
0acfe57b0c format code 2015-10-15 11:42:26 +00:00
Claire Raymond
c592d9c246 update 2015-10-15 11:25:57 +00:00
V2 Ray
9071b3ea10 more comments 2015-10-15 11:15:59 +00:00
V2Ray
a84c03d5db Remove windows config 2015-10-14 21:02:08 +02:00
V2Ray
ef6a200fe8 Add a default value to configFile 2015-10-14 18:14:55 +02:00
V2Ray
51773ea27d Add a config for windows client 2015-10-14 18:13:37 +02:00
V2Ray
a03eaa0316 Split directRay from ray.go 2015-10-14 15:07:13 +02:00
V2Ray
e79f4450b4 typo 2015-10-14 15:01:09 +02:00
V2Ray
4bc91b0215 Fix test 2015-10-14 14:56:11 +02:00
V2Ray
890d185979 Cleanup root directory 2015-10-14 14:51:19 +02:00
V2Ray
1b80a1a85a Handle multiple UDP packets in socks. 2015-10-14 09:56:04 +02:00
V2Ray
2a00e2c6e9 Fix for IPv4 address 2015-10-14 08:43:04 +02:00
V2Ray
8408b7735c format code 2015-10-14 01:15:29 +02:00
V2Ray
3c946daf88 Fix infinate look in retry 2015-10-14 00:57:00 +02:00
V2Ray
7cd2f32d7e Always show running message. 2015-10-14 00:08:52 +02:00
V2Ray
99671a173f Customize UDP server address 2015-10-14 00:04:49 +02:00
V2Ray
3c259b7069 Remove unused const 2015-10-13 23:55:54 +02:00
V2Ray
4ac3eab385 format code 2015-10-13 22:00:12 +02:00
V2Ray
8c5865d4e7 Lazy initialize of socks5 response 2015-10-13 22:00:03 +02:00
V2Ray
7cc8d90f26 test case for wrong auth method 2015-10-13 21:55:12 +02:00
V2Ray
b9b1e3fe61 Fix line separator 2015-10-13 21:45:09 +02:00
V2Ray
3bd4238e88 Line separator 2015-10-13 21:41:53 +02:00
V2Ray
dc7d4a2309 Test case for wrong user account in socks5 2015-10-13 21:29:27 +02:00
V2Ray
efb881d73c Remove log level detection during runtime 2015-10-13 18:27:29 +02:00
V2Ray
1675063dc6 Always print version 2015-10-13 14:30:37 +02:00
V2Ray
9cf5c3edfb Merge branch 'master' of https://github.com/v2ray/v2ray-core 2015-10-13 13:55:18 +02:00
V2Ray
1d40220d31 Remove error defination 2015-10-13 13:55:06 +02:00
V2Ray
93625dd656 Add a retry mechanism 2015-10-13 12:27:50 +02:00
V2 Ray
06dac18f81 Merge pull request #40 from kxjhlele/patch-1
Update install.sh
2015-10-13 11:25:16 +02:00
kxjhlele
b2cd6e739e Update install.sh
go get -u github.com/v2ray/v2ray-core
2015-10-13 16:52:48 +08:00
152 changed files with 4654 additions and 1629 deletions

View File

@@ -27,7 +27,8 @@ deploy:
- "$GOPATH/bin/v2ray-windows-32.zip"
- "$GOPATH/bin/v2ray-linux-64.zip"
- "$GOPATH/bin/v2ray-linux-32.zip"
- "$GOPATH/bin/v2ray-armv6.zip"
- "$GOPATH/bin/v2ray-linux-arm.zip"
- "$GOPATH/bin/v2ray-linux-arm64.zip"
skip_cleanup: true
on:
tags: true

View File

@@ -7,27 +7,9 @@
[中文](https://github.com/V2Ray/v2ray-core/blob/master/README.md) | [English](https://github.com/V2Ray/v2ray-core/blob/master/spec/en/README.md)
V2Ray 是一个模块化的代理软件包,它的目标是提供常用的代理软件模块,化网络代理软件的开发。
V2Ray 是一个模块化的代理软件包,它的目标是提供常用的代理软件模块,化网络代理软件的开发。
## 联系方式
* 聊天室https://gitter.im/v2ray/v2ray-core
* Twitterhttps://twitter.com/projectv2ray
* 私下联系love@v2ray.com
* [捐赠](https://github.com/v2ray/v2ray-core/blob/master/spec/donate.md)
## 使用说明
* [简明教程](https://github.com/V2Ray/v2ray-core/blob/master/spec/guide.md)
* [建议或意见](https://github.com/v2ray/v2ray-core/issues)
* [Issue 指引](https://github.com/V2Ray/v2ray-core/blob/master/spec/issue.md)
* [当前状态](https://github.com/V2Ray/v2ray-core/blob/master/spec/status.md)
* [错误信息](https://github.com/V2Ray/v2ray-core/blob/master/spec/errors.md)
* [性能测试](https://github.com/V2Ray/v2ray-core/blob/master/spec/benchmark.md)
## 开发人员相关
* [概要设计](https://github.com/V2Ray/v2ray-core/blob/master/spec/design.md)
* [开发计划](https://github.com/V2Ray/v2ray-core/blob/master/spec/roadmap.md)
* [Help Wanted](https://github.com/v2ray/v2ray-core/labels/help%20wanted)所有被标记为“Help Wanted”的 Issue 都接受 Pull Request如果你对本项目感兴趣并想做点贡献请挑选其中之一完善之不甚感激。
* [开发指引](https://github.com/V2Ray/v2ray-core/blob/master/spec/develop.md)
[官方网站](https://www.v2ray.com/)
## License
[The MIT License (MIT)](https://raw.githubusercontent.com/v2ray/v2ray-core/master/LICENSE)

11
app/packet_dispatcher.go Normal file
View File

@@ -0,0 +1,11 @@
package app
import (
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/transport/ray"
)
// PacketDispatcher dispatch a packet and possibly further network payload to its destination.
type PacketDispatcher interface {
DispatchToOutbound(packet v2net.Packet) ray.InboundRay
}

View File

@@ -0,0 +1,39 @@
package config
import (
routerconfig "github.com/v2ray/v2ray-core/app/router/config"
v2net "github.com/v2ray/v2ray-core/common/net"
)
type DetourTag string
type ConnectionConfig interface {
Protocol() string
Settings() interface{}
}
type LogConfig interface {
AccessLog() string
}
type InboundDetourConfig interface {
Protocol() string
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

@@ -0,0 +1,9 @@
package config
import (
"errors"
)
var (
BadConfiguration = errors.New("Bad configuration.")
)

View File

@@ -0,0 +1,36 @@
package json
import (
"encoding/json"
"github.com/v2ray/v2ray-core/common/log"
proxyconfig "github.com/v2ray/v2ray-core/proxy/common/config"
proxyjson "github.com/v2ray/v2ray-core/proxy/common/config/json"
)
type ConnectionConfig struct {
ProtocolString string `json:"protocol"`
SettingsMessage json.RawMessage `json:"settings"`
Type proxyconfig.Type `json:"-"`
}
func (c *ConnectionConfig) Protocol() string {
return c.ProtocolString
}
func (c *ConnectionConfig) Settings() interface{} {
return loadConnectionConfig(c.SettingsMessage, c.Protocol(), c.Type)
}
func loadConnectionConfig(message json.RawMessage, protocol string, cType proxyconfig.Type) interface{} {
configObj := proxyjson.CreateConfig(protocol, cType)
if configObj == nil {
panic("Unknown protocol " + protocol)
}
err := json.Unmarshal(message, configObj)
if err != nil {
log.Error("Unable to parse connection config: %v", err)
panic("Failed to parse connection config.")
}
return configObj
}

View File

@@ -0,0 +1,27 @@
package json
import (
"encoding/json"
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 *v2netjson.PortRange `json:"port"`
SettingsValue json.RawMessage `json:"settings"`
}
func (this *InboundDetourConfig) Protocol() string {
return this.ProtocolValue
}
func (this *InboundDetourConfig) PortRange() v2net.PortRange {
return this.PortRangeValue
}
func (this *InboundDetourConfig) Settings() interface{} {
return loadConnectionConfig(this.SettingsValue, this.ProtocolValue, proxyconfig.TypeInbound)
}

View File

@@ -0,0 +1,93 @@
package json
import (
"encoding/json"
"io/ioutil"
"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"`
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 {
return config.PortValue
}
func (config *Config) LogConfig() config.LogConfig {
if config.LogConfigValue == nil {
return nil
}
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
}
return config.InboundConfigValue
}
func (config *Config) OutboundConfig() config.ConnectionConfig {
if config.OutboundConfigValue == nil {
return nil
}
return config.OutboundConfigValue
}
func (this *Config) InboundDetours() []config.InboundDetourConfig {
detours := make([]config.InboundDetourConfig, len(this.InboundDetoursValue))
for idx, detour := range this.InboundDetoursValue {
detours[idx] = detour
}
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)
if err != nil {
log.Error("Failed to read server config file (%s): %v", file, err)
return nil, err
}
jsonConfig := &Config{}
err = json.Unmarshal(rawConfig, jsonConfig)
if err != nil {
log.Error("Failed to load server config: %v", err)
return nil, err
}
jsonConfig.InboundConfigValue.Type = proxyconfig.TypeInbound
jsonConfig.OutboundConfigValue.Type = proxyconfig.TypeOutbound
return jsonConfig, err
}

View File

@@ -4,11 +4,11 @@ import (
"path/filepath"
"testing"
"github.com/v2ray/v2ray-core/config"
"github.com/v2ray/v2ray-core/config/json"
"github.com/v2ray/v2ray-core/app/point/config/json"
_ "github.com/v2ray/v2ray-core/proxy/dokodemo/config/json"
_ "github.com/v2ray/v2ray-core/proxy/freedom/config/json"
_ "github.com/v2ray/v2ray-core/proxy/socks/config/json"
_ "github.com/v2ray/v2ray-core/proxy/vmess"
_ "github.com/v2ray/v2ray-core/proxy/vmess/config/json"
"github.com/v2ray/v2ray-core/testing/unit"
)
@@ -27,10 +27,10 @@ func TestClientSampleConfig(t *testing.T) {
assert.Pointer(pointConfig.OutboundConfig()).IsNotNil()
assert.String(pointConfig.InboundConfig().Protocol()).Equals("socks")
assert.Pointer(pointConfig.InboundConfig().Settings(config.TypeInbound)).IsNotNil()
assert.Pointer(pointConfig.InboundConfig().Settings()).IsNotNil()
assert.String(pointConfig.OutboundConfig().Protocol()).Equals("vmess")
assert.Pointer(pointConfig.OutboundConfig().Settings(config.TypeOutbound)).IsNotNil()
assert.Pointer(pointConfig.OutboundConfig().Settings()).IsNotNil()
}
func TestServerSampleConfig(t *testing.T) {
@@ -47,8 +47,27 @@ func TestServerSampleConfig(t *testing.T) {
assert.Pointer(pointConfig.OutboundConfig()).IsNotNil()
assert.String(pointConfig.InboundConfig().Protocol()).Equals("vmess")
assert.Pointer(pointConfig.InboundConfig().Settings(config.TypeInbound)).IsNotNil()
assert.Pointer(pointConfig.InboundConfig().Settings()).IsNotNil()
assert.String(pointConfig.OutboundConfig().Protocol()).Equals("freedom")
assert.Pointer(pointConfig.OutboundConfig().Settings(config.TypeOutbound)).IsNotNil()
assert.Pointer(pointConfig.OutboundConfig().Settings()).IsNotNil()
}
func TestDetourConfig(t *testing.T) {
assert := unit.Assert(t)
// TODO: fix for Windows
baseDir := "$GOPATH/src/github.com/v2ray/v2ray-core/release/config"
pointConfig, err := json.LoadConfig(filepath.Join(baseDir, "vpoint_dns_detour.json"))
assert.Error(err).IsNil()
detours := pointConfig.InboundDetours()
assert.Int(len(detours)).Equals(1)
detour := detours[0]
assert.String(detour.Protocol()).Equals("dokodemo-door")
assert.Uint16(detour.PortRange().From()).Equals(uint16(28394))
assert.Uint16(detour.PortRange().To()).Equals(uint16(28394))
assert.Pointer(detour.Settings()).IsNotNil()
}

View File

@@ -0,0 +1,9 @@
package json
type LogConfig struct {
AccessLogValue string `json:"access"`
}
func (config *LogConfig) AccessLog() string {
return config.AccessLogValue
}

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

@@ -0,0 +1,105 @@
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 {
ProtocolValue string
SettingsValue interface{}
}
func (config *ConnectionConfig) Protocol() string {
return config.ProtocolValue
}
func (config *ConnectionConfig) Settings() interface{} {
return config.SettingsValue
}
type LogConfig struct {
AccessLogValue string
}
type PortRange struct {
FromValue uint16
ToValue uint16
}
func (this *PortRange) From() uint16 {
return this.FromValue
}
func (this *PortRange) To() uint16 {
return this.ToValue
}
type InboundDetourConfig struct {
ConnectionConfig
PortRangeValue *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
RouterConfigValue routerconfig.RouterConfig
InboundConfigValue *ConnectionConfig
OutboundConfigValue *ConnectionConfig
InboundDetoursValue []*InboundDetourConfig
OutboundDetoursValue []*OutboundDetourConfig
}
func (config *Config) Port() uint16 {
return config.PortValue
}
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
}
func (config *Config) OutboundConfig() config.ConnectionConfig {
return config.OutboundConfigValue
}
func (this *Config) InboundDetours() []config.InboundDetourConfig {
detours := make([]config.InboundDetourConfig, len(this.InboundDetoursValue))
for idx, detour := range this.InboundDetoursValue {
detours[idx] = detour
}
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

@@ -0,0 +1,56 @@
package point
import (
"github.com/v2ray/v2ray-core/app/point/config"
"github.com/v2ray/v2ray-core/common/log"
"github.com/v2ray/v2ray-core/common/retry"
"github.com/v2ray/v2ray-core/proxy/common/connhandler"
)
type InboundConnectionHandlerWithPort struct {
port uint16
handler connhandler.InboundConnectionHandler
}
type InboundDetourHandler struct {
point *Point
config config.InboundDetourConfig
ich []*InboundConnectionHandlerWithPort
}
func (this *InboundDetourHandler) Initialize() error {
ichFactory := connhandler.GetInboundConnectionHandlerFactory(this.config.Protocol())
if ichFactory == nil {
log.Error("Unknown inbound connection handler factory %s", this.config.Protocol())
return config.BadConfiguration
}
ports := this.config.PortRange()
this.ich = make([]*InboundConnectionHandlerWithPort, 0, ports.From()-ports.To()+1)
for i := ports.From(); i <= ports.To(); i++ {
ichConfig := this.config.Settings()
ich, err := ichFactory.Create(this.point, ichConfig)
if err != nil {
log.Error("Failed to create inbound connection handler: %v", err)
return err
}
this.ich = append(this.ich, &InboundConnectionHandlerWithPort{
port: i,
handler: ich,
})
}
return nil
}
func (this *InboundDetourHandler) Start() error {
for _, ich := range this.ich {
return retry.Timed(100 /* times */, 100 /* ms */).On(func() error {
err := ich.handler.Listen(ich.port)
if err != nil {
return err
}
return nil
})
}
return nil
}

149
app/point/point.go Normal file
View File

@@ -0,0 +1,149 @@
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"
"github.com/v2ray/v2ray-core/proxy/common/connhandler"
"github.com/v2ray/v2ray-core/transport/ray"
)
// Point is an single server in V2Ray system.
type Point struct {
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.
// The server is not started at this point.
func NewPoint(pConfig config.PointConfig) (*Point, error) {
var vpoint = new(Point)
vpoint.port = pConfig.Port()
ichFactory := connhandler.GetInboundConnectionHandlerFactory(pConfig.InboundConfig().Protocol())
if ichFactory == nil {
log.Error("Unknown inbound connection handler factory %s", pConfig.InboundConfig().Protocol())
return nil, config.BadConfiguration
}
ichConfig := pConfig.InboundConfig().Settings()
ich, err := ichFactory.Create(vpoint, ichConfig)
if err != nil {
log.Error("Failed to create inbound connection handler: %v", err)
return nil, err
}
vpoint.ich = ich
ochFactory := connhandler.GetOutboundConnectionHandlerFactory(pConfig.OutboundConfig().Protocol())
if ochFactory == nil {
log.Error("Unknown outbound connection handler factory %s", pConfig.OutboundConfig().Protocol())
return nil, config.BadConfiguration
}
ochConfig := pConfig.OutboundConfig().Settings()
och, err := ochFactory.Create(ochConfig)
if err != nil {
log.Error("Failed to create outbound connection handler: %v", err)
return nil, err
}
vpoint.och = och
detours := pConfig.InboundDetours()
if len(detours) > 0 {
vpoint.idh = make([]*InboundDetourHandler, len(detours))
for idx, detourConfig := range detours {
detourHandler := &InboundDetourHandler{
point: vpoint,
config: detourConfig,
}
err := detourHandler.Initialize()
if err != nil {
return nil, err
}
vpoint.idh[idx] = detourHandler
}
}
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
}
// Start starts the Point server, and return any error during the process.
// In the case of any errors, the state of the server is unpredicatable.
func (vp *Point) Start() error {
if vp.port <= 0 {
log.Error("Invalid port %d", vp.port)
return config.BadConfiguration
}
err := retry.Timed(100 /* times */, 100 /* ms */).On(func() error {
err := vp.ich.Listen(vp.port)
if err != nil {
return err
}
log.Warning("Point server started on port %d", vp.port)
return nil
})
if err != nil {
return err
}
for _, detourHandler := range vp.idh {
err := detourHandler.Start()
if err != nil {
return err
}
}
return nil
}
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
}

37
app/router/router.go Normal file
View File

@@ -0,0 +1,37 @@
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.Destination) (config.DetourTag, error)
}
type RouterFactory interface {
Create(rawConfig interface{}) (Router, error)
}
var (
routerCache = make(map[string]RouterFactory)
)
func RegisterRouter(name string, factory RouterFactory) error {
// TODO: check name
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

@@ -124,7 +124,7 @@ func (p *bufferPool) cleanup(tick <-chan time.Time) {
}
}
var smallPool = newBufferPool(1024, 16, 64)
var smallPool = newBufferPool(1024, 64, 512)
var mediumPool = newBufferPool(8*1024, 256, 2048)
var largePool = newBufferPool(64*1024, 128, 1024)

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{}) {
@@ -72,7 +70,7 @@ func (queue *TimedQueue) RemovedEntries() <-chan interface{} {
func (queue *TimedQueue) cleanup(tick <-chan time.Time) {
for now := range tick {
nowSec := now.UTC().Unix()
nowSec := now.Unix()
for {
queue.access.RLock()
queueLen := queue.queue.Len()

View File

@@ -12,7 +12,7 @@ func TestTimedQueue(t *testing.T) {
removed := make(map[string]bool)
nowSec := time.Now().UTC().Unix()
nowSec := time.Now().Unix()
q := NewTimedQueue(2)
go func() {
@@ -51,7 +51,7 @@ func TestTimedQueue(t *testing.T) {
<-tick
assert.Bool(removed["Values"]).IsFalse()
q.Add("Value1", time.Now().UTC().Unix()+10)
q.Add("Value1", time.Now().Unix()+10)
<-tick
v1, ok = removed["Value1"]

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,133 +0,0 @@
package errors
import (
"fmt"
)
func HasCode(err error, code int) bool {
if errWithCode, ok := err.(ErrorWithCode); ok {
return errWithCode.Code() == code
}
return false
}
type ErrorWithCode interface {
error
Code() int
}
type ErrorCode int
func (code ErrorCode) Code() int {
return int(code)
}
func (code ErrorCode) Prefix() string {
return fmt.Sprintf("[Error 0x%04X] ", code.Code())
}
type AuthenticationError struct {
ErrorCode
AuthDetail interface{}
}
func NewAuthenticationError(detail interface{}) AuthenticationError {
return AuthenticationError{
ErrorCode: 1,
AuthDetail: detail,
}
}
func (err AuthenticationError) Error() string {
return fmt.Sprintf("%sInvalid auth %v", err.Prefix(), err.AuthDetail)
}
type ProtocolVersionError struct {
ErrorCode
Version int
}
func NewProtocolVersionError(version int) ProtocolVersionError {
return ProtocolVersionError{
ErrorCode: 2,
Version: version,
}
}
func (err ProtocolVersionError) Error() string {
return fmt.Sprintf("%sInvalid version %d", err.Prefix(), err.Version)
}
type CorruptedPacketError struct {
ErrorCode
}
var corruptedPacketErrorInstance = CorruptedPacketError{ErrorCode: 3}
func NewCorruptedPacketError() CorruptedPacketError {
return corruptedPacketErrorInstance
}
func (err CorruptedPacketError) Error() string {
return err.Prefix() + "Corrupted packet."
}
type IPFormatError struct {
ErrorCode
IP []byte
}
func NewIPFormatError(ip []byte) IPFormatError {
return IPFormatError{
ErrorCode: 4,
IP: ip,
}
}
func (err IPFormatError) Error() string {
return fmt.Sprintf("%sInvalid IP %v", err.Prefix(), err.IP)
}
type ConfigurationError struct {
ErrorCode
}
var configurationErrorInstance = ConfigurationError{ErrorCode: 5}
func NewConfigurationError() ConfigurationError {
return configurationErrorInstance
}
func (r ConfigurationError) Error() string {
return r.Prefix() + "Invalid configuration."
}
type InvalidOperationError struct {
ErrorCode
Operation string
}
func NewInvalidOperationError(operation string) InvalidOperationError {
return InvalidOperationError{
ErrorCode: 6,
Operation: operation,
}
}
func (r InvalidOperationError) Error() string {
return r.Prefix() + "Invalid operation: " + r.Operation
}
type BadConfigurationError struct {
ErrorCode
}
var badConfigurationErrorInstance = BadConfigurationError{ErrorCode: 6}
func NewBadConfigurationError() BadConfigurationError {
return badConfigurationErrorInstance
}
func (r BadConfigurationError) Error() string {
return r.Prefix() + "Bad configuration."
}

View File

@@ -1,23 +0,0 @@
package errors_test
import (
"testing"
"github.com/v2ray/v2ray-core/common/errors"
"github.com/v2ray/v2ray-core/testing/unit"
)
type MockError struct {
errors.ErrorCode
}
func (err MockError) Error() string {
return "This is a fake error."
}
func TestHasCode(t *testing.T) {
assert := unit.Assert(t)
err := MockError{ErrorCode: 101}
assert.Error(err).HasCode(101)
}

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

@@ -3,6 +3,8 @@ package log
import (
"log"
"os"
"github.com/v2ray/v2ray-core/common/platform"
)
// AccessStatus is the status of an access request from clients.
@@ -63,7 +65,7 @@ func (logger *fileAccessLogger) Run() {
func newFileAccessLogger(path string) accessLogger {
file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
log.Printf("Unable to create or open file (%s): %v\n", path, err)
log.Printf("Unable to create or open file (%s): %v%s", path, err, platform.LineSeparator())
return nil
}
return &fileAccessLogger{

View File

@@ -1,9 +1,11 @@
package log
import (
"errors"
"fmt"
"log"
"io"
"os"
"github.com/v2ray/v2ray-core/common/platform"
)
const (
@@ -13,41 +15,83 @@ const (
ErrorLevel = LogLevel(3)
)
var logLevel = WarningLevel
type LogLevel int
func SetLogLevel(level LogLevel) {
logLevel = level
type logger interface {
WriteLog(prefix, format string, v ...interface{})
}
func writeLog(level LogLevel, prefix, format string, v ...interface{}) string {
if level < logLevel {
return ""
}
type noOpLogger struct {
}
func (l *noOpLogger) WriteLog(prefix, format string, v ...interface{}) {
// Swallow
}
type streamLogger struct {
writer io.Writer
}
func (l *streamLogger) WriteLog(prefix, format string, v ...interface{}) {
var data string
if v == nil || len(v) == 0 {
data = format
} else {
data = fmt.Sprintf(format, v...)
}
log.Println(prefix + data)
return data
l.writer.Write([]byte(prefix + data + platform.LineSeparator()))
}
var (
noOpLoggerInstance logger = &noOpLogger{}
streamLoggerInstance logger = &streamLogger{
writer: os.Stdout,
}
debugLogger = noOpLoggerInstance
infoLogger = noOpLoggerInstance
warningLogger = noOpLoggerInstance
errorLogger = noOpLoggerInstance
)
type LogLevel int
func SetLogLevel(level LogLevel) {
debugLogger = noOpLoggerInstance
if level <= DebugLevel {
debugLogger = streamLoggerInstance
}
infoLogger = noOpLoggerInstance
if level <= InfoLevel {
infoLogger = streamLoggerInstance
}
warningLogger = noOpLoggerInstance
if level <= WarningLevel {
warningLogger = streamLoggerInstance
}
errorLogger = noOpLoggerInstance
if level <= ErrorLevel {
errorLogger = streamLoggerInstance
}
}
// Debug outputs a debug log with given format and optional arguments.
func Debug(format string, v ...interface{}) {
writeLog(DebugLevel, "[Debug]", format, v...)
debugLogger.WriteLog("[Debug]", format, v...)
}
// Info outputs an info log with given format and optional arguments.
func Info(format string, v ...interface{}) {
writeLog(InfoLevel, "[Info]", format, v...)
infoLogger.WriteLog("[Info]", format, v...)
}
// Warning outputs a warning log with given format and optional arguments.
func Warning(format string, v ...interface{}) {
writeLog(WarningLevel, "[Warning]", format, v...)
warningLogger.WriteLog("[Warning]", format, v...)
}
func Error(format string, v ...interface{}) error {
data := writeLog(ErrorLevel, "[Error]", format, v...)
return errors.New(data)
// Error outputs an error log with given format and optional arguments.
func Error(format string, v ...interface{}) {
errorLogger.WriteLog("[Error]", format, v...)
}

35
common/log/log_test.go Normal file
View File

@@ -0,0 +1,35 @@
package log
import (
"bytes"
"testing"
"github.com/v2ray/v2ray-core/testing/unit"
)
func TestLogLevelSetting(t *testing.T) {
assert := unit.Assert(t)
assert.Pointer(debugLogger).Equals(noOpLoggerInstance)
SetLogLevel(DebugLevel)
assert.Pointer(debugLogger).Equals(streamLoggerInstance)
SetLogLevel(InfoLevel)
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

@@ -4,7 +4,6 @@ import (
"net"
"strconv"
"github.com/v2ray/v2ray-core/common/errors"
"github.com/v2ray/v2ray-core/common/log"
)
@@ -23,6 +22,15 @@ type Address interface {
String() string // String representation of this Address
}
func allZeros(data []byte) bool {
for _, v := range data {
if v != 0 {
return false
}
}
return true
}
// IPAddress creates an Address with given IP and port.
func IPAddress(ip []byte, port uint16) Address {
switch len(ip) {
@@ -32,6 +40,9 @@ func IPAddress(ip []byte, port uint16) Address {
ip: [4]byte{ip[0], ip[1], ip[2], ip[3]},
}
case net.IPv6len:
if allZeros(ip[0:10]) && ip[10] == 0xff && ip[11] == 0xff {
return IPAddress(ip[12:16], port)
}
return IPv6Address{
PortAddress: PortAddress{port: port},
ip: [16]byte{
@@ -42,7 +53,7 @@ func IPAddress(ip []byte, port uint16) Address {
},
}
default:
log.Error(errors.NewIPFormatError(ip).Error())
log.Error("Invalid IP format: %v", ip)
return nil
}
}

View File

@@ -1,6 +1,7 @@
package net
import (
"net"
"testing"
"github.com/v2ray/v2ray-core/testing/unit"
@@ -55,3 +56,13 @@ func TestDomainAddress(t *testing.T) {
assert.Uint16(addr.Port()).Equals(port)
assert.String(addr.String()).Equals("v2ray.com:443")
}
func TestNetIPv4Address(t *testing.T) {
assert := unit.Assert(t)
ip := net.IPv4(1, 2, 3, 4)
port := uint16(80)
addr := IPAddress(ip, port)
assert.Bool(addr.IsIPv4()).IsTrue()
assert.String(addr.String()).Equals("1.2.3.4:80")
}

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,46 @@
package json
import (
"encoding/json"
"errors"
"strings"
v2net "github.com/v2ray/v2ray-core/common/net"
)
type NetworkList []string
func NewNetworkList(networks []string) NetworkList {
list := NetworkList(make([]string, len(networks)))
for idx, network := range networks {
list[idx] = strings.ToLower(strings.TrimSpace(network))
}
return list
}
func (this *NetworkList) UnmarshalJSON(data []byte) error {
var strList []string
err := json.Unmarshal(data, &strList)
if err == nil {
*this = NewNetworkList(strList)
return nil
}
var str string
err = json.Unmarshal(data, &str)
if err == nil {
strList := strings.Split(str, ",")
*this = NewNetworkList(strList)
return nil
}
return errors.New("Unknown format of network list: " + string(data))
}
func (this *NetworkList) HasNetwork(network v2net.Network) bool {
for _, value := range *this {
if value == string(network) {
return true
}
}
return false
}

View File

@@ -0,0 +1,28 @@
package json
import (
"encoding/json"
"testing"
"github.com/v2ray/v2ray-core/testing/unit"
)
func TestArrayNetworkList(t *testing.T) {
assert := unit.Assert(t)
var list NetworkList
err := json.Unmarshal([]byte("[\"Tcp\"]"), &list)
assert.Error(err).IsNil()
assert.Bool(list.HasNetwork("tcp")).IsTrue()
assert.Bool(list.HasNetwork("udp")).IsFalse()
}
func TestStringNetworkList(t *testing.T) {
assert := unit.Assert(t)
var list NetworkList
err := json.Unmarshal([]byte("\"TCP, ip\""), &list)
assert.Error(err).IsNil()
assert.Bool(list.HasNetwork("tcp")).IsTrue()
assert.Bool(list.HasNetwork("udp")).IsFalse()
}

View File

@@ -0,0 +1,79 @@
package json
import (
"encoding/json"
"errors"
"strconv"
"strings"
"github.com/v2ray/v2ray-core/common/log"
)
var (
InvalidPortRange = errors.New("Invalid port range.")
)
type PortRange struct {
from uint16
to uint16
}
func (this *PortRange) From() uint16 {
return this.from
}
func (this *PortRange) To() uint16 {
return this.to
}
func (this *PortRange) UnmarshalJSON(data []byte) error {
var maybeint int
err := json.Unmarshal(data, &maybeint)
if err == nil {
if maybeint <= 0 || maybeint >= 65535 {
log.Error("Invalid port [%s]", string(data))
return InvalidPortRange
}
this.from = uint16(maybeint)
this.to = uint16(maybeint)
return nil
}
var maybestring string
err = json.Unmarshal(data, &maybestring)
if err == nil {
pair := strings.SplitN(maybestring, "-", 2)
if len(pair) == 1 {
value, err := strconv.Atoi(pair[0])
if err != nil || value <= 0 || value >= 65535 {
log.Error("Invalid from port %s", pair[0])
return InvalidPortRange
}
this.from = uint16(value)
this.to = uint16(value)
return nil
} else if len(pair) == 2 {
from, err := strconv.Atoi(pair[0])
if err != nil || from <= 0 || from >= 65535 {
log.Error("Invalid from port %s", pair[0])
return InvalidPortRange
}
this.from = uint16(from)
to, err := strconv.Atoi(pair[1])
if err != nil || to <= 0 || to >= 65535 {
log.Error("Invalid to port %s", pair[1])
return InvalidPortRange
}
this.to = uint16(to)
if this.from > this.to {
log.Error("Invalid port range %d -> %d", this.from, this.to)
return InvalidPortRange
}
return nil
}
}
return InvalidPortRange
}

View File

@@ -0,0 +1,69 @@
package json
import (
"encoding/json"
"testing"
"github.com/v2ray/v2ray-core/testing/unit"
)
func TestIntPort(t *testing.T) {
assert := unit.Assert(t)
var portRange PortRange
err := json.Unmarshal([]byte("1234"), &portRange)
assert.Error(err).IsNil()
assert.Uint16(portRange.from).Equals(uint16(1234))
assert.Uint16(portRange.to).Equals(uint16(1234))
}
func TestOverRangeIntPort(t *testing.T) {
assert := unit.Assert(t)
var portRange PortRange
err := json.Unmarshal([]byte("70000"), &portRange)
assert.Error(err).Equals(InvalidPortRange)
err = json.Unmarshal([]byte("-1"), &portRange)
assert.Error(err).Equals(InvalidPortRange)
}
func TestSingleStringPort(t *testing.T) {
assert := unit.Assert(t)
var portRange PortRange
err := json.Unmarshal([]byte("\"1234\""), &portRange)
assert.Error(err).IsNil()
assert.Uint16(portRange.from).Equals(uint16(1234))
assert.Uint16(portRange.to).Equals(uint16(1234))
}
func TestStringPairPort(t *testing.T) {
assert := unit.Assert(t)
var portRange PortRange
err := json.Unmarshal([]byte("\"1234-5678\""), &portRange)
assert.Error(err).IsNil()
assert.Uint16(portRange.from).Equals(uint16(1234))
assert.Uint16(portRange.to).Equals(uint16(5678))
}
func TestOverRangeStringPort(t *testing.T) {
assert := unit.Assert(t)
var portRange PortRange
err := json.Unmarshal([]byte("\"65536\""), &portRange)
assert.Error(err).Equals(InvalidPortRange)
err = json.Unmarshal([]byte("\"70000-80000\""), &portRange)
assert.Error(err).Equals(InvalidPortRange)
err = json.Unmarshal([]byte("\"1-90000\""), &portRange)
assert.Error(err).Equals(InvalidPortRange)
err = json.Unmarshal([]byte("\"700-600\""), &portRange)
assert.Error(err).Equals(InvalidPortRange)
}

12
common/net/network.go Normal file
View File

@@ -0,0 +1,12 @@
package net
const (
TCPNetwork = Network("tcp")
UDPNetwork = Network("udp")
)
type Network string
type NetworkList interface {
HasNetwork(Network) bool
}

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,13 @@
package testing
import (
"sync/atomic"
)
var (
port = int32(30000)
)
func PickPort() uint16 {
return uint16(atomic.AddInt32(&port, 1))
}

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

@@ -1,6 +1,7 @@
package net
import (
"io"
"net"
"time"
)
@@ -12,21 +13,19 @@ var (
type TimeOutReader struct {
timeout int
connection net.Conn
worker io.Reader
}
func NewTimeOutReader(timeout int, connection net.Conn) *TimeOutReader {
return &TimeOutReader{
timeout: timeout,
reader := &TimeOutReader{
connection: connection,
}
reader.SetTimeOut(timeout)
return reader
}
func (reader *TimeOutReader) Read(p []byte) (n int, err error) {
deadline := time.Duration(reader.timeout) * time.Second
reader.connection.SetReadDeadline(time.Now().Add(deadline))
n, err = reader.connection.Read(p)
reader.connection.SetReadDeadline(emptyTime)
return
func (reader *TimeOutReader) Read(p []byte) (int, error) {
return reader.worker.Read(p)
}
func (reader *TimeOutReader) GetTimeOut() int {
@@ -35,4 +34,35 @@ func (reader *TimeOutReader) GetTimeOut() int {
func (reader *TimeOutReader) SetTimeOut(value int) {
reader.timeout = value
if value > 0 {
reader.worker = &timedReaderWorker{
timeout: value,
connection: reader.connection,
}
} else {
reader.worker = &noOpReaderWorker{
connection: reader.connection,
}
}
}
type timedReaderWorker struct {
timeout int
connection net.Conn
}
func (this *timedReaderWorker) Read(p []byte) (int, error) {
deadline := time.Duration(this.timeout) * time.Second
this.connection.SetReadDeadline(time.Now().Add(deadline))
nBytes, err := this.connection.Read(p)
this.connection.SetReadDeadline(emptyTime)
return nBytes, err
}
type noOpReaderWorker struct {
connection net.Conn
}
func (this *noOpReaderWorker) Read(p []byte) (int, error) {
return this.connection.Read(p)
}

View File

@@ -17,6 +17,20 @@ func ReadFrom(reader io.Reader, buffer *alloc.Buffer) (*alloc.Buffer, error) {
return buffer, err
}
// ReadAllBytes reads all bytes required from reader, if no error happens.
func ReadAllBytes(reader io.Reader, buffer []byte) (int, error) {
bytesRead := 0
bytesAsked := len(buffer)
for bytesRead < bytesAsked {
nBytes, err := reader.Read(buffer[bytesRead:])
bytesRead += nBytes
if err != nil {
return bytesRead, err
}
}
return bytesRead, nil
}
// ReaderToChan dumps all content from a given reader to a chan by constantly reading it until EOF.
func ReaderToChan(stream chan<- *alloc.Buffer, reader io.Reader) error {
allocate := alloc.NewBuffer

View File

@@ -6,11 +6,10 @@ import (
"os"
)
type otherPlatformEnvironment struct {
}
var environmentInstance = &otherPlatformEnvironment{}
func (e *otherPlatformEnvironment) ExpandEnv(s string) string {
func ExpandEnv(s string) string {
return os.ExpandEnv(s)
}
func LineSeparator() string {
return "\n"
}

View File

@@ -1,10 +0,0 @@
// Package platform provides platform specific functionalities.
package platform
type environment interface {
ExpandEnv(s string) string
}
func ExpandEnv(s string) string {
return environmentInstance.ExpandEnv(s)
}

View File

@@ -2,16 +2,11 @@
package platform
import (
"os"
)
type windowsEnvironment struct {
}
var environmentInstance = &windowsEnvironment{}
func (e *windowsEnvironment) ExpandEnv(s string) string {
func ExpandEnv(s string) string {
// TODO
return s
}
func LineSeparator() string {
return "\r\n"
}

45
common/retry/retry.go Normal file
View File

@@ -0,0 +1,45 @@
package retry
import (
"errors"
"time"
)
var (
RetryFailed = errors.New("All retry attempts failed.")
)
type RetryStrategy interface {
On(func() error) error
}
type retryer struct {
NextDelay func(int) int
}
func (r *retryer) On(method func() error) error {
attempt := 0
for {
err := method()
if err == nil {
return nil
}
delay := r.NextDelay(attempt)
if delay < 0 {
return RetryFailed
}
<-time.After(time.Duration(delay) * time.Millisecond)
attempt++
}
}
func Timed(attempts int, delay int) RetryStrategy {
return &retryer{
NextDelay: func(attempt int) int {
if attempt >= attempts {
return -1
}
return delay
},
}
}

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

@@ -1,24 +0,0 @@
package config
type Type string
const (
TypeInbound = Type("inbound")
TypeOutbound = Type("outbound")
)
type ConnectionConfig interface {
Protocol() string
Settings(configType Type) interface{}
}
type LogConfig interface {
AccessLog() string
}
type PointConfig interface {
Port() uint16
LogConfig() LogConfig
InboundConfig() ConnectionConfig
OutboundConfig() ConnectionConfig
}

View File

@@ -1,20 +0,0 @@
package json
import (
"github.com/v2ray/v2ray-core/config"
)
type ConfigObjectCreator func() interface{}
var (
configCache = make(map[string]ConfigObjectCreator)
)
func getConfigKey(protocol string, cType config.Type) string {
return protocol + "_" + string(cType)
}
func RegisterConfigType(protocol string, cType config.Type, creator ConfigObjectCreator) {
// TODO: check name
configCache[getConfigKey(protocol, cType)] = creator
}

View File

@@ -1,92 +0,0 @@
package json
import (
"encoding/json"
"io/ioutil"
"os"
"github.com/v2ray/v2ray-core/common/log"
"github.com/v2ray/v2ray-core/config"
)
type ConnectionConfig struct {
ProtocolString string `json:"protocol"`
SettingsMessage json.RawMessage `json:"settings"`
}
func (config *ConnectionConfig) Protocol() string {
return config.ProtocolString
}
func (config *ConnectionConfig) Settings(configType config.Type) interface{} {
creator, found := configCache[getConfigKey(config.Protocol(), configType)]
if !found {
panic("Unknown protocol " + config.Protocol())
}
configObj := creator()
err := json.Unmarshal(config.SettingsMessage, configObj)
if err != nil {
log.Error("Unable to parse connection config: %v", err)
panic("Failed to parse connection config.")
}
return configObj
}
type LogConfig struct {
AccessLogValue string `json:"access"`
}
func (config *LogConfig) AccessLog() string {
return config.AccessLogValue
}
// 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"`
}
func (config *Config) Port() uint16 {
return config.PortValue
}
func (config *Config) LogConfig() config.LogConfig {
if config.LogConfigValue == nil {
return nil
}
return config.LogConfigValue
}
func (config *Config) InboundConfig() config.ConnectionConfig {
if config.InboundConfigValue == nil {
return nil
}
return config.InboundConfigValue
}
func (config *Config) OutboundConfig() config.ConnectionConfig {
if config.OutboundConfigValue == nil {
return nil
}
return config.OutboundConfigValue
}
func LoadConfig(file string) (*Config, error) {
fixedFile := os.ExpandEnv(file)
rawConfig, err := ioutil.ReadFile(fixedFile)
if err != nil {
log.Error("Failed to read server config file (%s): %v", file, err)
return nil, err
}
jsonConfig := &Config{}
err = json.Unmarshal(rawConfig, jsonConfig)
if err != nil {
log.Error("Failed to load server config: %v", err)
return nil, err
}
return jsonConfig, err
}

26
core.go
View File

@@ -1,20 +1,20 @@
// Package core provides common definitions and functionalities of V2Ray.
package core
import (
"fmt"
"github.com/v2ray/v2ray-core/common/platform"
)
var (
version = "0.8"
build = "Custom"
version = "0.14"
build = "Custom"
codename = "Post Apocalypse"
intro = "A stable and unbreakable connection for everyone."
)
const (
Codename = "Post Apocalypse"
Intro = "A stable and unbreakable connection for everyone."
)
func Version() string {
return version
}
func Build() string {
return build
func PrintVersion() {
fmt.Printf("V2Ray %s (%s) %s%s", version, codename, build, platform.LineSeparator())
fmt.Printf("%s%s", intro, platform.LineSeparator())
}

102
point.go
View File

@@ -1,102 +0,0 @@
package core
import (
"github.com/v2ray/v2ray-core/common/errors"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/config"
)
var (
inboundFactories = make(map[string]InboundConnectionHandlerFactory)
outboundFactories = make(map[string]OutboundConnectionHandlerFactory)
)
func RegisterInboundConnectionHandlerFactory(name string, factory InboundConnectionHandlerFactory) error {
// TODO check name
inboundFactories[name] = factory
return nil
}
func RegisterOutboundConnectionHandlerFactory(name string, factory OutboundConnectionHandlerFactory) error {
// TODO check name
outboundFactories[name] = factory
return nil
}
// Point is an single server in V2Ray system.
type Point struct {
port uint16
ich InboundConnectionHandler
och OutboundConnectionHandler
}
// NewPoint returns a new Point server based on given configuration.
// The server is not started at this point.
func NewPoint(pConfig config.PointConfig) (*Point, error) {
var vpoint = new(Point)
vpoint.port = pConfig.Port()
ichFactory, ok := inboundFactories[pConfig.InboundConfig().Protocol()]
if !ok {
log.Error("Unknown inbound connection handler factory %s", pConfig.InboundConfig().Protocol())
return nil, errors.NewBadConfigurationError()
}
ichConfig := pConfig.InboundConfig().Settings(config.TypeInbound)
ich, err := ichFactory.Create(vpoint, ichConfig)
if err != nil {
log.Error("Failed to create inbound connection handler: %v", err)
return nil, err
}
vpoint.ich = ich
ochFactory, ok := outboundFactories[pConfig.OutboundConfig().Protocol()]
if !ok {
log.Error("Unknown outbound connection handler factory %s", pConfig.OutboundConfig().Protocol())
return nil, errors.NewBadConfigurationError()
}
ochConfig := pConfig.OutboundConfig().Settings(config.TypeOutbound)
och, err := ochFactory.Create(vpoint, ochConfig)
if err != nil {
log.Error("Failed to create outbound connection handler: %v", err)
return nil, err
}
vpoint.och = och
return vpoint, nil
}
type InboundConnectionHandlerFactory interface {
Create(vp *Point, config interface{}) (InboundConnectionHandler, error)
}
type InboundConnectionHandler interface {
Listen(port uint16) error
}
type OutboundConnectionHandlerFactory interface {
Create(VP *Point, config interface{}) (OutboundConnectionHandler, error)
}
type OutboundConnectionHandler interface {
Dispatch(firstPacket v2net.Packet, ray OutboundRay) error
}
// Start starts the Point server, and return any error during the process.
// In the case of any errors, the state of the server is unpredicatable.
func (vp *Point) Start() error {
if vp.port <= 0 {
log.Error("Invalid port %d", vp.port)
return errors.NewBadConfigurationError()
}
err := vp.ich.Listen(vp.port)
// TODO: handle error
return err
}
func (p *Point) DispatchToOutbound(packet v2net.Packet) InboundRay {
ray := NewRay()
go p.och.Dispatch(packet, ray)
return ray
}

View File

@@ -0,0 +1,40 @@
package blackhole
import (
"io/ioutil"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/proxy/common/connhandler"
"github.com/v2ray/v2ray-core/transport/ray"
)
// BlackHole is an outbound connection that sliently swallow the entire payload.
type BlackHole struct {
}
func NewBlackHole() *BlackHole {
return &BlackHole{}
}
func (bh *BlackHole) Dispatch(firstPacket v2net.Packet, ray ray.OutboundRay) error {
if chunk := firstPacket.Chunk(); chunk != nil {
chunk.Release()
}
close(ray.OutboundOutput())
if firstPacket.MoreChunks() {
v2net.ChanToWriter(ioutil.Discard, ray.OutboundInput())
}
return nil
}
type BlackHoleFactory struct {
}
func (factory BlackHoleFactory) Create(config interface{}) (connhandler.OutboundConnectionHandler, error) {
return NewBlackHole(), nil
}
func init() {
connhandler.RegisterOutboundConnectionHandlerFactory("blackhole", BlackHoleFactory{})
}

View File

@@ -0,0 +1,14 @@
package json
import (
"github.com/v2ray/v2ray-core/proxy/common/config/json"
)
type BlackHoleConfig struct {
}
func init() {
json.RegisterOutboundConnectionConfig("blackhole", func() interface{} {
return new(BlackHoleConfig)
})
}

View File

@@ -0,0 +1,9 @@
package config
import (
"errors"
)
var (
BadConfiguration = errors.New("Bad proxy configuration.")
)

View File

@@ -0,0 +1,45 @@
package json
import (
"github.com/v2ray/v2ray-core/proxy/common/config"
)
type ConfigObjectCreator func() interface{}
var (
configCache map[string]ConfigObjectCreator
)
func getConfigKey(protocol string, cType config.Type) string {
return protocol + "_" + string(cType)
}
func registerConfigType(protocol string, cType config.Type, creator ConfigObjectCreator) error {
// TODO: check name
configCache[getConfigKey(protocol, cType)] = creator
return nil
}
func RegisterInboundConnectionConfig(protocol string, creator ConfigObjectCreator) error {
return registerConfigType(protocol, config.TypeInbound, creator)
}
func RegisterOutboundConnectionConfig(protocol string, creator ConfigObjectCreator) error {
return registerConfigType(protocol, config.TypeOutbound, creator)
}
func CreateConfig(protocol string, cType config.Type) interface{} {
creator, found := configCache[getConfigKey(protocol, cType)]
if !found {
return nil
}
return creator()
}
func initializeConfigCache() {
configCache = make(map[string]ConfigObjectCreator)
}
func init() {
initializeConfigCache()
}

View File

@@ -0,0 +1,46 @@
package json
import (
"testing"
"github.com/v2ray/v2ray-core/proxy/common/config"
"github.com/v2ray/v2ray-core/testing/unit"
)
func TestRegisterInboundConfig(t *testing.T) {
assert := unit.Assert(t)
initializeConfigCache()
protocol := "test_protocol"
creator := func() interface{} {
return true
}
err := RegisterInboundConnectionConfig(protocol, creator)
assert.Error(err).IsNil()
configObj := CreateConfig(protocol, config.TypeInbound)
assert.Bool(configObj.(bool)).IsTrue()
configObj = CreateConfig(protocol, config.TypeOutbound)
assert.Pointer(configObj).IsNil()
}
func TestRegisterOutboundConfig(t *testing.T) {
assert := unit.Assert(t)
initializeConfigCache()
protocol := "test_protocol"
creator := func() interface{} {
return true
}
err := RegisterOutboundConnectionConfig(protocol, creator)
assert.Error(err).IsNil()
configObj := CreateConfig(protocol, config.TypeOutbound)
assert.Bool(configObj.(bool)).IsTrue()
configObj = CreateConfig(protocol, config.TypeInbound)
assert.Pointer(configObj).IsNil()
}

View File

@@ -0,0 +1,8 @@
package config
type Type string
const (
TypeInbound = Type("inbound")
TypeOutbound = Type("outbound")
)

View File

@@ -0,0 +1,18 @@
package connhandler
import (
"github.com/v2ray/v2ray-core/app"
)
// A InboundConnectionHandlerFactory creates InboundConnectionHandler on demand.
type InboundConnectionHandlerFactory interface {
// Create creates a new InboundConnectionHandler with given configuration.
Create(dispatch app.PacketDispatcher, config interface{}) (InboundConnectionHandler, error)
}
// A InboundConnectionHandler handles inbound network connections to V2Ray.
type InboundConnectionHandler interface {
// Listen starts a InboundConnectionHandler by listen on a specific port. This method is called
// exactly once during runtime.
Listen(port uint16) error
}

View File

@@ -0,0 +1,18 @@
package connhandler
import (
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/transport/ray"
)
// An OutboundConnectionHandlerFactory creates OutboundConnectionHandler on demand.
type OutboundConnectionHandlerFactory interface {
// Create creates a new OutboundConnectionHandler with given config.
Create(config interface{}) (OutboundConnectionHandler, error)
}
// An OutboundConnectionHandler handles outbound network connection for V2Ray.
type OutboundConnectionHandler interface {
// Dispatch sends one or more Packets to its destination.
Dispatch(firstPacket v2net.Packet, ray ray.OutboundRay) error
}

View File

@@ -0,0 +1,34 @@
package connhandler
var (
inboundFactories = make(map[string]InboundConnectionHandlerFactory)
outboundFactories = make(map[string]OutboundConnectionHandlerFactory)
)
func RegisterInboundConnectionHandlerFactory(name string, factory InboundConnectionHandlerFactory) error {
// TODO check name
inboundFactories[name] = factory
return nil
}
func RegisterOutboundConnectionHandlerFactory(name string, factory OutboundConnectionHandlerFactory) error {
// TODO check name
outboundFactories[name] = factory
return nil
}
func GetInboundConnectionHandlerFactory(name string) InboundConnectionHandlerFactory {
factory, found := inboundFactories[name]
if !found {
return nil
}
return factory
}
func GetOutboundConnectionHandlerFactory(name string) OutboundConnectionHandlerFactory {
factory, found := outboundFactories[name]
if !found {
return nil
}
return factory
}

View File

@@ -0,0 +1,10 @@
package errors
import (
"errors"
)
var (
InvalidAuthentication = errors.New("Invalid authentication.")
InvalidProtocolVersion = errors.New("Invalid protocol version.")
)

View File

@@ -0,0 +1,19 @@
package json
import (
v2netjson "github.com/v2ray/v2ray-core/common/net/json"
"github.com/v2ray/v2ray-core/proxy/common/config/json"
)
type DokodemoConfig struct {
Host string `json:"address"`
Port int `json:"port"`
Network *v2netjson.NetworkList `json:"network"`
Timeout int `json:"timeout"`
}
func init() {
json.RegisterInboundConnectionConfig("dokodemo-door", func() interface{} {
return new(DokodemoConfig)
})
}

145
proxy/dokodemo/dokodemo.go Normal file
View File

@@ -0,0 +1,145 @@
package dokodemo
import (
"io"
"net"
"sync"
"github.com/v2ray/v2ray-core/app"
"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/common/retry"
"github.com/v2ray/v2ray-core/proxy/dokodemo/config/json"
)
type DokodemoDoor struct {
config *json.DokodemoConfig
accepting bool
address v2net.Address
dispatcher app.PacketDispatcher
}
func NewDokodemoDoor(dispatcher app.PacketDispatcher, config *json.DokodemoConfig) *DokodemoDoor {
d := &DokodemoDoor{
config: config,
dispatcher: dispatcher,
}
ip := net.ParseIP(config.Host)
if ip != nil {
d.address = v2net.IPAddress(ip, uint16(config.Port))
} else {
d.address = v2net.DomainAddress(config.Host, uint16(config.Port))
}
return d
}
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},
Port: int(port),
Zone: "",
})
if err != nil {
log.Error("Dokodemo failed to listen on port %d: %v", port, err)
return err
}
go this.AcceptTCPConnections(tcpListener)
return nil
}
func (this *DokodemoDoor) AcceptTCPConnections(tcpListener *net.TCPListener) {
for this.accepting {
retry.Timed(100, 100).On(func() error {
connection, err := tcpListener.AcceptTCP()
if err != nil {
log.Error("Dokodemo failed to accept new connections: %v", err)
return err
}
go this.HandleTCPConnection(connection)
return nil
})
}
}
func (this *DokodemoDoor) HandleTCPConnection(conn *net.TCPConn) {
defer conn.Close()
packet := v2net.NewPacket(v2net.NewTCPDestination(this.address), nil, true)
ray := this.dispatcher.DispatchToOutbound(packet)
var inputFinish, outputFinish sync.Mutex
inputFinish.Lock()
outputFinish.Lock()
reader := v2net.NewTimeOutReader(this.config.Timeout, conn)
go dumpInput(reader, ray.InboundInput(), &inputFinish)
go dumpOutput(conn, ray.InboundOutput(), &outputFinish)
outputFinish.Lock()
}
func dumpInput(reader io.Reader, input chan<- *alloc.Buffer, finish *sync.Mutex) {
v2net.ReaderToChan(input, reader)
finish.Unlock()
close(input)
}
func dumpOutput(writer io.Writer, output <-chan *alloc.Buffer, finish *sync.Mutex) {
v2net.ChanToWriter(writer, output)
finish.Unlock()
}

View File

@@ -0,0 +1,19 @@
package dokodemo
import (
"github.com/v2ray/v2ray-core/app"
"github.com/v2ray/v2ray-core/proxy/common/connhandler"
"github.com/v2ray/v2ray-core/proxy/dokodemo/config/json"
)
type DokodemoDoorFactory struct {
}
func (this DokodemoDoorFactory) Create(dispatcher app.PacketDispatcher, rawConfig interface{}) (connhandler.InboundConnectionHandler, error) {
config := rawConfig.(*json.DokodemoConfig)
return NewDokodemoDoor(dispatcher, config), nil
}
func init() {
connhandler.RegisterInboundConnectionHandlerFactory("dokodemo-door", DokodemoDoorFactory{})
}

View File

@@ -0,0 +1,139 @@
package dokodemo
import (
"net"
"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/servers/tcp"
"github.com/v2ray/v2ray-core/testing/servers/udp"
"github.com/v2ray/v2ray-core/testing/unit"
)
func TestDokodemoTCP(t *testing.T) {
assert := unit.Assert(t)
port := v2nettesting.PickPort()
data2Send := "Data to be sent to remote."
tcpServer := &tcp.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 := tcpServer.Start()
assert.Error(err).IsNil()
pointPort := v2nettesting.PickPort()
networkList := v2netjson.NetworkList([]string{"tcp"})
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()
tcpClient, err := net.DialTCP("tcp", nil, &net.TCPAddr{
IP: []byte{127, 0, 0, 1},
Port: int(pointPort),
Zone: "",
})
assert.Error(err).IsNil()
tcpClient.Write([]byte(data2Send))
tcpClient.CloseWrite()
response := make([]byte, 1024)
nBytes, err := tcpClient.Read(response)
assert.Error(err).IsNil()
tcpClient.Close()
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

@@ -1,15 +1,14 @@
package json
import (
"github.com/v2ray/v2ray-core/config"
"github.com/v2ray/v2ray-core/config/json"
"github.com/v2ray/v2ray-core/proxy/common/config/json"
)
type FreedomConfiguration struct {
}
func init() {
json.RegisterConfigType("freedom", config.TypeOutbound, func() interface{} {
json.RegisterOutboundConnectionConfig("freedom", func() interface{} {
return &FreedomConfiguration{}
})
}

View File

@@ -4,10 +4,10 @@ import (
"net"
"sync"
"github.com/v2ray/v2ray-core"
"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/ray"
)
type FreedomConnection struct {
@@ -17,12 +17,13 @@ func NewFreedomConnection() *FreedomConnection {
return &FreedomConnection{}
}
func (vconn *FreedomConnection) Dispatch(firstPacket v2net.Packet, ray core.OutboundRay) error {
func (vconn *FreedomConnection) Dispatch(firstPacket v2net.Packet, ray ray.OutboundRay) error {
conn, err := net.Dial(firstPacket.Destination().Network(), firstPacket.Destination().Address().String())
log.Info("Freedom: Opening connection to %s", firstPacket.Destination().String())
if err != nil {
close(ray.OutboundOutput())
return log.Error("Freedom: Failed to open connection: %s : %v", firstPacket.Destination().String(), err)
log.Error("Freedom: Failed to open connection: %s : %v", firstPacket.Destination().String(), err)
return err
}
input := ray.OutboundInput()

View File

@@ -2,18 +2,22 @@ package freedom
import (
"bytes"
"fmt"
"io/ioutil"
"net"
"testing"
"golang.org/x/net/proxy"
"github.com/v2ray/v2ray-core"
"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"
"github.com/v2ray/v2ray-core/proxy/common/connhandler"
_ "github.com/v2ray/v2ray-core/proxy/socks"
"github.com/v2ray/v2ray-core/proxy/socks/config/json"
"github.com/v2ray/v2ray-core/testing/mocks"
proxymocks "github.com/v2ray/v2ray-core/proxy/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"
@@ -37,14 +41,15 @@ func TestUDPSend(t *testing.T) {
udpServerAddr, err := udpServer.Start()
assert.Error(err).IsNil()
ich := &mocks.InboundConnectionHandler{
Data2Send: []byte("Not Used"),
DataReturned: bytes.NewBuffer(make([]byte, 0, 1024)),
connOutput := bytes.NewBuffer(make([]byte, 0, 1024))
ich := &proxymocks.InboundConnectionHandler{
ConnInput: bytes.NewReader([]byte("Not Used")),
ConnOutput: connOutput,
}
core.RegisterInboundConnectionHandlerFactory("mock_ich", ich)
connhandler.RegisterInboundConnectionHandlerFactory("mock_ich", ich)
pointPort := uint16(38724)
pointPort := v2nettesting.PickPort()
config := mocks.Config{
PortValue: pointPort,
InboundConfigValue: &mocks.ConnectionConfig{
@@ -57,23 +62,22 @@ func TestUDPSend(t *testing.T) {
},
}
point, err := core.NewPoint(&config)
point, err := point.NewPoint(&config)
assert.Error(err).IsNil()
err = point.Start()
assert.Error(err).IsNil()
data2SendBuffer := alloc.NewBuffer()
data2SendBuffer.Clear()
data2SendBuffer := alloc.NewBuffer().Clear()
data2SendBuffer.Append([]byte(data2Send))
dest := v2net.NewUDPDestination(udpServerAddr)
ich.Communicate(v2net.NewPacket(dest, data2SendBuffer, false))
assert.Bytes(ich.DataReturned.Bytes()).Equals([]byte("Processed: Data to be sent to remote"))
assert.Bytes(connOutput.Bytes()).Equals([]byte("Processed: Data to be sent to remote"))
}
func TestSocksTcpConnect(t *testing.T) {
assert := unit.Assert(t)
port := uint16(38293)
port := v2nettesting.PickPort()
data2Send := "Data to be sent to remote"
@@ -89,7 +93,7 @@ func TestSocksTcpConnect(t *testing.T) {
_, err := tcpServer.Start()
assert.Error(err).IsNil()
pointPort := uint16(38724)
pointPort := v2nettesting.PickPort()
config := mocks.Config{
PortValue: pointPort,
InboundConfigValue: &mocks.ConnectionConfig{
@@ -104,16 +108,16 @@ func TestSocksTcpConnect(t *testing.T) {
},
}
point, err := core.NewPoint(&config)
point, err := point.NewPoint(&config)
assert.Error(err).IsNil()
err = point.Start()
assert.Error(err).IsNil()
socks5Client, err := proxy.SOCKS5("tcp", "127.0.0.1:38724", nil, proxy.Direct)
socks5Client, err := proxy.SOCKS5("tcp", fmt.Sprintf("127.0.0.1:%d", pointPort), nil, proxy.Direct)
assert.Error(err).IsNil()
targetServer := "127.0.0.1:38293"
targetServer := fmt.Sprintf("127.0.0.1:%d", port)
conn, err := socks5Client.Dial("tcp", targetServer)
assert.Error(err).IsNil()

View File

@@ -1,16 +1,16 @@
package freedom
import (
"github.com/v2ray/v2ray-core"
"github.com/v2ray/v2ray-core/proxy/common/connhandler"
)
type FreedomFactory struct {
}
func (factory FreedomFactory) Create(vp *core.Point, config interface{}) (core.OutboundConnectionHandler, error) {
func (factory FreedomFactory) Create(config interface{}) (connhandler.OutboundConnectionHandler, error) {
return NewFreedomConnection(), nil
}
func init() {
core.RegisterOutboundConnectionHandlerFactory("freedom", FreedomFactory{})
connhandler.RegisterOutboundConnectionHandlerFactory("freedom", FreedomFactory{})
}

View File

@@ -0,0 +1,14 @@
package json
import (
"github.com/v2ray/v2ray-core/proxy/common/config/json"
)
type HttpProxyConfig struct {
}
func init() {
json.RegisterInboundConnectionConfig("http", func() interface{} {
return new(HttpProxyConfig)
})
}

36
proxy/http/http.go Normal file
View File

@@ -0,0 +1,36 @@
package http
import (
"net"
// "net/http"
"github.com/v2ray/v2ray-core/app"
"github.com/v2ray/v2ray-core/common/log"
jsonconfig "github.com/v2ray/v2ray-core/proxy/http/config/json"
)
type HttpProxyServer struct {
accepting bool
dispatcher app.PacketDispatcher
config *jsonconfig.HttpProxyConfig
}
func NewHttpProxyServer(dispatcher app.PacketDispatcher, config *jsonconfig.HttpProxyConfig) *HttpProxyServer {
return &HttpProxyServer{
dispatcher: dispatcher,
config: config,
}
}
func (server *HttpProxyServer) Listen(port uint16) error {
_, err := net.ListenTCP("tcp", &net.TCPAddr{
IP: []byte{0, 0, 0, 0},
Port: int(port),
Zone: "",
})
if err != nil {
log.Error("HTTP Proxy failed to listen on port %d: %v", port, err)
return err
}
return nil
}

View File

@@ -1,8 +1,11 @@
package json
import (
"github.com/v2ray/v2ray-core/config"
"github.com/v2ray/v2ray-core/config/json"
"encoding/json"
"errors"
"net"
jsonconfig "github.com/v2ray/v2ray-core/proxy/common/config/json"
)
const (
@@ -15,38 +18,71 @@ type SocksAccount struct {
Password string `json:"pass"`
}
type SocksConfig struct {
AuthMethod string `json:"auth"`
Accounts []SocksAccount `json:"accounts"`
UDPEnabled bool `json:"udp"`
type SocksAccountMap map[string]string
accountMap map[string]string
}
func (config *SocksConfig) Initialize() {
config.accountMap = make(map[string]string)
for _, account := range config.Accounts {
config.accountMap[account.Username] = account.Password
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 (config *SocksConfig) IsNoAuth() bool {
return config.AuthMethod == AuthMethodNoAuth
}
func (config *SocksConfig) IsPassword() bool {
return config.AuthMethod == AuthMethodUserPass
}
func (config *SocksConfig) HasAccount(user, pass string) bool {
if actualPass, found := config.accountMap[user]; found {
func (this *SocksAccountMap) HasAccount(user, pass string) bool {
if actualPass, found := (*this)[user]; found {
return actualPass == pass
}
return false
}
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 {
return sc.AuthMethod == AuthMethodNoAuth
}
func (sc *SocksConfig) IsPassword() bool {
return sc.AuthMethod == AuthMethodUserPass
}
func (sc *SocksConfig) HasAccount(user, pass string) bool {
return sc.Accounts.HasAccount(user, pass)
}
func (sc *SocksConfig) IP() net.IP {
return net.IP(sc.HostIP)
}
func init() {
json.RegisterConfigType("socks", config.TypeInbound, 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

@@ -5,9 +5,10 @@ import (
"io"
"github.com/v2ray/v2ray-core/common/alloc"
"github.com/v2ray/v2ray-core/common/errors"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
proxyerrors "github.com/v2ray/v2ray-core/proxy/common/errors"
"github.com/v2ray/v2ray-core/transport"
)
const (
@@ -49,7 +50,7 @@ func ReadAuthentication(reader io.Reader) (auth Socks5AuthenticationRequest, aut
}
if nBytes < 2 {
log.Info("Socks expected 2 bytes read, but only %d bytes read", nBytes)
err = errors.NewCorruptedPacketError()
err = transport.CorruptedPacket
return
}
@@ -58,26 +59,27 @@ func ReadAuthentication(reader io.Reader) (auth Socks5AuthenticationRequest, aut
auth4.Command = buffer.Value[1]
auth4.Port = binary.BigEndian.Uint16(buffer.Value[2:4])
copy(auth4.IP[:], buffer.Value[4:8])
err = NewSocksVersion4Error()
err = Socks4Downgrade
return
}
auth.version = buffer.Value[0]
if auth.version != socksVersion {
err = errors.NewProtocolVersionError(int(auth.version))
log.Warning("Unknown protocol version %d", auth.version)
err = proxyerrors.InvalidProtocolVersion
return
}
auth.nMethods = buffer.Value[1]
if auth.nMethods <= 0 {
log.Info("Zero length of authentication methods")
err = errors.NewCorruptedPacketError()
err = transport.CorruptedPacket
return
}
if nBytes-2 != int(auth.nMethods) {
log.Info("Unmatching number of auth methods, expecting %d, but got %d", auth.nMethods, nBytes)
err = errors.NewCorruptedPacketError()
err = transport.CorruptedPacket
return
}
copy(auth.authMethods[:], buffer.Value[2:nBytes])
@@ -194,7 +196,7 @@ func ReadRequest(reader io.Reader) (request *Socks5Request, err error) {
return
}
if nBytes < 4 {
err = errors.NewCorruptedPacketError()
err = transport.CorruptedPacket
return
}
request = &Socks5Request{
@@ -210,7 +212,7 @@ func ReadRequest(reader io.Reader) (request *Socks5Request, err error) {
return
}
if nBytes != 4 {
err = errors.NewCorruptedPacketError()
err = transport.CorruptedPacket
return
}
case AddrTypeDomain:
@@ -226,7 +228,7 @@ func ReadRequest(reader io.Reader) (request *Socks5Request, err error) {
if nBytes != int(domainLength) {
log.Info("Unable to read domain with %d bytes, expecting %d bytes", nBytes, domainLength)
err = errors.NewCorruptedPacketError()
err = transport.CorruptedPacket
return
}
request.Domain = string(buffer.Value[:domainLength])
@@ -236,12 +238,12 @@ func ReadRequest(reader io.Reader) (request *Socks5Request, err error) {
return
}
if nBytes != 16 {
err = errors.NewCorruptedPacketError()
err = transport.CorruptedPacket
return
}
default:
log.Info("Unexpected address type %d", request.AddrType)
err = errors.NewCorruptedPacketError()
err = transport.CorruptedPacket
return
}
@@ -250,7 +252,7 @@ func ReadRequest(reader io.Reader) (request *Socks5Request, err error) {
return
}
if nBytes != 2 {
err = errors.NewCorruptedPacketError()
err = transport.CorruptedPacket
return
}

View File

@@ -1,23 +1,14 @@
package protocol
import (
"errors"
"github.com/v2ray/v2ray-core/common/alloc"
"github.com/v2ray/v2ray-core/common/errors"
)
type SocksVersion4Error struct {
errors.ErrorCode
}
var socksVersion4ErrorInstance = SocksVersion4Error{ErrorCode: 1000}
func NewSocksVersion4Error() SocksVersion4Error {
return socksVersion4ErrorInstance
}
func (err SocksVersion4Error) Error() string {
return err.Prefix() + "Request is socks version 4."
}
var (
Socks4Downgrade = errors.New("Downgraded to Socks 4.")
)
type Socks4AuthenticationRequest struct {
Version byte

View File

@@ -18,7 +18,7 @@ func TestSocks4AuthenticationRequestRead(t *testing.T) {
0x72, 0x72, 0x72, 0x72,
}
_, request4, err := ReadAuthentication(bytes.NewReader(rawRequest))
assert.Error(err).HasCode(1000)
assert.Error(err).Equals(Socks4Downgrade)
assert.Byte(request4.Version).Named("Version").Equals(0x04)
assert.Byte(request4.Command).Named("Command").Equals(0x01)
assert.Uint16(request4.Port).Named("Port").Equals(53)
@@ -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

@@ -1,37 +1,47 @@
package socks
import (
"errors"
"io"
"net"
"strconv"
"sync"
"time"
"github.com/v2ray/v2ray-core"
"github.com/v2ray/v2ray-core/app"
"github.com/v2ray/v2ray-core/common/alloc"
"github.com/v2ray/v2ray-core/common/errors"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/common/retry"
proxyerrors "github.com/v2ray/v2ray-core/proxy/common/errors"
jsonconfig "github.com/v2ray/v2ray-core/proxy/socks/config/json"
"github.com/v2ray/v2ray-core/proxy/socks/protocol"
)
var (
UnsupportedSocksCommand = errors.New("Unsupported socks command.")
UnsupportedAuthMethod = errors.New("Unsupported auth method.")
)
// SocksServer is a SOCKS 5 proxy server
type SocksServer struct {
accepting bool
vPoint *core.Point
config *jsonconfig.SocksConfig
accepting bool
dispatcher app.PacketDispatcher
config *jsonconfig.SocksConfig
}
func NewSocksServer(vp *core.Point, config *jsonconfig.SocksConfig) *SocksServer {
func NewSocksServer(dispatcher app.PacketDispatcher, config *jsonconfig.SocksConfig) *SocksServer {
return &SocksServer{
vPoint: vp,
config: config,
dispatcher: dispatcher,
config: config,
}
}
func (server *SocksServer) Listen(port uint16) error {
listener, err := net.Listen("tcp", ":"+strconv.Itoa(int(port)))
listener, err := net.ListenTCP("tcp", &net.TCPAddr{
IP: []byte{0, 0, 0, 0},
Port: int(port),
Zone: "",
})
if err != nil {
log.Error("Socks failed to listen on port %d: %v", port, err)
return err
@@ -44,29 +54,33 @@ func (server *SocksServer) Listen(port uint16) error {
return nil
}
func (server *SocksServer) AcceptConnections(listener net.Listener) {
func (server *SocksServer) AcceptConnections(listener *net.TCPListener) {
for server.accepting {
connection, err := listener.Accept()
if err != nil {
log.Error("Socks failed to accept new connection %v", err)
continue
}
go server.HandleConnection(connection)
retry.Timed(100 /* times */, 100 /* ms */).On(func() error {
connection, err := listener.AcceptTCP()
if err != nil {
log.Error("Socks failed to accept new connection %v", err)
return err
}
go server.HandleConnection(connection)
return nil
})
}
}
func (server *SocksServer) HandleConnection(connection net.Conn) error {
func (server *SocksServer) HandleConnection(connection *net.TCPConn) error {
defer connection.Close()
reader := v2net.NewTimeOutReader(120, connection)
auth, auth4, err := protocol.ReadAuthentication(reader)
if err != nil && !errors.HasCode(err, 1000) {
if err != nil && err != protocol.Socks4Downgrade {
log.Error("Socks failed to read authentication: %v", err)
return err
}
if err != nil && errors.HasCode(err, 1000) {
if err != nil && err == protocol.Socks4Downgrade {
return server.handleSocks4(reader, connection, auth4)
} else {
return server.handleSocks5(reader, connection, auth)
@@ -87,7 +101,7 @@ func (server *SocksServer) handleSocks5(reader *v2net.TimeOutReader, writer io.W
return err
}
log.Warning("Socks client doesn't support allowed any auth methods.")
return errors.NewInvalidOperationError("Unsupported auth methods.")
return UnsupportedAuthMethod
}
authResponse := protocol.NewAuthenticationResponse(expectedAuthMethod)
@@ -113,9 +127,8 @@ func (server *SocksServer) handleSocks5(reader *v2net.TimeOutReader, writer io.W
return err
}
if status != byte(0) {
err = errors.NewAuthenticationError(upRequest.AuthDetail())
log.Warning(err.Error())
return err
log.Warning("Invalid user account: %s", upRequest.AuthDetail())
return proxyerrors.InvalidAuthentication
}
}
@@ -129,10 +142,11 @@ func (server *SocksServer) handleSocks5(reader *v2net.TimeOutReader, writer io.W
return server.handleUDP(reader, writer)
}
response := protocol.NewSocks5Response()
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)
@@ -143,18 +157,15 @@ func (server *SocksServer) handleSocks5(reader *v2net.TimeOutReader, writer io.W
return err
}
log.Warning("Unsupported socks command %d", request.Command)
return errors.NewInvalidOperationError("Socks command " + strconv.Itoa(int(request.Command)))
return UnsupportedSocksCommand
}
response := protocol.NewSocks5Response()
response.Error = protocol.ErrorSuccess
// 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)
@@ -185,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()
@@ -228,7 +236,8 @@ func (server *SocksServer) handleSocks4(reader io.Reader, writer io.Writer, auth
responseBuffer.Release()
if result == protocol.Socks4RequestRejected {
return errors.NewInvalidOperationError("Socks4 command " + strconv.Itoa(int(auth.Command)))
log.Warning("Unsupported socks 4 command %d", auth.Command)
return UnsupportedSocksCommand
}
dest := v2net.NewTCPDestination(v2net.IPAddress(auth.IP[:], auth.Port))
@@ -243,7 +252,7 @@ func (server *SocksServer) handleSocks4(reader io.Reader, writer io.Writer, auth
}
func (server *SocksServer) transport(reader io.Reader, writer io.Writer, firstPacket v2net.Packet) {
ray := server.vPoint.DispatchToOutbound(firstPacket)
ray := server.dispatcher.DispatchToOutbound(firstPacket)
input := ray.InboundInput()
output := ray.InboundOutput()

View File

@@ -2,28 +2,34 @@ package socks
import (
"bytes"
"fmt"
"io/ioutil"
"net"
"testing"
"golang.org/x/net/proxy"
"github.com/v2ray/v2ray-core"
"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"
"github.com/v2ray/v2ray-core/testing/mocks"
proxymocks "github.com/v2ray/v2ray-core/proxy/testing/mocks"
"github.com/v2ray/v2ray-core/testing/unit"
)
func TestSocksTcpConnect(t *testing.T) {
assert := unit.Assert(t)
port := uint16(12385)
port := v2nettesting.PickPort()
och := &mocks.OutboundConnectionHandler{
Data2Send: bytes.NewBuffer(make([]byte, 0, 1024)),
Data2Return: []byte("The data to be returned to socks server."),
connInput := []byte("The data to be returned to socks server.")
connOutput := bytes.NewBuffer(make([]byte, 0, 1024))
och := &proxymocks.OutboundConnectionHandler{
ConnOutput: connOutput,
ConnInput: bytes.NewReader(connInput),
}
core.RegisterOutboundConnectionHandlerFactory("mock_och", och)
connhandler.RegisterOutboundConnectionHandlerFactory("mock_och", och)
config := mocks.Config{
PortValue: port,
@@ -39,13 +45,13 @@ func TestSocksTcpConnect(t *testing.T) {
},
}
point, err := core.NewPoint(&config)
point, err := point.NewPoint(&config)
assert.Error(err).IsNil()
err = point.Start()
assert.Error(err).IsNil()
socks5Client, err := proxy.SOCKS5("tcp", "127.0.0.1:12385", nil, proxy.Direct)
socks5Client, err := proxy.SOCKS5("tcp", fmt.Sprintf("127.0.0.1:%d", port), nil, proxy.Direct)
assert.Error(err).IsNil()
targetServer := "google.com:80"
@@ -62,21 +68,23 @@ func TestSocksTcpConnect(t *testing.T) {
assert.Error(err).IsNil()
conn.Close()
assert.Bytes([]byte(data2Send)).Equals(och.Data2Send.Bytes())
assert.Bytes(dataReturned).Equals(och.Data2Return)
assert.Bytes([]byte(data2Send)).Equals(connOutput.Bytes())
assert.Bytes(dataReturned).Equals(connInput)
assert.String(targetServer).Equals(och.Destination.Address().String())
}
func TestSocksTcpConnectWithUserPass(t *testing.T) {
assert := unit.Assert(t)
port := uint16(12386)
port := v2nettesting.PickPort()
och := &mocks.OutboundConnectionHandler{
Data2Send: bytes.NewBuffer(make([]byte, 0, 1024)),
Data2Return: []byte("The data to be returned to socks server."),
connInput := []byte("The data to be returned to socks server.")
connOutput := bytes.NewBuffer(make([]byte, 0, 1024))
och := &proxymocks.OutboundConnectionHandler{
ConnInput: bytes.NewReader(connInput),
ConnOutput: connOutput,
}
core.RegisterOutboundConnectionHandlerFactory("mock_och", och)
connhandler.RegisterOutboundConnectionHandlerFactory("mock_och", och)
config := mocks.Config{
PortValue: port,
@@ -84,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",
},
},
},
@@ -98,13 +103,13 @@ func TestSocksTcpConnectWithUserPass(t *testing.T) {
},
}
point, err := core.NewPoint(&config)
point, err := point.NewPoint(&config)
assert.Error(err).IsNil()
err = point.Start()
assert.Error(err).IsNil()
socks5Client, err := proxy.SOCKS5("tcp", "127.0.0.1:12386", &proxy.Auth{"userx", "passy"}, proxy.Direct)
socks5Client, err := proxy.SOCKS5("tcp", fmt.Sprintf("127.0.0.1:%d", port), &proxy.Auth{"userx", "passy"}, proxy.Direct)
assert.Error(err).IsNil()
targetServer := "1.2.3.4:443"
@@ -121,21 +126,111 @@ func TestSocksTcpConnectWithUserPass(t *testing.T) {
assert.Error(err).IsNil()
conn.Close()
assert.Bytes([]byte(data2Send)).Equals(och.Data2Send.Bytes())
assert.Bytes(dataReturned).Equals(och.Data2Return)
assert.Bytes([]byte(data2Send)).Equals(connOutput.Bytes())
assert.Bytes(dataReturned).Equals(connInput)
assert.String(targetServer).Equals(och.Destination.Address().String())
}
func TestSocksTcpConnectWithWrongUserPass(t *testing.T) {
assert := unit.Assert(t)
port := v2nettesting.PickPort()
connInput := []byte("The data to be returned to socks server.")
connOutput := bytes.NewBuffer(make([]byte, 0, 1024))
och := &proxymocks.OutboundConnectionHandler{
ConnInput: bytes.NewReader(connInput),
ConnOutput: connOutput,
}
connhandler.RegisterOutboundConnectionHandlerFactory("mock_och", och)
config := mocks.Config{
PortValue: port,
InboundConfigValue: &mocks.ConnectionConfig{
ProtocolValue: "socks",
SettingsValue: &json.SocksConfig{
AuthMethod: "password",
Accounts: json.SocksAccountMap{
"userx": "passy",
},
},
},
OutboundConfigValue: &mocks.ConnectionConfig{
ProtocolValue: "mock_och",
SettingsValue: nil,
},
}
point, err := point.NewPoint(&config)
assert.Error(err).IsNil()
err = point.Start()
assert.Error(err).IsNil()
socks5Client, err := proxy.SOCKS5("tcp", fmt.Sprintf("127.0.0.1:%d", port), &proxy.Auth{"userx", "passz"}, proxy.Direct)
assert.Error(err).IsNil()
targetServer := "1.2.3.4:443"
_, err = socks5Client.Dial("tcp", targetServer)
assert.Error(err).IsNotNil()
}
func TestSocksTcpConnectWithWrongAuthMethod(t *testing.T) {
assert := unit.Assert(t)
port := v2nettesting.PickPort()
connInput := []byte("The data to be returned to socks server.")
connOutput := bytes.NewBuffer(make([]byte, 0, 1024))
och := &proxymocks.OutboundConnectionHandler{
ConnInput: bytes.NewReader(connInput),
ConnOutput: connOutput,
}
connhandler.RegisterOutboundConnectionHandlerFactory("mock_och", och)
config := mocks.Config{
PortValue: port,
InboundConfigValue: &mocks.ConnectionConfig{
ProtocolValue: "socks",
SettingsValue: &json.SocksConfig{
AuthMethod: "password",
Accounts: json.SocksAccountMap{
"userx": "passy",
},
},
},
OutboundConfigValue: &mocks.ConnectionConfig{
ProtocolValue: "mock_och",
SettingsValue: nil,
},
}
point, err := point.NewPoint(&config)
assert.Error(err).IsNil()
err = point.Start()
assert.Error(err).IsNil()
socks5Client, err := proxy.SOCKS5("tcp", fmt.Sprintf("127.0.0.1:%d", port), nil, proxy.Direct)
assert.Error(err).IsNil()
targetServer := "1.2.3.4:443"
_, err = socks5Client.Dial("tcp", targetServer)
assert.Error(err).IsNotNil()
}
func TestSocksUdpSend(t *testing.T) {
assert := unit.Assert(t)
port := uint16(12372)
port := v2nettesting.PickPort()
och := &mocks.OutboundConnectionHandler{
Data2Send: bytes.NewBuffer(make([]byte, 0, 1024)),
Data2Return: []byte("The data to be returned to socks server."),
connInput := []byte("The data to be returned to socks server.")
connOutput := bytes.NewBuffer(make([]byte, 0, 1024))
och := &proxymocks.OutboundConnectionHandler{
ConnInput: bytes.NewReader(connInput),
ConnOutput: connOutput,
}
core.RegisterOutboundConnectionHandlerFactory("mock_och", och)
connhandler.RegisterOutboundConnectionHandlerFactory("mock_och", och)
config := mocks.Config{
PortValue: port,
@@ -152,7 +247,7 @@ func TestSocksUdpSend(t *testing.T) {
},
}
point, err := core.NewPoint(&config)
point, err := point.NewPoint(&config)
assert.Error(err).IsNil()
err = point.Start()
@@ -179,7 +274,7 @@ func TestSocksUdpSend(t *testing.T) {
nBytes, err := conn.Read(response)
assert.Error(err).IsNil()
assert.Bytes(response[10:nBytes]).Equals(och.Data2Return)
assert.Bytes(data2Send).Equals(och.Data2Send.Bytes())
assert.Bytes(response[10:nBytes]).Equals(connInput)
assert.Bytes(data2Send).Equals(connOutput.Bytes())
assert.String(och.Destination.String()).Equals("udp:8.8.4.4:53")
}

View File

@@ -1,19 +1,18 @@
package socks
import (
"github.com/v2ray/v2ray-core"
"github.com/v2ray/v2ray-core/app"
"github.com/v2ray/v2ray-core/proxy/common/connhandler"
"github.com/v2ray/v2ray-core/proxy/socks/config/json"
)
type SocksServerFactory struct {
}
func (factory SocksServerFactory) Create(vp *core.Point, rawConfig interface{}) (core.InboundConnectionHandler, error) {
config := rawConfig.(*json.SocksConfig)
config.Initialize()
return NewSocksServer(vp, config), nil
func (factory SocksServerFactory) Create(dispatcher app.PacketDispatcher, rawConfig interface{}) (connhandler.InboundConnectionHandler, error) {
return NewSocksServer(dispatcher, rawConfig.(*json.SocksConfig)), nil
}
func init() {
core.RegisterInboundConnectionHandlerFactory("socks", SocksServerFactory{})
connhandler.RegisterInboundConnectionHandlerFactory("socks", SocksServerFactory{})
}

View File

@@ -9,10 +9,6 @@ import (
"github.com/v2ray/v2ray-core/proxy/socks/protocol"
)
const (
bufferSize = 2 * 1024
)
var udpAddress v2net.Address
func (server *SocksServer) ListenUDP(port uint16) error {
@@ -26,8 +22,7 @@ func (server *SocksServer) ListenUDP(port uint16) error {
log.Error("Socks failed to listen UDP on port %d: %v", port, err)
return err
}
// TODO: make this configurable
udpAddress = v2net.IPAddress([]byte{127, 0, 0, 1}, port)
udpAddress = v2net.IPAddress(server.config.IP(), port)
go server.AcceptPackets(conn)
return nil
@@ -51,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 {
@@ -68,10 +65,10 @@ func (server *SocksServer) AcceptPackets(conn *net.UDPConn) error {
}
func (server *SocksServer) handlePacket(conn *net.UDPConn, packet v2net.Packet, clientAddr *net.UDPAddr, targetAddr v2net.Address) {
ray := server.vPoint.DispatchToOutbound(packet)
ray := server.dispatcher.DispatchToOutbound(packet)
close(ray.InboundInput())
if data, ok := <-ray.InboundOutput(); ok {
for data := range ray.InboundOutput() {
response := &protocol.Socks5UDPRequest{
Fragment: 0,
Address: targetAddr,

View File

@@ -0,0 +1,55 @@
package mocks
import (
"io"
"sync"
"github.com/v2ray/v2ray-core/app"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/proxy/common/connhandler"
)
type InboundConnectionHandler struct {
Port uint16
Dispatcher app.PacketDispatcher
ConnInput io.Reader
ConnOutput io.Writer
}
func (this *InboundConnectionHandler) Listen(port uint16) error {
this.Port = port
return nil
}
func (this *InboundConnectionHandler) Communicate(packet v2net.Packet) error {
ray := this.Dispatcher.DispatchToOutbound(packet)
input := ray.InboundInput()
output := ray.InboundOutput()
readFinish := &sync.Mutex{}
writeFinish := &sync.Mutex{}
readFinish.Lock()
writeFinish.Lock()
go func() {
v2net.ReaderToChan(input, this.ConnInput)
close(input)
readFinish.Unlock()
}()
go func() {
v2net.ChanToWriter(this.ConnOutput, output)
writeFinish.Unlock()
}()
readFinish.Lock()
writeFinish.Lock()
return nil
}
func (this *InboundConnectionHandler) Create(dispatcher app.PacketDispatcher, config interface{}) (connhandler.InboundConnectionHandler, error) {
this.Dispatcher = dispatcher
return this, nil
}

View File

@@ -0,0 +1,49 @@
package mocks
import (
"io"
"sync"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/proxy/common/connhandler"
"github.com/v2ray/v2ray-core/transport/ray"
)
type OutboundConnectionHandler struct {
Destination v2net.Destination
ConnInput io.Reader
ConnOutput io.Writer
}
func (this *OutboundConnectionHandler) Dispatch(packet v2net.Packet, ray ray.OutboundRay) error {
input := ray.OutboundInput()
output := ray.OutboundOutput()
this.Destination = packet.Destination()
if packet.Chunk() != nil {
this.ConnOutput.Write(packet.Chunk().Value)
packet.Chunk().Release()
}
if packet.MoreChunks() {
writeFinish := &sync.Mutex{}
writeFinish.Lock()
go func() {
v2net.ChanToWriter(this.ConnOutput, input)
writeFinish.Unlock()
}()
writeFinish.Lock()
}
v2net.ReaderToChan(output, this.ConnInput)
close(output)
return nil
}
func (this *OutboundConnectionHandler) Create(config interface{}) (connhandler.OutboundConnectionHandler, error) {
return this, nil
}

View File

@@ -1,82 +0,0 @@
package vmess
import (
"net"
"strings"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/config"
"github.com/v2ray/v2ray-core/config/json"
"github.com/v2ray/v2ray-core/proxy/vmess/protocol/user"
)
// VMessUser is an authenticated user account in VMess configuration.
type VMessUser struct {
Id string `json:"id"`
Email string `json:"email"`
}
func (u *VMessUser) ToUser() (user.User, error) {
id, err := user.NewID(u.Id)
return user.User{
Id: id,
}, err
}
// VMessInboundConfig is
type VMessInboundConfig struct {
AllowedClients []VMessUser `json:"clients"`
UDPEnabled bool `json:"udp"`
}
type VNextConfig struct {
Address string `json:"address"`
Port uint16 `json:"port"`
Users []VMessUser `json:"users"`
Network string `json:"network"`
}
func (config VNextConfig) HasNetwork(network string) bool {
return strings.Contains(config.Network, network)
}
func (config VNextConfig) ToVNextServer(network string) VNextServer {
users := make([]user.User, 0, len(config.Users))
for _, user := range config.Users {
vuser, err := user.ToUser()
if err != nil {
panic(log.Error("Failed to convert %v to User.", user))
}
users = append(users, vuser)
}
ip := net.ParseIP(config.Address)
if ip == nil {
panic(log.Error("Unable to parse VNext IP: %s", config.Address))
}
address := v2net.IPAddress(ip, config.Port)
var dest v2net.Destination
if network == "tcp" {
dest = v2net.NewTCPDestination(address)
} else {
dest = v2net.NewUDPDestination(address)
}
return VNextServer{
Destination: dest,
Users: users,
}
}
type VMessOutboundConfig struct {
VNextList []VNextConfig `json:"vnext"`
}
func init() {
json.RegisterConfigType("vmess", config.TypeInbound, func() interface{} {
return new(VMessInboundConfig)
})
json.RegisterConfigType("vmess", config.TypeOutbound, func() interface{} {
return new(VMessOutboundConfig)
})
}

View File

@@ -1,8 +1,9 @@
package user
package config
import (
"crypto/md5"
"encoding/hex"
"errors"
"github.com/v2ray/v2ray-core/common/log"
)
@@ -11,6 +12,10 @@ const (
IDBytesLen = 16
)
var (
InvalidID = errors.New("Invalid ID.")
)
// The ID of en entity, in the form of an UUID.
type ID struct {
String string
@@ -18,10 +23,11 @@ type ID struct {
cmdKey [IDBytesLen]byte
}
func NewID(id string) (ID, error) {
func NewID(id string) (*ID, error) {
idBytes, err := UUIDToID(id)
if err != nil {
return ID{}, log.Error("Failed to parse id %s", id)
log.Error("Failed to parse id %s", id)
return &ID{}, InvalidID
}
md5hash := md5.New()
@@ -29,7 +35,7 @@ func NewID(id string) (ID, error) {
md5hash.Write([]byte("c48619fe-8f02-49e0-b9e9-edf763e17e21"))
cmdKey := md5.Sum(nil)
return ID{
return &ID{
String: id,
Bytes: idBytes,
cmdKey: cmdKey,
@@ -46,7 +52,8 @@ var byteGroups = []int{8, 4, 4, 4, 12}
func UUIDToID(uuid string) (v [IDBytesLen]byte, err error) {
text := []byte(uuid)
if len(text) < 32 {
err = log.Error("uuid: invalid UUID string: %s", text)
log.Error("uuid: invalid UUID string: %s", text)
err = InvalidID
return
}

View File

@@ -1,4 +1,4 @@
package user
package config
import (
"testing"

View File

@@ -0,0 +1,5 @@
package config
type Inbound interface {
AllowedUsers() []User
}

View File

@@ -0,0 +1,24 @@
package json
import (
"github.com/v2ray/v2ray-core/proxy/common/config/json"
vmessconfig "github.com/v2ray/v2ray-core/proxy/vmess/config"
)
type Inbound struct {
AllowedClients []*ConfigUser `json:"clients"`
}
func (c *Inbound) AllowedUsers() []vmessconfig.User {
users := make([]vmessconfig.User, 0, len(c.AllowedClients))
for _, rawUser := range c.AllowedClients {
users = append(users, rawUser)
}
return users
}
func init() {
json.RegisterInboundConnectionConfig("vmess", func() interface{} {
return new(Inbound)
})
}

View File

@@ -0,0 +1,63 @@
package json
import (
"encoding/json"
"net"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
proxyconfig "github.com/v2ray/v2ray-core/proxy/common/config"
jsonconfig "github.com/v2ray/v2ray-core/proxy/common/config/json"
vmessconfig "github.com/v2ray/v2ray-core/proxy/vmess/config"
)
type RawConfigTarget struct {
Address string `json:"address"`
Port uint16 `json:"port"`
Users []*ConfigUser `json:"users"`
}
type ConfigTarget struct {
Address v2net.Address
Users []*ConfigUser
}
func (t *ConfigTarget) UnmarshalJSON(data []byte) error {
var rawConfig RawConfigTarget
if err := json.Unmarshal(data, &rawConfig); err != nil {
return err
}
t.Users = rawConfig.Users
ip := net.ParseIP(rawConfig.Address)
if ip == nil {
log.Error("Unable to parse IP: %s", rawConfig.Address)
return proxyconfig.BadConfiguration
}
t.Address = v2net.IPAddress(ip, rawConfig.Port)
return nil
}
type Outbound struct {
TargetList []*ConfigTarget `json:"vnext"`
}
func (o *Outbound) Targets() []*vmessconfig.OutboundTarget {
targets := make([]*vmessconfig.OutboundTarget, 0, 2*len(o.TargetList))
for _, rawTarget := range o.TargetList {
users := make([]vmessconfig.User, 0, len(rawTarget.Users))
for _, rawUser := range rawTarget.Users {
users = append(users, rawUser)
}
targets = append(targets, &vmessconfig.OutboundTarget{
Destination: v2net.NewTCPDestination(rawTarget.Address),
Accounts: users,
})
}
return targets
}
func init() {
jsonconfig.RegisterOutboundConnectionConfig("vmess", func() interface{} {
return new(Outbound)
})
}

Some files were not shown because too many files have changed in this diff Show More