mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-10-28 22:17:17 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89be28c86c | ||
|
|
31c4d09d09 |
+60
-40
@@ -21,10 +21,7 @@ import (
|
||||
"golang.org/x/net/http2"
|
||||
)
|
||||
|
||||
const (
|
||||
idleTimeout = 30 * time.Second
|
||||
maxDownloadSize int64 = 256 * 1024 * 1024
|
||||
)
|
||||
const idleTimeout = 30 * time.Second
|
||||
|
||||
// DO NOT EDIT. Ignored by geodata, rejected by Lua.
|
||||
const luaGuardHeader = "\x12\x01\x00"
|
||||
@@ -36,6 +33,7 @@ type stage struct {
|
||||
|
||||
type downloader struct {
|
||||
ctx context.Context
|
||||
httpClient *http.Client
|
||||
httpsClient *http.Client
|
||||
}
|
||||
|
||||
@@ -63,11 +61,12 @@ func (c *idleConn) Write(b []byte) (int, error) {
|
||||
func newDownloader(ctx context.Context, dispatcher routing.Dispatcher, outbound string) *downloader {
|
||||
return &downloader{
|
||||
ctx: ctx,
|
||||
httpsClient: newClient(ctx, dispatcher, outbound),
|
||||
httpClient: newClient(ctx, dispatcher, outbound, false),
|
||||
httpsClient: newClient(ctx, dispatcher, outbound, true),
|
||||
}
|
||||
}
|
||||
|
||||
func newClient(baseCtx context.Context, dispatcher routing.Dispatcher, outbound string) *http.Client {
|
||||
func newClient(baseCtx context.Context, dispatcher routing.Dispatcher, outbound string, isHTTPS bool) *http.Client {
|
||||
dial := func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
var conn net.Conn
|
||||
err := task.Run(ctx, func() error {
|
||||
@@ -92,33 +91,53 @@ func newClient(baseCtx context.Context, dispatcher routing.Dispatcher, outbound
|
||||
Conn: conn,
|
||||
}, nil
|
||||
}
|
||||
return &http.Client{
|
||||
Transport: &http2.Transport{
|
||||
DialTLSContext: func(ctx context.Context, network string, address string, cfg *tls.Config) (net.Conn, error) {
|
||||
conn, err := dial(ctx, network, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
host, _, _ := net.SplitHostPort(address)
|
||||
tlsConn := utls.UClient(conn, &utls.Config{ServerName: host}, utls.HelloChrome_Auto)
|
||||
handshakeCtx, cancel := context.WithTimeout(ctx, idleTimeout)
|
||||
defer cancel()
|
||||
if err := tlsConn.HandshakeContext(handshakeCtx); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
return tlsConn, nil
|
||||
if isHTTPS {
|
||||
return &http.Client{
|
||||
Transport: &http2.Transport{
|
||||
DialTLSContext: func(ctx context.Context, network string, address string, cfg *tls.Config) (net.Conn, error) {
|
||||
conn, err := dial(ctx, network, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
host, _, _ := net.SplitHostPort(address)
|
||||
tlsConn := utls.UClient(conn, &utls.Config{ServerName: host}, utls.HelloChrome_Auto)
|
||||
handshakeCtx, cancel := context.WithTimeout(ctx, idleTimeout)
|
||||
defer cancel()
|
||||
if err := tlsConn.HandshakeContext(handshakeCtx); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
return tlsConn, nil
|
||||
},
|
||||
},
|
||||
},
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if req.URL.Scheme != "https" {
|
||||
return errors.New("redirected to non-https URL: ", req.URL.String())
|
||||
}
|
||||
if len(via) >= 20 {
|
||||
return errors.New("stopped after 20 redirects")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if req.URL.Scheme != "https" {
|
||||
return errors.New("redirected to non-https URL: ", req.URL.String())
|
||||
}
|
||||
if len(via) >= 10 {
|
||||
return errors.New("stopped after 10 redirects")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
} else {
|
||||
return &http.Client{
|
||||
Transport: &http.Transport{
|
||||
Proxy: nil,
|
||||
DisableKeepAlives: true,
|
||||
DialContext: dial,
|
||||
ResponseHeaderTimeout: idleTimeout,
|
||||
},
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if req.URL.Scheme != "https" {
|
||||
return errors.New("redirected to non-https URL: ", req.URL.String())
|
||||
}
|
||||
if len(via) >= 10 {
|
||||
return errors.New("stopped after 10 redirects")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,26 +203,27 @@ func (d *downloader) fetch(rawURL string, writer io.Writer) error {
|
||||
}
|
||||
utils.TryDefaultHeadersWith(req.Header, "nav")
|
||||
|
||||
resp, err := d.httpsClient.Do(req)
|
||||
var client *http.Client
|
||||
if req.URL.Scheme == "https" {
|
||||
client = d.httpsClient
|
||||
} else {
|
||||
client = d.httpClient
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
return errors.New("unexpected status code: ", resp.StatusCode)
|
||||
}
|
||||
if resp.ContentLength > maxDownloadSize {
|
||||
return errors.New("geodata download exceeds 256 MiB")
|
||||
}
|
||||
|
||||
n, err := io.Copy(writer, io.LimitReader(resp.Body, maxDownloadSize+1))
|
||||
n, err := io.Copy(writer, resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n > maxDownloadSize {
|
||||
return errors.New("geodata download exceeds 256 MiB")
|
||||
}
|
||||
if n == 0 {
|
||||
return errors.New("empty response body")
|
||||
}
|
||||
|
||||
@@ -7,13 +7,10 @@ import (
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
commongeodata "github.com/xtls/xray-core/common/geodata"
|
||||
xlua "github.com/xtls/xray-core/common/lua"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/core"
|
||||
"github.com/yuin/gopher-lua/parse"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
@@ -34,11 +31,11 @@ func TestDownloadOneLuaGuard(t *testing.T) {
|
||||
if err := os.WriteFile(filepath.Join(dir, "asset.lua"), nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(tc.body))
|
||||
}))
|
||||
defer server.Close()
|
||||
d := &downloader{ctx: context.Background(), httpsClient: server.Client()}
|
||||
d := &downloader{ctx: context.Background(), httpClient: server.Client()}
|
||||
staged, err := d.downloadOne(&Asset{Url: server.URL, File: "asset.lua"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -74,53 +71,3 @@ func TestDownloadOneLuaGuard(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtobufConfigValidation(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("xray.location.asset", dir)
|
||||
for _, name := range []string{"asset.dat", "asset.DAT"} {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := os.Mkdir(filepath.Join(dir, "directory.dat"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server, err := core.New(&core.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = server.Close() })
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
config *Config
|
||||
wantError string
|
||||
}{
|
||||
{"minutely cron", &Config{Cron: "* * * * *"}, ""},
|
||||
{"minimum interval", &Config{Cron: "@every 1m"}, ""},
|
||||
{"short interval", &Config{Cron: "@every 59s"}, "interval must be at least 1 minute"},
|
||||
{"fractional interval", &Config{Cron: "@every 59.999s"}, "interval must be at least 1 minute"},
|
||||
{"invalid cron", &Config{Cron: "invalid"}, "invalid geodata cron"},
|
||||
{"dat extension", &Config{Cron: "@daily", Assets: []*Asset{{Url: "https://example.com/asset.dat", File: "asset.dat"}}}, ""},
|
||||
{"uppercase extension", &Config{Cron: "@daily", Assets: []*Asset{{Url: "https://example.com/asset.dat", File: "asset.DAT"}}}, ""},
|
||||
{"invalid extension", &Config{Cron: "@daily", Assets: []*Asset{{Url: "https://example.com/asset.dat", File: "asset.lua"}}}, "extension must be .dat"},
|
||||
{"missing extension", &Config{Cron: "@daily", Assets: []*Asset{{Url: "https://example.com/asset.dat", File: "asset"}}}, "extension must be .dat"},
|
||||
{"missing file", &Config{Cron: "@daily", Assets: []*Asset{{Url: "https://example.com/asset.dat", File: "missing.dat"}}}, "invalid geodata asset file"},
|
||||
{"directory", &Config{Cron: "@daily", Assets: []*Asset{{Url: "https://example.com/asset.dat", File: "directory.dat"}}}, "asset is not a regular file"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
config, err := serial.ToTypedMessage(tc.config).GetInstance()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = core.CreateObject(server, config)
|
||||
if tc.wantError == "" {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else if err == nil || !strings.Contains(err.Error(), tc.wantError) {
|
||||
t.Fatalf("CreateObject() error = %v; want %q", err, tc.wantError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+3
-23
@@ -2,16 +2,12 @@ package geodata
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/robfig/cron/v3"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
commongeodata "github.com/xtls/xray-core/common/geodata"
|
||||
"github.com/xtls/xray-core/common/platform/filesystem"
|
||||
"github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
)
|
||||
@@ -29,24 +25,6 @@ func New(ctx context.Context, config *Config) (*Instance, error) {
|
||||
if config.Cron == "" {
|
||||
return &Instance{}, nil
|
||||
}
|
||||
if len(config.Assets) > 100 {
|
||||
return nil, errors.New("geodata supports at most 100 assets")
|
||||
}
|
||||
for _, asset := range config.Assets {
|
||||
if !strings.EqualFold(filepath.Ext(asset.GetFile()), ".dat") {
|
||||
return nil, errors.New("geodata asset file extension must be .dat")
|
||||
}
|
||||
if _, err := filesystem.StatAsset(asset.GetFile()); err != nil {
|
||||
return nil, errors.New("invalid geodata asset file: ", asset.GetFile()).Base(err)
|
||||
}
|
||||
}
|
||||
schedule, err := cron.ParseStandard(config.Cron)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid geodata cron").Base(err)
|
||||
}
|
||||
if interval, ok := schedule.(cron.ConstantDelaySchedule); ok && interval.Delay < time.Minute {
|
||||
return nil, errors.New("geodata cron interval must be at least 1 minute")
|
||||
}
|
||||
|
||||
g := &Instance{
|
||||
assets: config.Assets,
|
||||
@@ -66,7 +44,9 @@ func New(ctx context.Context, config *Config) (*Instance, error) {
|
||||
cron.WithChain(cron.SkipIfStillRunning(cron.DiscardLogger)),
|
||||
cron.WithLogger(cron.DiscardLogger),
|
||||
)
|
||||
g.tasker.Schedule(schedule, cron.FuncJob(g.execute))
|
||||
if _, err := g.tasker.AddFunc(config.Cron, g.execute); err != nil {
|
||||
return nil, errors.New("invalid geodata cron").Base(err)
|
||||
}
|
||||
errors.LogInfo(ctx, "scheduled geodata reload with cron: ", config.Cron)
|
||||
|
||||
return g, nil
|
||||
|
||||
@@ -24,7 +24,6 @@ import (
|
||||
"github.com/xtls/xray-core/features/outbound"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
routing_session "github.com/xtls/xray-core/features/routing/session"
|
||||
"github.com/xtls/xray-core/proxy/blackhole"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
)
|
||||
|
||||
@@ -397,7 +396,7 @@ end`)
|
||||
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{Tag: "default", ProxySettings: serial.ToTypedMessage(&blackhole.Config{})},
|
||||
{Tag: "default", ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Block}}})},
|
||||
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||
})},
|
||||
|
||||
+5
-16
@@ -1,11 +1,10 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/proxy/blackhole"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
@@ -19,24 +18,14 @@ type BlackholeConfig struct {
|
||||
}
|
||||
|
||||
func (v *BlackholeConfig) Build() (proto.Message, error) {
|
||||
config := new(blackhole.Config)
|
||||
if v.Response != nil {
|
||||
responseName := strings.ToLower(v.Response.Type)
|
||||
switch responseName {
|
||||
switch strings.ToLower(v.Response.Type) {
|
||||
case "none", "":
|
||||
config.Response = &blackhole.Response{Type: "none"}
|
||||
case "http":
|
||||
config.Response = &blackhole.Response{Type: "http"}
|
||||
case "custom":
|
||||
data, err := base64.StdEncoding.DecodeString(v.Response.CustomResponseData)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to decode custom response data: " + err.Error())
|
||||
}
|
||||
config.Response = &blackhole.Response{Type: "custom", CustomResponseData: data}
|
||||
default:
|
||||
return nil, errors.New("unknown blackhole response: " + responseName)
|
||||
errors.PrintDeprecatedFeatureWarning(`"blackhole" outbound response`, `the "responder" outbound`)
|
||||
return (&ResponderConfig{Type: v.Response.Type, Response: v.Response.CustomResponseData}).Build()
|
||||
}
|
||||
}
|
||||
|
||||
return config, nil
|
||||
return &freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Block}}}, nil
|
||||
}
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
package conf_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "github.com/xtls/xray-core/infra/conf"
|
||||
"github.com/xtls/xray-core/proxy/blackhole"
|
||||
)
|
||||
|
||||
func TestHTTPResponseJSON(t *testing.T) {
|
||||
creator := func() Buildable {
|
||||
return new(BlackholeConfig)
|
||||
}
|
||||
|
||||
runMultiTestCase(t, []TestCase{
|
||||
{
|
||||
Input: `{
|
||||
"response": {
|
||||
"type": "http"
|
||||
}
|
||||
}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &blackhole.Config{
|
||||
Response: &blackhole.Response{Type: "http"},
|
||||
},
|
||||
},
|
||||
{
|
||||
Input: `{}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &blackhole.Config{},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestCustomResponseJSON(t *testing.T) {
|
||||
creator := func() Buildable {
|
||||
return new(BlackholeConfig)
|
||||
}
|
||||
|
||||
runMultiTestCase(t, []TestCase{
|
||||
{
|
||||
Input: `{
|
||||
"response": {
|
||||
"type": "custom",
|
||||
"customResponseData": "Y3VzdG9tIHJlc3BvbnNl"
|
||||
}
|
||||
}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &blackhole.Config{
|
||||
Response: &blackhole.Response{
|
||||
Type: "custom",
|
||||
CustomResponseData: []byte("custom response"),
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"github.com/robfig/cron/v3"
|
||||
"github.com/xtls/xray-core/app/geodata"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/platform/filesystem"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
@@ -18,6 +19,9 @@ func (c *GeodataAssetConfig) Build() (*geodata.Asset, error) {
|
||||
if err := validateHTTPS(c.URL); err != nil {
|
||||
return nil, errors.New("invalid geodata asset url: ", c.URL).Base(err)
|
||||
}
|
||||
if _, err := filesystem.StatAsset(c.File); err != nil {
|
||||
return nil, errors.New("invalid geodata asset file: ", c.File).Base(err)
|
||||
}
|
||||
return &geodata.Asset{
|
||||
Url: c.URL,
|
||||
File: c.File,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package conf_test
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/app/geodata"
|
||||
@@ -8,6 +9,8 @@ import (
|
||||
)
|
||||
|
||||
func TestGeodataConfig(t *testing.T) {
|
||||
t.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
||||
|
||||
creator := func() Buildable {
|
||||
return new(GeodataConfig)
|
||||
}
|
||||
@@ -35,7 +38,27 @@ func TestGeodataConfig(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestGeodataAssetConfig(t *testing.T) {
|
||||
t.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
||||
|
||||
if _, err := (&GeodataAssetConfig{
|
||||
URL: "https://example.com/geoip.dat",
|
||||
File: "geoip.dat",
|
||||
}).Build(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := (&GeodataAssetConfig{
|
||||
URL: "https://example.com/geoip.dat",
|
||||
File: "missing.dat",
|
||||
}).Build(); err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeodataAssetConfigInvalidURL(t *testing.T) {
|
||||
t.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
||||
|
||||
for _, rawURL := range []string{
|
||||
"",
|
||||
"http://example.com/geoip.dat",
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/proxy/responder"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type ResponderConfig struct {
|
||||
Type string `json:"type"`
|
||||
Response string `json:"response"`
|
||||
}
|
||||
|
||||
func (c *ResponderConfig) Build() (proto.Message, error) {
|
||||
config := new(responder.Config)
|
||||
switch strings.ToLower(c.Type) {
|
||||
case "http":
|
||||
response := http.Response{
|
||||
StatusCode: 403,
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
Header: http.Header{
|
||||
"Connection": {"close"},
|
||||
"Cache-Control": {"max-age=3600, public"},
|
||||
},
|
||||
}
|
||||
var data bytes.Buffer
|
||||
common.Must(response.Write(&data))
|
||||
config.Response = data.Bytes()
|
||||
case "custom":
|
||||
data, err := base64.StdEncoding.DecodeString(c.Response)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to decode response").Base(err)
|
||||
}
|
||||
config.Response = data
|
||||
default:
|
||||
return nil, errors.New("unknown responder response type: ", c.Type)
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package conf_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/core"
|
||||
. "github.com/xtls/xray-core/infra/conf"
|
||||
"github.com/xtls/xray-core/proxy/responder"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func TestResponderConfig(t *testing.T) {
|
||||
parser := loadJSON(func() Buildable { return new(ResponderConfig) })
|
||||
httpResponse := []byte("HTTP/1.1 403 Forbidden\r\n" +
|
||||
"Cache-Control: max-age=3600, public\r\n" +
|
||||
"Connection: close\r\n" +
|
||||
"Content-Length: 0\r\n\r\n")
|
||||
|
||||
runMultiTestCase(t, []TestCase{
|
||||
{Input: `{"type":"http"}`, Parser: parser, Output: &responder.Config{Response: httpResponse}},
|
||||
{Input: `{"type":"HtTp"}`, Parser: parser, Output: &responder.Config{Response: httpResponse}},
|
||||
{Input: `{"type":"custom","response":"aGVsbG8="}`, Parser: parser, Output: &responder.Config{Response: []byte("hello")}},
|
||||
{Input: `{"type":"CuStOm","response":"aGVsbG8="}`, Parser: parser, Output: &responder.Config{Response: []byte("hello")}},
|
||||
{Input: `{"type":"custom","response":"AP+A"}`, Parser: parser, Output: &responder.Config{Response: []byte{0, 255, 128}}},
|
||||
{Input: `{"type":"custom","response":""}`, Parser: parser, Output: &responder.Config{}},
|
||||
{Input: `{"type":"custom"}`, Parser: parser, Output: &responder.Config{}},
|
||||
{
|
||||
Input: `{
|
||||
"protocol": "ReSpOnDeR",
|
||||
"tag": "reply",
|
||||
"settings": {"type": "custom", "response": "aGVsbG8="}
|
||||
}`,
|
||||
Parser: func(s string) (proto.Message, error) {
|
||||
var config OutboundDetourConfig
|
||||
if err := json.Unmarshal([]byte(s), &config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return config.Build()
|
||||
},
|
||||
Output: &core.OutboundHandlerConfig{
|
||||
Tag: "reply",
|
||||
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{}),
|
||||
ProxySettings: serial.ToTypedMessage(&responder.Config{Response: []byte("hello")}),
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestResponderConfigErrors(t *testing.T) {
|
||||
parser := loadJSON(func() Buildable { return new(ResponderConfig) })
|
||||
for _, input := range []string{
|
||||
`{}`,
|
||||
`{"type":""}`,
|
||||
`{"type":"unknown"}`,
|
||||
`{"type":"none"}`,
|
||||
`{"type":"custom","response":"!"}`,
|
||||
} {
|
||||
if _, err := parser(input); err == nil {
|
||||
t.Fatalf("expected error for %s", input)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,7 @@ var (
|
||||
"block": func() interface{} { return new(BlackholeConfig) },
|
||||
"blackhole": func() interface{} { return new(BlackholeConfig) },
|
||||
"loopback": func() interface{} { return new(LoopbackConfig) },
|
||||
"responder": func() interface{} { return new(ResponderConfig) },
|
||||
"direct": func() interface{} { return new(FreedomConfig) },
|
||||
"freedom": func() interface{} { return new(FreedomConfig) },
|
||||
"http": func() interface{} { return new(HTTPClientConfig) },
|
||||
|
||||
@@ -35,13 +35,13 @@ import (
|
||||
_ "github.com/xtls/xray-core/app/observatory"
|
||||
|
||||
// Inbound and outbound proxies.
|
||||
_ "github.com/xtls/xray-core/proxy/blackhole"
|
||||
_ "github.com/xtls/xray-core/proxy/dns"
|
||||
_ "github.com/xtls/xray-core/proxy/dokodemo"
|
||||
_ "github.com/xtls/xray-core/proxy/freedom"
|
||||
_ "github.com/xtls/xray-core/proxy/http"
|
||||
_ "github.com/xtls/xray-core/proxy/loopback"
|
||||
_ "github.com/xtls/xray-core/proxy/masque"
|
||||
_ "github.com/xtls/xray-core/proxy/responder"
|
||||
_ "github.com/xtls/xray-core/proxy/shadowsocks"
|
||||
_ "github.com/xtls/xray-core/proxy/socks"
|
||||
_ "github.com/xtls/xray-core/proxy/trojan"
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
// Package blackhole is an outbound handler that blocks all connections.
|
||||
package blackhole
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/dice"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/signal"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
)
|
||||
|
||||
// Handler is an outbound connection that silently swallow the entire payload.
|
||||
type Handler struct {
|
||||
response []byte
|
||||
}
|
||||
|
||||
var http403response = http.Response{
|
||||
StatusCode: 403,
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
Header: http.Header{
|
||||
"Connection": {"close"},
|
||||
"Cache-Control": {"max-age=3600, public"},
|
||||
},
|
||||
}
|
||||
|
||||
// New creates a new blackhole handler.
|
||||
func New(ctx context.Context, config *Config) (*Handler, error) {
|
||||
response := []byte{}
|
||||
if config.Response != nil {
|
||||
switch config.Response.Type {
|
||||
case "", "none":
|
||||
case "http":
|
||||
var data bytes.Buffer
|
||||
common.Must(http403response.Write(&data))
|
||||
response = data.Bytes()
|
||||
case "custom":
|
||||
response = config.Response.CustomResponseData
|
||||
default:
|
||||
return nil, errors.New("unknown blackhole response: " + config.Response.Type)
|
||||
}
|
||||
}
|
||||
return &Handler{
|
||||
response: response,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Process implements OutboundHandler.Dispatch().
|
||||
func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
ob := outbounds[len(outbounds)-1]
|
||||
ob.Name = "blackhole"
|
||||
|
||||
if len(h.response) > 0 {
|
||||
mbc := buf.MultiBufferContainer{}
|
||||
common.Must2(mbc.Write(h.response))
|
||||
link.Writer.WriteMultiBuffer(mbc.MultiBuffer)
|
||||
// Sleep a little here to make sure the response is sent to client.
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
defer common.Interrupt(link.Writer)
|
||||
defer common.Interrupt(link.Reader)
|
||||
// wait to drain all the possible incoming UDP data
|
||||
if ob.Target.Network == net.Network_UDP {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
timer := signal.CancelAfterInactivity(ctx, func() {
|
||||
cancel()
|
||||
}, time.Duration(30+dice.Roll(61))*time.Second)
|
||||
go buf.Copy(link.Reader, buf.Discard, buf.UpdateActivity(timer))
|
||||
<-ctx.Done()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
|
||||
return New(ctx, config.(*Config))
|
||||
}))
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package blackhole_test
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/proxy/blackhole"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
func TestBlackholeHTTPResponse(t *testing.T) {
|
||||
ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{}})
|
||||
handler, err := blackhole.New(ctx, &blackhole.Config{
|
||||
Response: &blackhole.Response{Type: "http"},
|
||||
})
|
||||
common.Must(err)
|
||||
|
||||
reader, writer := pipe.New(pipe.WithoutSizeLimit())
|
||||
|
||||
dataCh := make(chan buf.MultiBuffer, 1)
|
||||
go func() {
|
||||
mb := common.Must2(reader.ReadMultiBuffer())
|
||||
dataCh <- mb
|
||||
}()
|
||||
link := transport.Link{
|
||||
Reader: reader,
|
||||
Writer: writer,
|
||||
}
|
||||
common.Must(handler.Process(ctx, &link, nil))
|
||||
mb := <-dataCh
|
||||
data := make([]byte, mb.Len())
|
||||
mb.Copy(data)
|
||||
resp := common.Must2(http.ReadResponse(bufio.NewReader(bytes.NewBuffer(data)), nil))
|
||||
if resp.StatusCode != 403 {
|
||||
t.Errorf("expected 403 response, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlackholeCustomResponse(t *testing.T) {
|
||||
ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{}})
|
||||
// slightly bigger than a buffer
|
||||
expected := make([]byte, buf.Size+1000)
|
||||
if _, err := rand.Read(expected); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler, err := blackhole.New(ctx, &blackhole.Config{
|
||||
Response: &blackhole.Response{
|
||||
Type: "custom",
|
||||
CustomResponseData: expected,
|
||||
},
|
||||
})
|
||||
common.Must(err)
|
||||
|
||||
reader, writer := pipe.New(pipe.WithoutSizeLimit())
|
||||
var actual buf.MultiBuffer
|
||||
var rerr error
|
||||
go func() {
|
||||
actual, rerr = reader.ReadMultiBuffer()
|
||||
}()
|
||||
|
||||
link := transport.Link{Reader: reader, Writer: writer}
|
||||
common.Must(handler.Process(ctx, &link, nil))
|
||||
common.Must(rerr)
|
||||
|
||||
if actual.String() != string(expected) {
|
||||
t.Errorf("custom response mismatch")
|
||||
}
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.11
|
||||
// protoc v6.33.5
|
||||
// source: proxy/blackhole/config.proto
|
||||
|
||||
package blackhole
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
unsafe "unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type Response struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"`
|
||||
CustomResponseData []byte `protobuf:"bytes,2,opt,name=custom_response_data,json=customResponseData,proto3" json:"custom_response_data,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Response) Reset() {
|
||||
*x = Response{}
|
||||
mi := &file_proxy_blackhole_config_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Response) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Response) ProtoMessage() {}
|
||||
|
||||
func (x *Response) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_proxy_blackhole_config_proto_msgTypes[0]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Response.ProtoReflect.Descriptor instead.
|
||||
func (*Response) Descriptor() ([]byte, []int) {
|
||||
return file_proxy_blackhole_config_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *Response) GetType() string {
|
||||
if x != nil {
|
||||
return x.Type
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Response) GetCustomResponseData() []byte {
|
||||
if x != nil {
|
||||
return x.CustomResponseData
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Response *Response `protobuf:"bytes,1,opt,name=response,proto3" json:"response,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Config) Reset() {
|
||||
*x = Config{}
|
||||
mi := &file_proxy_blackhole_config_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Config) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Config) ProtoMessage() {}
|
||||
|
||||
func (x *Config) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_proxy_blackhole_config_proto_msgTypes[1]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
|
||||
func (*Config) Descriptor() ([]byte, []int) {
|
||||
return file_proxy_blackhole_config_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *Config) GetResponse() *Response {
|
||||
if x != nil {
|
||||
return x.Response
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_proxy_blackhole_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_proxy_blackhole_config_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"\x1cproxy/blackhole/config.proto\x12\x14xray.proxy.blackhole\"P\n" +
|
||||
"\bResponse\x12\x12\n" +
|
||||
"\x04type\x18\x01 \x01(\tR\x04type\x120\n" +
|
||||
"\x14custom_response_data\x18\x02 \x01(\fR\x12customResponseData\"D\n" +
|
||||
"\x06Config\x12:\n" +
|
||||
"\bresponse\x18\x01 \x01(\v2\x1e.xray.proxy.blackhole.ResponseR\bresponseB^\n" +
|
||||
"\x18com.xray.proxy.blackholeP\x01Z)github.com/xtls/xray-core/proxy/blackhole\xaa\x02\x14Xray.Proxy.Blackholeb\x06proto3"
|
||||
|
||||
var (
|
||||
file_proxy_blackhole_config_proto_rawDescOnce sync.Once
|
||||
file_proxy_blackhole_config_proto_rawDescData []byte
|
||||
)
|
||||
|
||||
func file_proxy_blackhole_config_proto_rawDescGZIP() []byte {
|
||||
file_proxy_blackhole_config_proto_rawDescOnce.Do(func() {
|
||||
file_proxy_blackhole_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_blackhole_config_proto_rawDesc), len(file_proxy_blackhole_config_proto_rawDesc)))
|
||||
})
|
||||
return file_proxy_blackhole_config_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_proxy_blackhole_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
|
||||
var file_proxy_blackhole_config_proto_goTypes = []any{
|
||||
(*Response)(nil), // 0: xray.proxy.blackhole.Response
|
||||
(*Config)(nil), // 1: xray.proxy.blackhole.Config
|
||||
}
|
||||
var file_proxy_blackhole_config_proto_depIdxs = []int32{
|
||||
0, // 0: xray.proxy.blackhole.Config.response:type_name -> xray.proxy.blackhole.Response
|
||||
1, // [1:1] is the sub-list for method output_type
|
||||
1, // [1:1] is the sub-list for method input_type
|
||||
1, // [1:1] is the sub-list for extension type_name
|
||||
1, // [1:1] is the sub-list for extension extendee
|
||||
0, // [0:1] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_proxy_blackhole_config_proto_init() }
|
||||
func file_proxy_blackhole_config_proto_init() {
|
||||
if File_proxy_blackhole_config_proto != nil {
|
||||
return
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_blackhole_config_proto_rawDesc), len(file_proxy_blackhole_config_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 2,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
GoTypes: file_proxy_blackhole_config_proto_goTypes,
|
||||
DependencyIndexes: file_proxy_blackhole_config_proto_depIdxs,
|
||||
MessageInfos: file_proxy_blackhole_config_proto_msgTypes,
|
||||
}.Build()
|
||||
File_proxy_blackhole_config_proto = out.File
|
||||
file_proxy_blackhole_config_proto_goTypes = nil
|
||||
file_proxy_blackhole_config_proto_depIdxs = nil
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package xray.proxy.blackhole;
|
||||
option csharp_namespace = "Xray.Proxy.Blackhole";
|
||||
option go_package = "github.com/xtls/xray-core/proxy/blackhole";
|
||||
option java_package = "com.xray.proxy.blackhole";
|
||||
option java_multiple_files = true;
|
||||
|
||||
message Response {
|
||||
string type = 1;
|
||||
bytes custom_response_data = 2;
|
||||
}
|
||||
|
||||
message Config {
|
||||
Response response = 1;
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package blackhole_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/proxy/blackhole"
|
||||
)
|
||||
|
||||
func TestHTTPResponse(t *testing.T) {
|
||||
handler, err := blackhole.New(context.Background(), &blackhole.Config{
|
||||
Response: &blackhole.Response{Type: "http"},
|
||||
})
|
||||
common.Must(err)
|
||||
if handler == nil {
|
||||
t.Error("expected HTTP response handler")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.11
|
||||
// protoc v6.33.5
|
||||
// source: proxy/responder/config.proto
|
||||
|
||||
package responder
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
unsafe "unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Response []byte `protobuf:"bytes,1,opt,name=response,proto3" json:"response,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Config) Reset() {
|
||||
*x = Config{}
|
||||
mi := &file_proxy_responder_config_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Config) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Config) ProtoMessage() {}
|
||||
|
||||
func (x *Config) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_proxy_responder_config_proto_msgTypes[0]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
|
||||
func (*Config) Descriptor() ([]byte, []int) {
|
||||
return file_proxy_responder_config_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *Config) GetResponse() []byte {
|
||||
if x != nil {
|
||||
return x.Response
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_proxy_responder_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_proxy_responder_config_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"\x1cproxy/responder/config.proto\x12\x14xray.proxy.responder\"$\n" +
|
||||
"\x06Config\x12\x1a\n" +
|
||||
"\bresponse\x18\x01 \x01(\fR\bresponseB^\n" +
|
||||
"\x18com.xray.proxy.responderP\x01Z)github.com/xtls/xray-core/proxy/responder\xaa\x02\x14Xray.Proxy.Responderb\x06proto3"
|
||||
|
||||
var (
|
||||
file_proxy_responder_config_proto_rawDescOnce sync.Once
|
||||
file_proxy_responder_config_proto_rawDescData []byte
|
||||
)
|
||||
|
||||
func file_proxy_responder_config_proto_rawDescGZIP() []byte {
|
||||
file_proxy_responder_config_proto_rawDescOnce.Do(func() {
|
||||
file_proxy_responder_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_responder_config_proto_rawDesc), len(file_proxy_responder_config_proto_rawDesc)))
|
||||
})
|
||||
return file_proxy_responder_config_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_proxy_responder_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
|
||||
var file_proxy_responder_config_proto_goTypes = []any{
|
||||
(*Config)(nil), // 0: xray.proxy.responder.Config
|
||||
}
|
||||
var file_proxy_responder_config_proto_depIdxs = []int32{
|
||||
0, // [0:0] is the sub-list for method output_type
|
||||
0, // [0:0] is the sub-list for method input_type
|
||||
0, // [0:0] is the sub-list for extension type_name
|
||||
0, // [0:0] is the sub-list for extension extendee
|
||||
0, // [0:0] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_proxy_responder_config_proto_init() }
|
||||
func file_proxy_responder_config_proto_init() {
|
||||
if File_proxy_responder_config_proto != nil {
|
||||
return
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_responder_config_proto_rawDesc), len(file_proxy_responder_config_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 1,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
GoTypes: file_proxy_responder_config_proto_goTypes,
|
||||
DependencyIndexes: file_proxy_responder_config_proto_depIdxs,
|
||||
MessageInfos: file_proxy_responder_config_proto_msgTypes,
|
||||
}.Build()
|
||||
File_proxy_responder_config_proto = out.File
|
||||
file_proxy_responder_config_proto_goTypes = nil
|
||||
file_proxy_responder_config_proto_depIdxs = nil
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package xray.proxy.responder;
|
||||
option csharp_namespace = "Xray.Proxy.Responder";
|
||||
option go_package = "github.com/xtls/xray-core/proxy/responder";
|
||||
option java_package = "com.xray.proxy.responder";
|
||||
option java_multiple_files = true;
|
||||
|
||||
message Config {
|
||||
bytes response = 1;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package responder
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
response []byte
|
||||
}
|
||||
|
||||
func New(_ context.Context, config *Config) (*Handler, error) {
|
||||
return &Handler{response: config.Response}, nil
|
||||
}
|
||||
|
||||
// Process implements proxy.Outbound.
|
||||
func (h *Handler) Process(ctx context.Context, link *transport.Link, _ internet.Dialer) error {
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
ob := outbounds[len(outbounds)-1]
|
||||
ob.Name = "responder"
|
||||
|
||||
return link.Writer.WriteMultiBuffer(buf.MergeBytes(nil, h.response))
|
||||
}
|
||||
|
||||
func init() {
|
||||
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
|
||||
return New(ctx, config.(*Config))
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package responder_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
_ "github.com/xtls/xray-core/app/proxyman/outbound"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/features/outbound"
|
||||
"github.com/xtls/xray-core/proxy/responder"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
type writerFunc func(buf.MultiBuffer) error
|
||||
|
||||
func (f writerFunc) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
return f(mb)
|
||||
}
|
||||
|
||||
func newHandler(t *testing.T, response []byte) *responder.Handler {
|
||||
t.Helper()
|
||||
handler, err := responder.New(context.Background(), &responder.Config{Response: response})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return handler
|
||||
}
|
||||
|
||||
func responseContext(network net.Network) context.Context {
|
||||
return session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
|
||||
Target: net.Destination{Network: network, Address: net.DomainAddress("responder.invalid"), Port: 80},
|
||||
}})
|
||||
}
|
||||
|
||||
func TestResponderResponse(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
response []byte
|
||||
}{
|
||||
{name: "empty"},
|
||||
{name: "binary", response: []byte{0, 255, 128, 1}},
|
||||
{name: "large", response: bytes.Repeat([]byte("response\x00\xff"), buf.Size)},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
handler := newHandler(t, test.response)
|
||||
want := string(test.response)
|
||||
for _, network := range []net.Network{net.Network_TCP, net.Network_UDP} {
|
||||
t.Run(network.String(), func(t *testing.T) {
|
||||
for range 2 {
|
||||
var output buf.MultiBufferContainer
|
||||
writes := 0
|
||||
writer := writerFunc(func(mb buf.MultiBuffer) error {
|
||||
writes++
|
||||
return output.WriteMultiBuffer(mb)
|
||||
})
|
||||
ctx := responseContext(network)
|
||||
// No reader or dialer: the handler must respond without using either.
|
||||
if err := handler.Process(ctx, &transport.Link{Writer: writer}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if writes != 1 || output.MultiBuffer.String() != want {
|
||||
t.Fatalf("writes = %d, response length = %d, want one write of %d bytes", writes, output.MultiBuffer.Len(), len(want))
|
||||
}
|
||||
if got := session.OutboundsFromContext(ctx)[0].Name; got != "responder" {
|
||||
t.Fatalf("outbound name = %q, want responder", got)
|
||||
}
|
||||
if len(output.MultiBuffer) > 0 {
|
||||
output.MultiBuffer[0].Bytes()[0] ^= 0xff
|
||||
}
|
||||
output.Close()
|
||||
if string(test.response) != want {
|
||||
t.Fatal("sending or modifying the response changed the configured payload")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponderConcurrent(t *testing.T) {
|
||||
response := bytes.Repeat([]byte("concurrent response\x00\xff"), buf.Size)
|
||||
want := string(response)
|
||||
handler := newHandler(t, response)
|
||||
for i := range 8 {
|
||||
t.Run(strconv.Itoa(i), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
var output buf.MultiBufferContainer
|
||||
defer output.Close()
|
||||
if err := handler.Process(responseContext(net.Network_TCP), &transport.Link{Writer: &output}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if output.MultiBuffer.String() != want {
|
||||
t.Fatal("concurrent response mismatch")
|
||||
}
|
||||
output.MultiBuffer[0].Bytes()[0] ^= 0xff
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponderWriteError(t *testing.T) {
|
||||
handler := newHandler(t, []byte("response"))
|
||||
want := errors.New("write failed")
|
||||
writer := writerFunc(func(mb buf.MultiBuffer) error {
|
||||
buf.ReleaseMulti(mb)
|
||||
return want
|
||||
})
|
||||
if err := handler.Process(responseContext(net.Network_TCP), &transport.Link{Writer: writer}, nil); !errors.Is(err, want) {
|
||||
t.Fatalf("Process returned %v, want %v", err, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponderDispatch(t *testing.T) {
|
||||
for _, response := range [][]byte{nil, bytes.Repeat([]byte("response\x00\xff"), buf.Size)} {
|
||||
name := "large"
|
||||
if len(response) == 0 {
|
||||
name = "empty"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
instance, err := core.New(&core.Config{
|
||||
App: []*serial.TypedMessage{serial.ToTypedMessage(&proxyman.OutboundConfig{})},
|
||||
Outbound: []*core.OutboundHandlerConfig{{
|
||||
Tag: "reply",
|
||||
ProxySettings: serial.ToTypedMessage(&responder.Config{Response: response}),
|
||||
}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer instance.Close()
|
||||
manager := instance.GetFeature(outbound.ManagerType()).(outbound.Manager)
|
||||
handler := manager.GetHandler("reply")
|
||||
if handler == nil {
|
||||
t.Fatal("responder handler not registered")
|
||||
}
|
||||
for _, network := range []net.Network{net.Network_TCP, net.Network_UDP} {
|
||||
t.Run(network.String(), func(t *testing.T) {
|
||||
input, upload := pipe.New()
|
||||
output, download := pipe.New(pipe.WithoutSizeLimit())
|
||||
defer input.Interrupt()
|
||||
defer output.Interrupt()
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
handler.Dispatch(responseContext(network), &transport.Link{Reader: input, Writer: download})
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("responder did not finish without incoming data")
|
||||
}
|
||||
// Read after Dispatch returns: normal closure must preserve queued data.
|
||||
var actual []byte
|
||||
for {
|
||||
mb, err := output.ReadMultiBufferTimeout(time.Second)
|
||||
actual = append(actual, []byte(mb.String())...)
|
||||
buf.ReleaseMulti(mb)
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if !bytes.Equal(actual, response) {
|
||||
t.Fatalf("response mismatch: got %d bytes, want %d", len(actual), len(response))
|
||||
}
|
||||
if err := upload.WriteMultiBuffer(buf.MergeBytes(nil, []byte("late request"))); err != io.ErrClosedPipe {
|
||||
t.Fatalf("input was not interrupted: got %v, want %v", err, io.ErrClosedPipe)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,6 @@ import (
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/proxy/blackhole"
|
||||
proxydns "github.com/xtls/xray-core/proxy/dns"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
)
|
||||
@@ -73,7 +72,7 @@ func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.Na
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
|
||||
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
|
||||
{Tag: "block", ProxySettings: serial.ToTypedMessage(&blackhole.Config{})},
|
||||
{Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Block}}})},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/proxy/blackhole"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
"github.com/xtls/xray-core/proxy/socks"
|
||||
"github.com/xtls/xray-core/testing/servers/tcp"
|
||||
@@ -78,7 +77,7 @@ func TestResolveIP(t *testing.T) {
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Block}}}),
|
||||
},
|
||||
{
|
||||
Tag: "direct",
|
||||
|
||||
@@ -21,7 +21,6 @@ import (
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/uuid"
|
||||
core "github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/proxy/blackhole"
|
||||
"github.com/xtls/xray-core/proxy/dokodemo"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
v2http "github.com/xtls/xray-core/proxy/http"
|
||||
@@ -406,7 +405,7 @@ func TestBlackhole(t *testing.T) {
|
||||
},
|
||||
{
|
||||
Tag: "blocked",
|
||||
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Block}}}),
|
||||
},
|
||||
},
|
||||
App: []*serial.TypedMessage{
|
||||
|
||||
@@ -17,7 +17,6 @@ import (
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/uuid"
|
||||
core "github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/proxy/blackhole"
|
||||
"github.com/xtls/xray-core/proxy/dokodemo"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
"github.com/xtls/xray-core/proxy/vmess"
|
||||
@@ -100,7 +99,7 @@ func TestReverseProxy(t *testing.T) {
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Block}}}),
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -275,7 +274,7 @@ func TestReverseProxyLongRunning(t *testing.T) {
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Block}}}),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/proxy/blackhole"
|
||||
"github.com/xtls/xray-core/proxy/dokodemo"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
"github.com/xtls/xray-core/proxy/http"
|
||||
@@ -331,7 +330,7 @@ func TestSocksBridageUDPWithRouting(t *testing.T) {
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Block}}}),
|
||||
},
|
||||
{
|
||||
Tag: "out",
|
||||
|
||||
Reference in New Issue
Block a user