Compare commits

..
Author SHA1 Message Date
Meo597 89be28c86c convert 2026-10-28 23:04:50 +08:00
Meo597 31c4d09d09 add responder 2026-10-28 22:31:00 +08:00
22 changed files with 499 additions and 528 deletions
+1 -2
View File
@@ -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}},
})},
+17 -59
View File
@@ -8,65 +8,23 @@ import (
var privateIPMatcher = sync.OnceValue(func() IPMatcher {
return common.Must2(IPReg.BuildIPMatcher(common.Must2(ParseIPRules([]string{
// https://www.iana.org/assignments/iana-ipv4-special-registry
"0.0.0.0/8", // "This network"
"0.0.0.0/32", // "This host on this network"
"10.0.0.0/8", // Private-Use
"100.64.0.0/10", // Shared Address Space
"127.0.0.0/8", // Loopback
"169.254.0.0/16", // Link Local
"172.16.0.0/12", // Private-Use
// "192.0.0.0/24", // IETF Protocol Assignments
"192.0.0.0/29", // IPv4 Service Continuity Prefix
"192.0.0.8/32", // IPv4 dummy address
"192.0.0.9/32", // Port Control Protocol Anycast
"192.0.0.10/32", // Traversal Using Relays around NAT Anycast
"192.0.0.170/32", // NAT64/DNS64 Discovery
"192.0.0.171/32", // NAT64/DNS64 Discovery
"192.0.2.0/24", // Documentation (TEST-NET-1)
// "192.31.196.0/24", // AS112-v4
"192.52.193.0/24", // AMT
// "192.88.99.0/24", // Deprecated (6to4 Relay Anycast)
"192.88.99.2/32", // 6a44-relay anycast address
"192.168.0.0/16", // Private-Use
// "192.175.48.0/24", // Direct Delegation AS112 Service
"198.18.0.0/15", // Benchmarking
"198.51.100.0/24", // Documentation (TEST-NET-2)
"203.0.113.0/24", // Documentation (TEST-NET-3)
"240.0.0.0/4", // Reserved
"255.255.255.255/32", // Limited Broadcast
// https://www.iana.org/assignments/multicast-addresses
"224.0.0.0/4",
// https://www.iana.org/assignments/iana-ipv6-special-registry
"::1/128", // Loopback Address
"::/128", // Unspecified Address
// "::ffff:0:0/96", // IPv4-mapped Address
"64:ff9b::/96", // IPv4-IPv6 Translat.
"64:ff9b:1::/48", // IPv4-IPv6 Translat.
"100::/64", // Discard-Only Address Block
"100:0:0:1::/64", // Dummy IPv6 Prefix
// "2001::/23", // IETF Protocol Assignments
"2001::/32", // TEREDO
"2001:1::1/128", // Port Control Protocol Anycast
"2001:1::2/128", // Traversal Using Relays around NAT Anycast
"2001:1::3/128", // DNS-SD Service Registration Protocol Anycast
"2001:2::/48", // Benchmarking
"2001:3::/32", // AMT
// "2001:4:112::/48", // AS112-v6
// "2001:10::/28", // Deprecated (previously ORCHID)
"2001:20::/28", // ORCHIDv2
"2001:30::/28", // Drone Remote ID Protocol Entity Tags (DETs) Prefix
"2001:db8::/32", // Documentation
"2002::/16", // 6to4
// "2620:4f:8000::/48", // Direct Delegation AS112 Service
"3fff::/20", // Documentation
"5f00::/16", // Segment Routing (SRv6) SIDs
"fc00::/7", // Unique-Local
"fe80::/10", // Link-Local Unicast
// https://www.iana.org/assignments/ipv6-multicast-addresses
"0.0.0.0/8",
"10.0.0.0/8",
"100.64.0.0/10",
"127.0.0.0/8",
"169.254.0.0/16",
"172.16.0.0/12",
"192.0.0.0/24",
"192.0.2.0/24",
"192.88.99.0/24",
"192.168.0.0/16",
"198.18.0.0/15",
"198.51.100.0/24",
"203.0.113.0/24",
"224.0.0.0/3",
"::/127",
"fc00::/7",
"fe80::/10",
"ff00::/8",
}))))
})
+5 -16
View File
@@ -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
}
-57
View File
@@ -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"),
},
},
},
})
}
+46
View File
@@ -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
}
+65
View File
@@ -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)
}
}
}
+3 -3
View File
@@ -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) },
@@ -237,11 +238,10 @@ type OutboundDetourConfig struct {
func requiresTransportSecurity(address *Address) bool {
if address == nil || address.Address == nil {
return true
return false
}
if address.Family().IsIP() {
ip := address.IP()
return !ip.IsPrivate() && !ip.IsLoopback() && !ip.IsLinkLocalUnicast()
return !geodata.GetPrivateIPMatcher().Match(address.IP())
}
domain := strings.TrimSuffix(strings.ToLower(address.Domain()), ".")
return !geodata.GetPrivateDomainMatcher().MatchAny(domain)
+1 -1
View File
@@ -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"
-88
View File
@@ -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))
}))
}
-76
View File
@@ -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")
}
}
-180
View File
@@ -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
}
-16
View File
@@ -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;
}
-19
View File
@@ -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")
}
}
+123
View File
@@ -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
}
+11
View File
@@ -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;
}
+34
View File
@@ -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))
}))
}
+187
View File
@@ -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)
}
})
}
})
}
}
+1 -2
View File
@@ -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 {
+1 -2
View File
@@ -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",
+1 -2
View File
@@ -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{
+2 -3
View File
@@ -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}}}),
},
},
}
+1 -2
View File
@@ -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",