mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-11-25 19:11:45 +00:00
VLESS Multiplex, Reverse Proxy: Refactor to move code into VLESS; Mux only uses settings.multiplex in VLESS/VMess outbound (#7364)
https://github.com/XTLS/Xray-core/pull/6748#issuecomment-5752780799 https://github.com/XTLS/Xray-core/issues/7240#issuecomment-6439951754 https://github.com/XTLS/Xray-core/pull/4231#issuecomment-6679992732 https://github.com/XTLS/Xray-core/pull/7355#issuecomment-6739539943 https://github.com/XTLS/Xray-core/pull/7359#issuecomment-6742147165 https://github.com/XTLS/Xray-core/pull/7364#issuecomment-6784892866 https://github.com/XTLS/Xray-core/pull/7364#issuecomment-6812285253 https://github.com/XTLS/Xray-core/pull/7364#issuecomment-6842747639 https://github.com/XTLS/Xray-core/pull/4231#issuecomment-7012427059 https://github.com/XTLS/Xray-core/pull/7364#issuecomment-7108550396 https://github.com/XTLS/Xray-core/pull/7364#issuecomment-7129493942 https://github.com/XTLS/Xray-core/pull/7364#issuecomment-7130454962 --------- Co-authored-by: Codex <codex@users.noreply.github.com> Co-authored-by: RPRX <63339210+RPRX@users.noreply.github.com>
This commit is contained in:
committed by
RPRXX
co-authored by
Codex
RPRX
parent
15b2499d34
commit
e17392a96e
@@ -26,9 +26,16 @@ import (
|
||||
|
||||
var errSniffingTimeout = errors.New("timeout on sniffing")
|
||||
|
||||
// Native readers own attempted-input accounting, timeout and interruption.
|
||||
type nativeReader interface {
|
||||
buf.TimeoutReader
|
||||
common.Interruptible
|
||||
SetUplinkCounter(stats.Counter)
|
||||
}
|
||||
|
||||
type cachedReader struct {
|
||||
sync.Mutex
|
||||
reader buf.TimeoutReader // *pipe.Reader or *buf.TimeoutWrapperReader
|
||||
reader buf.TimeoutReader
|
||||
cache buf.MultiBuffer
|
||||
}
|
||||
|
||||
@@ -86,9 +93,7 @@ func (r *cachedReader) Interrupt() {
|
||||
r.cache = buf.ReleaseMulti(r.cache)
|
||||
}
|
||||
r.Unlock()
|
||||
if p, ok := r.reader.(*pipe.Reader); ok {
|
||||
p.Interrupt()
|
||||
}
|
||||
common.Interrupt(r.reader)
|
||||
}
|
||||
|
||||
// DefaultDispatcher is a default implementation of Dispatcher.
|
||||
@@ -194,15 +199,13 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st
|
||||
user = sessionInbound.User
|
||||
}
|
||||
|
||||
link.Reader = &buf.TimeoutWrapperReader{Reader: link.Reader}
|
||||
var uplinkCounter stats.Counter
|
||||
|
||||
if user != nil && len(user.Email) > 0 {
|
||||
p := policyManager.ForLevel(user.Level)
|
||||
if p.Stats.UserUplink {
|
||||
name := "user>>>" + user.Email + ">>>traffic>>>uplink"
|
||||
if c, _ := statsManager.GetOrRegisterCounter(name); c != nil {
|
||||
link.Reader.(*buf.TimeoutWrapperReader).Counter = c
|
||||
}
|
||||
uplinkCounter, _ = statsManager.GetOrRegisterCounter(name)
|
||||
}
|
||||
if p.Stats.UserDownlink {
|
||||
name := "user>>>" + user.Email + ">>>traffic>>>downlink"
|
||||
@@ -218,6 +221,11 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st
|
||||
}
|
||||
}
|
||||
|
||||
if reader, ok := link.Reader.(nativeReader); ok {
|
||||
reader.SetUplinkCounter(uplinkCounter)
|
||||
} else {
|
||||
link.Reader = &buf.TimeoutWrapperReader{Reader: link.Reader, Counter: uplinkCounter}
|
||||
}
|
||||
return link
|
||||
}
|
||||
|
||||
|
||||
+33
-121
@@ -328,13 +328,12 @@ func (*OutboundConfig) Descriptor() ([]byte, []int) {
|
||||
type SenderConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
// Send traffic through the given IP. Only IP is allowed.
|
||||
Via *net.IPOrDomain `protobuf:"bytes,1,opt,name=via,proto3" json:"via,omitempty"`
|
||||
StreamSettings *internet.StreamConfig `protobuf:"bytes,2,opt,name=stream_settings,json=streamSettings,proto3" json:"stream_settings,omitempty"`
|
||||
MultiplexSettings *MultiplexingConfig `protobuf:"bytes,4,opt,name=multiplex_settings,json=multiplexSettings,proto3" json:"multiplex_settings,omitempty"`
|
||||
ViaCidr string `protobuf:"bytes,5,opt,name=via_cidr,json=viaCidr,proto3" json:"via_cidr,omitempty"`
|
||||
TargetStrategy internet.DomainStrategy `protobuf:"varint,6,opt,name=target_strategy,json=targetStrategy,proto3,enum=xray.transport.internet.DomainStrategy" json:"target_strategy,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
Via *net.IPOrDomain `protobuf:"bytes,1,opt,name=via,proto3" json:"via,omitempty"`
|
||||
StreamSettings *internet.StreamConfig `protobuf:"bytes,2,opt,name=stream_settings,json=streamSettings,proto3" json:"stream_settings,omitempty"`
|
||||
ViaCidr string `protobuf:"bytes,5,opt,name=via_cidr,json=viaCidr,proto3" json:"via_cidr,omitempty"`
|
||||
TargetStrategy internet.DomainStrategy `protobuf:"varint,6,opt,name=target_strategy,json=targetStrategy,proto3,enum=xray.transport.internet.DomainStrategy" json:"target_strategy,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *SenderConfig) Reset() {
|
||||
@@ -381,13 +380,6 @@ func (x *SenderConfig) GetStreamSettings() *internet.StreamConfig {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *SenderConfig) GetMultiplexSettings() *MultiplexingConfig {
|
||||
if x != nil {
|
||||
return x.MultiplexSettings
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *SenderConfig) GetViaCidr() string {
|
||||
if x != nil {
|
||||
return x.ViaCidr
|
||||
@@ -402,78 +394,6 @@ func (x *SenderConfig) GetTargetStrategy() internet.DomainStrategy {
|
||||
return internet.DomainStrategy(0)
|
||||
}
|
||||
|
||||
type MultiplexingConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
// Whether or not Mux is enabled.
|
||||
Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"`
|
||||
// Max number of concurrent connections that one Mux connection can handle.
|
||||
Concurrency int32 `protobuf:"varint,2,opt,name=concurrency,proto3" json:"concurrency,omitempty"`
|
||||
// Transport XUDP in another Mux.
|
||||
XudpConcurrency int32 `protobuf:"varint,3,opt,name=xudpConcurrency,proto3" json:"xudpConcurrency,omitempty"`
|
||||
// "reject" (default), "allow" or "skip".
|
||||
XudpProxyUDP443 string `protobuf:"bytes,4,opt,name=xudpProxyUDP443,proto3" json:"xudpProxyUDP443,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *MultiplexingConfig) Reset() {
|
||||
*x = MultiplexingConfig{}
|
||||
mi := &file_app_proxyman_config_proto_msgTypes[6]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *MultiplexingConfig) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*MultiplexingConfig) ProtoMessage() {}
|
||||
|
||||
func (x *MultiplexingConfig) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_app_proxyman_config_proto_msgTypes[6]
|
||||
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 MultiplexingConfig.ProtoReflect.Descriptor instead.
|
||||
func (*MultiplexingConfig) Descriptor() ([]byte, []int) {
|
||||
return file_app_proxyman_config_proto_rawDescGZIP(), []int{6}
|
||||
}
|
||||
|
||||
func (x *MultiplexingConfig) GetEnabled() bool {
|
||||
if x != nil {
|
||||
return x.Enabled
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *MultiplexingConfig) GetConcurrency() int32 {
|
||||
if x != nil {
|
||||
return x.Concurrency
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *MultiplexingConfig) GetXudpConcurrency() int32 {
|
||||
if x != nil {
|
||||
return x.XudpConcurrency
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *MultiplexingConfig) GetXudpProxyUDP443() string {
|
||||
if x != nil {
|
||||
return x.XudpProxyUDP443
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var File_app_proxyman_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_app_proxyman_config_proto_rawDesc = "" +
|
||||
@@ -498,18 +418,12 @@ const file_app_proxyman_config_proto_rawDesc = "" +
|
||||
"\x03tag\x18\x01 \x01(\tR\x03tag\x12M\n" +
|
||||
"\x11receiver_settings\x18\x02 \x01(\v2 .xray.common.serial.TypedMessageR\x10receiverSettings\x12G\n" +
|
||||
"\x0eproxy_settings\x18\x03 \x01(\v2 .xray.common.serial.TypedMessageR\rproxySettings\"\x10\n" +
|
||||
"\x0eOutboundConfig\"\xd6\x02\n" +
|
||||
"\x0eOutboundConfig\"\x9a\x02\n" +
|
||||
"\fSenderConfig\x12-\n" +
|
||||
"\x03via\x18\x01 \x01(\v2\x1b.xray.common.net.IPOrDomainR\x03via\x12N\n" +
|
||||
"\x0fstream_settings\x18\x02 \x01(\v2%.xray.transport.internet.StreamConfigR\x0estreamSettings\x12T\n" +
|
||||
"\x12multiplex_settings\x18\x04 \x01(\v2%.xray.app.proxyman.MultiplexingConfigR\x11multiplexSettings\x12\x19\n" +
|
||||
"\x0fstream_settings\x18\x02 \x01(\v2%.xray.transport.internet.StreamConfigR\x0estreamSettings\x12\x19\n" +
|
||||
"\bvia_cidr\x18\x05 \x01(\tR\aviaCidr\x12P\n" +
|
||||
"\x0ftarget_strategy\x18\x06 \x01(\x0e2'.xray.transport.internet.DomainStrategyR\x0etargetStrategyJ\x04\b\x03\x10\x04\"\xa4\x01\n" +
|
||||
"\x12MultiplexingConfig\x12\x18\n" +
|
||||
"\aenabled\x18\x01 \x01(\bR\aenabled\x12 \n" +
|
||||
"\vconcurrency\x18\x02 \x01(\x05R\vconcurrency\x12(\n" +
|
||||
"\x0fxudpConcurrency\x18\x03 \x01(\x05R\x0fxudpConcurrency\x12(\n" +
|
||||
"\x0fxudpProxyUDP443\x18\x04 \x01(\tR\x0fxudpProxyUDP443BU\n" +
|
||||
"\x0ftarget_strategy\x18\x06 \x01(\x0e2'.xray.transport.internet.DomainStrategyR\x0etargetStrategyJ\x04\b\x03\x10\x04J\x04\b\x04\x10\x05R\x12multiplex_settingsBU\n" +
|
||||
"\x15com.xray.app.proxymanP\x01Z&github.com/xtls/xray-core/app/proxyman\xaa\x02\x11Xray.App.Proxymanb\x06proto3"
|
||||
|
||||
var (
|
||||
@@ -524,7 +438,7 @@ func file_app_proxyman_config_proto_rawDescGZIP() []byte {
|
||||
return file_app_proxyman_config_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_app_proxyman_config_proto_msgTypes = make([]protoimpl.MessageInfo, 7)
|
||||
var file_app_proxyman_config_proto_msgTypes = make([]protoimpl.MessageInfo, 6)
|
||||
var file_app_proxyman_config_proto_goTypes = []any{
|
||||
(*InboundConfig)(nil), // 0: xray.app.proxyman.InboundConfig
|
||||
(*SniffingConfig)(nil), // 1: xray.app.proxyman.SniffingConfig
|
||||
@@ -532,33 +446,31 @@ var file_app_proxyman_config_proto_goTypes = []any{
|
||||
(*InboundHandlerConfig)(nil), // 3: xray.app.proxyman.InboundHandlerConfig
|
||||
(*OutboundConfig)(nil), // 4: xray.app.proxyman.OutboundConfig
|
||||
(*SenderConfig)(nil), // 5: xray.app.proxyman.SenderConfig
|
||||
(*MultiplexingConfig)(nil), // 6: xray.app.proxyman.MultiplexingConfig
|
||||
(*geodata.DomainRule)(nil), // 7: xray.common.geodata.DomainRule
|
||||
(*geodata.IPRule)(nil), // 8: xray.common.geodata.IPRule
|
||||
(*net.PortList)(nil), // 9: xray.common.net.PortList
|
||||
(*net.IPOrDomain)(nil), // 10: xray.common.net.IPOrDomain
|
||||
(*internet.StreamConfig)(nil), // 11: xray.transport.internet.StreamConfig
|
||||
(*serial.TypedMessage)(nil), // 12: xray.common.serial.TypedMessage
|
||||
(internet.DomainStrategy)(0), // 13: xray.transport.internet.DomainStrategy
|
||||
(*geodata.DomainRule)(nil), // 6: xray.common.geodata.DomainRule
|
||||
(*geodata.IPRule)(nil), // 7: xray.common.geodata.IPRule
|
||||
(*net.PortList)(nil), // 8: xray.common.net.PortList
|
||||
(*net.IPOrDomain)(nil), // 9: xray.common.net.IPOrDomain
|
||||
(*internet.StreamConfig)(nil), // 10: xray.transport.internet.StreamConfig
|
||||
(*serial.TypedMessage)(nil), // 11: xray.common.serial.TypedMessage
|
||||
(internet.DomainStrategy)(0), // 12: xray.transport.internet.DomainStrategy
|
||||
}
|
||||
var file_app_proxyman_config_proto_depIdxs = []int32{
|
||||
7, // 0: xray.app.proxyman.SniffingConfig.domains_excluded:type_name -> xray.common.geodata.DomainRule
|
||||
8, // 1: xray.app.proxyman.SniffingConfig.ips_excluded:type_name -> xray.common.geodata.IPRule
|
||||
9, // 2: xray.app.proxyman.ReceiverConfig.port_list:type_name -> xray.common.net.PortList
|
||||
10, // 3: xray.app.proxyman.ReceiverConfig.listen:type_name -> xray.common.net.IPOrDomain
|
||||
11, // 4: xray.app.proxyman.ReceiverConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig
|
||||
6, // 0: xray.app.proxyman.SniffingConfig.domains_excluded:type_name -> xray.common.geodata.DomainRule
|
||||
7, // 1: xray.app.proxyman.SniffingConfig.ips_excluded:type_name -> xray.common.geodata.IPRule
|
||||
8, // 2: xray.app.proxyman.ReceiverConfig.port_list:type_name -> xray.common.net.PortList
|
||||
9, // 3: xray.app.proxyman.ReceiverConfig.listen:type_name -> xray.common.net.IPOrDomain
|
||||
10, // 4: xray.app.proxyman.ReceiverConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig
|
||||
1, // 5: xray.app.proxyman.ReceiverConfig.sniffing_settings:type_name -> xray.app.proxyman.SniffingConfig
|
||||
12, // 6: xray.app.proxyman.InboundHandlerConfig.receiver_settings:type_name -> xray.common.serial.TypedMessage
|
||||
12, // 7: xray.app.proxyman.InboundHandlerConfig.proxy_settings:type_name -> xray.common.serial.TypedMessage
|
||||
10, // 8: xray.app.proxyman.SenderConfig.via:type_name -> xray.common.net.IPOrDomain
|
||||
11, // 9: xray.app.proxyman.SenderConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig
|
||||
6, // 10: xray.app.proxyman.SenderConfig.multiplex_settings:type_name -> xray.app.proxyman.MultiplexingConfig
|
||||
13, // 11: xray.app.proxyman.SenderConfig.target_strategy:type_name -> xray.transport.internet.DomainStrategy
|
||||
12, // [12:12] is the sub-list for method output_type
|
||||
12, // [12:12] is the sub-list for method input_type
|
||||
12, // [12:12] is the sub-list for extension type_name
|
||||
12, // [12:12] is the sub-list for extension extendee
|
||||
0, // [0:12] is the sub-list for field type_name
|
||||
11, // 6: xray.app.proxyman.InboundHandlerConfig.receiver_settings:type_name -> xray.common.serial.TypedMessage
|
||||
11, // 7: xray.app.proxyman.InboundHandlerConfig.proxy_settings:type_name -> xray.common.serial.TypedMessage
|
||||
9, // 8: xray.app.proxyman.SenderConfig.via:type_name -> xray.common.net.IPOrDomain
|
||||
10, // 9: xray.app.proxyman.SenderConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig
|
||||
12, // 10: xray.app.proxyman.SenderConfig.target_strategy:type_name -> xray.transport.internet.DomainStrategy
|
||||
11, // [11:11] is the sub-list for method output_type
|
||||
11, // [11:11] is the sub-list for method input_type
|
||||
11, // [11:11] is the sub-list for extension type_name
|
||||
11, // [11:11] is the sub-list for extension extendee
|
||||
0, // [0:11] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_app_proxyman_config_proto_init() }
|
||||
@@ -572,7 +484,7 @@ func file_app_proxyman_config_proto_init() {
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_proxyman_config_proto_rawDesc), len(file_app_proxyman_config_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 7,
|
||||
NumMessages: 6,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
|
||||
@@ -57,19 +57,8 @@ message SenderConfig {
|
||||
// Send traffic through the given IP. Only IP is allowed.
|
||||
xray.common.net.IPOrDomain via = 1;
|
||||
xray.transport.internet.StreamConfig stream_settings = 2;
|
||||
reserved 3;
|
||||
MultiplexingConfig multiplex_settings = 4;
|
||||
reserved 3, 4;
|
||||
reserved "multiplex_settings";
|
||||
string via_cidr = 5;
|
||||
xray.transport.internet.DomainStrategy target_strategy = 6;
|
||||
}
|
||||
|
||||
message MultiplexingConfig {
|
||||
// Whether or not Mux is enabled.
|
||||
bool enabled = 1;
|
||||
// Max number of concurrent connections that one Mux connection can handle.
|
||||
int32 concurrency = 2;
|
||||
// Transport XUDP in another Mux.
|
||||
int32 xudpConcurrency = 3;
|
||||
// "reject" (default), "allow" or "skip".
|
||||
string xudpProxyUDP443 = 4;
|
||||
}
|
||||
|
||||
@@ -6,12 +6,12 @@ import (
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"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/policy"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
"github.com/xtls/xray-core/features/stats"
|
||||
"github.com/xtls/xray-core/proxy"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
@@ -48,7 +48,6 @@ type AlwaysOnInboundHandler struct {
|
||||
receiverConfig *proxyman.ReceiverConfig
|
||||
proxy proxy.Inbound
|
||||
workers []worker
|
||||
mux *mux.Server
|
||||
tag string
|
||||
}
|
||||
|
||||
@@ -82,11 +81,14 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
|
||||
return nil, errors.New("not an inbound proxy.")
|
||||
}
|
||||
|
||||
dispatcher := new(struct{ routing.Dispatcher })
|
||||
if err := core.RequireFeatures(ctx, func(d routing.Dispatcher) { dispatcher.Dispatcher = d }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h := &AlwaysOnInboundHandler{
|
||||
receiverConfig: receiverConfig,
|
||||
proxyConfig: proxyConfig,
|
||||
proxy: p,
|
||||
mux: mux.NewServer(ctx),
|
||||
tag: tag,
|
||||
}
|
||||
|
||||
@@ -117,7 +119,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
|
||||
proxy: p,
|
||||
stream: mss,
|
||||
tag: tag,
|
||||
dispatcher: h.mux,
|
||||
dispatcher: dispatcher,
|
||||
sniffingRequest: sniffingRequest,
|
||||
uplinkCounter: uplinkCounter,
|
||||
downlinkCounter: downlinkCounter,
|
||||
@@ -139,7 +141,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
|
||||
stream: mss,
|
||||
recvOrigDest: receiverConfig.ReceiveOriginalDestination,
|
||||
tag: tag,
|
||||
dispatcher: h.mux,
|
||||
dispatcher: dispatcher,
|
||||
sniffingRequest: sniffingRequest,
|
||||
uplinkCounter: uplinkCounter,
|
||||
downlinkCounter: downlinkCounter,
|
||||
@@ -154,7 +156,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
|
||||
proxy: p,
|
||||
address: address,
|
||||
port: net.Port(port),
|
||||
dispatcher: h.mux,
|
||||
dispatcher: dispatcher,
|
||||
sniffingRequest: sniffingRequest,
|
||||
uplinkCounter: uplinkCounter,
|
||||
downlinkCounter: downlinkCounter,
|
||||
@@ -192,7 +194,6 @@ func (h *AlwaysOnInboundHandler) Close() error {
|
||||
for _, worker := range h.workers {
|
||||
errs = append(errs, worker.Close())
|
||||
}
|
||||
errs = append(errs, h.mux.Close())
|
||||
errs = append(errs, common.Close(h.proxy))
|
||||
if err := errors.Combine(errs...); err != nil {
|
||||
return errors.New("failed to close all resources").Base(err)
|
||||
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
@@ -60,9 +59,6 @@ type Handler struct {
|
||||
streamSettings *internet.MemoryStreamConfig
|
||||
proxyConfig proto.Message
|
||||
proxy proxy.Outbound
|
||||
mux *mux.ClientManager
|
||||
xudp *mux.ClientManager
|
||||
udp443 string
|
||||
uplinkCounter stats.Counter
|
||||
downlinkCounter stats.Counter
|
||||
}
|
||||
@@ -117,57 +113,6 @@ func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbou
|
||||
return nil, errors.New("not an outbound handler")
|
||||
}
|
||||
|
||||
if h.senderSettings != nil && h.senderSettings.MultiplexSettings != nil {
|
||||
if config := h.senderSettings.MultiplexSettings; config.Enabled {
|
||||
if config.Concurrency < 0 {
|
||||
h.mux = &mux.ClientManager{Enabled: false}
|
||||
}
|
||||
if config.Concurrency == 0 {
|
||||
config.Concurrency = 8 // same as before
|
||||
}
|
||||
if config.Concurrency > 0 && config.Concurrency < 128 && h.streamSettings != nil && h.streamSettings.ProtocolName == "xdrive" {
|
||||
config.Concurrency = 128
|
||||
}
|
||||
if config.Concurrency > 0 {
|
||||
h.mux = &mux.ClientManager{
|
||||
Enabled: true,
|
||||
Picker: &mux.IncrementalWorkerPicker{
|
||||
Factory: &mux.DialingWorkerFactory{
|
||||
Proxy: proxyHandler,
|
||||
Dialer: h,
|
||||
Strategy: mux.ClientStrategy{
|
||||
MaxConcurrency: uint32(config.Concurrency),
|
||||
MaxConnection: 1024,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
if config.XudpConcurrency < 0 {
|
||||
h.xudp = &mux.ClientManager{Enabled: false}
|
||||
}
|
||||
if config.XudpConcurrency == 0 {
|
||||
h.xudp = nil // same as before
|
||||
}
|
||||
if config.XudpConcurrency > 0 {
|
||||
h.xudp = &mux.ClientManager{
|
||||
Enabled: true,
|
||||
Picker: &mux.IncrementalWorkerPicker{
|
||||
Factory: &mux.DialingWorkerFactory{
|
||||
Proxy: proxyHandler,
|
||||
Dialer: h,
|
||||
Strategy: mux.ClientStrategy{
|
||||
MaxConcurrency: uint32(config.XudpConcurrency),
|
||||
MaxConnection: 1024,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
h.udp443 = config.XudpProxyUDP443
|
||||
}
|
||||
}
|
||||
|
||||
h.proxy = proxyHandler
|
||||
return h, nil
|
||||
}
|
||||
@@ -206,43 +151,19 @@ func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) {
|
||||
}
|
||||
}
|
||||
}
|
||||
reader, writer := link.Reader, link.Writer
|
||||
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
|
||||
link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
|
||||
link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
|
||||
}
|
||||
if h.mux != nil {
|
||||
test := func(err error) {
|
||||
if err != nil {
|
||||
err := errors.New("failed to process mux outbound traffic").Base(err)
|
||||
session.SubmitOutboundErrorToOriginator(ctx, err)
|
||||
errors.LogInfo(ctx, err.Error())
|
||||
common.Interrupt(link.Writer)
|
||||
common.Interrupt(link.Reader)
|
||||
}
|
||||
}
|
||||
if ob.Target.Network == net.Network_UDP && ob.Target.Port == 443 {
|
||||
switch h.udp443 {
|
||||
case "reject":
|
||||
test(errors.New("XUDP rejected UDP/443 traffic"))
|
||||
return
|
||||
case "skip":
|
||||
goto out
|
||||
}
|
||||
}
|
||||
if h.xudp != nil && ob.Target.Network == net.Network_UDP {
|
||||
if !h.xudp.Enabled {
|
||||
goto out
|
||||
}
|
||||
test(h.xudp.Dispatch(ctx, link))
|
||||
return
|
||||
}
|
||||
if h.mux.Enabled {
|
||||
test(h.mux.Dispatch(ctx, link))
|
||||
return
|
||||
}
|
||||
}
|
||||
out:
|
||||
|
||||
err := h.proxy.Process(ctx, link, h)
|
||||
var completion interface{ DeferWriterClose() bool }
|
||||
if goerrors.As(err, &completion) && completion.DeferWriterClose() {
|
||||
go common.Close(writer)
|
||||
common.Interrupt(reader)
|
||||
return
|
||||
}
|
||||
var errC error
|
||||
if err != nil {
|
||||
errC = errors.Cause(err)
|
||||
@@ -255,15 +176,15 @@ out:
|
||||
err := errors.New("failed to process outbound traffic").Base(err)
|
||||
session.SubmitOutboundErrorToOriginator(ctx, err)
|
||||
errors.LogInfo(ctx, err.Error())
|
||||
common.Interrupt(link.Writer)
|
||||
common.Interrupt(writer)
|
||||
} else {
|
||||
if errC != nil && goerrors.Is(errC, io.ErrClosedPipe) {
|
||||
common.Interrupt(link.Writer)
|
||||
common.Interrupt(writer)
|
||||
} else {
|
||||
common.Close(link.Writer)
|
||||
common.Close(writer)
|
||||
}
|
||||
}
|
||||
common.Interrupt(link.Reader)
|
||||
common.Interrupt(reader)
|
||||
}
|
||||
|
||||
func (h *Handler) DestIpAddress() net.IP {
|
||||
@@ -335,7 +256,6 @@ func (h *Handler) Start() error {
|
||||
|
||||
// Close implements common.Closable.
|
||||
func (h *Handler) Close() error {
|
||||
common.Close(h.mux)
|
||||
common.Close(h.proxy)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,235 +0,0 @@
|
||||
package reverse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"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/common/task"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// Bridge is a component in reverse proxy, that relays connections from Portal to local address.
|
||||
type Bridge struct {
|
||||
dispatcher routing.Dispatcher
|
||||
tag string
|
||||
domain string
|
||||
workers []*BridgeWorker
|
||||
monitorTask *task.Periodic
|
||||
}
|
||||
|
||||
// NewBridge creates a new Bridge instance.
|
||||
func NewBridge(config *BridgeConfig, dispatcher routing.Dispatcher) (*Bridge, error) {
|
||||
if config.Tag == "" {
|
||||
return nil, errors.New("bridge tag is empty")
|
||||
}
|
||||
if config.Domain == "" {
|
||||
return nil, errors.New("bridge domain is empty")
|
||||
}
|
||||
|
||||
b := &Bridge{
|
||||
dispatcher: dispatcher,
|
||||
tag: config.Tag,
|
||||
domain: config.Domain,
|
||||
}
|
||||
b.monitorTask = &task.Periodic{
|
||||
Execute: b.monitor,
|
||||
Interval: time.Second * 2,
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (b *Bridge) cleanup() {
|
||||
var activeWorkers []*BridgeWorker
|
||||
|
||||
for _, w := range b.workers {
|
||||
if w.IsActive() {
|
||||
activeWorkers = append(activeWorkers, w)
|
||||
}
|
||||
if w.Closed() {
|
||||
if w.Timer != nil {
|
||||
w.Timer.SetTimeout(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(activeWorkers) != len(b.workers) {
|
||||
b.workers = activeWorkers
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bridge) monitor() error {
|
||||
b.cleanup()
|
||||
|
||||
var numConnections uint32
|
||||
var numWorker uint32
|
||||
|
||||
for _, w := range b.workers {
|
||||
if w.IsActive() {
|
||||
numConnections += w.Connections()
|
||||
numWorker++
|
||||
}
|
||||
}
|
||||
|
||||
if numWorker == 0 || numConnections/numWorker > 16 {
|
||||
worker, err := NewBridgeWorker(b.domain, b.tag, b.dispatcher)
|
||||
if err != nil {
|
||||
errors.LogWarningInner(context.Background(), err, "failed to create bridge worker")
|
||||
return nil
|
||||
}
|
||||
b.workers = append(b.workers, worker)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *Bridge) Start() error {
|
||||
return b.monitorTask.Start()
|
||||
}
|
||||
|
||||
func (b *Bridge) Close() error {
|
||||
return b.monitorTask.Close()
|
||||
}
|
||||
|
||||
type BridgeWorker struct {
|
||||
Tag string
|
||||
Worker *mux.ServerWorker
|
||||
Dispatcher routing.Dispatcher
|
||||
State Control_State
|
||||
Timer *signal.ActivityTimer
|
||||
}
|
||||
|
||||
func NewBridgeWorker(domain string, tag string, d routing.Dispatcher) (*BridgeWorker, error) {
|
||||
ctx := context.Background()
|
||||
ctx = session.ContextWithInbound(ctx, &session.Inbound{
|
||||
Tag: tag,
|
||||
})
|
||||
link, err := d.Dispatch(ctx, net.Destination{
|
||||
Network: net.Network_TCP,
|
||||
Address: net.DomainAddress(domain),
|
||||
Port: 0,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
w := &BridgeWorker{
|
||||
Dispatcher: d,
|
||||
Tag: tag,
|
||||
}
|
||||
|
||||
worker, err := mux.NewServerWorker(context.Background(), w, link)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
w.Worker = worker
|
||||
|
||||
terminate := func() {
|
||||
worker.Close()
|
||||
}
|
||||
w.Timer = signal.CancelAfterInactivity(ctx, terminate, 60*time.Second)
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) Type() interface{} {
|
||||
return routing.DispatcherType()
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) IsActive() bool {
|
||||
return w.State == Control_ACTIVE && !w.Worker.Closed()
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) Closed() bool {
|
||||
return w.Worker.Closed()
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) Connections() uint32 {
|
||||
return w.Worker.ActiveConnections()
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) handleInternalConn(link *transport.Link) {
|
||||
reader := link.Reader
|
||||
for {
|
||||
mb, err := reader.ReadMultiBuffer()
|
||||
if err != nil {
|
||||
if w.Timer != nil {
|
||||
if w.Closed() {
|
||||
w.Timer.SetTimeout(0)
|
||||
} else {
|
||||
w.Timer.SetTimeout(24 * time.Hour)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if w.Timer != nil {
|
||||
w.Timer.Update()
|
||||
}
|
||||
for _, b := range mb {
|
||||
var ctl Control
|
||||
if err := proto.Unmarshal(b.Bytes(), &ctl); err != nil {
|
||||
errors.LogInfoInner(context.Background(), err, "failed to parse proto message")
|
||||
if w.Timer != nil {
|
||||
w.Timer.SetTimeout(0)
|
||||
}
|
||||
return
|
||||
}
|
||||
if ctl.State != w.State {
|
||||
w.State = ctl.State
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) {
|
||||
if !isInternalDomain(dest) {
|
||||
if session.InboundFromContext(ctx) == nil {
|
||||
ctx = session.ContextWithInbound(ctx, &session.Inbound{
|
||||
Tag: w.Tag,
|
||||
})
|
||||
}
|
||||
return w.Dispatcher.Dispatch(ctx, dest)
|
||||
}
|
||||
|
||||
opt := []pipe.Option{pipe.WithSizeLimit(16 * 1024)}
|
||||
uplinkReader, uplinkWriter := pipe.New(opt...)
|
||||
downlinkReader, downlinkWriter := pipe.New(opt...)
|
||||
|
||||
go w.handleInternalConn(&transport.Link{
|
||||
Reader: downlinkReader,
|
||||
Writer: uplinkWriter,
|
||||
})
|
||||
|
||||
return &transport.Link{
|
||||
Reader: uplinkReader,
|
||||
Writer: downlinkWriter,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) DispatchLink(ctx context.Context, dest net.Destination, link *transport.Link) error {
|
||||
if !isInternalDomain(dest) {
|
||||
if session.InboundFromContext(ctx) == nil {
|
||||
ctx = session.ContextWithInbound(ctx, &session.Inbound{
|
||||
Tag: w.Tag,
|
||||
})
|
||||
}
|
||||
return w.Dispatcher.DispatchLink(ctx, dest, link)
|
||||
}
|
||||
w.handleInternalConn(link)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,356 +0,0 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.12
|
||||
// protoc (unknown)
|
||||
// source: app/reverse/config.proto
|
||||
|
||||
package reverse
|
||||
|
||||
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 Control_State int32
|
||||
|
||||
const (
|
||||
Control_ACTIVE Control_State = 0
|
||||
Control_DRAIN Control_State = 1
|
||||
)
|
||||
|
||||
// Enum value maps for Control_State.
|
||||
var (
|
||||
Control_State_name = map[int32]string{
|
||||
0: "ACTIVE",
|
||||
1: "DRAIN",
|
||||
}
|
||||
Control_State_value = map[string]int32{
|
||||
"ACTIVE": 0,
|
||||
"DRAIN": 1,
|
||||
}
|
||||
)
|
||||
|
||||
func (x Control_State) Enum() *Control_State {
|
||||
p := new(Control_State)
|
||||
*p = x
|
||||
return p
|
||||
}
|
||||
|
||||
func (x Control_State) String() string {
|
||||
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
|
||||
}
|
||||
|
||||
func (Control_State) Descriptor() protoreflect.EnumDescriptor {
|
||||
return file_app_reverse_config_proto_enumTypes[0].Descriptor()
|
||||
}
|
||||
|
||||
func (Control_State) Type() protoreflect.EnumType {
|
||||
return &file_app_reverse_config_proto_enumTypes[0]
|
||||
}
|
||||
|
||||
func (x Control_State) Number() protoreflect.EnumNumber {
|
||||
return protoreflect.EnumNumber(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Control_State.Descriptor instead.
|
||||
func (Control_State) EnumDescriptor() ([]byte, []int) {
|
||||
return file_app_reverse_config_proto_rawDescGZIP(), []int{0, 0}
|
||||
}
|
||||
|
||||
type Control struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
State Control_State `protobuf:"varint,1,opt,name=state,proto3,enum=xray.app.reverse.Control_State" json:"state,omitempty"`
|
||||
Random []byte `protobuf:"bytes,99,opt,name=random,proto3" json:"random,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Control) Reset() {
|
||||
*x = Control{}
|
||||
mi := &file_app_reverse_config_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Control) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Control) ProtoMessage() {}
|
||||
|
||||
func (x *Control) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_app_reverse_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 Control.ProtoReflect.Descriptor instead.
|
||||
func (*Control) Descriptor() ([]byte, []int) {
|
||||
return file_app_reverse_config_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *Control) GetState() Control_State {
|
||||
if x != nil {
|
||||
return x.State
|
||||
}
|
||||
return Control_ACTIVE
|
||||
}
|
||||
|
||||
func (x *Control) GetRandom() []byte {
|
||||
if x != nil {
|
||||
return x.Random
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type BridgeConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"`
|
||||
Domain string `protobuf:"bytes,2,opt,name=domain,proto3" json:"domain,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *BridgeConfig) Reset() {
|
||||
*x = BridgeConfig{}
|
||||
mi := &file_app_reverse_config_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *BridgeConfig) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*BridgeConfig) ProtoMessage() {}
|
||||
|
||||
func (x *BridgeConfig) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_app_reverse_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 BridgeConfig.ProtoReflect.Descriptor instead.
|
||||
func (*BridgeConfig) Descriptor() ([]byte, []int) {
|
||||
return file_app_reverse_config_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *BridgeConfig) GetTag() string {
|
||||
if x != nil {
|
||||
return x.Tag
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *BridgeConfig) GetDomain() string {
|
||||
if x != nil {
|
||||
return x.Domain
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type PortalConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"`
|
||||
Domain string `protobuf:"bytes,2,opt,name=domain,proto3" json:"domain,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *PortalConfig) Reset() {
|
||||
*x = PortalConfig{}
|
||||
mi := &file_app_reverse_config_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *PortalConfig) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*PortalConfig) ProtoMessage() {}
|
||||
|
||||
func (x *PortalConfig) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_app_reverse_config_proto_msgTypes[2]
|
||||
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 PortalConfig.ProtoReflect.Descriptor instead.
|
||||
func (*PortalConfig) Descriptor() ([]byte, []int) {
|
||||
return file_app_reverse_config_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
func (x *PortalConfig) GetTag() string {
|
||||
if x != nil {
|
||||
return x.Tag
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *PortalConfig) GetDomain() string {
|
||||
if x != nil {
|
||||
return x.Domain
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
BridgeConfig []*BridgeConfig `protobuf:"bytes,1,rep,name=bridge_config,json=bridgeConfig,proto3" json:"bridge_config,omitempty"`
|
||||
PortalConfig []*PortalConfig `protobuf:"bytes,2,rep,name=portal_config,json=portalConfig,proto3" json:"portal_config,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Config) Reset() {
|
||||
*x = Config{}
|
||||
mi := &file_app_reverse_config_proto_msgTypes[3]
|
||||
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_app_reverse_config_proto_msgTypes[3]
|
||||
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_app_reverse_config_proto_rawDescGZIP(), []int{3}
|
||||
}
|
||||
|
||||
func (x *Config) GetBridgeConfig() []*BridgeConfig {
|
||||
if x != nil {
|
||||
return x.BridgeConfig
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Config) GetPortalConfig() []*PortalConfig {
|
||||
if x != nil {
|
||||
return x.PortalConfig
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_app_reverse_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_app_reverse_config_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"\x18app/reverse/config.proto\x12\x10xray.app.reverse\"x\n" +
|
||||
"\aControl\x125\n" +
|
||||
"\x05state\x18\x01 \x01(\x0e2\x1f.xray.app.reverse.Control.StateR\x05state\x12\x16\n" +
|
||||
"\x06random\x18c \x01(\fR\x06random\"\x1e\n" +
|
||||
"\x05State\x12\n" +
|
||||
"\n" +
|
||||
"\x06ACTIVE\x10\x00\x12\t\n" +
|
||||
"\x05DRAIN\x10\x01\"8\n" +
|
||||
"\fBridgeConfig\x12\x10\n" +
|
||||
"\x03tag\x18\x01 \x01(\tR\x03tag\x12\x16\n" +
|
||||
"\x06domain\x18\x02 \x01(\tR\x06domain\"8\n" +
|
||||
"\fPortalConfig\x12\x10\n" +
|
||||
"\x03tag\x18\x01 \x01(\tR\x03tag\x12\x16\n" +
|
||||
"\x06domain\x18\x02 \x01(\tR\x06domain\"\x92\x01\n" +
|
||||
"\x06Config\x12C\n" +
|
||||
"\rbridge_config\x18\x01 \x03(\v2\x1e.xray.app.reverse.BridgeConfigR\fbridgeConfig\x12C\n" +
|
||||
"\rportal_config\x18\x02 \x03(\v2\x1e.xray.app.reverse.PortalConfigR\fportalConfigBV\n" +
|
||||
"\x16com.xray.proxy.reverseP\x01Z%github.com/xtls/xray-core/app/reverse\xaa\x02\x12Xray.Proxy.Reverseb\x06proto3"
|
||||
|
||||
var (
|
||||
file_app_reverse_config_proto_rawDescOnce sync.Once
|
||||
file_app_reverse_config_proto_rawDescData []byte
|
||||
)
|
||||
|
||||
func file_app_reverse_config_proto_rawDescGZIP() []byte {
|
||||
file_app_reverse_config_proto_rawDescOnce.Do(func() {
|
||||
file_app_reverse_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_reverse_config_proto_rawDesc), len(file_app_reverse_config_proto_rawDesc)))
|
||||
})
|
||||
return file_app_reverse_config_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_app_reverse_config_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
|
||||
var file_app_reverse_config_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
|
||||
var file_app_reverse_config_proto_goTypes = []any{
|
||||
(Control_State)(0), // 0: xray.app.reverse.Control.State
|
||||
(*Control)(nil), // 1: xray.app.reverse.Control
|
||||
(*BridgeConfig)(nil), // 2: xray.app.reverse.BridgeConfig
|
||||
(*PortalConfig)(nil), // 3: xray.app.reverse.PortalConfig
|
||||
(*Config)(nil), // 4: xray.app.reverse.Config
|
||||
}
|
||||
var file_app_reverse_config_proto_depIdxs = []int32{
|
||||
0, // 0: xray.app.reverse.Control.state:type_name -> xray.app.reverse.Control.State
|
||||
2, // 1: xray.app.reverse.Config.bridge_config:type_name -> xray.app.reverse.BridgeConfig
|
||||
3, // 2: xray.app.reverse.Config.portal_config:type_name -> xray.app.reverse.PortalConfig
|
||||
3, // [3:3] is the sub-list for method output_type
|
||||
3, // [3:3] is the sub-list for method input_type
|
||||
3, // [3:3] is the sub-list for extension type_name
|
||||
3, // [3:3] is the sub-list for extension extendee
|
||||
0, // [0:3] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_app_reverse_config_proto_init() }
|
||||
func file_app_reverse_config_proto_init() {
|
||||
if File_app_reverse_config_proto != nil {
|
||||
return
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_reverse_config_proto_rawDesc), len(file_app_reverse_config_proto_rawDesc)),
|
||||
NumEnums: 1,
|
||||
NumMessages: 4,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
GoTypes: file_app_reverse_config_proto_goTypes,
|
||||
DependencyIndexes: file_app_reverse_config_proto_depIdxs,
|
||||
EnumInfos: file_app_reverse_config_proto_enumTypes,
|
||||
MessageInfos: file_app_reverse_config_proto_msgTypes,
|
||||
}.Build()
|
||||
File_app_reverse_config_proto = out.File
|
||||
file_app_reverse_config_proto_goTypes = nil
|
||||
file_app_reverse_config_proto_depIdxs = nil
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package xray.app.reverse;
|
||||
option csharp_namespace = "Xray.Proxy.Reverse";
|
||||
option go_package = "github.com/xtls/xray-core/app/reverse";
|
||||
option java_package = "com.xray.proxy.reverse";
|
||||
option java_multiple_files = true;
|
||||
|
||||
message Control {
|
||||
enum State {
|
||||
ACTIVE = 0;
|
||||
DRAIN = 1;
|
||||
}
|
||||
|
||||
State state = 1;
|
||||
bytes random = 99;
|
||||
}
|
||||
|
||||
message BridgeConfig {
|
||||
string tag = 1;
|
||||
string domain = 2;
|
||||
}
|
||||
|
||||
message PortalConfig {
|
||||
string tag = 1;
|
||||
string domain = 2;
|
||||
}
|
||||
|
||||
message Config {
|
||||
repeated BridgeConfig bridge_config = 1;
|
||||
repeated PortalConfig portal_config = 2;
|
||||
}
|
||||
@@ -1,308 +0,0 @@
|
||||
package reverse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"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/common/signal"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
"github.com/xtls/xray-core/features/outbound"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type Portal struct {
|
||||
ohm outbound.Manager
|
||||
tag string
|
||||
domain string
|
||||
picker *StaticMuxPicker
|
||||
client *mux.ClientManager
|
||||
}
|
||||
|
||||
func NewPortal(config *PortalConfig, ohm outbound.Manager) (*Portal, error) {
|
||||
if config.Tag == "" {
|
||||
return nil, errors.New("portal tag is empty")
|
||||
}
|
||||
|
||||
if config.Domain == "" {
|
||||
return nil, errors.New("portal domain is empty")
|
||||
}
|
||||
|
||||
picker, err := NewStaticMuxPicker()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Portal{
|
||||
ohm: ohm,
|
||||
tag: config.Tag,
|
||||
domain: config.Domain,
|
||||
picker: picker,
|
||||
client: &mux.ClientManager{
|
||||
Picker: picker,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *Portal) Start() error {
|
||||
return p.ohm.AddHandler(context.Background(), &Outbound{
|
||||
portal: p,
|
||||
tag: p.tag,
|
||||
})
|
||||
}
|
||||
|
||||
func (p *Portal) Close() error {
|
||||
return p.ohm.RemoveHandler(context.Background(), p.tag)
|
||||
}
|
||||
|
||||
func (p *Portal) HandleConnection(ctx context.Context, link *transport.Link) error {
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
ob := outbounds[len(outbounds)-1]
|
||||
if ob == nil {
|
||||
return errors.New("outbound metadata not found")
|
||||
}
|
||||
|
||||
if isDomain(ob.Target, p.domain) {
|
||||
muxClient, err := mux.NewClientWorker(*link, mux.ClientStrategy{})
|
||||
if err != nil {
|
||||
return errors.New("failed to create mux client worker").Base(err)
|
||||
}
|
||||
|
||||
worker, err := NewPortalWorker(muxClient)
|
||||
if err != nil {
|
||||
return errors.New("failed to create portal worker").Base(err)
|
||||
}
|
||||
|
||||
p.picker.AddWorker(worker)
|
||||
|
||||
if _, ok := link.Reader.(*pipe.Reader); !ok {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-muxClient.WaitClosed():
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
|
||||
link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
|
||||
link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
|
||||
}
|
||||
|
||||
return p.client.Dispatch(ctx, link)
|
||||
}
|
||||
|
||||
type Outbound struct {
|
||||
portal *Portal
|
||||
tag string
|
||||
}
|
||||
|
||||
func (o *Outbound) Tag() string {
|
||||
return o.tag
|
||||
}
|
||||
|
||||
func (o *Outbound) Dispatch(ctx context.Context, link *transport.Link) {
|
||||
if err := o.portal.HandleConnection(ctx, link); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to process reverse connection")
|
||||
common.Interrupt(link.Writer)
|
||||
common.Interrupt(link.Reader)
|
||||
}
|
||||
}
|
||||
|
||||
func (o *Outbound) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *Outbound) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SenderSettings implements outbound.Handler.
|
||||
func (o *Outbound) SenderSettings() *serial.TypedMessage {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ProxySettings implements outbound.Handler.
|
||||
func (o *Outbound) ProxySettings() *serial.TypedMessage {
|
||||
return nil
|
||||
}
|
||||
|
||||
type StaticMuxPicker struct {
|
||||
access sync.Mutex
|
||||
workers []*PortalWorker
|
||||
cTask *task.Periodic
|
||||
}
|
||||
|
||||
func NewStaticMuxPicker() (*StaticMuxPicker, error) {
|
||||
p := &StaticMuxPicker{}
|
||||
p.cTask = &task.Periodic{
|
||||
Execute: p.cleanup,
|
||||
Interval: time.Second * 30,
|
||||
}
|
||||
p.cTask.Start()
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (p *StaticMuxPicker) cleanup() error {
|
||||
p.access.Lock()
|
||||
defer p.access.Unlock()
|
||||
|
||||
var activeWorkers []*PortalWorker
|
||||
for _, w := range p.workers {
|
||||
if !w.Closed() {
|
||||
activeWorkers = append(activeWorkers, w)
|
||||
} else {
|
||||
w.timer.SetTimeout(0)
|
||||
}
|
||||
}
|
||||
|
||||
if len(activeWorkers) != len(p.workers) {
|
||||
p.workers = activeWorkers
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *StaticMuxPicker) PickAvailable() (*mux.ClientWorker, error) {
|
||||
p.access.Lock()
|
||||
defer p.access.Unlock()
|
||||
|
||||
if len(p.workers) == 0 {
|
||||
return nil, errors.New("empty worker list")
|
||||
}
|
||||
|
||||
var minIdx int = -1
|
||||
var minConn uint32 = 9999
|
||||
for i, w := range p.workers {
|
||||
if w.draining {
|
||||
continue
|
||||
}
|
||||
if w.IsFull() {
|
||||
continue
|
||||
}
|
||||
if w.client.ActiveConnections() < minConn {
|
||||
minConn = w.client.ActiveConnections()
|
||||
minIdx = i
|
||||
}
|
||||
}
|
||||
|
||||
if minIdx == -1 {
|
||||
for i, w := range p.workers {
|
||||
if w.IsFull() {
|
||||
continue
|
||||
}
|
||||
if w.client.ActiveConnections() < minConn {
|
||||
minConn = w.client.ActiveConnections()
|
||||
minIdx = i
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if minIdx != -1 {
|
||||
return p.workers[minIdx].client, nil
|
||||
}
|
||||
|
||||
return nil, errors.New("no mux client worker available")
|
||||
}
|
||||
|
||||
func (p *StaticMuxPicker) AddWorker(worker *PortalWorker) {
|
||||
p.access.Lock()
|
||||
defer p.access.Unlock()
|
||||
|
||||
p.workers = append(p.workers, worker)
|
||||
}
|
||||
|
||||
type PortalWorker struct {
|
||||
client *mux.ClientWorker
|
||||
control *task.Periodic
|
||||
writer buf.Writer
|
||||
reader buf.Reader
|
||||
draining bool
|
||||
counter uint32
|
||||
timer *signal.ActivityTimer
|
||||
}
|
||||
|
||||
func NewPortalWorker(client *mux.ClientWorker) (*PortalWorker, error) {
|
||||
opt := []pipe.Option{pipe.WithSizeLimit(16 * 1024)}
|
||||
uplinkReader, uplinkWriter := pipe.New(opt...)
|
||||
downlinkReader, downlinkWriter := pipe.New(opt...)
|
||||
|
||||
ctx := context.Background()
|
||||
outbounds := []*session.Outbound{{
|
||||
Target: net.UDPDestination(net.DomainAddress(internalDomain), 0),
|
||||
}}
|
||||
ctx = session.ContextWithOutbounds(ctx, outbounds)
|
||||
f := client.Dispatch(ctx, &transport.Link{
|
||||
Reader: uplinkReader,
|
||||
Writer: downlinkWriter,
|
||||
})
|
||||
if !f {
|
||||
return nil, errors.New("unable to dispatch control connection")
|
||||
}
|
||||
terminate := func() {
|
||||
client.Close()
|
||||
}
|
||||
w := &PortalWorker{
|
||||
client: client,
|
||||
reader: downlinkReader,
|
||||
writer: uplinkWriter,
|
||||
timer: signal.CancelAfterInactivity(ctx, terminate, 24*time.Hour), // // prevent leak
|
||||
}
|
||||
w.control = &task.Periodic{
|
||||
Execute: w.heartbeat,
|
||||
Interval: time.Second * 2,
|
||||
}
|
||||
w.control.Start()
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func (w *PortalWorker) heartbeat() error {
|
||||
if w.Closed() {
|
||||
return errors.New("client worker stopped")
|
||||
}
|
||||
|
||||
if w.draining || w.writer == nil {
|
||||
return errors.New("already disposed")
|
||||
}
|
||||
|
||||
msg := &Control{}
|
||||
msg.FillInRandom()
|
||||
|
||||
if w.client.TotalConnections() > 256 {
|
||||
w.draining = true
|
||||
msg.State = Control_DRAIN
|
||||
|
||||
defer func() {
|
||||
common.Close(w.writer)
|
||||
common.Interrupt(w.reader)
|
||||
w.writer = nil
|
||||
}()
|
||||
}
|
||||
|
||||
w.counter = (w.counter + 1) % 5
|
||||
if w.draining || w.counter == 1 {
|
||||
b, err := proto.Marshal(msg)
|
||||
common.Must(err)
|
||||
mb := buf.MergeBytes(nil, b)
|
||||
w.timer.Update()
|
||||
return w.writer.WriteMultiBuffer(mb)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *PortalWorker) IsFull() bool {
|
||||
return w.client.IsFull()
|
||||
}
|
||||
|
||||
func (w *PortalWorker) Closed() bool {
|
||||
return w.client.Closed()
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package reverse_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/app/reverse"
|
||||
"github.com/xtls/xray-core/common"
|
||||
)
|
||||
|
||||
func TestStaticPickerEmpty(t *testing.T) {
|
||||
picker, err := reverse.NewStaticMuxPicker()
|
||||
common.Must(err)
|
||||
worker, err := picker.PickAvailable()
|
||||
if err == nil {
|
||||
t.Error("expected error, but nil")
|
||||
}
|
||||
if worker != nil {
|
||||
t.Error("expected nil worker, but not nil")
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
package reverse
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
core "github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/features/outbound"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
)
|
||||
|
||||
const (
|
||||
internalDomain = "reverse"
|
||||
)
|
||||
|
||||
func isDomain(dest net.Destination, domain string) bool {
|
||||
return dest.Address.Family().IsDomain() && dest.Address.Domain() == domain
|
||||
}
|
||||
|
||||
func isInternalDomain(dest net.Destination) bool {
|
||||
return isDomain(dest, internalDomain)
|
||||
}
|
||||
|
||||
func init() {
|
||||
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
|
||||
r := new(Reverse)
|
||||
if err := core.RequireFeatures(ctx, func(d routing.Dispatcher, om outbound.Manager) error {
|
||||
return r.Init(config.(*Config), d, om)
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r, nil
|
||||
}))
|
||||
}
|
||||
|
||||
type Reverse struct {
|
||||
bridges []*Bridge
|
||||
portals []*Portal
|
||||
}
|
||||
|
||||
func (r *Reverse) Init(config *Config, d routing.Dispatcher, ohm outbound.Manager) error {
|
||||
for _, bConfig := range config.BridgeConfig {
|
||||
b, err := NewBridge(bConfig, d)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.bridges = append(r.bridges, b)
|
||||
}
|
||||
|
||||
for _, pConfig := range config.PortalConfig {
|
||||
p, err := NewPortal(pConfig, ohm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.portals = append(r.portals, p)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reverse) Type() interface{} {
|
||||
return (*Reverse)(nil)
|
||||
}
|
||||
|
||||
func (r *Reverse) Start() error {
|
||||
for _, b := range r.bridges {
|
||||
if err := b.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for _, p := range r.portals {
|
||||
if err := p.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reverse) Close() error {
|
||||
var errs []error
|
||||
for _, b := range r.bridges {
|
||||
errs = append(errs, b.Close())
|
||||
}
|
||||
|
||||
for _, p := range r.portals {
|
||||
errs = append(errs, p.Close())
|
||||
}
|
||||
|
||||
return errors.Combine(errs...)
|
||||
}
|
||||
@@ -1,420 +0,0 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"context"
|
||||
goerrors "errors"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/signal/done"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
"github.com/xtls/xray-core/common/xudp"
|
||||
"github.com/xtls/xray-core/proxy"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
type ClientManager struct {
|
||||
Enabled bool // whether mux is enabled from user config
|
||||
Picker WorkerPicker
|
||||
}
|
||||
|
||||
func (m *ClientManager) Dispatch(ctx context.Context, link *transport.Link) error {
|
||||
for i := 0; i < 16; i++ {
|
||||
worker, err := m.Picker.PickAvailable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if worker.Dispatch(ctx, link) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return errors.New("unable to find an available mux client")
|
||||
}
|
||||
|
||||
type WorkerPicker interface {
|
||||
PickAvailable() (*ClientWorker, error)
|
||||
}
|
||||
|
||||
type IncrementalWorkerPicker struct {
|
||||
Factory ClientWorkerFactory
|
||||
|
||||
access sync.Mutex
|
||||
workers []*ClientWorker
|
||||
cleanupTask *task.Periodic
|
||||
}
|
||||
|
||||
func (p *IncrementalWorkerPicker) cleanupFunc() error {
|
||||
p.access.Lock()
|
||||
defer p.access.Unlock()
|
||||
|
||||
if len(p.workers) == 0 {
|
||||
return errors.New("no worker")
|
||||
}
|
||||
|
||||
p.cleanup()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *IncrementalWorkerPicker) cleanup() {
|
||||
var activeWorkers []*ClientWorker
|
||||
for _, w := range p.workers {
|
||||
if !w.Closed() {
|
||||
activeWorkers = append(activeWorkers, w)
|
||||
}
|
||||
}
|
||||
p.workers = activeWorkers
|
||||
}
|
||||
|
||||
func (p *IncrementalWorkerPicker) findAvailable() int {
|
||||
for idx, w := range p.workers {
|
||||
if !w.IsFull() {
|
||||
return idx
|
||||
}
|
||||
}
|
||||
|
||||
return -1
|
||||
}
|
||||
|
||||
func (p *IncrementalWorkerPicker) pickInternal() (*ClientWorker, bool, error) {
|
||||
p.access.Lock()
|
||||
defer p.access.Unlock()
|
||||
|
||||
idx := p.findAvailable()
|
||||
if idx >= 0 {
|
||||
n := len(p.workers)
|
||||
if n > 1 && idx != n-1 {
|
||||
p.workers[n-1], p.workers[idx] = p.workers[idx], p.workers[n-1]
|
||||
}
|
||||
return p.workers[idx], false, nil
|
||||
}
|
||||
|
||||
p.cleanup()
|
||||
|
||||
worker, err := p.Factory.Create()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
p.workers = append(p.workers, worker)
|
||||
|
||||
if p.cleanupTask == nil {
|
||||
p.cleanupTask = &task.Periodic{
|
||||
Interval: time.Second * 30,
|
||||
Execute: p.cleanupFunc,
|
||||
}
|
||||
}
|
||||
|
||||
return worker, true, nil
|
||||
}
|
||||
|
||||
func (p *IncrementalWorkerPicker) PickAvailable() (*ClientWorker, error) {
|
||||
worker, start, err := p.pickInternal()
|
||||
if start {
|
||||
common.Must(p.cleanupTask.Start())
|
||||
}
|
||||
|
||||
return worker, err
|
||||
}
|
||||
|
||||
type ClientWorkerFactory interface {
|
||||
Create() (*ClientWorker, error)
|
||||
}
|
||||
|
||||
type DialingWorkerFactory struct {
|
||||
Proxy proxy.Outbound
|
||||
Dialer internet.Dialer
|
||||
Strategy ClientStrategy
|
||||
}
|
||||
|
||||
func (f *DialingWorkerFactory) Create() (*ClientWorker, error) {
|
||||
opts := []pipe.Option{pipe.WithSizeLimit(64 * 1024)}
|
||||
uplinkReader, upLinkWriter := pipe.New(opts...)
|
||||
downlinkReader, downlinkWriter := pipe.New(opts...)
|
||||
|
||||
c, err := NewClientWorker(transport.Link{
|
||||
Reader: downlinkReader,
|
||||
Writer: upLinkWriter,
|
||||
}, f.Strategy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
go func(p proxy.Outbound, d internet.Dialer, c common.Closable) {
|
||||
outbounds := []*session.Outbound{{
|
||||
Target: net.TCPDestination(muxCoolAddress, muxCoolPort),
|
||||
}}
|
||||
ctx := session.ContextWithOutbounds(context.Background(), outbounds)
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
|
||||
if errP := p.Process(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter}, d); errP != nil {
|
||||
errC := errors.Cause(errP)
|
||||
if !(goerrors.Is(errC, io.EOF) || goerrors.Is(errC, io.ErrClosedPipe) || goerrors.Is(errC, context.Canceled)) {
|
||||
errors.LogInfoInner(ctx, errP, "failed to handler mux client connection")
|
||||
}
|
||||
}
|
||||
common.Must(c.Close())
|
||||
cancel()
|
||||
}(f.Proxy, f.Dialer, c.done)
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
type ClientStrategy struct {
|
||||
MaxConcurrency uint32
|
||||
MaxConnection uint32
|
||||
}
|
||||
|
||||
type ClientWorker struct {
|
||||
sessionManager *SessionManager
|
||||
link transport.Link
|
||||
done *done.Instance
|
||||
timer *time.Ticker
|
||||
strategy ClientStrategy
|
||||
}
|
||||
|
||||
var (
|
||||
muxCoolAddress = net.DomainAddress("v1.mux.cool")
|
||||
muxCoolPort = net.Port(9527)
|
||||
)
|
||||
|
||||
// NewClientWorker creates a new mux.Client.
|
||||
func NewClientWorker(stream transport.Link, s ClientStrategy) (*ClientWorker, error) {
|
||||
writer := buf.NewBufferedWriter(stream.Writer)
|
||||
writer.SetBuffered(false)
|
||||
stream.Writer = writer
|
||||
c := &ClientWorker{
|
||||
sessionManager: NewSessionManager(),
|
||||
link: stream,
|
||||
done: done.New(),
|
||||
timer: time.NewTicker(time.Second * 16),
|
||||
strategy: s,
|
||||
}
|
||||
|
||||
go c.fetchOutput()
|
||||
go c.monitor()
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (m *ClientWorker) TotalConnections() uint32 {
|
||||
return uint32(m.sessionManager.Count())
|
||||
}
|
||||
|
||||
func (m *ClientWorker) ActiveConnections() uint32 {
|
||||
return uint32(m.sessionManager.Size())
|
||||
}
|
||||
|
||||
// Closed returns true if this Client is closed.
|
||||
func (m *ClientWorker) Closed() bool {
|
||||
return m.done.Done()
|
||||
}
|
||||
|
||||
func (m *ClientWorker) WaitClosed() <-chan struct{} {
|
||||
return m.done.Wait()
|
||||
}
|
||||
|
||||
func (m *ClientWorker) Close() error {
|
||||
return m.done.Close()
|
||||
}
|
||||
|
||||
func (m *ClientWorker) monitor() {
|
||||
defer m.timer.Stop()
|
||||
|
||||
for {
|
||||
checkSize := m.sessionManager.Size()
|
||||
checkCount := m.sessionManager.Count()
|
||||
select {
|
||||
case <-m.done.Wait():
|
||||
m.sessionManager.Close()
|
||||
common.Interrupt(m.link.Writer)
|
||||
common.Interrupt(m.link.Reader)
|
||||
return
|
||||
case <-m.timer.C:
|
||||
if m.sessionManager.CloseIfNoSessionAndIdle(checkSize, checkCount) {
|
||||
common.Must(m.done.Close())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func writeFirstPayload(reader buf.Reader, writer *Writer) error {
|
||||
err := buf.CopyOnceTimeout(reader, writer, time.Millisecond*100)
|
||||
if err == buf.ErrNotTimeoutReader || err == buf.ErrReadTimeout {
|
||||
return writer.WriteMultiBuffer(buf.MultiBuffer{})
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func fetchInput(ctx context.Context, s *Session, output buf.Writer) {
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
ob := outbounds[len(outbounds)-1]
|
||||
transferType := protocol.TransferTypeStream
|
||||
if ob.Target.Network == net.Network_UDP {
|
||||
transferType = protocol.TransferTypePacket
|
||||
}
|
||||
s.transferType = transferType
|
||||
var inbound *session.Inbound
|
||||
if session.IsReverseMuxFromContext(ctx) {
|
||||
inbound = session.InboundFromContext(ctx)
|
||||
}
|
||||
writer := NewWriter(s.ID, ob.Target, output, transferType, xudp.GetGlobalID(ctx), inbound)
|
||||
defer s.Close(false)
|
||||
defer writer.Close()
|
||||
|
||||
errors.LogInfo(ctx, "dispatching request to ", ob.Target)
|
||||
if err := writeFirstPayload(s.input, writer); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to write first payload")
|
||||
writer.hasError = true
|
||||
return
|
||||
}
|
||||
|
||||
if err := buf.Copy(s.input, writer); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to fetch all input")
|
||||
writer.hasError = true
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (m *ClientWorker) IsClosing() bool {
|
||||
sm := m.sessionManager
|
||||
if m.strategy.MaxConnection > 0 && sm.Count() >= int(m.strategy.MaxConnection) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsFull returns true if this ClientWorker is unable to accept more connections.
|
||||
// it might be because it is closing, or the number of connections has reached the limit.
|
||||
func (m *ClientWorker) IsFull() bool {
|
||||
if m.IsClosing() || m.Closed() {
|
||||
return true
|
||||
}
|
||||
|
||||
sm := m.sessionManager
|
||||
if m.strategy.MaxConcurrency > 0 && sm.Size() >= int(m.strategy.MaxConcurrency) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (m *ClientWorker) Dispatch(ctx context.Context, link *transport.Link) bool {
|
||||
if m.IsFull() {
|
||||
return false
|
||||
}
|
||||
|
||||
sm := m.sessionManager
|
||||
s := sm.Allocate(&m.strategy, link.Reader, link.Writer)
|
||||
if s == nil {
|
||||
return false
|
||||
}
|
||||
go fetchInput(ctx, s, m.link.Writer)
|
||||
if _, ok := link.Reader.(*pipe.Reader); !ok {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-s.done.Wait():
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (m *ClientWorker) handleStatueKeepAlive(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if meta.Option.Has(OptionData) {
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *ClientWorker) handleStatusNew(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if meta.Option.Has(OptionData) {
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *ClientWorker) handleStatusKeep(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if !meta.Option.Has(OptionData) {
|
||||
return nil
|
||||
}
|
||||
|
||||
s, found := m.sessionManager.Get(meta.SessionID)
|
||||
if !found {
|
||||
// Notify remote peer to close this session.
|
||||
closingWriter := NewResponseWriter(meta.SessionID, m.link.Writer, protocol.TransferTypeStream)
|
||||
closingWriter.Close()
|
||||
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
|
||||
rr := s.NewReader(reader, &meta.Target)
|
||||
err := buf.Copy(rr, s.output)
|
||||
if err != nil && buf.IsWriteError(err) {
|
||||
errors.LogInfoInner(context.Background(), err, "failed to write to downstream. closing session ", s.ID)
|
||||
s.Close(false)
|
||||
return buf.Copy(rr, buf.Discard)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *ClientWorker) handleStatusEnd(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if s, found := m.sessionManager.Get(meta.SessionID); found {
|
||||
s.Close(false)
|
||||
}
|
||||
if meta.Option.Has(OptionData) {
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *ClientWorker) fetchOutput() {
|
||||
defer func() {
|
||||
common.Must(m.done.Close())
|
||||
}()
|
||||
|
||||
reader := &buf.BufferedReader{Reader: m.link.Reader}
|
||||
|
||||
var meta FrameMetadata
|
||||
for {
|
||||
err := meta.Unmarshal(reader, false)
|
||||
if err != nil {
|
||||
if errors.Cause(err) != io.EOF {
|
||||
errors.LogInfoInner(context.Background(), err, "failed to read metadata")
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
switch meta.SessionStatus {
|
||||
case SessionStatusKeepAlive:
|
||||
err = m.handleStatueKeepAlive(&meta, reader)
|
||||
case SessionStatusEnd:
|
||||
err = m.handleStatusEnd(&meta, reader)
|
||||
case SessionStatusNew:
|
||||
err = m.handleStatusNew(&meta, reader)
|
||||
case SessionStatusKeep:
|
||||
err = m.handleStatusKeep(&meta, reader)
|
||||
default:
|
||||
status := meta.SessionStatus
|
||||
errors.LogError(context.Background(), "unknown status: ", status)
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
errors.LogInfoInner(context.Background(), err, "failed to process data")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
package mux_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/testing/mocks"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
func TestIncrementalPickerFailure(t *testing.T) {
|
||||
mockCtl := gomock.NewController(t)
|
||||
defer mockCtl.Finish()
|
||||
|
||||
mockWorkerFactory := mocks.NewMuxClientWorkerFactory(mockCtl)
|
||||
mockWorkerFactory.EXPECT().Create().Return(nil, errors.New("test"))
|
||||
|
||||
picker := mux.IncrementalWorkerPicker{
|
||||
Factory: mockWorkerFactory,
|
||||
}
|
||||
|
||||
_, err := picker.PickAvailable()
|
||||
if err == nil {
|
||||
t.Error("expected error, but nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWorkerEOF(t *testing.T) {
|
||||
reader, writer := pipe.New(pipe.WithoutSizeLimit())
|
||||
common.Must(writer.Close())
|
||||
|
||||
worker, err := mux.NewClientWorker(transport.Link{Reader: reader, Writer: writer}, mux.ClientStrategy{})
|
||||
common.Must(err)
|
||||
|
||||
time.Sleep(time.Millisecond * 500)
|
||||
|
||||
f := worker.Dispatch(context.Background(), nil)
|
||||
if f {
|
||||
t.Error("expected failed dispatching, but actually not")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWorkerClose(t *testing.T) {
|
||||
mockCtl := gomock.NewController(t)
|
||||
defer mockCtl.Finish()
|
||||
|
||||
r1, w1 := pipe.New(pipe.WithoutSizeLimit())
|
||||
worker1, err := mux.NewClientWorker(transport.Link{
|
||||
Reader: r1,
|
||||
Writer: w1,
|
||||
}, mux.ClientStrategy{
|
||||
MaxConcurrency: 4,
|
||||
MaxConnection: 4,
|
||||
})
|
||||
common.Must(err)
|
||||
|
||||
r2, w2 := pipe.New(pipe.WithoutSizeLimit())
|
||||
worker2, err := mux.NewClientWorker(transport.Link{
|
||||
Reader: r2,
|
||||
Writer: w2,
|
||||
}, mux.ClientStrategy{
|
||||
MaxConcurrency: 4,
|
||||
MaxConnection: 4,
|
||||
})
|
||||
common.Must(err)
|
||||
|
||||
factory := mocks.NewMuxClientWorkerFactory(mockCtl)
|
||||
gomock.InOrder(
|
||||
factory.EXPECT().Create().Return(worker1, nil),
|
||||
factory.EXPECT().Create().Return(worker2, nil),
|
||||
)
|
||||
|
||||
picker := &mux.IncrementalWorkerPicker{
|
||||
Factory: factory,
|
||||
}
|
||||
manager := &mux.ClientManager{
|
||||
Picker: picker,
|
||||
}
|
||||
|
||||
tr1, tw1 := pipe.New(pipe.WithoutSizeLimit())
|
||||
ctx1 := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
|
||||
Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80),
|
||||
}})
|
||||
common.Must(manager.Dispatch(ctx1, &transport.Link{
|
||||
Reader: tr1,
|
||||
Writer: tw1,
|
||||
}))
|
||||
defer tw1.Close()
|
||||
|
||||
common.Must(w1.Close())
|
||||
|
||||
time.Sleep(time.Millisecond * 500)
|
||||
if !worker1.Closed() {
|
||||
t.Error("worker1 is not finished")
|
||||
}
|
||||
|
||||
tr2, tw2 := pipe.New(pipe.WithoutSizeLimit())
|
||||
ctx2 := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
|
||||
Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80),
|
||||
}})
|
||||
common.Must(manager.Dispatch(ctx2, &transport.Link{
|
||||
Reader: tr2,
|
||||
Writer: tw2,
|
||||
}))
|
||||
defer tw2.Close()
|
||||
|
||||
common.Must(w2.Close())
|
||||
}
|
||||
|
||||
func TestClientWorkerUDPSource(t *testing.T) {
|
||||
downR, downW := pipe.New(pipe.WithoutSizeLimit())
|
||||
upR, upW := pipe.New(pipe.WithoutSizeLimit())
|
||||
worker, err := mux.NewClientWorker(transport.Link{Reader: downR, Writer: upW}, mux.ClientStrategy{})
|
||||
common.Must(err)
|
||||
|
||||
inR, inW := pipe.New(pipe.WithoutSizeLimit())
|
||||
outR, outW := pipe.New(pipe.WithoutSizeLimit())
|
||||
ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
|
||||
Target: net.UDPDestination(net.ParseAddress("8.8.8.8"), 53),
|
||||
}})
|
||||
if !worker.Dispatch(ctx, &transport.Link{Reader: inR, Writer: outW}) {
|
||||
t.Fatal("failed to dispatch")
|
||||
}
|
||||
b := buf.New()
|
||||
b.WriteString("query")
|
||||
common.Must(inW.WriteMultiBuffer(buf.MultiBuffer{b}))
|
||||
mb, err := upR.ReadMultiBuffer() // New frame, the session is UDP from now on
|
||||
common.Must(err)
|
||||
buf.ReleaseMulti(mb)
|
||||
|
||||
srcs := []net.Destination{
|
||||
net.UDPDestination(net.ParseAddress("1.1.1.1"), 1111),
|
||||
net.UDPDestination(net.DomainAddress("example.com"), 2222),
|
||||
net.UDPDestination(net.ParseAddress("3.3.3.3"), 3333),
|
||||
}
|
||||
w := mux.NewResponseWriter(1, downW, protocol.TransferTypePacket)
|
||||
var got buf.MultiBuffer
|
||||
for i := range srcs {
|
||||
b := buf.New()
|
||||
b.WriteString("reply")
|
||||
b.UDP = &srcs[i]
|
||||
common.Must(w.WriteMultiBuffer(buf.MultiBuffer{b}))
|
||||
// keep earlier replies around while the next frame is parsed
|
||||
mb, err := outR.ReadMultiBuffer()
|
||||
common.Must(err)
|
||||
got = append(got, mb...)
|
||||
}
|
||||
for i, b := range got {
|
||||
if b.UDP == nil || *b.UDP != srcs[i] {
|
||||
t.Errorf("reply %d: source = %v, want %v", i, b.UDP, srcs[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package mux_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
)
|
||||
|
||||
func BenchmarkFrameWrite(b *testing.B) {
|
||||
frame := mux.FrameMetadata{
|
||||
Target: net.TCPDestination(net.DomainAddress("www.example.com"), net.Port(80)),
|
||||
SessionID: 1,
|
||||
SessionStatus: mux.SessionStatusNew,
|
||||
}
|
||||
writer := buf.New()
|
||||
defer writer.Release()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
common.Must(frame.WriteTo(writer))
|
||||
writer.Clear()
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
package mux
|
||||
@@ -1,60 +0,0 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/crypto"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
)
|
||||
|
||||
// PacketReader is an io.Reader that reads whole chunk of Mux frames every time.
|
||||
type PacketReader struct {
|
||||
reader io.Reader
|
||||
eof bool
|
||||
dest net.Destination
|
||||
}
|
||||
|
||||
// NewPacketReader creates a new PacketReader.
|
||||
// dest is copied because the caller reuses it for the next frame.
|
||||
func NewPacketReader(reader io.Reader, dest *net.Destination) *PacketReader {
|
||||
return &PacketReader{
|
||||
reader: reader,
|
||||
eof: false,
|
||||
dest: *dest,
|
||||
}
|
||||
}
|
||||
|
||||
// ReadMultiBuffer implements buf.Reader.
|
||||
func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
if r.eof {
|
||||
return nil, io.EOF
|
||||
}
|
||||
|
||||
size, err := serial.ReadUint16(r.reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if size > buf.Size {
|
||||
return nil, errors.New("packet size too large: ", size)
|
||||
}
|
||||
|
||||
b := buf.New()
|
||||
if _, err := b.ReadFullFrom(r.reader, int32(size)); err != nil {
|
||||
b.Release()
|
||||
return nil, err
|
||||
}
|
||||
r.eof = true
|
||||
if r.dest.Network == net.Network_UDP {
|
||||
b.UDP = &r.dest // only one packet is read, so b owns r.dest
|
||||
}
|
||||
return buf.MultiBuffer{b}, nil
|
||||
}
|
||||
|
||||
// NewStreamReader creates a new StreamReader.
|
||||
func NewStreamReader(reader *buf.BufferedReader) buf.Reader {
|
||||
return crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, reader, 1)
|
||||
}
|
||||
@@ -1,386 +0,0 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/signal/done"
|
||||
"github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
dispatcher routing.Dispatcher
|
||||
}
|
||||
|
||||
// NewServer creates a new mux.Server.
|
||||
func NewServer(ctx context.Context) *Server {
|
||||
s := &Server{}
|
||||
core.RequireFeatures(ctx, func(d routing.Dispatcher) {
|
||||
s.dispatcher = d
|
||||
})
|
||||
return s
|
||||
}
|
||||
|
||||
// Type implements common.HasType.
|
||||
func (s *Server) Type() interface{} {
|
||||
return s.dispatcher.Type()
|
||||
}
|
||||
|
||||
// Dispatch implements routing.Dispatcher
|
||||
func (s *Server) Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) {
|
||||
if dest.Address != muxCoolAddress {
|
||||
return s.dispatcher.Dispatch(ctx, dest)
|
||||
}
|
||||
|
||||
opts := pipe.OptionsFromContext(ctx)
|
||||
uplinkReader, uplinkWriter := pipe.New(opts...)
|
||||
downlinkReader, downlinkWriter := pipe.New(opts...)
|
||||
|
||||
_, err := NewServerWorker(ctx, s.dispatcher, &transport.Link{
|
||||
Reader: uplinkReader,
|
||||
Writer: downlinkWriter,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &transport.Link{Reader: downlinkReader, Writer: uplinkWriter}, nil
|
||||
}
|
||||
|
||||
// DispatchLink implements routing.Dispatcher
|
||||
func (s *Server) DispatchLink(ctx context.Context, dest net.Destination, link *transport.Link) error {
|
||||
if dest.Address != muxCoolAddress {
|
||||
return s.dispatcher.DispatchLink(ctx, dest, link)
|
||||
}
|
||||
worker, err := NewServerWorker(ctx, s.dispatcher, link)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-worker.done.Wait():
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Start implements common.Runnable.
|
||||
func (s *Server) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close implements common.Closable.
|
||||
func (s *Server) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type ServerWorker struct {
|
||||
dispatcher routing.Dispatcher
|
||||
link *transport.Link
|
||||
sessionManager *SessionManager
|
||||
done *done.Instance
|
||||
timer *time.Ticker
|
||||
}
|
||||
|
||||
func NewServerWorker(ctx context.Context, d routing.Dispatcher, link *transport.Link) (*ServerWorker, error) {
|
||||
writer := buf.NewBufferedWriter(link.Writer)
|
||||
writer.SetBuffered(false)
|
||||
worker := &ServerWorker{
|
||||
dispatcher: d,
|
||||
link: &transport.Link{Reader: link.Reader, Writer: writer},
|
||||
sessionManager: NewSessionManager(),
|
||||
done: done.New(),
|
||||
timer: time.NewTicker(60 * time.Second),
|
||||
}
|
||||
if inbound := session.InboundFromContext(ctx); inbound != nil {
|
||||
inbound.CanSpliceCopy = 3
|
||||
}
|
||||
go worker.run(ctx)
|
||||
go worker.monitor()
|
||||
return worker, nil
|
||||
}
|
||||
|
||||
func handle(ctx context.Context, s *Session, output buf.Writer) {
|
||||
writer := NewResponseWriter(s.ID, output, s.transferType)
|
||||
if err := buf.Copy(s.input, writer); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "session ", s.ID, " ends.")
|
||||
writer.hasError = true
|
||||
}
|
||||
|
||||
writer.Close()
|
||||
s.Close(false)
|
||||
}
|
||||
|
||||
func (w *ServerWorker) monitor() {
|
||||
defer w.timer.Stop()
|
||||
|
||||
for {
|
||||
checkSize := w.sessionManager.Size()
|
||||
checkCount := w.sessionManager.Count()
|
||||
select {
|
||||
case <-w.done.Wait():
|
||||
w.sessionManager.Close()
|
||||
common.Interrupt(w.link.Writer)
|
||||
common.Interrupt(w.link.Reader)
|
||||
return
|
||||
case <-w.timer.C:
|
||||
if w.sessionManager.CloseIfNoSessionAndIdle(checkSize, checkCount) {
|
||||
common.Must(w.done.Close())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *ServerWorker) ActiveConnections() uint32 {
|
||||
return uint32(w.sessionManager.Size())
|
||||
}
|
||||
|
||||
func (w *ServerWorker) Closed() bool {
|
||||
return w.done.Done()
|
||||
}
|
||||
|
||||
func (w *ServerWorker) WaitClosed() <-chan struct{} {
|
||||
return w.done.Wait()
|
||||
}
|
||||
|
||||
func (w *ServerWorker) Close() error {
|
||||
return w.done.Close()
|
||||
}
|
||||
|
||||
func (w *ServerWorker) handleStatusKeepAlive(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if meta.Option.Has(OptionData) {
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
ctx = session.SubContextFromMuxInbound(ctx)
|
||||
if meta.Inbound != nil && meta.Inbound.Source.IsValid() && meta.Inbound.Local.IsValid() {
|
||||
if inbound := session.InboundFromContext(ctx); inbound != nil {
|
||||
newInbound := *inbound
|
||||
newInbound.Source = meta.Inbound.Source
|
||||
newInbound.Local = meta.Inbound.Local
|
||||
ctx = session.ContextWithInbound(ctx, &newInbound)
|
||||
}
|
||||
}
|
||||
errors.LogInfo(ctx, "received request for ", meta.Target)
|
||||
{
|
||||
msg := &log.AccessMessage{
|
||||
To: meta.Target,
|
||||
Status: log.AccessAccepted,
|
||||
Reason: "",
|
||||
}
|
||||
if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() {
|
||||
msg.From = inbound.Source
|
||||
msg.Email = inbound.User.Email
|
||||
}
|
||||
ctx = log.ContextWithAccessMessage(ctx, msg)
|
||||
}
|
||||
|
||||
if network := session.AllowedNetworkFromContext(ctx); network != net.Network_Unknown {
|
||||
if meta.Target.Network != network {
|
||||
return errors.New("unexpected network ", meta.Target.Network) // it will break the whole Mux connection
|
||||
}
|
||||
}
|
||||
|
||||
if meta.GlobalID != [8]byte{} { // MUST ignore empty Global ID
|
||||
mb, err := NewPacketReader(reader, &meta.Target).ReadMultiBuffer()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
XUDPManager.Lock()
|
||||
x := XUDPManager.Map[meta.GlobalID]
|
||||
if x == nil {
|
||||
x = &XUDP{GlobalID: meta.GlobalID}
|
||||
XUDPManager.Map[meta.GlobalID] = x
|
||||
XUDPManager.Unlock()
|
||||
} else {
|
||||
if x.Status == Initializing { // nearly impossible
|
||||
XUDPManager.Unlock()
|
||||
errors.LogWarningInner(ctx, errors.New("conflict"), "XUDP hit ", meta.GlobalID)
|
||||
// It's not a good idea to return an err here, so just let client wait.
|
||||
// Client will receive an End frame after sending a Keep frame.
|
||||
return nil
|
||||
}
|
||||
x.Status = Initializing
|
||||
XUDPManager.Unlock()
|
||||
x.Mux.Close(false) // detach from previous Mux
|
||||
b := buf.New()
|
||||
b.Write(mb[0].Bytes())
|
||||
b.UDP = mb[0].UDP
|
||||
if err = x.Mux.output.WriteMultiBuffer(mb); err != nil {
|
||||
x.Interrupt()
|
||||
mb = buf.MultiBuffer{b}
|
||||
} else {
|
||||
b.Release()
|
||||
mb = nil
|
||||
}
|
||||
errors.LogInfoInner(ctx, err, "XUDP hit ", meta.GlobalID)
|
||||
}
|
||||
if mb != nil {
|
||||
ctx = session.ContextWithTimeoutOnly(ctx, true)
|
||||
// Actually, it won't return an error in Xray-core's implementations.
|
||||
link, err := w.dispatcher.Dispatch(ctx, meta.Target)
|
||||
if err != nil {
|
||||
XUDPManager.Lock()
|
||||
delete(XUDPManager.Map, x.GlobalID)
|
||||
XUDPManager.Unlock()
|
||||
err = errors.New("XUDP new ", meta.GlobalID).Base(errors.New("failed to dispatch request to ", meta.Target).Base(err))
|
||||
return err // it will break the whole Mux connection
|
||||
}
|
||||
link.Writer.WriteMultiBuffer(mb) // it's meaningless to test a new pipe
|
||||
x.Mux = &Session{
|
||||
input: link.Reader,
|
||||
output: link.Writer,
|
||||
}
|
||||
errors.LogInfoInner(ctx, err, "XUDP new ", meta.GlobalID)
|
||||
}
|
||||
x.Mux = &Session{
|
||||
input: x.Mux.input,
|
||||
output: x.Mux.output,
|
||||
parent: w.sessionManager,
|
||||
ID: meta.SessionID,
|
||||
transferType: protocol.TransferTypePacket,
|
||||
XUDP: x,
|
||||
}
|
||||
x.Status = Active
|
||||
if !w.sessionManager.Add(x.Mux) {
|
||||
x.Mux.Close(false)
|
||||
return errors.New("failed to add new session")
|
||||
}
|
||||
go handle(ctx, x.Mux, w.link.Writer)
|
||||
return nil
|
||||
}
|
||||
|
||||
link, err := w.dispatcher.Dispatch(ctx, meta.Target)
|
||||
if err != nil {
|
||||
if meta.Option.Has(OptionData) {
|
||||
buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
return errors.New("failed to dispatch request.").Base(err)
|
||||
}
|
||||
s := &Session{
|
||||
input: link.Reader,
|
||||
output: link.Writer,
|
||||
parent: w.sessionManager,
|
||||
ID: meta.SessionID,
|
||||
transferType: protocol.TransferTypeStream,
|
||||
}
|
||||
if meta.Target.Network == net.Network_UDP {
|
||||
s.transferType = protocol.TransferTypePacket
|
||||
}
|
||||
if !w.sessionManager.Add(s) {
|
||||
s.Close(false)
|
||||
return errors.New("failed to add new session")
|
||||
}
|
||||
go handle(ctx, s, w.link.Writer)
|
||||
if !meta.Option.Has(OptionData) {
|
||||
return nil
|
||||
}
|
||||
|
||||
rr := s.NewReader(reader, &meta.Target)
|
||||
err = buf.Copy(rr, s.output)
|
||||
|
||||
if err != nil && buf.IsWriteError(err) {
|
||||
s.Close(false)
|
||||
return buf.Copy(rr, buf.Discard)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (w *ServerWorker) handleStatusKeep(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if !meta.Option.Has(OptionData) {
|
||||
return nil
|
||||
}
|
||||
|
||||
s, found := w.sessionManager.Get(meta.SessionID)
|
||||
if !found {
|
||||
// Notify remote peer to close this session.
|
||||
closingWriter := NewResponseWriter(meta.SessionID, w.link.Writer, protocol.TransferTypeStream)
|
||||
closingWriter.Close()
|
||||
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
|
||||
rr := s.NewReader(reader, &meta.Target)
|
||||
err := buf.Copy(rr, s.output)
|
||||
|
||||
if err != nil && buf.IsWriteError(err) {
|
||||
errors.LogInfoInner(context.Background(), err, "failed to write to downstream writer. closing session ", s.ID)
|
||||
s.Close(false)
|
||||
return buf.Copy(rr, buf.Discard)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (w *ServerWorker) handleStatusEnd(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if s, found := w.sessionManager.Get(meta.SessionID); found {
|
||||
s.Close(false)
|
||||
}
|
||||
if meta.Option.Has(OptionData) {
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *ServerWorker) handleFrame(ctx context.Context, reader *buf.BufferedReader) error {
|
||||
var meta FrameMetadata
|
||||
err := meta.Unmarshal(reader, session.IsReverseMuxFromContext(ctx))
|
||||
if err != nil {
|
||||
return errors.New("failed to read metadata").Base(err)
|
||||
}
|
||||
|
||||
switch meta.SessionStatus {
|
||||
case SessionStatusKeepAlive:
|
||||
err = w.handleStatusKeepAlive(&meta, reader)
|
||||
case SessionStatusEnd:
|
||||
err = w.handleStatusEnd(&meta, reader)
|
||||
case SessionStatusNew:
|
||||
err = w.handleStatusNew(session.ContextWithIsReverseMux(ctx, false), &meta, reader)
|
||||
case SessionStatusKeep:
|
||||
err = w.handleStatusKeep(&meta, reader)
|
||||
default:
|
||||
status := meta.SessionStatus
|
||||
return errors.New("unknown status: ", status)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return errors.New("failed to process data").Base(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *ServerWorker) run(ctx context.Context) {
|
||||
defer func() {
|
||||
common.Must(w.done.Close())
|
||||
}()
|
||||
|
||||
reader := &buf.BufferedReader{Reader: w.link.Reader}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
err := w.handleFrame(ctx, reader)
|
||||
if err != nil {
|
||||
if errors.Cause(err) != io.EOF {
|
||||
errors.LogInfoInner(ctx, err, "unexpected EOF")
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,254 +0,0 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/signal/done"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
type SessionManager struct {
|
||||
sync.RWMutex
|
||||
sessions map[uint16]*Session
|
||||
count uint16
|
||||
closed bool
|
||||
}
|
||||
|
||||
func NewSessionManager() *SessionManager {
|
||||
return &SessionManager{
|
||||
count: 0,
|
||||
sessions: make(map[uint16]*Session, 16),
|
||||
}
|
||||
}
|
||||
|
||||
func (m *SessionManager) Closed() bool {
|
||||
m.RLock()
|
||||
defer m.RUnlock()
|
||||
|
||||
return m.closed
|
||||
}
|
||||
|
||||
func (m *SessionManager) Size() int {
|
||||
m.RLock()
|
||||
defer m.RUnlock()
|
||||
|
||||
return len(m.sessions)
|
||||
}
|
||||
|
||||
func (m *SessionManager) Count() int {
|
||||
m.RLock()
|
||||
defer m.RUnlock()
|
||||
|
||||
return int(m.count)
|
||||
}
|
||||
|
||||
func (m *SessionManager) Allocate(Strategy *ClientStrategy, input buf.Reader, output buf.Writer) *Session {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
MaxConcurrency := int(Strategy.MaxConcurrency)
|
||||
MaxConnection := uint16(Strategy.MaxConnection)
|
||||
|
||||
if m.closed || (MaxConcurrency > 0 && len(m.sessions) >= MaxConcurrency) || (MaxConnection > 0 && m.count >= MaxConnection) {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.count++
|
||||
s := &Session{
|
||||
input: input,
|
||||
output: output,
|
||||
ID: m.count,
|
||||
parent: m,
|
||||
done: done.New(),
|
||||
}
|
||||
m.sessions[s.ID] = s
|
||||
return s
|
||||
}
|
||||
|
||||
func (m *SessionManager) Add(s *Session) bool {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
if m.closed {
|
||||
return false
|
||||
}
|
||||
|
||||
m.count++
|
||||
m.sessions[s.ID] = s
|
||||
return true
|
||||
}
|
||||
|
||||
func (m *SessionManager) Remove(locked bool, id uint16) {
|
||||
if !locked {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
}
|
||||
locked = true
|
||||
|
||||
if m.closed {
|
||||
return
|
||||
}
|
||||
|
||||
delete(m.sessions, id)
|
||||
|
||||
/*
|
||||
if len(m.sessions) == 0 {
|
||||
m.sessions = make(map[uint16]*Session, 16)
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
func (m *SessionManager) Get(id uint16) (*Session, bool) {
|
||||
m.RLock()
|
||||
defer m.RUnlock()
|
||||
|
||||
if m.closed {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
s, found := m.sessions[id]
|
||||
return s, found
|
||||
}
|
||||
|
||||
func (m *SessionManager) CloseIfNoSessionAndIdle(checkSize int, checkCount int) bool {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
if m.closed {
|
||||
return true
|
||||
}
|
||||
|
||||
if len(m.sessions) != 0 || checkSize != 0 || checkCount != int(m.count) {
|
||||
return false
|
||||
}
|
||||
|
||||
m.closed = true
|
||||
|
||||
m.sessions = nil
|
||||
return true
|
||||
}
|
||||
|
||||
func (m *SessionManager) Close() error {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
if m.closed {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.closed = true
|
||||
|
||||
for _, s := range m.sessions {
|
||||
s.Close(true)
|
||||
}
|
||||
|
||||
m.sessions = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// Session represents a client connection in a Mux connection.
|
||||
type Session struct {
|
||||
input buf.Reader
|
||||
output buf.Writer
|
||||
parent *SessionManager
|
||||
ID uint16
|
||||
transferType protocol.TransferType
|
||||
closed bool
|
||||
done *done.Instance
|
||||
XUDP *XUDP
|
||||
}
|
||||
|
||||
// Close closes all resources associated with this session.
|
||||
func (s *Session) Close(locked bool) error {
|
||||
if !locked {
|
||||
s.parent.Lock()
|
||||
defer s.parent.Unlock()
|
||||
}
|
||||
locked = true
|
||||
if s.closed {
|
||||
return nil
|
||||
}
|
||||
s.closed = true
|
||||
if s.done != nil {
|
||||
s.done.Close()
|
||||
}
|
||||
if s.XUDP == nil {
|
||||
common.Interrupt(s.input)
|
||||
common.Close(s.output)
|
||||
} else {
|
||||
// Stop existing handle(), then trigger writer.Close().
|
||||
// Note that s.output may be dispatcher.SizeStatWriter.
|
||||
s.input.(*pipe.Reader).ReturnAnError(io.EOF)
|
||||
runtime.Gosched()
|
||||
// If the error set by ReturnAnError still exists, clear it.
|
||||
s.input.(*pipe.Reader).Recover()
|
||||
XUDPManager.Lock()
|
||||
if s.XUDP.Status == Active {
|
||||
s.XUDP.Expire = time.Now().Add(time.Minute)
|
||||
s.XUDP.Status = Expiring
|
||||
errors.LogDebug(context.Background(), "XUDP put ", s.XUDP.GlobalID)
|
||||
}
|
||||
XUDPManager.Unlock()
|
||||
}
|
||||
s.parent.Remove(locked, s.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewReader creates a buf.Reader based on the transfer type of this Session.
|
||||
func (s *Session) NewReader(reader *buf.BufferedReader, dest *net.Destination) buf.Reader {
|
||||
if s.transferType == protocol.TransferTypeStream {
|
||||
return NewStreamReader(reader)
|
||||
}
|
||||
return NewPacketReader(reader, dest)
|
||||
}
|
||||
|
||||
const (
|
||||
Initializing = 0
|
||||
Active = 1
|
||||
Expiring = 2
|
||||
)
|
||||
|
||||
type XUDP struct {
|
||||
GlobalID [8]byte
|
||||
Status uint64
|
||||
Expire time.Time
|
||||
Mux *Session
|
||||
}
|
||||
|
||||
func (x *XUDP) Interrupt() {
|
||||
common.Interrupt(x.Mux.input)
|
||||
common.Close(x.Mux.output)
|
||||
}
|
||||
|
||||
var XUDPManager struct {
|
||||
sync.Mutex
|
||||
Map map[[8]byte]*XUDP
|
||||
}
|
||||
|
||||
func init() {
|
||||
XUDPManager.Map = make(map[[8]byte]*XUDP)
|
||||
go func() {
|
||||
for {
|
||||
time.Sleep(time.Minute)
|
||||
now := time.Now()
|
||||
XUDPManager.Lock()
|
||||
for id, x := range XUDPManager.Map {
|
||||
if x.Status == Expiring && now.After(x.Expire) {
|
||||
x.Interrupt()
|
||||
delete(XUDPManager.Map, id)
|
||||
errors.LogDebug(context.Background(), "XUDP del ", id)
|
||||
}
|
||||
}
|
||||
XUDPManager.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package mux_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "github.com/xtls/xray-core/common/mux"
|
||||
)
|
||||
|
||||
func TestSessionManagerAdd(t *testing.T) {
|
||||
m := NewSessionManager()
|
||||
|
||||
s := m.Allocate(&ClientStrategy{}, nil, nil)
|
||||
if s.ID != 1 {
|
||||
t.Error("id: ", s.ID)
|
||||
}
|
||||
if m.Size() != 1 {
|
||||
t.Error("size: ", m.Size())
|
||||
}
|
||||
|
||||
s = m.Allocate(&ClientStrategy{}, nil, nil)
|
||||
if s.ID != 2 {
|
||||
t.Error("id: ", s.ID)
|
||||
}
|
||||
if m.Size() != 2 {
|
||||
t.Error("size: ", m.Size())
|
||||
}
|
||||
|
||||
s = &Session{
|
||||
ID: 4,
|
||||
}
|
||||
m.Add(s)
|
||||
if s.ID != 4 {
|
||||
t.Error("id: ", s.ID)
|
||||
}
|
||||
if m.Size() != 3 {
|
||||
t.Error("size: ", m.Size())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionManagerClose(t *testing.T) {
|
||||
m := NewSessionManager()
|
||||
s := m.Allocate(&ClientStrategy{}, nil, nil)
|
||||
|
||||
if m.CloseIfNoSessionAndIdle(m.Size(), m.Count()) {
|
||||
t.Error("able to close")
|
||||
}
|
||||
m.Remove(false, s.ID)
|
||||
if !m.CloseIfNoSessionAndIdle(m.Size(), m.Count()) {
|
||||
t.Error("not able to close")
|
||||
}
|
||||
}
|
||||
@@ -1,136 +0,0 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
)
|
||||
|
||||
type Writer struct {
|
||||
dest net.Destination
|
||||
writer buf.Writer
|
||||
id uint16
|
||||
followup bool
|
||||
hasError bool
|
||||
transferType protocol.TransferType
|
||||
globalID [8]byte
|
||||
inbound *session.Inbound
|
||||
}
|
||||
|
||||
func NewWriter(id uint16, dest net.Destination, writer buf.Writer, transferType protocol.TransferType, globalID [8]byte, inbound *session.Inbound) *Writer {
|
||||
return &Writer{
|
||||
id: id,
|
||||
dest: dest,
|
||||
writer: writer,
|
||||
followup: false,
|
||||
transferType: transferType,
|
||||
globalID: globalID,
|
||||
inbound: inbound,
|
||||
}
|
||||
}
|
||||
|
||||
func NewResponseWriter(id uint16, writer buf.Writer, transferType protocol.TransferType) *Writer {
|
||||
return &Writer{
|
||||
id: id,
|
||||
writer: writer,
|
||||
followup: true,
|
||||
transferType: transferType,
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Writer) getNextFrameMeta() FrameMetadata {
|
||||
meta := FrameMetadata{
|
||||
SessionID: w.id,
|
||||
Target: w.dest,
|
||||
GlobalID: w.globalID,
|
||||
Inbound: w.inbound,
|
||||
}
|
||||
|
||||
if w.followup {
|
||||
meta.SessionStatus = SessionStatusKeep
|
||||
} else {
|
||||
w.followup = true
|
||||
meta.SessionStatus = SessionStatusNew
|
||||
}
|
||||
|
||||
return meta
|
||||
}
|
||||
|
||||
func (w *Writer) writeMetaOnly() error {
|
||||
meta := w.getNextFrameMeta()
|
||||
b := buf.New()
|
||||
if err := meta.WriteTo(b); err != nil {
|
||||
return err
|
||||
}
|
||||
return w.writer.WriteMultiBuffer(buf.MultiBuffer{b})
|
||||
}
|
||||
|
||||
func writeMetaWithFrame(writer buf.Writer, meta FrameMetadata, data buf.MultiBuffer) error {
|
||||
frame := buf.New()
|
||||
if len(data) == 1 {
|
||||
frame.UDP = data[0].UDP
|
||||
}
|
||||
if err := meta.WriteTo(frame); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := serial.WriteUint16(frame, uint16(data.Len())); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
mb2 := make(buf.MultiBuffer, 0, len(data)+1)
|
||||
mb2 = append(mb2, frame)
|
||||
mb2 = append(mb2, data...)
|
||||
return writer.WriteMultiBuffer(mb2)
|
||||
}
|
||||
|
||||
func (w *Writer) writeData(mb buf.MultiBuffer) error {
|
||||
meta := w.getNextFrameMeta()
|
||||
meta.Option.Set(OptionData)
|
||||
|
||||
return writeMetaWithFrame(w.writer, meta, mb)
|
||||
}
|
||||
|
||||
// WriteMultiBuffer implements buf.Writer.
|
||||
func (w *Writer) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
defer buf.ReleaseMulti(mb)
|
||||
|
||||
if mb.IsEmpty() {
|
||||
return w.writeMetaOnly()
|
||||
}
|
||||
|
||||
for !mb.IsEmpty() {
|
||||
var chunk buf.MultiBuffer
|
||||
if w.transferType == protocol.TransferTypeStream {
|
||||
mb, chunk = buf.SplitSize(mb, 8*1024)
|
||||
} else {
|
||||
mb2, b := buf.SplitFirst(mb)
|
||||
mb = mb2
|
||||
chunk = buf.MultiBuffer{b}
|
||||
}
|
||||
if err := w.writeData(chunk); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close implements common.Closable.
|
||||
func (w *Writer) Close() error {
|
||||
meta := FrameMetadata{
|
||||
SessionID: w.id,
|
||||
SessionStatus: SessionStatusEnd,
|
||||
}
|
||||
if w.hasError {
|
||||
meta.Option.Set(OptionError)
|
||||
}
|
||||
|
||||
frame := buf.New()
|
||||
common.Must(meta.WriteTo(frame))
|
||||
|
||||
w.writer.WriteMultiBuffer(buf.MultiBuffer{frame})
|
||||
return nil
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package core
|
||||
|
||||
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/io.go -mock_names Reader=Reader,Writer=Writer io Reader,Writer
|
||||
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/log.go -mock_names Handler=LogHandler github.com/xtls/xray-core/common/log Handler
|
||||
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/mux.go -mock_names ClientWorkerFactory=MuxClientWorkerFactory github.com/xtls/xray-core/common/mux ClientWorkerFactory
|
||||
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/dns.go -mock_names Client=DNSClient github.com/xtls/xray-core/features/dns Client
|
||||
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/outbound.go -mock_names Manager=OutboundManager,HandlerSelector=OutboundHandlerSelector github.com/xtls/xray-core/features/outbound Manager,HandlerSelector
|
||||
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/proxy.go -mock_names Inbound=ProxyInbound,Outbound=ProxyOutbound github.com/xtls/xray-core/proxy Inbound,Outbound
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"github.com/xtls/xray-core/app/reverse"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type BridgeConfig struct {
|
||||
Tag string `json:"tag"`
|
||||
Domain string `json:"domain"`
|
||||
}
|
||||
|
||||
func (c *BridgeConfig) Build() (*reverse.BridgeConfig, error) {
|
||||
return &reverse.BridgeConfig{
|
||||
Tag: c.Tag,
|
||||
Domain: c.Domain,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type PortalConfig struct {
|
||||
Tag string `json:"tag"`
|
||||
Domain string `json:"domain"`
|
||||
}
|
||||
|
||||
func (c *PortalConfig) Build() (*reverse.PortalConfig, error) {
|
||||
return &reverse.PortalConfig{
|
||||
Tag: c.Tag,
|
||||
Domain: c.Domain,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type ReverseConfig struct {
|
||||
Bridges []BridgeConfig `json:"bridges"`
|
||||
Portals []PortalConfig `json:"portals"`
|
||||
}
|
||||
|
||||
func (c *ReverseConfig) Build() (proto.Message, error) {
|
||||
config := &reverse.Config{}
|
||||
for _, bconfig := range c.Bridges {
|
||||
b, err := bconfig.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config.BridgeConfig = append(config.BridgeConfig, b)
|
||||
}
|
||||
|
||||
for _, pconfig := range c.Portals {
|
||||
p, err := pconfig.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config.PortalConfig = append(config.PortalConfig, p)
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package conf_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/app/reverse"
|
||||
"github.com/xtls/xray-core/infra/conf"
|
||||
)
|
||||
|
||||
func TestReverseConfig(t *testing.T) {
|
||||
creator := func() conf.Buildable {
|
||||
return new(conf.ReverseConfig)
|
||||
}
|
||||
|
||||
runMultiTestCase(t, []TestCase{
|
||||
{
|
||||
Input: `{
|
||||
"bridges": [{
|
||||
"tag": "test",
|
||||
"domain": "test.example.com"
|
||||
}]
|
||||
}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &reverse.Config{
|
||||
BridgeConfig: []*reverse.BridgeConfig{
|
||||
{Tag: "test", Domain: "test.example.com"},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Input: `{
|
||||
"portals": [{
|
||||
"tag": "test",
|
||||
"domain": "test.example.com"
|
||||
}]
|
||||
}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &reverse.Config{
|
||||
PortalConfig: []*reverse.PortalConfig{
|
||||
{Tag: "test", Domain: "test.example.com"},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -529,26 +529,25 @@ func TestXDriveOutboundConfig(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, input := range []string{
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`,
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": 0, "xudpConcurrency": 8, "xudpProxyUDP443": "allow"}}`,
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpConcurrency": 8, "xudpProxyUDP443": "allow"}}, ` + xdriveStream + `}`,
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "reverse": {"tag": "r"}}, ` + xdriveStream + `}`,
|
||||
`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `}]}]}, ` + xdriveStream + `, "mux": {"enabled": true}}`,
|
||||
`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `}]}], "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
|
||||
} {
|
||||
if err := build(input); err != nil {
|
||||
t.Errorf("%s: %v", input, err)
|
||||
}
|
||||
}
|
||||
for _, c := range []struct{ input, err string }{
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, "encryption": "none"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"encryption"`},
|
||||
{`{"protocol": "vless", "settings": {"address": "example.com", "port": 443, ` + xdriveID + `, "encryption": "none"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"encryption"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `}`, `"mux"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": false}}`, `"mux"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": -1}}`, `"mux"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "xudpConcurrency": -1}}`, `"mux"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "xudpProxyUDP443": "skip"}}`, `"mux"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision"}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": -1}}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision"}]}]}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": -1}}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "testpre": 1}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"testpre"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, "encryption": "none", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"encryption"`},
|
||||
{`{"protocol": "vless", "settings": {"address": "example.com", "port": 443, ` + xdriveID + `, "encryption": "none", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"encryption"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `}`, `"settings.multiplex.concurrency"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"settings.multiplex.concurrency"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"xudpConcurrency": 8}}, ` + xdriveStream + `}`, `"settings.multiplex.concurrency"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpProxyUDP443": "skip"}}, ` + xdriveStream + `}`, `"settings.multiplex.concurrency"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision"}]}], "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "testpre": 1, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"testpre"`},
|
||||
{`{"protocol": "vmess", "settings": {` + xdriveServer + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"},
|
||||
{`{"protocol": "trojan", "settings": {"address": "example.com", "port": 443, "password": "p"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"},
|
||||
{`{"protocol": "freedom", ` + xdriveStream + `}`, "VLESS"},
|
||||
|
||||
+27
-1
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/xtls/xray-core/common/uuid"
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/proxy/vless/inbound"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/proxy/vless/outbound"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
@@ -236,6 +237,25 @@ func (c *VLessReverseConfig) Build() (*vless.Reverse, error) {
|
||||
return r, nil
|
||||
}
|
||||
|
||||
type MultiplexConfig struct {
|
||||
Concurrency int16 `json:"concurrency"`
|
||||
XudpConcurrency int16 `json:"xudpConcurrency"`
|
||||
XudpProxyUDP443 string `json:"xudpProxyUDP443"`
|
||||
}
|
||||
|
||||
func (c *MultiplexConfig) Build() (*vless.Multiplex, error) {
|
||||
if c == nil {
|
||||
return nil, nil
|
||||
}
|
||||
udp443 := c.XudpProxyUDP443
|
||||
if udp443 == "" {
|
||||
udp443 = "reject"
|
||||
}
|
||||
return multiplex.NormalizeConfig(&vless.Multiplex{
|
||||
Concurrency: int32(c.Concurrency), XudpConcurrency: int32(c.XudpConcurrency), XudpProxyUDP443: udp443,
|
||||
})
|
||||
}
|
||||
|
||||
type VLessOutboundVnext struct {
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
@@ -251,6 +271,7 @@ type VLessOutboundConfig struct {
|
||||
Flow string `json:"flow"`
|
||||
Seed string `json:"seed"`
|
||||
Encryption string `json:"encryption"`
|
||||
Multiplex *MultiplexConfig `json:"multiplex"`
|
||||
Reverse *VLessReverseConfig `json:"reverse"`
|
||||
Testpre uint32 `json:"testpre"`
|
||||
Testseed []uint32 `json:"testseed"`
|
||||
@@ -259,7 +280,12 @@ type VLessOutboundConfig struct {
|
||||
|
||||
// Build implements Buildable
|
||||
func (c *VLessOutboundConfig) Build() (proto.Message, error) {
|
||||
config := new(outbound.Config)
|
||||
multiplex, err := c.Multiplex.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config := &outbound.Config{Multiplex: multiplex}
|
||||
|
||||
if c.Address != nil {
|
||||
c.Vnext = []*VLessOutboundVnext{
|
||||
{
|
||||
|
||||
+6
-1
@@ -117,13 +117,18 @@ type VMessOutboundConfig struct {
|
||||
Security string `json:"security"`
|
||||
Experiments string `json:"experiments"`
|
||||
Receivers []*VMessOutboundTarget `json:"vnext"`
|
||||
Multiplex *MultiplexConfig `json:"multiplex"`
|
||||
}
|
||||
|
||||
// Build implements Buildable
|
||||
func (c *VMessOutboundConfig) Build() (proto.Message, error) {
|
||||
errors.PrintNonRemovalDeprecatedFeatureWarning("VMess (with no Forward Secrecy, etc.)", "VLESS Encryption")
|
||||
|
||||
config := new(outbound.Config)
|
||||
multiplex, err := c.Multiplex.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config := &outbound.Config{Multiplex: multiplex}
|
||||
if c.Address != nil {
|
||||
c.Receivers = []*VMessOutboundTarget{
|
||||
{
|
||||
|
||||
+13
-46
@@ -107,30 +107,6 @@ func (c *SniffingConfig) Build() (*proxyman.SniffingConfig, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
type MuxConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Concurrency int16 `json:"concurrency"`
|
||||
XudpConcurrency int16 `json:"xudpConcurrency"`
|
||||
XudpProxyUDP443 string `json:"xudpProxyUDP443"`
|
||||
}
|
||||
|
||||
// Build creates MultiplexingConfig, Concurrency < 0 completely disables mux.
|
||||
func (m *MuxConfig) Build() (*proxyman.MultiplexingConfig, error) {
|
||||
switch m.XudpProxyUDP443 {
|
||||
case "":
|
||||
m.XudpProxyUDP443 = "reject"
|
||||
case "reject", "allow", "skip":
|
||||
default:
|
||||
return nil, errors.New(`unknown "xudpProxyUDP443": `, m.XudpProxyUDP443)
|
||||
}
|
||||
return &proxyman.MultiplexingConfig{
|
||||
Enabled: m.Enabled,
|
||||
Concurrency: int32(m.Concurrency),
|
||||
XudpConcurrency: int32(m.XudpConcurrency),
|
||||
XudpProxyUDP443: m.XudpProxyUDP443,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type InboundDetourConfig struct {
|
||||
Protocol string `json:"protocol"`
|
||||
PortList *PortList `json:"port"`
|
||||
@@ -213,7 +189,7 @@ func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
|
||||
if _, ok := ts.(*masque.ServerConfig); !ok && receiverSettings.StreamSettings != nil && receiverSettings.StreamSettings.ProtocolName == "masque" {
|
||||
return nil, errors.New("the masque transport can only be used by the masque inbound")
|
||||
}
|
||||
if err := validateXDrive(ts, receiverSettings.StreamSettings, nil, receiverSettings.PortList); err != nil {
|
||||
if err := validateXDrive(ts, receiverSettings.StreamSettings, receiverSettings.PortList); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -231,7 +207,7 @@ type OutboundDetourConfig struct {
|
||||
Settings *json.RawMessage `json:"settings"`
|
||||
StreamSetting *StreamConfig `json:"streamSettings"`
|
||||
ProxySettings *json.RawMessage `json:"proxySettings"`
|
||||
MuxSettings *MuxConfig `json:"mux"`
|
||||
LegacyMux json.RawMessage `json:"mux,omitempty"`
|
||||
TargetStrategy string `json:"targetStrategy"`
|
||||
}
|
||||
|
||||
@@ -270,8 +246,8 @@ func validateOutboundTransportSecurity(rawConfig interface{}, senderSettings *pr
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateXDrive allows only VLESS with encryption on xdrive, and on the client Mux.Cool for every connection
|
||||
func validateXDrive(ts proto.Message, ss *internet.StreamConfig, ms *proxyman.MultiplexingConfig, pl *net.PortList) error {
|
||||
// validateXDrive allows only encrypted VLESS on xdrive, with native multiplex on every client connection.
|
||||
func validateXDrive(ts proto.Message, ss *internet.StreamConfig, pl *net.PortList) error {
|
||||
if ss == nil || ss.ProtocolName != "xdrive" {
|
||||
return nil
|
||||
}
|
||||
@@ -288,9 +264,9 @@ func validateXDrive(ts proto.Message, ss *internet.StreamConfig, ms *proxyman.Mu
|
||||
if account.Encryption == "none" {
|
||||
return errors.New(`the xdrive transport needs VLESS "encryption", run "xray vlessenc" to get one`)
|
||||
}
|
||||
// reverse opens its own mux
|
||||
if account.Reverse == nil && (ms == nil || !ms.Enabled || ms.Concurrency < 0 || ms.XudpConcurrency < 0 || ms.XudpProxyUDP443 == "skip") {
|
||||
return errors.New(`the xdrive transport needs "mux" enabled, with no negative "concurrency" or "xudpConcurrency" and no "xudpProxyUDP443":"skip"`)
|
||||
// Reverse opens its own multiplexed connection.
|
||||
if account.Reverse == nil && (c.Multiplex.GetConcurrency() == 0 || c.Multiplex.GetXudpProxyUDP443() == "skip") {
|
||||
return errors.New(`the xdrive transport needs positive "settings.multiplex.concurrency" and does not support "xudpProxyUDP443":"skip"`)
|
||||
}
|
||||
if account.Testpre != 0 {
|
||||
return errors.New(`the xdrive transport doesn't support VLESS "testpre"`)
|
||||
@@ -376,14 +352,6 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
|
||||
senderSettings.StreamSettings = ss
|
||||
}
|
||||
|
||||
if c.MuxSettings != nil {
|
||||
ms, err := c.MuxSettings.Build()
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to build Mux config").Base(err)
|
||||
}
|
||||
senderSettings.MultiplexSettings = ms
|
||||
}
|
||||
|
||||
settings := []byte("{}")
|
||||
if c.Settings != nil {
|
||||
settings = ([]byte)(*c.Settings)
|
||||
@@ -392,13 +360,17 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to load outbound detour config for protocol ", c.Protocol).Base(err)
|
||||
}
|
||||
if c.LegacyMux != nil {
|
||||
errors.LogWarning(context.Background(), `The legacy "mux" setting is ignored. To enable Multiplex for VLESS or VMess outbounds, use "settings.multiplex". If Multiplex is disabled, Xray will use ordinary outbound connections.`)
|
||||
}
|
||||
ts, err := rawConfig.(Buildable).Build()
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to build outbound handler for protocol ", c.Protocol).Base(err)
|
||||
}
|
||||
if err := validateXDrive(ts, senderSettings.StreamSettings, senderSettings.MultiplexSettings, nil); err != nil {
|
||||
if err := validateXDrive(ts, senderSettings.StreamSettings, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := validateOutboundTransportSecurity(rawConfig, senderSettings); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -478,7 +450,7 @@ type Config struct {
|
||||
API *APIConfig `json:"api"`
|
||||
Metrics *MetricsConfig `json:"metrics"`
|
||||
Stats *StatsConfig `json:"stats"`
|
||||
Reverse *ReverseConfig `json:"reverse"`
|
||||
Reverse *json.RawMessage `json:"reverse"`
|
||||
FakeDNS *FakeDNSConfig `json:"fakeDns"`
|
||||
Observatory *ObservatoryConfig `json:"observatory"`
|
||||
BurstObservatory *BurstObservatoryConfig `json:"burstObservatory"`
|
||||
@@ -680,11 +652,6 @@ func (c *Config) Build() (*core.Config, error) {
|
||||
|
||||
if c.Reverse != nil {
|
||||
return nil, errors.PrintRemovedFeatureError(`"legacy reverse"`, `"VLESS Reverse Proxy"`)
|
||||
r, err := c.Reverse.Build()
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to build reverse configuration").Base(err)
|
||||
}
|
||||
config.App = append(config.App, serial.ToTypedMessage(r))
|
||||
}
|
||||
|
||||
if c.FakeDNS != nil {
|
||||
|
||||
+101
-37
@@ -1,6 +1,7 @@
|
||||
package conf_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
@@ -10,7 +11,6 @@ import (
|
||||
"github.com/xtls/xray-core/app/log"
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
"github.com/xtls/xray-core/app/router"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
clog "github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
core "github.com/xtls/xray-core/core"
|
||||
. "github.com/xtls/xray-core/infra/conf"
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/proxy/vmess"
|
||||
"github.com/xtls/xray-core/proxy/vmess/inbound"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
@@ -225,49 +226,112 @@ func TestSniffingConfig_Build(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMuxConfig_Build(t *testing.T) {
|
||||
tests := []struct {
|
||||
func TestMultiplexConfig_Build(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
fields string
|
||||
want *proxyman.MultiplexingConfig
|
||||
want *vless.Multiplex
|
||||
bad bool
|
||||
}{
|
||||
{"default", `{"enabled": true, "concurrency": 16}`, &proxyman.MultiplexingConfig{
|
||||
Enabled: true,
|
||||
Concurrency: 16,
|
||||
XudpConcurrency: 0,
|
||||
XudpProxyUDP443: "reject",
|
||||
}},
|
||||
{"empty def", `{}`, &proxyman.MultiplexingConfig{
|
||||
Enabled: false,
|
||||
Concurrency: 0,
|
||||
XudpConcurrency: 0,
|
||||
XudpProxyUDP443: "reject",
|
||||
}},
|
||||
{"not enable", `{"enabled": false, "concurrency": 4}`, &proxyman.MultiplexingConfig{
|
||||
Enabled: false,
|
||||
Concurrency: 4,
|
||||
XudpConcurrency: 0,
|
||||
XudpProxyUDP443: "reject",
|
||||
}},
|
||||
{"forbidden", `{"enabled": false, "concurrency": -1}`, &proxyman.MultiplexingConfig{
|
||||
Enabled: false,
|
||||
Concurrency: -1,
|
||||
XudpConcurrency: 0,
|
||||
XudpProxyUDP443: "reject",
|
||||
}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
m := &MuxConfig{}
|
||||
common.Must(json.Unmarshal([]byte(tt.fields), m))
|
||||
if got, _ := m.Build(); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("MuxConfig.Build() = %v, want %v", got, tt.want)
|
||||
{name: "empty", fields: `{}`},
|
||||
{name: "both zero", fields: `{"concurrency":0,"xudpConcurrency":0}`},
|
||||
{name: "regular pool", fields: `{"concurrency":4}`, want: &vless.Multiplex{Concurrency: 4, XudpProxyUDP443: "reject"}},
|
||||
{name: "XUDP only", fields: `{"xudpConcurrency":8}`, want: &vless.Multiplex{XudpConcurrency: 8, XudpProxyUDP443: "reject"}},
|
||||
{name: "negative concurrency", fields: `{"concurrency":-1,"xudpConcurrency":8}`, bad: true},
|
||||
{name: "negative XUDP concurrency", fields: `{"concurrency":4,"xudpConcurrency":-1}`, bad: true},
|
||||
{name: "invalid UDP policy", fields: `{"concurrency":4,"xudpProxyUDP443":"invalid"}`, bad: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var config MultiplexConfig
|
||||
if err := json.Unmarshal([]byte(tc.fields), &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := config.Build()
|
||||
if (err != nil) != tc.bad || !proto.Equal(got, tc.want) {
|
||||
t.Fatalf("Build() = %v, %v, want config %v, error %t", got, err, tc.want, tc.bad)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutboundMultiplexConfig(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
legacy string
|
||||
native string
|
||||
want *vless.Multiplex
|
||||
}{
|
||||
{name: "absent"},
|
||||
{name: "legacy enabled", legacy: `{"enabled":true,"concurrency":16}`},
|
||||
{name: "legacy disabled", legacy: `{"enabled":false}`},
|
||||
{name: "legacy null", legacy: `null`},
|
||||
{name: "legacy empty", legacy: `{}`},
|
||||
{name: "legacy values are not decoded", legacy: `{"enabled":"ignored","concurrency":"ignored"}`},
|
||||
{name: "empty native object", native: `{}`},
|
||||
{name: "enabled flag alone does not create a pool", native: `{"enabled":true}`},
|
||||
{
|
||||
name: "positive concurrency with old enabled flag", native: `{"concurrency":4,"enabled":false}`,
|
||||
want: &vless.Multiplex{Concurrency: 4, XudpProxyUDP443: "reject"},
|
||||
},
|
||||
{
|
||||
name: "native XUDP only", native: `{"xudpConcurrency":8}`,
|
||||
want: &vless.Multiplex{XudpConcurrency: 8, XudpProxyUDP443: "reject"},
|
||||
},
|
||||
{
|
||||
name: "native options override legacy", legacy: `{"enabled":true,"concurrency":16}`,
|
||||
native: `{"concurrency":4,"xudpConcurrency":8,"xudpProxyUDP443":"allow"}`,
|
||||
want: &vless.Multiplex{Concurrency: 4, XudpConcurrency: 8, XudpProxyUDP443: "allow"},
|
||||
},
|
||||
{name: "empty native with legacy enabled", legacy: `{"enabled":true}`, native: `{}`},
|
||||
}
|
||||
for _, protoName := range []string{"vless", "vmess"} {
|
||||
for _, tc := range tests {
|
||||
t.Run(protoName+"/"+tc.name, func(t *testing.T) {
|
||||
settings := `"address":"127.0.0.1","port":443,"id":"d19768cb-2891-4c3c-b45d-863f8fd64b6d"`
|
||||
if protoName == "vless" {
|
||||
settings += `,"encryption":"none"`
|
||||
}
|
||||
if tc.native != "" {
|
||||
settings += `,"multiplex":` + tc.native
|
||||
}
|
||||
input := `{"protocol":"` + protoName + `","settings":{` + settings + `}`
|
||||
if tc.legacy != "" {
|
||||
input += `,"mux":` + tc.legacy
|
||||
}
|
||||
|
||||
var config OutboundDetourConfig
|
||||
if err := json.Unmarshal([]byte(input+"}"), &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := string(config.LegacyMux); got != tc.legacy {
|
||||
t.Errorf("legacy mux marker = %q, want %q", got, tc.legacy)
|
||||
}
|
||||
serialized, err := json.Marshal(config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if hasMux := bytes.Contains(serialized, []byte(`"mux":`)); hasMux != (tc.legacy != "") {
|
||||
t.Errorf("serialized config changed legacy mux presence: %s", serialized)
|
||||
}
|
||||
built, err := config.Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
proxyConfig, err := built.ProxySettings.GetInstance()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := proxyConfig.(interface{ GetMultiplex() *vless.Multiplex }).GetMultiplex()
|
||||
if !proto.Equal(got, tc.want) {
|
||||
t.Errorf("multiplex = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfig_Override(t *testing.T) {
|
||||
legacyReverse := json.RawMessage(`{}`)
|
||||
tests := []struct {
|
||||
name string
|
||||
orig *Config
|
||||
@@ -285,7 +349,7 @@ func TestConfig_Override(t *testing.T) {
|
||||
Policy: &PolicyConfig{},
|
||||
API: &APIConfig{},
|
||||
Stats: &StatsConfig{},
|
||||
Reverse: &ReverseConfig{},
|
||||
Reverse: &legacyReverse,
|
||||
},
|
||||
"",
|
||||
&Config{
|
||||
@@ -295,7 +359,7 @@ func TestConfig_Override(t *testing.T) {
|
||||
Policy: &PolicyConfig{},
|
||||
API: &APIConfig{},
|
||||
Stats: &StatsConfig{},
|
||||
Reverse: &ReverseConfig{},
|
||||
Reverse: &legacyReverse,
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -24,7 +24,6 @@ import (
|
||||
_ "github.com/xtls/xray-core/app/log"
|
||||
_ "github.com/xtls/xray-core/app/metrics"
|
||||
_ "github.com/xtls/xray-core/app/policy"
|
||||
_ "github.com/xtls/xray-core/app/reverse"
|
||||
_ "github.com/xtls/xray-core/app/router"
|
||||
_ "github.com/xtls/xray-core/app/stats"
|
||||
|
||||
|
||||
@@ -184,6 +184,66 @@ func (x *Account) GetTestseed() []uint32 {
|
||||
return nil
|
||||
}
|
||||
|
||||
type Multiplex struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Concurrency int32 `protobuf:"varint,1,opt,name=concurrency,proto3" json:"concurrency,omitempty"`
|
||||
XudpConcurrency int32 `protobuf:"varint,2,opt,name=xudpConcurrency,proto3" json:"xudpConcurrency,omitempty"`
|
||||
XudpProxyUDP443 string `protobuf:"bytes,3,opt,name=xudpProxyUDP443,proto3" json:"xudpProxyUDP443,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Multiplex) Reset() {
|
||||
*x = Multiplex{}
|
||||
mi := &file_proxy_vless_account_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Multiplex) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Multiplex) ProtoMessage() {}
|
||||
|
||||
func (x *Multiplex) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_proxy_vless_account_proto_msgTypes[2]
|
||||
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 Multiplex.ProtoReflect.Descriptor instead.
|
||||
func (*Multiplex) Descriptor() ([]byte, []int) {
|
||||
return file_proxy_vless_account_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
func (x *Multiplex) GetConcurrency() int32 {
|
||||
if x != nil {
|
||||
return x.Concurrency
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Multiplex) GetXudpConcurrency() int32 {
|
||||
if x != nil {
|
||||
return x.XudpConcurrency
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Multiplex) GetXudpProxyUDP443() string {
|
||||
if x != nil {
|
||||
return x.XudpProxyUDP443
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var File_proxy_vless_account_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_proxy_vless_account_proto_rawDesc = "" +
|
||||
@@ -203,7 +263,11 @@ const file_proxy_vless_account_proto_rawDesc = "" +
|
||||
"\apadding\x18\x06 \x01(\tR\apadding\x123\n" +
|
||||
"\areverse\x18\a \x01(\v2\x19.xray.proxy.vless.ReverseR\areverse\x12\x18\n" +
|
||||
"\atestpre\x18\b \x01(\rR\atestpre\x12\x1a\n" +
|
||||
"\btestseed\x18\t \x03(\rR\btestseedBR\n" +
|
||||
"\btestseed\x18\t \x03(\rR\btestseed\"\x81\x01\n" +
|
||||
"\tMultiplex\x12 \n" +
|
||||
"\vconcurrency\x18\x01 \x01(\x05R\vconcurrency\x12(\n" +
|
||||
"\x0fxudpConcurrency\x18\x02 \x01(\x05R\x0fxudpConcurrency\x12(\n" +
|
||||
"\x0fxudpProxyUDP443\x18\x03 \x01(\tR\x0fxudpProxyUDP443BR\n" +
|
||||
"\x14com.xray.proxy.vlessP\x01Z%github.com/xtls/xray-core/proxy/vless\xaa\x02\x10Xray.Proxy.Vlessb\x06proto3"
|
||||
|
||||
var (
|
||||
@@ -218,14 +282,15 @@ func file_proxy_vless_account_proto_rawDescGZIP() []byte {
|
||||
return file_proxy_vless_account_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_proxy_vless_account_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
|
||||
var file_proxy_vless_account_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
|
||||
var file_proxy_vless_account_proto_goTypes = []any{
|
||||
(*Reverse)(nil), // 0: xray.proxy.vless.Reverse
|
||||
(*Account)(nil), // 1: xray.proxy.vless.Account
|
||||
(*proxyman.SniffingConfig)(nil), // 2: xray.app.proxyman.SniffingConfig
|
||||
(*Multiplex)(nil), // 2: xray.proxy.vless.Multiplex
|
||||
(*proxyman.SniffingConfig)(nil), // 3: xray.app.proxyman.SniffingConfig
|
||||
}
|
||||
var file_proxy_vless_account_proto_depIdxs = []int32{
|
||||
2, // 0: xray.proxy.vless.Reverse.sniffing:type_name -> xray.app.proxyman.SniffingConfig
|
||||
3, // 0: xray.proxy.vless.Reverse.sniffing:type_name -> xray.app.proxyman.SniffingConfig
|
||||
0, // 1: xray.proxy.vless.Account.reverse:type_name -> xray.proxy.vless.Reverse
|
||||
2, // [2:2] is the sub-list for method output_type
|
||||
2, // [2:2] is the sub-list for method input_type
|
||||
@@ -245,7 +310,7 @@ func file_proxy_vless_account_proto_init() {
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_vless_account_proto_rawDesc), len(file_proxy_vless_account_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 2,
|
||||
NumMessages: 3,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
|
||||
@@ -29,3 +29,9 @@ message Account {
|
||||
uint32 testpre = 8;
|
||||
repeated uint32 testseed = 9;
|
||||
}
|
||||
|
||||
message Multiplex {
|
||||
int32 concurrency = 1;
|
||||
int32 xudpConcurrency = 2;
|
||||
string xudpProxyUDP443 = 3;
|
||||
}
|
||||
|
||||
@@ -11,16 +11,13 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/app/dispatcher"
|
||||
"github.com/xtls/xray-core/app/reverse"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/retry"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/signal"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
@@ -28,7 +25,6 @@ import (
|
||||
"github.com/xtls/xray-core/features"
|
||||
"github.com/xtls/xray-core/features/dns"
|
||||
"github.com/xtls/xray-core/features/extension"
|
||||
feature_inbound "github.com/xtls/xray-core/features/inbound"
|
||||
"github.com/xtls/xray-core/features/outbound"
|
||||
"github.com/xtls/xray-core/features/policy"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
@@ -37,6 +33,8 @@ import (
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/proxy/vless/encoding"
|
||||
"github.com/xtls/xray-core/proxy/vless/encryption"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/proxy/vless/reverse"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/internet/reality"
|
||||
"github.com/xtls/xray-core/transport/internet/stat"
|
||||
@@ -72,14 +70,12 @@ func init() {
|
||||
|
||||
// Handler is an inbound connection handler that handles messages in VLess protocol.
|
||||
type Handler struct {
|
||||
inboundHandlerManager feature_inbound.Manager
|
||||
policyManager policy.Manager
|
||||
stats stats.Manager
|
||||
validator vless.Validator
|
||||
decryption *encryption.ServerInstance
|
||||
outboundHandlerManager outbound.Manager
|
||||
observer features.Feature
|
||||
defaultDispatcher routing.Dispatcher
|
||||
ctx context.Context
|
||||
fallbacks map[string]map[string]map[string]*Fallback // or nil
|
||||
// regexps map[string]*regexp.Regexp // or nil
|
||||
@@ -89,13 +85,11 @@ type Handler struct {
|
||||
func New(ctx context.Context, config *Config, dc dns.Client, validator vless.Validator) (*Handler, error) {
|
||||
v := core.MustFromContext(ctx)
|
||||
handler := &Handler{
|
||||
inboundHandlerManager: v.GetFeature(feature_inbound.ManagerType()).(feature_inbound.Manager),
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
stats: v.GetFeature(stats.ManagerType()).(stats.Manager),
|
||||
validator: validator,
|
||||
outboundHandlerManager: v.GetFeature(outbound.ManagerType()).(outbound.Manager),
|
||||
observer: v.GetFeature(extension.ObservatoryType()),
|
||||
defaultDispatcher: v.GetFeature(routing.DispatcherType()).(routing.Dispatcher),
|
||||
ctx: ctx,
|
||||
}
|
||||
|
||||
@@ -188,7 +182,7 @@ func isMuxAndNotXUDP(request *protocol.RequestHeader, first *buf.Buffer) bool {
|
||||
firstBytes[6] == 2) // Network type: UDP
|
||||
}
|
||||
|
||||
func (h *Handler) GetReverse(a *vless.MemoryAccount) (*Reverse, error) {
|
||||
func (h *Handler) GetReverse(a *vless.MemoryAccount) (*reverse.PublicEndpoint, error) {
|
||||
u := h.validator.Get(a.ID.UUID())
|
||||
if u == nil {
|
||||
return nil, errors.New("reverse: user " + a.ID.String() + " doesn't exist anymore")
|
||||
@@ -199,25 +193,28 @@ func (h *Handler) GetReverse(a *vless.MemoryAccount) (*Reverse, error) {
|
||||
}
|
||||
r := h.outboundHandlerManager.GetHandler(a.Reverse.Tag)
|
||||
if r == nil {
|
||||
picker, _ := reverse.NewStaticMuxPicker()
|
||||
r = &Reverse{tag: a.Reverse.Tag, picker: picker, client: &mux.ClientManager{Picker: picker}}
|
||||
r = reverse.NewPublicEndpoint(a.Reverse.Tag, h.observer)
|
||||
for len(h.outboundHandlerManager.ListHandlers(h.ctx)) == 0 {
|
||||
time.Sleep(time.Second) // prevents this outbound from becoming the default outbound
|
||||
}
|
||||
if err := h.outboundHandlerManager.AddHandler(h.ctx, r); err != nil {
|
||||
r.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if r, ok := r.(*Reverse); ok {
|
||||
if r, ok := r.(*reverse.PublicEndpoint); ok {
|
||||
return r, nil
|
||||
}
|
||||
return nil, errors.New("reverse: outbound " + a.Reverse.Tag + " is not type Reverse")
|
||||
return nil, errors.New("reverse: outbound " + a.Reverse.Tag + " is not type PublicEndpoint")
|
||||
}
|
||||
|
||||
func (h *Handler) RemoveReverse(u *protocol.MemoryUser) {
|
||||
if u != nil {
|
||||
a := u.Account.(*vless.MemoryAccount)
|
||||
if a.Reverse != nil && a.Reverse.Tag != "" {
|
||||
if publicEndpoint, ok := h.outboundHandlerManager.GetHandler(a.Reverse.Tag).(*reverse.PublicEndpoint); ok {
|
||||
publicEndpoint.Close()
|
||||
}
|
||||
h.outboundHandlerManager.RemoveHandler(h.ctx, a.Reverse.Tag)
|
||||
}
|
||||
}
|
||||
@@ -541,10 +538,6 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
|
||||
return errors.New("for safety reasons, user " + account.ID.String() + " is not allowed to use forward proxy")
|
||||
}
|
||||
|
||||
responseAddons := &encoding.Addons{
|
||||
// Flow: requestAddons.Flow,
|
||||
}
|
||||
|
||||
var input *bytes.Reader
|
||||
var rawInput **bytes.Buffer
|
||||
switch requestAddons.Flow {
|
||||
@@ -607,85 +600,29 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
|
||||
}
|
||||
|
||||
bufferWriter := buf.NewBufferedWriter(buf.NewWriter(connection))
|
||||
if err := encoding.EncodeResponseHeader(bufferWriter, request, responseAddons); err != nil {
|
||||
if err := encoding.EncodeResponseHeader(bufferWriter, request, &encoding.Addons{}); err != nil {
|
||||
return errors.New("failed to encode response header").Base(err)
|
||||
}
|
||||
clientWriter := encoding.EncodeBodyAddons(bufferWriter, request, requestAddons, trafficState, false, ctx, connection, nil)
|
||||
bufferWriter.SetFlushNext()
|
||||
link := &transport.Link{Reader: clientReader, Writer: clientWriter}
|
||||
|
||||
if request.Command == protocol.RequestCommandRvs {
|
||||
r, err := h.GetReverse(account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return r.NewMux(ctx, dispatcher.WrapLink(ctx, h.policyManager, h.stats, &transport.Link{Reader: clientReader, Writer: clientWriter}), h.observer)
|
||||
return r.Accept(ctx, dispatcher.WrapLink(ctx, h.policyManager, h.stats, link))
|
||||
}
|
||||
|
||||
if err := dispatch.DispatchLink(
|
||||
ctx, request.Destination(), &transport.Link{
|
||||
Reader: clientReader,
|
||||
Writer: clientWriter,
|
||||
},
|
||||
); err != nil {
|
||||
if request.Command == protocol.RequestCommandMux {
|
||||
worker := multiplex.NewServerWorker(ctx, dispatch.DispatchLink, link)
|
||||
<-worker.WaitClosed()
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := dispatch.DispatchLink(ctx, request.Destination(), link); err != nil {
|
||||
return errors.New("failed to dispatch request").Base(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Reverse struct {
|
||||
tag string
|
||||
picker *reverse.StaticMuxPicker
|
||||
client *mux.ClientManager
|
||||
}
|
||||
|
||||
func (r *Reverse) Tag() string {
|
||||
return r.tag
|
||||
}
|
||||
|
||||
func (r *Reverse) NewMux(ctx context.Context, link *transport.Link, observer features.Feature) error {
|
||||
muxClient, err := mux.NewClientWorker(*link, mux.ClientStrategy{})
|
||||
if err != nil {
|
||||
return errors.New("failed to create mux client worker").Base(err)
|
||||
}
|
||||
worker, err := reverse.NewPortalWorker(muxClient)
|
||||
if err != nil {
|
||||
return errors.New("failed to create portal worker").Base(err)
|
||||
}
|
||||
r.picker.AddWorker(worker)
|
||||
if burstObs, ok := observer.(extension.BurstObservatory); ok {
|
||||
go burstObs.Check([]string{r.Tag()})
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-muxClient.WaitClosed():
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reverse) Dispatch(ctx context.Context, link *transport.Link) {
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
ob := outbounds[len(outbounds)-1]
|
||||
if ob != nil {
|
||||
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
|
||||
link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
|
||||
link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
|
||||
}
|
||||
r.client.Dispatch(session.ContextWithIsReverseMux(ctx, true), link)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Reverse) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reverse) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reverse) SenderSettings() *serial.TypedMessage {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reverse) ProxySettings() *serial.TypedMessage {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
|
||||
// Control intents carry no encoded DATA or caller payload.
|
||||
type carrier struct {
|
||||
sync.RWMutex
|
||||
sessions map[uint16]*Session
|
||||
|
||||
ready map[uint16]*Session // nil is a bounded END for an unknown wire ID
|
||||
unknown int
|
||||
count uint16
|
||||
active int
|
||||
client bool
|
||||
link transport.Link
|
||||
writeMutex sync.Mutex
|
||||
control *sync.Cond
|
||||
ctx context.Context
|
||||
cancel context.CancelCauseFunc
|
||||
timer *time.Timer
|
||||
}
|
||||
|
||||
func newCarrier(parent context.Context, link transport.Link, idle time.Duration, client bool) *carrier {
|
||||
ctx, cancel := context.WithCancelCause(parent)
|
||||
c := &carrier{
|
||||
sessions: make(map[uint16]*Session, 16), link: link, ctx: ctx, cancel: cancel,
|
||||
client: client,
|
||||
}
|
||||
c.control = sync.NewCond(&c.RWMutex)
|
||||
c.ready = make(map[uint16]*Session)
|
||||
context.AfterFunc(c.ctx, func() { common.Interrupt(c.link.Reader) })
|
||||
c.Lock()
|
||||
checkSize, checkCount := c.active, c.count
|
||||
c.timer = time.AfterFunc(idle, func() {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
if c.Closed() {
|
||||
return
|
||||
}
|
||||
if c.active == 0 && checkSize == 0 && c.count == checkCount {
|
||||
c.cancel(nil)
|
||||
return
|
||||
}
|
||||
checkSize, checkCount = c.active, c.count
|
||||
c.timer.Reset(idle)
|
||||
})
|
||||
c.Unlock()
|
||||
context.AfterFunc(c.ctx, c.shutdown)
|
||||
go c.controlLoop()
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *carrier) admitLocked(s *Session) bool {
|
||||
if c.Closed() || s.phase != outputOpen || c.sessions[s.ID] != nil {
|
||||
return false
|
||||
}
|
||||
c.count++
|
||||
c.active++
|
||||
c.invalidateUnknownLocked(s.ID)
|
||||
c.sessions[s.ID] = s
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *carrier) queueReadyLocked(s *Session) {
|
||||
if c.ready[s.ID] != s {
|
||||
c.ready[s.ID] = s
|
||||
c.control.Broadcast()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *carrier) scheduleLocked(s *Session) {
|
||||
if !c.Closed() && c.sessions[s.ID] == s && (s.phase == outputDone || s.packetReady()) {
|
||||
c.queueReadyLocked(s)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *carrier) invalidateUnknownLocked(id uint16) bool {
|
||||
if s, ok := c.ready[id]; ok && s == nil {
|
||||
delete(c.ready, id)
|
||||
c.unknown--
|
||||
c.control.Broadcast()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *carrier) unknownEnd(id uint16) {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
for !c.Closed() {
|
||||
if _, queued := c.ready[id]; queued || c.sessions[id] != nil {
|
||||
return
|
||||
}
|
||||
if c.unknown < 16 {
|
||||
c.ready[id] = nil
|
||||
c.unknown++
|
||||
c.control.Broadcast()
|
||||
return
|
||||
}
|
||||
c.control.Wait()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *carrier) controlLoop() {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
for !c.Closed() {
|
||||
if len(c.ready) == 0 {
|
||||
c.control.Wait()
|
||||
continue
|
||||
}
|
||||
// Advance the iterator under the lock. Physical sends never hold it.
|
||||
for id, selected := range c.ready {
|
||||
c.Unlock()
|
||||
c.writeMutex.Lock()
|
||||
var frames buf.MultiBuffer
|
||||
var err error
|
||||
raw, terminal := c.responseTurn(id, selected)
|
||||
if terminal {
|
||||
frames = endFrame(id, selected != nil && selected.endFailed)
|
||||
} else if len(raw) != 0 {
|
||||
frames, err = selected.encodeBatch(&raw)
|
||||
buf.ReleaseMulti(raw)
|
||||
}
|
||||
err = c.writeAndUnlock(frames, err)
|
||||
c.Lock()
|
||||
if err != nil || c.Closed() {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No logical lock spans physical I/O or a codec/address callback.
|
||||
func (c *carrier) writeAndUnlock(frames buf.MultiBuffer, err error) error {
|
||||
if err != nil || c.Closed() {
|
||||
buf.ReleaseMulti(frames)
|
||||
} else if len(frames) != 0 {
|
||||
if r, ok := c.link.Reader.(*responseReader); ok {
|
||||
r.activity.Update()
|
||||
}
|
||||
err = c.link.Writer.WriteMultiBuffer(frames)
|
||||
}
|
||||
if err != nil {
|
||||
c.cancel(err)
|
||||
}
|
||||
c.writeMutex.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *carrier) ActiveConnections() uint32 {
|
||||
c.RLock()
|
||||
defer c.RUnlock()
|
||||
return uint32(c.active)
|
||||
}
|
||||
func (c *carrier) Closed() bool { return c.ctx.Err() != nil }
|
||||
func (c *carrier) WaitClosed() <-chan struct{} { return c.ctx.Done() }
|
||||
|
||||
// Err reports the first close cause, excluding normal cancellation.
|
||||
func (c *carrier) Err() error {
|
||||
err := context.Cause(c.ctx)
|
||||
if err == context.Canceled {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *carrier) Close() error {
|
||||
c.cancel(nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *carrier) shutdown() {
|
||||
c.Lock()
|
||||
c.timer.Stop()
|
||||
c.ready = nil
|
||||
c.control.Broadcast()
|
||||
sessions := c.sessions
|
||||
c.sessions, c.active = nil, 0
|
||||
c.Unlock()
|
||||
for _, s := range sessions {
|
||||
s.abort()
|
||||
}
|
||||
common.Interrupt(c.link.Writer)
|
||||
}
|
||||
|
||||
func (c *carrier) readFrame(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader, accept func(context.Context, *FrameMetadata, *buf.BufferedReader) error) error {
|
||||
var target *Session
|
||||
data := meta.Option.Has(OptionData)
|
||||
switch meta.SessionStatus {
|
||||
case SessionStatusNew:
|
||||
if accept != nil {
|
||||
return accept(session.ContextWithIsReverseMux(ctx, false), meta, reader)
|
||||
}
|
||||
case SessionStatusKeep:
|
||||
if !data {
|
||||
return nil
|
||||
}
|
||||
c.RLock()
|
||||
s, found := c.sessions[meta.SessionID]
|
||||
if found && s.phase == outputOpen {
|
||||
target = s
|
||||
}
|
||||
c.RUnlock()
|
||||
if !found && !c.client {
|
||||
c.unknownEnd(meta.SessionID)
|
||||
}
|
||||
case SessionStatusEnd:
|
||||
c.RLock()
|
||||
s := c.sessions[meta.SessionID]
|
||||
c.RUnlock()
|
||||
if s != nil {
|
||||
s.abort()
|
||||
}
|
||||
case SessionStatusKeepAlive:
|
||||
default:
|
||||
return errors.New("unknown status: ", meta.SessionStatus)
|
||||
}
|
||||
if data {
|
||||
return copyFramePayload(reader, target, meta.Target)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *carrier) run(ctx context.Context, accept func(context.Context, *FrameMetadata, *buf.BufferedReader) error) {
|
||||
var err error
|
||||
defer func() { c.cancel(err) }()
|
||||
reader := &buf.BufferedReader{Reader: c.link.Reader}
|
||||
defer func() { buf.ReleaseMulti(reader.Buffer) }()
|
||||
for !c.Closed() {
|
||||
var meta FrameMetadata
|
||||
err = meta.Unmarshal(reader, session.IsReverseMuxFromContext(ctx))
|
||||
if errors.Cause(err) == io.EOF {
|
||||
err = nil // clean EOF before the next metadata prefix
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
err = frameReadError(c.readFrame(ctx, &meta, reader, accept))
|
||||
}
|
||||
if err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to process multiplex frame")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"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/proxy/vless"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
|
||||
// NormalizeConfig validates the pool settings and returns nil when both pools are off.
|
||||
func NormalizeConfig(config *vless.Multiplex) (*vless.Multiplex, error) {
|
||||
if config.GetConcurrency() < 0 || config.GetXudpConcurrency() < 0 {
|
||||
return nil, errors.New(`multiplex "concurrency" and "xudpConcurrency" must be non-negative`)
|
||||
}
|
||||
switch config.GetXudpProxyUDP443() {
|
||||
case "", "reject", "allow", "skip":
|
||||
default:
|
||||
return nil, errors.New(`unknown "xudpProxyUDP443": `, config.GetXudpProxyUDP443())
|
||||
}
|
||||
if config.GetConcurrency() == 0 && config.GetXudpConcurrency() == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// Client owns the logical stream pools.
|
||||
type Client struct {
|
||||
config *vless.Multiplex
|
||||
tcp *Pool
|
||||
udp *Pool
|
||||
}
|
||||
|
||||
func NewClient(ctx context.Context, config *vless.Multiplex, network string, open func(context.Context) (context.Context, *transport.Link, error)) *Client {
|
||||
c := &Client{config: config}
|
||||
pool := func(concurrency int32) *Pool {
|
||||
return NewPool(ctx, ClientStrategy{MaxConcurrency: uint32(concurrency), MaxConnection: 1024}, open)
|
||||
}
|
||||
if concurrency := config.GetConcurrency(); concurrency > 0 {
|
||||
if network == "xdrive" {
|
||||
concurrency = max(concurrency, 128)
|
||||
}
|
||||
c.tcp = pool(concurrency)
|
||||
}
|
||||
if concurrency := config.GetXudpConcurrency(); concurrency > 0 {
|
||||
c.udp = pool(concurrency)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Client) Dispatch(ctx context.Context, link *transport.Link) (bool, error) {
|
||||
if c == nil {
|
||||
return false, nil
|
||||
}
|
||||
pool := c.tcp
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
target := outbounds[len(outbounds)-1].Target
|
||||
if target.Network == net.Network_UDP && c.udp != nil {
|
||||
pool = c.udp
|
||||
}
|
||||
if pool == nil {
|
||||
return false, nil
|
||||
}
|
||||
if target.Network == net.Network_UDP && target.Port == 443 {
|
||||
switch c.config.GetXudpProxyUDP443() {
|
||||
case "reject", "":
|
||||
return true, errors.New("XUDP rejected UDP/443 traffic")
|
||||
case "skip":
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, Dispatch(ctx, link, pool.Admit)
|
||||
}
|
||||
|
||||
type deferredWriterClose struct{}
|
||||
|
||||
func (deferredWriterClose) Error() string { return "defer link writer close" }
|
||||
func (deferredWriterClose) DeferWriterClose() bool { return true }
|
||||
|
||||
// Dispatch runs a logical child. The caller owns the application endpoints.
|
||||
func Dispatch(ctx context.Context, link *transport.Link, admit func(context.Context, *Session) error, finish ...func(context.Context)) error {
|
||||
s := NewSession(ctx, link)
|
||||
if err := admit(ctx, s); err != nil {
|
||||
return err
|
||||
}
|
||||
go fetchInput(ctx, s)
|
||||
callerDone := ctx.Done()
|
||||
if session.TimeoutOnlyFromContext(ctx) {
|
||||
callerDone = nil
|
||||
}
|
||||
select {
|
||||
case <-callerDone:
|
||||
s.Close()
|
||||
case <-s.WaitClosed():
|
||||
}
|
||||
// The session is sealed. Only a response write already in progress can
|
||||
// still hold the application writer.
|
||||
writingResponse := s.writingResponse.Load()
|
||||
if len(finish) != 0 {
|
||||
if writingResponse {
|
||||
go finish[0](s.parent.ctx)
|
||||
} else {
|
||||
finish[0](s.parent.ctx)
|
||||
}
|
||||
} else if writingResponse {
|
||||
return deferredWriterClose{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Pool serializes unpublished opening with cancelable admission.
|
||||
type Pool struct {
|
||||
ctx context.Context
|
||||
access sync.Mutex
|
||||
opening chan struct{}
|
||||
workers []*ClientWorker
|
||||
strategy ClientStrategy
|
||||
open func(context.Context) (context.Context, *transport.Link, error)
|
||||
}
|
||||
|
||||
// NewPool borrows ctx; open must return a context derived from its input context.
|
||||
func NewPool(ctx context.Context, strategy ClientStrategy, open func(context.Context) (context.Context, *transport.Link, error)) *Pool {
|
||||
return &Pool{ctx: ctx, strategy: strategy, open: open}
|
||||
}
|
||||
|
||||
func (p *Pool) Admit(ctx context.Context, s *Session) error {
|
||||
p.access.Lock()
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
p.access.Unlock()
|
||||
return err
|
||||
}
|
||||
if p.ctx.Err() != nil {
|
||||
p.access.Unlock()
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
for _, worker := range p.workers {
|
||||
if worker.TryAdmit(ctx, s) {
|
||||
p.access.Unlock()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if p.opening == nil {
|
||||
p.opening = make(chan struct{})
|
||||
break
|
||||
}
|
||||
wait := p.opening
|
||||
p.access.Unlock()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-p.ctx.Done():
|
||||
return io.ErrClosedPipe
|
||||
case <-wait:
|
||||
}
|
||||
p.access.Lock()
|
||||
}
|
||||
p.access.Unlock()
|
||||
opening, cancel := context.WithCancel(p.ctx)
|
||||
stopCaller := context.AfterFunc(ctx, cancel)
|
||||
physicalCtx, physicalLink, err := p.open(opening)
|
||||
if !stopCaller() && err == nil {
|
||||
err = context.Canceled
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
err = ctx.Err()
|
||||
}
|
||||
if p.ctx.Err() != nil {
|
||||
err = io.ErrClosedPipe
|
||||
}
|
||||
p.access.Lock()
|
||||
close(p.opening)
|
||||
p.opening = nil
|
||||
var worker *ClientWorker
|
||||
if err == nil {
|
||||
worker = NewClientWorker(physicalCtx, *physicalLink, p.strategy)
|
||||
if !worker.TryAdmit(ctx, s) {
|
||||
err = ctx.Err()
|
||||
if err == nil {
|
||||
err = errors.New("unable to admit multiplex child")
|
||||
}
|
||||
} else {
|
||||
p.workers = append(p.workers, worker)
|
||||
}
|
||||
}
|
||||
p.access.Unlock()
|
||||
if err != nil {
|
||||
cancel()
|
||||
if physicalLink != nil {
|
||||
common.Interrupt(physicalLink.Reader)
|
||||
common.Interrupt(physicalLink.Writer)
|
||||
}
|
||||
return err
|
||||
}
|
||||
context.AfterFunc(worker.ctx, func() {
|
||||
cancel()
|
||||
p.access.Lock()
|
||||
p.workers = slices.DeleteFunc(p.workers, func(current *ClientWorker) bool { return current == worker })
|
||||
p.access.Unlock()
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
type ClientStrategy struct {
|
||||
MaxConcurrency uint32
|
||||
MaxConnection uint32
|
||||
}
|
||||
|
||||
type ClientWorker struct {
|
||||
*carrier
|
||||
strategy ClientStrategy
|
||||
}
|
||||
|
||||
func NewClientWorker(ctx context.Context, stream transport.Link, strategy ClientStrategy) *ClientWorker {
|
||||
c := &ClientWorker{carrier: newCarrier(ctx, stream, 16*time.Second, true), strategy: strategy}
|
||||
go c.run(context.Background(), nil)
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *ClientWorker) TotalConnections() uint32 {
|
||||
c.RLock()
|
||||
defer c.RUnlock()
|
||||
return uint32(c.count)
|
||||
}
|
||||
|
||||
func writeFirstPayload(s *Session) error {
|
||||
err := buf.CopyOnceTimeout(s.input, s, time.Millisecond*100)
|
||||
if err == buf.ErrNotTimeoutReader || err == buf.ErrReadTimeout {
|
||||
return s.WriteMultiBuffer(nil)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func fetchInput(ctx context.Context, s *Session) {
|
||||
var err error
|
||||
defer func() { s.CloseWithError(err) }()
|
||||
errors.LogInfo(ctx, "dispatching request to ", s.target)
|
||||
if err = writeFirstPayload(s); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to write first payload")
|
||||
return
|
||||
}
|
||||
if err = buf.Copy(s.input, s); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to fetch all input")
|
||||
}
|
||||
}
|
||||
|
||||
// TryAdmit publishes this prepared child without input or foreign cleanup.
|
||||
func (m *ClientWorker) TryAdmit(ctx context.Context, s *Session) bool {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
if ctx.Err() != nil || m.Closed() || m.count == 65535 ||
|
||||
(m.strategy.MaxConcurrency > 0 && m.active >= int(m.strategy.MaxConcurrency)) ||
|
||||
(m.strategy.MaxConnection > 0 && uint32(m.count) >= m.strategy.MaxConnection) {
|
||||
return false
|
||||
}
|
||||
s.parent, s.ID, s.phase, s.done = m.carrier, m.count+1, outputOpen, make(chan struct{})
|
||||
return m.admitLocked(s)
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"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/proxy/vless"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
func TestClientUDP443Policy(t *testing.T) {
|
||||
ctx := session.ContextWithOutbounds(t.Context(), []*session.Outbound{{
|
||||
Target: net.UDPDestination(net.LocalHostIP, 443),
|
||||
}})
|
||||
for _, policy := range []string{"reject", "skip"} {
|
||||
t.Run(policy, func(t *testing.T) {
|
||||
opened := false
|
||||
client := NewClient(ctx, &vless.Multiplex{Concurrency: 1, XudpProxyUDP443: policy}, "", func(context.Context) (context.Context, *transport.Link, error) {
|
||||
opened = true
|
||||
return nil, nil, context.Canceled
|
||||
})
|
||||
handled, err := client.Dispatch(ctx, &transport.Link{})
|
||||
wantRejected := policy == "reject"
|
||||
if opened || handled != wantRejected || (err != nil) != wantRejected {
|
||||
t.Fatalf("Dispatch() = (%t, %v), opened carrier = %t, want rejected = %t without opening a carrier", handled, err, opened, wantRejected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWithoutPoolLeavesUDP443ToOutbound(t *testing.T) {
|
||||
ctx := session.ContextWithOutbounds(t.Context(), []*session.Outbound{{
|
||||
Target: net.UDPDestination(net.LocalHostIP, 443),
|
||||
}})
|
||||
client := NewClient(ctx, &vless.Multiplex{XudpProxyUDP443: "reject"}, "", nil)
|
||||
if handled, err := client.Dispatch(ctx, &transport.Link{}); handled || err != nil {
|
||||
t.Fatalf("Dispatch without a pool = (%t, %v), want fallback", handled, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolFailure(t *testing.T) {
|
||||
calls := 0
|
||||
owner, stop := context.WithCancel(context.Background())
|
||||
defer stop()
|
||||
pool := NewPool(owner, ClientStrategy{}, func(context.Context) (context.Context, *transport.Link, error) {
|
||||
calls++
|
||||
return nil, nil, errors.New("test")
|
||||
})
|
||||
ctx := testOutboundContext()
|
||||
s := NewSession(ctx, &transport.Link{Writer: buf.Discard})
|
||||
if err := pool.Admit(ctx, s); err == nil || calls != 1 {
|
||||
t.Fatalf("expected one failed opening, got %d calls and %v", calls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWorkerEOF(t *testing.T) {
|
||||
reader, writer := pipe.New(pipe.WithoutSizeLimit())
|
||||
common.Must(writer.Close())
|
||||
|
||||
worker := NewClientWorker(context.Background(), transport.Link{Reader: reader, Writer: writer}, ClientStrategy{})
|
||||
|
||||
select {
|
||||
case <-worker.WaitClosed():
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("worker did not close after EOF")
|
||||
}
|
||||
|
||||
ctx := testOutboundContext()
|
||||
f := worker.TryAdmit(ctx, NewSession(ctx, &transport.Link{Writer: buf.Discard}))
|
||||
if f {
|
||||
t.Error("expected failed dispatching, but actually not")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWorkerClose(t *testing.T) {
|
||||
r1, w1 := pipe.New(pipe.WithoutSizeLimit())
|
||||
r2, w2 := pipe.New(pipe.WithoutSizeLimit())
|
||||
links := []*transport.Link{{Reader: r1, Writer: w1}, {Reader: r2, Writer: w2}}
|
||||
owner, stop := context.WithCancel(context.Background())
|
||||
defer stop()
|
||||
pool := NewPool(owner, ClientStrategy{MaxConcurrency: 4, MaxConnection: 4}, func(ctx context.Context) (context.Context, *transport.Link, error) {
|
||||
if len(links) == 0 {
|
||||
return nil, nil, errors.New("unexpected opening")
|
||||
}
|
||||
link := links[0]
|
||||
links = links[1:]
|
||||
return ctx, link, nil
|
||||
})
|
||||
ctx := testOutboundContext()
|
||||
worker1 := NewSession(ctx, &transport.Link{Writer: buf.Discard})
|
||||
common.Must(pool.Admit(ctx, worker1))
|
||||
tr1, tw1 := pipe.New(pipe.WithoutSizeLimit())
|
||||
ctx1 := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80)}})
|
||||
child1 := NewSession(ctx1, &transport.Link{Reader: tr1, Writer: tw1})
|
||||
common.Must(pool.Admit(ctx1, child1))
|
||||
go fetchInput(ctx1, child1)
|
||||
defer tw1.Close()
|
||||
common.Must(w1.Close())
|
||||
select {
|
||||
case <-worker1.parent.WaitClosed():
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("first worker did not close")
|
||||
}
|
||||
tr2, tw2 := pipe.New(pipe.WithoutSizeLimit())
|
||||
ctx2 := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80)}})
|
||||
child2 := NewSession(ctx2, &transport.Link{Reader: tr2, Writer: tw2})
|
||||
common.Must(pool.Admit(ctx2, child2))
|
||||
go fetchInput(ctx2, child2)
|
||||
defer tw2.Close()
|
||||
common.Must(w2.Close())
|
||||
}
|
||||
|
||||
func TestClientWorkerUDPSource(t *testing.T) {
|
||||
downR, downW := pipe.New(pipe.WithoutSizeLimit())
|
||||
upR, upW := pipe.New(pipe.WithoutSizeLimit())
|
||||
worker := NewClientWorker(context.Background(), transport.Link{Reader: downR, Writer: upW}, ClientStrategy{})
|
||||
t.Cleanup(func() {
|
||||
worker.Close()
|
||||
downW.Close()
|
||||
upR.Interrupt()
|
||||
})
|
||||
|
||||
inR, inW := pipe.New(pipe.WithoutSizeLimit())
|
||||
outR, outW := pipe.New(pipe.WithoutSizeLimit())
|
||||
t.Cleanup(func() {
|
||||
inW.Close()
|
||||
outR.Interrupt()
|
||||
})
|
||||
ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
|
||||
Target: net.UDPDestination(net.ParseAddress("8.8.8.8"), 53),
|
||||
}})
|
||||
child := NewSession(ctx, &transport.Link{Reader: inR, Writer: outW})
|
||||
if !worker.TryAdmit(ctx, child) {
|
||||
t.Fatal("failed to dispatch")
|
||||
}
|
||||
go fetchInput(ctx, child)
|
||||
b := buf.New()
|
||||
b.WriteString("query")
|
||||
common.Must(inW.WriteMultiBuffer(buf.MultiBuffer{b}))
|
||||
mb, err := upR.ReadMultiBuffer() // New frame, the session is UDP from now on
|
||||
common.Must(err)
|
||||
buf.ReleaseMulti(mb)
|
||||
|
||||
srcs := []net.Destination{
|
||||
net.UDPDestination(net.ParseAddress("1.1.1.1"), 1111),
|
||||
net.UDPDestination(net.DomainAddress("example.com"), 2222),
|
||||
net.UDPDestination(net.ParseAddress("3.3.3.3"), 3333),
|
||||
}
|
||||
response := &Session{ID: 1, target: net.Destination{Network: net.Network_UDP}}
|
||||
var got buf.MultiBuffer
|
||||
defer func() { buf.ReleaseMulti(got) }()
|
||||
for i := range srcs {
|
||||
b := buf.New()
|
||||
b.WriteString("reply")
|
||||
b.UDP = &srcs[i]
|
||||
data := buf.MultiBuffer{b}
|
||||
frames, err := response.encodeBatch(&data)
|
||||
buf.ReleaseMulti(data)
|
||||
if err != nil {
|
||||
buf.ReleaseMulti(frames)
|
||||
t.Fatal(err)
|
||||
}
|
||||
common.Must(downW.WriteMultiBuffer(frames))
|
||||
// keep earlier replies around while the next frame is parsed
|
||||
mb, err := outR.ReadMultiBuffer()
|
||||
common.Must(err)
|
||||
got = append(got, mb...)
|
||||
}
|
||||
if len(got) != len(srcs) {
|
||||
t.Fatalf("received %d replies, want %d", len(got), len(srcs))
|
||||
}
|
||||
for i, b := range got {
|
||||
if string(b.Bytes()) != "reply" {
|
||||
t.Errorf("reply %d: payload = %q", i, b.Bytes())
|
||||
}
|
||||
if b.UDP == nil || *b.UDP != srcs[i] {
|
||||
t.Errorf("reply %d: source = %v, want %v", i, b.UDP, srcs[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testOutboundContext() context.Context {
|
||||
return session.ContextWithOutbounds(context.Background(), []*session.Outbound{{Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80)}})
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/signal"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
|
||||
type responseReader struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
activity *signal.ActivityTimer
|
||||
open func() (buf.Reader, error)
|
||||
body buf.Reader
|
||||
terminal error
|
||||
}
|
||||
|
||||
func (r *responseReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if r.open != nil {
|
||||
r.body, r.terminal = r.open()
|
||||
r.open = nil
|
||||
}
|
||||
for r.terminal == nil {
|
||||
data, err := r.body.ReadMultiBuffer()
|
||||
r.terminal = err
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
buf.ReleaseMulti(data)
|
||||
return nil, err
|
||||
}
|
||||
if !data.IsEmpty() {
|
||||
r.activity.Update()
|
||||
return data, nil
|
||||
}
|
||||
buf.ReleaseMulti(data)
|
||||
}
|
||||
return nil, r.terminal
|
||||
}
|
||||
|
||||
func (r *responseReader) Interrupt() {
|
||||
r.cancel()
|
||||
r.activity.SetTimeout(0)
|
||||
}
|
||||
|
||||
func OpenLink(ctx context.Context, cancel context.CancelFunc, writer buf.Writer, activity *signal.ActivityTimer, openResponse func() (buf.Reader, error)) (*transport.Link, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
cancel()
|
||||
activity.SetTimeout(0)
|
||||
return nil, err
|
||||
}
|
||||
return &transport.Link{Reader: &responseReader{ctx: ctx, cancel: cancel, activity: activity, open: openResponse}, Writer: writer}, nil
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package mux
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
@@ -9,9 +9,8 @@ import (
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/xudp"
|
||||
)
|
||||
|
||||
type SessionStatus byte
|
||||
@@ -35,12 +34,7 @@ const (
|
||||
TargetNetworkUDP TargetNetwork = 0x02
|
||||
)
|
||||
|
||||
var addrParser = protocol.NewAddressParser(
|
||||
protocol.AddressFamilyByte(byte(protocol.AddressTypeIPv4), net.AddressFamilyIPv4),
|
||||
protocol.AddressFamilyByte(byte(protocol.AddressTypeDomain), net.AddressFamilyDomain),
|
||||
protocol.AddressFamilyByte(byte(protocol.AddressTypeIPv6), net.AddressFamilyIPv6),
|
||||
protocol.PortThenAddress(),
|
||||
)
|
||||
var addrParser = xudp.AddrParser
|
||||
|
||||
/*
|
||||
Frame format
|
||||
@@ -85,16 +79,13 @@ func (f FrameMetadata) WriteTo(b *buf.Buffer) error {
|
||||
return err
|
||||
}
|
||||
if f.Inbound != nil {
|
||||
if f.Inbound.Source.Network == net.Network_TCP || f.Inbound.Source.Network == net.Network_UDP {
|
||||
common.Must(b.WriteByte(byte(f.Inbound.Source.Network - 1)))
|
||||
if err := addrParser.WriteAddressPort(b, f.Inbound.Source.Address, f.Inbound.Source.Port); err != nil {
|
||||
return err
|
||||
for _, dst := range [...]net.Destination{f.Inbound.Source, f.Inbound.Local} {
|
||||
if dst.Network != net.Network_TCP && dst.Network != net.Network_UDP {
|
||||
break
|
||||
}
|
||||
if f.Inbound.Local.Network == net.Network_TCP || f.Inbound.Local.Network == net.Network_UDP {
|
||||
common.Must(b.WriteByte(byte(f.Inbound.Local.Network - 1)))
|
||||
if err := addrParser.WriteAddressPort(b, f.Inbound.Local.Address, f.Inbound.Local.Port); err != nil {
|
||||
return err
|
||||
}
|
||||
common.Must(b.WriteByte(byte(dst.Network - 1)))
|
||||
if err := addrParser.WriteAddressPort(b, dst.Address, dst.Port); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else if b.UDP != nil { // make sure it's user's proxy request
|
||||
@@ -112,21 +103,12 @@ func (f FrameMetadata) WriteTo(b *buf.Buffer) error {
|
||||
|
||||
// Unmarshal reads FrameMetadata from the given reader.
|
||||
func (f *FrameMetadata) Unmarshal(reader io.Reader, readSourceAndLocal bool) error {
|
||||
metaLen, err := serial.ReadUint16(reader)
|
||||
b, err := readBlock(reader, 512, "invalid metalen ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if metaLen > 512 {
|
||||
return errors.New("invalid metalen ", metaLen)
|
||||
}
|
||||
|
||||
b := buf.New()
|
||||
defer b.Release()
|
||||
|
||||
if _, err := b.ReadFullFrom(reader, int32(metaLen)); err != nil {
|
||||
return err
|
||||
}
|
||||
return f.UnmarshalFromBuffer(b, readSourceAndLocal)
|
||||
return frameReadError(f.UnmarshalFromBuffer(b, readSourceAndLocal))
|
||||
}
|
||||
|
||||
// UnmarshalFromBuffer reads a FrameMetadata from the given buffer.
|
||||
@@ -146,73 +128,29 @@ func (f *FrameMetadata) UnmarshalFromBuffer(b *buf.Buffer, readSourceAndLocal bo
|
||||
if b.Len() < 8 {
|
||||
return errors.New("insufficient buffer: ", b.Len())
|
||||
}
|
||||
network := TargetNetwork(b.Byte(4))
|
||||
b.Advance(5)
|
||||
|
||||
addr, port, err := addrParser.ReadAddressPort(nil, b)
|
||||
b.Advance(4)
|
||||
target, err := readDestination(b, "")
|
||||
if err != nil {
|
||||
return errors.New("failed to parse address and port").Base(err)
|
||||
}
|
||||
|
||||
switch network {
|
||||
case TargetNetworkTCP:
|
||||
f.Target = net.TCPDestination(addr, port)
|
||||
case TargetNetworkUDP:
|
||||
f.Target = net.UDPDestination(addr, port)
|
||||
default:
|
||||
return errors.New("unknown network type: ", network)
|
||||
return err
|
||||
}
|
||||
f.Target = target
|
||||
}
|
||||
|
||||
if f.SessionStatus == SessionStatusNew && readSourceAndLocal {
|
||||
f.Inbound = &session.Inbound{}
|
||||
|
||||
if b.Len() == 0 {
|
||||
return nil // for heartbeat, etc.
|
||||
for i, dst := range [...]*net.Destination{&f.Inbound.Source, &f.Inbound.Local} {
|
||||
if b.Len() == 0 || b.Byte(0) == 0 { // heartbeat, absent endpoint, or padding
|
||||
break
|
||||
}
|
||||
parsed, err := readDestination(b, [...]string{"reading source: ", "reading local: "}[i])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*dst = parsed
|
||||
}
|
||||
network := TargetNetwork(b.Byte(0))
|
||||
if network == 0 {
|
||||
return nil // may be padding
|
||||
}
|
||||
b.Advance(1)
|
||||
addr, port, err := addrParser.ReadAddressPort(nil, b)
|
||||
if err != nil {
|
||||
return errors.New("reading source: failed to parse address and port").Base(err)
|
||||
}
|
||||
switch network {
|
||||
case TargetNetworkTCP:
|
||||
f.Inbound.Source = net.TCPDestination(addr, port)
|
||||
case TargetNetworkUDP:
|
||||
f.Inbound.Source = net.UDPDestination(addr, port)
|
||||
default:
|
||||
return errors.New("reading source: unknown network type: ", network)
|
||||
}
|
||||
|
||||
if b.Len() == 0 {
|
||||
return nil
|
||||
}
|
||||
network = TargetNetwork(b.Byte(0))
|
||||
if network == 0 {
|
||||
return nil
|
||||
}
|
||||
b.Advance(1)
|
||||
addr, port, err = addrParser.ReadAddressPort(nil, b)
|
||||
if err != nil {
|
||||
return errors.New("reading local: failed to parse address and port").Base(err)
|
||||
}
|
||||
switch network {
|
||||
case TargetNetworkTCP:
|
||||
f.Inbound.Local = net.TCPDestination(addr, port)
|
||||
case TargetNetworkUDP:
|
||||
f.Inbound.Local = net.UDPDestination(addr, port)
|
||||
default:
|
||||
return errors.New("reading local: unknown network type: ", network)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Application data is essential, to test whether the pipe is closed.
|
||||
if f.SessionStatus == SessionStatusNew && f.Option.Has(OptionData) &&
|
||||
f.Target.Network == net.Network_UDP && b.Len() >= 8 {
|
||||
copy(f.GlobalID[:], b.Bytes())
|
||||
@@ -220,3 +158,20 @@ func (f *FrameMetadata) UnmarshalFromBuffer(b *buf.Buffer, readSourceAndLocal bo
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func readDestination(b *buf.Buffer, prefix string) (net.Destination, error) {
|
||||
network := TargetNetwork(b.Byte(0))
|
||||
b.Advance(1)
|
||||
addr, port, err := addrParser.ReadAddressPort(nil, b)
|
||||
if err != nil {
|
||||
return net.Destination{}, errors.New(prefix, "failed to parse address and port").Base(err)
|
||||
}
|
||||
switch network {
|
||||
case TargetNetworkTCP:
|
||||
return net.TCPDestination(addr, port), nil
|
||||
case TargetNetworkUDP:
|
||||
return net.UDPDestination(addr, port), nil
|
||||
default:
|
||||
return net.Destination{}, errors.New(prefix, "unknown network type: ", network)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package multiplex_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
)
|
||||
|
||||
func TestFrameEndpoints(t *testing.T) {
|
||||
target := net.TCPDestination(net.DomainAddress("example.test"), 443)
|
||||
src := net.TCPDestination(net.LocalHostIP, 2053)
|
||||
local := net.UDPDestination(net.ParseAddress("::1"), 5060)
|
||||
// Wire bytes from the codec before consolidating its endpoint decoder.
|
||||
const targetBytes = "000701000101bb020c6578616d706c652e74657374"
|
||||
const sourceBytes = "010805017f000001"
|
||||
const localBytes = "0213c40300000000000000000000000000000001"
|
||||
for _, tc := range []struct {
|
||||
name, wire string
|
||||
input session.Inbound
|
||||
}{
|
||||
{"heartbeat", "0015" + targetBytes, session.Inbound{}},
|
||||
{"source-only", "001d" + targetBytes + sourceBytes, session.Inbound{Source: src}},
|
||||
{"both", "0031" + targetBytes + sourceBytes + localBytes, session.Inbound{Source: src, Local: local}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
frame := multiplex.FrameMetadata{
|
||||
Target: target, SessionID: 7, SessionStatus: multiplex.SessionStatusNew, Inbound: &tc.input,
|
||||
}
|
||||
wire := buf.New()
|
||||
defer wire.Release()
|
||||
if err := frame.WriteTo(wire); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := hex.EncodeToString(wire.Bytes()); got != tc.wire {
|
||||
t.Fatalf("metadata = %s, want %s", got, tc.wire)
|
||||
}
|
||||
reader := io.MultiReader(bytes.NewReader(wire.Bytes()), bytes.NewReader([]byte("payload")))
|
||||
var decoded multiplex.FrameMetadata
|
||||
if err := decoded.Unmarshal(reader, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if decoded.Inbound == nil || decoded.Target != target ||
|
||||
decoded.Inbound.Source != tc.input.Source || decoded.Inbound.Local != tc.input.Local {
|
||||
t.Fatalf("unexpected endpoint metadata: %+v", decoded)
|
||||
}
|
||||
if rest, err := io.ReadAll(reader); err != nil || string(rest) != "payload" {
|
||||
t.Fatalf("payload was consumed with metadata: %q, err = %v", rest, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkFrameWrite(b *testing.B) {
|
||||
frame := multiplex.FrameMetadata{
|
||||
Target: net.TCPDestination(net.DomainAddress("www.example.com"), net.Port(80)),
|
||||
SessionID: 1,
|
||||
SessionStatus: multiplex.SessionStatusNew,
|
||||
}
|
||||
writer := buf.New()
|
||||
defer writer.Release()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
common.Must(frame.WriteTo(writer))
|
||||
writer.Clear()
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package mux_test
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"io"
|
||||
@@ -7,9 +7,8 @@ import (
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
. "github.com/xtls/xray-core/common/mux"
|
||||
"github.com/xtls/xray-core/common/crypto"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
@@ -33,31 +32,38 @@ func TestReaderWriter(t *testing.T) {
|
||||
pReader, pWriter := pipe.New(pipe.WithSizeLimit(1024))
|
||||
|
||||
dest := net.TCPDestination(net.DomainAddress("example.com"), 80)
|
||||
writer := NewWriter(1, dest, pWriter, protocol.TransferTypeStream, [8]byte{}, &session.Inbound{})
|
||||
s1 := &Session{ID: 1, target: dest, inbound: &session.Inbound{}, first: true}
|
||||
|
||||
dest2 := net.TCPDestination(net.LocalHostIP, 443)
|
||||
writer2 := NewWriter(2, dest2, pWriter, protocol.TransferTypeStream, [8]byte{}, &session.Inbound{})
|
||||
s2 := &Session{ID: 2, target: dest2, inbound: &session.Inbound{}, first: true}
|
||||
|
||||
dest3 := net.TCPDestination(net.LocalHostIPv6, 18374)
|
||||
writer3 := NewWriter(3, dest3, pWriter, protocol.TransferTypeStream, [8]byte{}, &session.Inbound{})
|
||||
s3 := &Session{ID: 3, target: dest3, inbound: &session.Inbound{}, first: true}
|
||||
|
||||
writePayload := func(writer *Writer, payload ...byte) error {
|
||||
writePayload := func(s *Session, payload ...byte) error {
|
||||
b := buf.New()
|
||||
b.Write(payload)
|
||||
return writer.WriteMultiBuffer(buf.MultiBuffer{b})
|
||||
data := buf.MultiBuffer{b}
|
||||
defer func() { buf.ReleaseMulti(data) }()
|
||||
frames, err := s.encodeBatch(&data)
|
||||
if err != nil {
|
||||
buf.ReleaseMulti(frames)
|
||||
return err
|
||||
}
|
||||
return pWriter.WriteMultiBuffer(frames)
|
||||
}
|
||||
|
||||
common.Must(writePayload(writer, 'a', 'b', 'c', 'd'))
|
||||
common.Must(writePayload(writer2))
|
||||
common.Must(writePayload(s1, 'a', 'b', 'c', 'd'))
|
||||
common.Must(writePayload(s2))
|
||||
|
||||
common.Must(writePayload(writer, 'e', 'f', 'g', 'h'))
|
||||
common.Must(writePayload(writer3, 'x'))
|
||||
common.Must(writePayload(s1, 'e', 'f', 'g', 'h'))
|
||||
common.Must(writePayload(s3, 'x'))
|
||||
|
||||
writer.Close()
|
||||
writer3.Close()
|
||||
common.Must(pWriter.WriteMultiBuffer(endFrame(s1.ID, false)))
|
||||
common.Must(pWriter.WriteMultiBuffer(endFrame(s3.ID, false)))
|
||||
|
||||
common.Must(writePayload(writer2, 'y'))
|
||||
writer2.Close()
|
||||
common.Must(writePayload(s2, 'y'))
|
||||
common.Must(pWriter.WriteMultiBuffer(endFrame(s2.ID, false)))
|
||||
|
||||
bytesReader := &buf.BufferedReader{Reader: pReader}
|
||||
|
||||
@@ -73,7 +79,7 @@ func TestReaderWriter(t *testing.T) {
|
||||
t.Error("metadata: ", r)
|
||||
}
|
||||
|
||||
data, err := readAll(NewStreamReader(bytesReader))
|
||||
data, err := readAll(crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, bytesReader, 1))
|
||||
common.Must(err)
|
||||
if s := data.String(); s != "abcd" {
|
||||
t.Error("data: ", s)
|
||||
@@ -104,7 +110,7 @@ func TestReaderWriter(t *testing.T) {
|
||||
t.Error("meta: ", r)
|
||||
}
|
||||
|
||||
data, err := readAll(NewStreamReader(bytesReader))
|
||||
data, err := readAll(crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, bytesReader, 1))
|
||||
common.Must(err)
|
||||
if s := data.String(); s != "efgh" {
|
||||
t.Error("data: ", s)
|
||||
@@ -123,7 +129,7 @@ func TestReaderWriter(t *testing.T) {
|
||||
t.Error("meta: ", r)
|
||||
}
|
||||
|
||||
data, err := readAll(NewStreamReader(bytesReader))
|
||||
data, err := readAll(crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, bytesReader, 1))
|
||||
common.Must(err)
|
||||
if s := data.String(); s != "x" {
|
||||
t.Error("data: ", s)
|
||||
@@ -165,7 +171,7 @@ func TestReaderWriter(t *testing.T) {
|
||||
t.Error("meta: ", r)
|
||||
}
|
||||
|
||||
data, err := readAll(NewStreamReader(bytesReader))
|
||||
data, err := readAll(crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, bytesReader, 1))
|
||||
common.Must(err)
|
||||
if s := data.String(); s != "y" {
|
||||
t.Error("data: ", s)
|
||||
@@ -0,0 +1,87 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
)
|
||||
|
||||
// frameReadError distinguishes truncation inside a frame from EOF between frames.
|
||||
func frameReadError(err error) error {
|
||||
if errors.Cause(err) == io.EOF {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// readBlock reads one length-prefixed frame component without retaining a partial buffer.
|
||||
func readBlock(reader io.Reader, limit uint16, oversized string) (*buf.Buffer, error) {
|
||||
size, err := serial.ReadUint16(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if size > limit {
|
||||
return nil, errors.New(oversized, size)
|
||||
}
|
||||
b := buf.New()
|
||||
if _, err := b.ReadFullFrom(reader, int32(size)); err != nil {
|
||||
b.Release()
|
||||
return nil, frameReadError(err)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// readPacket reads one complete packet; its destination belongs to the buffer.
|
||||
func readPacket(reader io.Reader, dest net.Destination) (buf.MultiBuffer, error) {
|
||||
b, err := readBlock(reader, buf.Size, "packet size too large: ")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if dest.Network == net.Network_UDP {
|
||||
b.UDP = &dest
|
||||
}
|
||||
return buf.MultiBuffer{b}, nil
|
||||
}
|
||||
|
||||
// copyFramePayload publishes stream data as it arrives and keeps packets whole.
|
||||
// A closed child discards the remainder without crossing the frame boundary.
|
||||
func copyFramePayload(reader *buf.BufferedReader, s *Session, dest net.Destination) (err error) {
|
||||
packet := s != nil && s.target.Network == net.Network_UDP
|
||||
var left int32
|
||||
if !packet {
|
||||
size, sizeErr := serial.ReadUint16(reader)
|
||||
if sizeErr != nil {
|
||||
return sizeErr
|
||||
}
|
||||
left = int32(size)
|
||||
}
|
||||
for packet || left > 0 {
|
||||
var mb buf.MultiBuffer
|
||||
if packet {
|
||||
mb, err = readPacket(reader, dest)
|
||||
} else {
|
||||
mb, err = reader.ReadAtMost(left)
|
||||
left -= mb.Len()
|
||||
// Coalesce cached pieces without reading more from the transport.
|
||||
for s != nil && left > 0 && reader.BufferedBytes() > 0 {
|
||||
var part buf.MultiBuffer
|
||||
part, err = reader.ReadAtMost(left)
|
||||
left -= part.Len()
|
||||
mb = append(mb, part...)
|
||||
}
|
||||
}
|
||||
if s == nil || mb.IsEmpty() {
|
||||
buf.ReleaseMulti(mb)
|
||||
} else if werr := s.writePayload(mb); werr != nil {
|
||||
s.Interrupt()
|
||||
s = nil
|
||||
}
|
||||
if packet || err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
|
||||
type ServerWorker struct {
|
||||
*carrier
|
||||
dispatch func(context.Context, net.Destination, *transport.Link) error
|
||||
}
|
||||
|
||||
func NewServerWorker(ctx context.Context, dispatch func(context.Context, net.Destination, *transport.Link) error, link *transport.Link) *ServerWorker {
|
||||
w := &ServerWorker{carrier: newCarrier(ctx, *link, 60*time.Second, false), dispatch: dispatch}
|
||||
go w.run(ctx, w.handleStatusNew)
|
||||
return w
|
||||
}
|
||||
|
||||
// A non-nil dispatch return rejects admission; accepted backend failures use the link.
|
||||
func (w *ServerWorker) dispatchFlow(ctx context.Context, dest net.Destination, flow *inboundFlow, output buf.Writer) {
|
||||
if err := w.dispatch(ctx, dest, &transport.Link{Reader: flow, Writer: output}); err != nil {
|
||||
if flow.GlobalID != [8]byte{} {
|
||||
XUDPManager.Lock()
|
||||
if XUDPManager.Map[flow.GlobalID] == flow {
|
||||
delete(XUDPManager.Map, flow.GlobalID)
|
||||
}
|
||||
XUDPManager.Unlock()
|
||||
}
|
||||
w.cancel(err)
|
||||
flow.Interrupt()
|
||||
flow.finish(true)
|
||||
errors.LogInfoInner(ctx, err, "failed to dispatch request to ", dest)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
w.RLock()
|
||||
previous := w.sessions[meta.SessionID]
|
||||
w.RUnlock()
|
||||
if previous != nil {
|
||||
previous.abort()
|
||||
}
|
||||
ctx = session.SubContextFromMuxInbound(ctx)
|
||||
if meta.Inbound != nil && meta.Inbound.Source.IsValid() && meta.Inbound.Local.IsValid() {
|
||||
if inbound := session.InboundFromContext(ctx); inbound != nil {
|
||||
newInbound := *inbound
|
||||
newInbound.Source = meta.Inbound.Source
|
||||
newInbound.Local = meta.Inbound.Local
|
||||
ctx = session.ContextWithInbound(ctx, &newInbound)
|
||||
}
|
||||
}
|
||||
errors.LogInfo(ctx, "received request for ", meta.Target)
|
||||
msg := &log.AccessMessage{
|
||||
To: meta.Target,
|
||||
Status: log.AccessAccepted,
|
||||
}
|
||||
if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() {
|
||||
msg.From = inbound.Source
|
||||
msg.Email = inbound.User.Email
|
||||
}
|
||||
ctx = log.ContextWithAccessMessage(ctx, msg)
|
||||
|
||||
if network := session.AllowedNetworkFromContext(ctx); network != net.Network_Unknown && meta.Target.Network != network {
|
||||
return errors.New("unexpected network ", meta.Target.Network)
|
||||
}
|
||||
|
||||
if meta.GlobalID != [8]byte{} {
|
||||
return w.bindXUDP(ctx, meta, reader)
|
||||
}
|
||||
|
||||
s := &Session{
|
||||
parent: w.carrier, phase: outputOpen,
|
||||
ID: meta.SessionID, target: net.Destination{Network: meta.Target.Network},
|
||||
}
|
||||
s.flow = newInboundFlow(ctx, [8]byte{})
|
||||
s.flow.binding = s
|
||||
w.Lock()
|
||||
admitted := w.admitLocked(s)
|
||||
w.Unlock()
|
||||
if !admitted {
|
||||
s.flow.Interrupt()
|
||||
return errors.New("failed to add new session")
|
||||
}
|
||||
var output buf.Writer = s
|
||||
if meta.Target.Network == net.Network_UDP {
|
||||
output = &flowOutput{s.flow}
|
||||
}
|
||||
go w.dispatchFlow(ctx, meta.Target, s.flow, output)
|
||||
if !meta.Option.Has(OptionData) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return copyFramePayload(reader, s, meta.Target)
|
||||
}
|
||||
@@ -1,15 +1,16 @@
|
||||
package mux_test
|
||||
package multiplex_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
@@ -32,66 +33,51 @@ func newLinkPair() (*transport.Link, *transport.Link) {
|
||||
return uplink, downlink
|
||||
}
|
||||
|
||||
type TestDispatcher struct {
|
||||
OnDispatch func(ctx context.Context, dest net.Destination) (*transport.Link, error)
|
||||
}
|
||||
|
||||
func (d *TestDispatcher) Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) {
|
||||
return d.OnDispatch(ctx, dest)
|
||||
}
|
||||
|
||||
func (d *TestDispatcher) DispatchLink(ctx context.Context, destination net.Destination, outbound *transport.Link) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *TestDispatcher) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *TestDispatcher) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*TestDispatcher) Type() interface{} {
|
||||
return routing.DispatcherType()
|
||||
}
|
||||
|
||||
func TestRegressionOutboundLeak(t *testing.T) {
|
||||
originalOutbounds := []*session.Outbound{{}}
|
||||
serverCtx := session.ContextWithOutbounds(context.Background(), originalOutbounds)
|
||||
|
||||
websiteUplink, websiteDownlink := newLinkPair()
|
||||
|
||||
dispatcher := TestDispatcher{
|
||||
OnDispatch: func(ctx context.Context, dest net.Destination) (*transport.Link, error) {
|
||||
// emulate what DefaultRouter.Dispatch does, and mutate something on the context
|
||||
ob := session.OutboundsFromContext(ctx)[0]
|
||||
ob.Target = dest
|
||||
return websiteDownlink, nil
|
||||
},
|
||||
dispatch := func(ctx context.Context, dest net.Destination, link *transport.Link) error {
|
||||
// Emulate DefaultDispatcher's context mutation while forwarding real data.
|
||||
ob := session.OutboundsFromContext(ctx)[0]
|
||||
ob.Target = dest
|
||||
return task.Run(ctx,
|
||||
func() error { return buf.Copy(link.Reader, websiteDownlink.Writer) },
|
||||
func() error { return buf.Copy(websiteDownlink.Reader, link.Writer) })
|
||||
}
|
||||
|
||||
muxServerUplink, muxServerDownlink := newLinkPair()
|
||||
_, err := mux.NewServerWorker(serverCtx, &dispatcher, muxServerUplink)
|
||||
common.Must(err)
|
||||
multiplexServerUplink, multiplexServerDownlink := newLinkPair()
|
||||
multiplex.NewServerWorker(serverCtx, dispatch, multiplexServerUplink)
|
||||
|
||||
client, err := mux.NewClientWorker(*muxServerDownlink, mux.ClientStrategy{})
|
||||
common.Must(err)
|
||||
client := multiplex.NewClientWorker(context.Background(), *multiplexServerDownlink, multiplex.ClientStrategy{})
|
||||
|
||||
clientCtx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
|
||||
Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80),
|
||||
}})
|
||||
|
||||
muxClientUplink, muxClientDownlink := newLinkPair()
|
||||
multiplexClientUplink, multiplexClientDownlink := newLinkPair()
|
||||
|
||||
ok := client.Dispatch(clientCtx, muxClientUplink)
|
||||
if !ok {
|
||||
t.Error("failed to dispatch")
|
||||
}
|
||||
dispatched := make(chan error, 1)
|
||||
go func() {
|
||||
dispatched <- multiplex.Dispatch(clientCtx, multiplexClientUplink, func(ctx context.Context, s *multiplex.Session) error {
|
||||
if !client.TryAdmit(ctx, s) {
|
||||
return fmt.Errorf("unable to admit test child")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}()
|
||||
defer func() {
|
||||
client.Close()
|
||||
if err := <-dispatched; err != nil {
|
||||
t.Error("failed to dispatch: ", err)
|
||||
}
|
||||
}()
|
||||
|
||||
{
|
||||
b := buf.FromBytes([]byte("hello"))
|
||||
common.Must(muxClientDownlink.Writer.WriteMultiBuffer(buf.MultiBuffer{b}))
|
||||
common.Must(multiplexClientDownlink.Writer.WriteMultiBuffer(buf.MultiBuffer{b}))
|
||||
}
|
||||
|
||||
resMb, err := websiteUplink.Reader.ReadMultiBuffer()
|
||||
@@ -106,7 +92,7 @@ func TestRegressionOutboundLeak(t *testing.T) {
|
||||
common.Must(websiteUplink.Writer.WriteMultiBuffer(buf.MultiBuffer{b}))
|
||||
}
|
||||
|
||||
resMb, err = muxClientDownlink.Reader.ReadMultiBuffer()
|
||||
resMb, err = multiplexClientDownlink.Reader.ReadMultiBuffer()
|
||||
common.Must(err)
|
||||
res = resMb.String()
|
||||
if res != "world" {
|
||||
@@ -0,0 +1,220 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"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/xudp"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
|
||||
// Session has one physical owner. Parent guards phase and registry identity;
|
||||
// Flow is immutable after publication; its retained route can outlive this ID.
|
||||
type Session struct {
|
||||
input buf.Reader
|
||||
output buf.Writer
|
||||
parent *carrier
|
||||
ID uint16
|
||||
target net.Destination
|
||||
globalID [8]byte
|
||||
inbound *session.Inbound
|
||||
first bool
|
||||
endFailed bool // immutable after the first local terminal transition
|
||||
phase byte
|
||||
done chan struct{}
|
||||
flow *inboundFlow
|
||||
producer sync.Mutex
|
||||
|
||||
writingResponse atomic.Bool
|
||||
}
|
||||
|
||||
const (
|
||||
outputStarting = iota
|
||||
outputOpen
|
||||
outputDone
|
||||
)
|
||||
|
||||
// NewSession prepares initiating metadata before any physical admission lock.
|
||||
func NewSession(ctx context.Context, link *transport.Link) *Session {
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
target := outbounds[len(outbounds)-1].Target
|
||||
s := &Session{
|
||||
input: link.Reader, output: link.Writer, target: target,
|
||||
globalID: xudp.GetGlobalID(ctx), first: true,
|
||||
}
|
||||
if session.IsReverseMuxFromContext(ctx) {
|
||||
s.inbound = session.InboundFromContext(ctx)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Initiating input is serial; native server callbacks are serialized per offer.
|
||||
// Existing producers own DATA through direct physical admission.
|
||||
func (s *Session) WriteMultiBuffer(raw buf.MultiBuffer) error {
|
||||
c := s.parent
|
||||
c.RLock()
|
||||
live := !c.Closed() && s.phase == outputOpen && c.sessions[s.ID] == s
|
||||
c.RUnlock()
|
||||
if !live {
|
||||
buf.ReleaseMulti(raw)
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
if !c.client {
|
||||
s.producer.Lock()
|
||||
defer s.producer.Unlock()
|
||||
}
|
||||
defer func() { buf.ReleaseMulti(raw) }()
|
||||
for {
|
||||
c.writeMutex.Lock()
|
||||
c.RLock()
|
||||
live := !c.Closed() && s.phase == outputOpen && c.sessions[s.ID] == s
|
||||
c.RUnlock()
|
||||
var frames buf.MultiBuffer
|
||||
var err error
|
||||
if live {
|
||||
frames, err = s.encodeBatch(&raw)
|
||||
}
|
||||
if err = c.writeAndUnlock(frames, err); err != nil {
|
||||
return err
|
||||
}
|
||||
if !live || c.Closed() {
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Session) writePayload(data buf.MultiBuffer) error {
|
||||
// The flow validates server admission for this immutable binding.
|
||||
x := s.flow
|
||||
if x == nil {
|
||||
s.parent.RLock()
|
||||
live := s.phase == outputOpen || s.phase == outputStarting
|
||||
if live {
|
||||
s.writingResponse.Store(true)
|
||||
}
|
||||
s.parent.RUnlock()
|
||||
if !live {
|
||||
buf.ReleaseMulti(data)
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
defer s.writingResponse.Store(false)
|
||||
return s.output.WriteMultiBuffer(data)
|
||||
}
|
||||
err := x.accept(data, s)
|
||||
if err != nil {
|
||||
buf.ReleaseMulti(data)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Session) Close() error {
|
||||
if s.parent.client {
|
||||
s.close(true)
|
||||
return nil
|
||||
}
|
||||
s.producer.Lock()
|
||||
defer s.producer.Unlock()
|
||||
s.close(false)
|
||||
return nil
|
||||
}
|
||||
func (s *Session) Interrupt() { s.close(true) }
|
||||
func (s *Session) WaitClosed() <-chan struct{} { return s.done }
|
||||
|
||||
func (s *Session) CloseWithError(err error) { s.close(err != nil) }
|
||||
|
||||
func (s *Session) close(failed bool) { s.seal(failed, true) }
|
||||
func (s *Session) abort() { s.seal(false, false) }
|
||||
|
||||
func (s *Session) seal(failed, local bool) {
|
||||
c, x := s.parent, s.flow
|
||||
if x != nil {
|
||||
x.access.Lock()
|
||||
defer x.access.Unlock()
|
||||
}
|
||||
c.Lock()
|
||||
s.closeLocked(x, failed, local)
|
||||
c.Unlock()
|
||||
}
|
||||
|
||||
// closeLocked seals the logical route under flow/carrier ownership. The role's
|
||||
// producer or carrier sender owns END; the first local failure flag is immutable.
|
||||
func (s *Session) closeLocked(x *inboundFlow, failed, local bool) {
|
||||
c := s.parent
|
||||
first := s.phase != outputDone
|
||||
// A borrowed peer pointer must not rewrite a client's first terminal state.
|
||||
if !first && (local || c.client) {
|
||||
return
|
||||
}
|
||||
registered := c.sessions[s.ID] == s
|
||||
if s.phase == outputOpen && registered {
|
||||
c.active--
|
||||
}
|
||||
s.phase = outputDone
|
||||
// A terminal row retained in the registry owns a pending END.
|
||||
if registered && local && !c.Closed() {
|
||||
s.endFailed = failed
|
||||
c.queueReadyLocked(s)
|
||||
} else if registered {
|
||||
delete(c.ready, s.ID)
|
||||
delete(c.sessions, s.ID)
|
||||
}
|
||||
if first {
|
||||
if s.done != nil {
|
||||
close(s.done)
|
||||
}
|
||||
if x != nil && x.binding == s {
|
||||
x.binding = nil
|
||||
if x.GlobalID == [8]byte{} {
|
||||
if x.requestErr == nil {
|
||||
x.requestErr = io.EOF
|
||||
}
|
||||
x.responseErr = io.ErrClosedPipe
|
||||
x.response = buf.ReleaseMulti(x.response)
|
||||
x.responseWake.Broadcast()
|
||||
} else {
|
||||
x.Expire = time.Now().Add(time.Minute)
|
||||
}
|
||||
x.requestWake.Broadcast()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var XUDPManager = struct {
|
||||
sync.Mutex
|
||||
Map map[[8]byte]*inboundFlow
|
||||
}{Map: make(map[[8]byte]*inboundFlow)}
|
||||
|
||||
func init() { time.AfterFunc(time.Minute, scheduleXUDPSweep) }
|
||||
|
||||
func scheduleXUDPSweep() {
|
||||
sweepXUDP(time.Now())
|
||||
time.AfterFunc(time.Minute, scheduleXUDPSweep)
|
||||
}
|
||||
|
||||
func sweepXUDP(now time.Time) {
|
||||
var expired []*inboundFlow
|
||||
XUDPManager.Lock()
|
||||
for id, x := range XUDPManager.Map {
|
||||
x.access.Lock()
|
||||
if x.binding == nil && !x.Expire.IsZero() && now.After(x.Expire) {
|
||||
expired = append(expired, x)
|
||||
delete(XUDPManager.Map, id)
|
||||
}
|
||||
x.access.Unlock()
|
||||
}
|
||||
XUDPManager.Unlock()
|
||||
for _, x := range expired {
|
||||
errors.LogDebug(context.Background(), "XUDP del ", x.GlobalID)
|
||||
x.expire()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
func TestCarrierAdmission(t *testing.T) {
|
||||
reader, writer := pipe.New(pipe.WithoutSizeLimit())
|
||||
worker := NewClientWorker(context.Background(), transport.Link{Reader: reader, Writer: buf.Discard}, ClientStrategy{})
|
||||
t.Cleanup(func() { worker.Close(); writer.Close() })
|
||||
for id := uint16(1); id <= 2; id++ {
|
||||
ctx := testOutboundContext()
|
||||
s := NewSession(ctx, &transport.Link{Writer: buf.Discard})
|
||||
if !worker.TryAdmit(ctx, s) || s.ID != id {
|
||||
t.Fatalf("id%d: %v", id, s)
|
||||
}
|
||||
if worker.ActiveConnections() != uint32(id) {
|
||||
t.Fatalf("active: %d", worker.ActiveConnections())
|
||||
}
|
||||
}
|
||||
// Preserve the original explicit-ID publication assertion, with a fully
|
||||
// initialized real physical owner instead of a standalone manager facade.
|
||||
s := &Session{ID: 4, parent: worker.carrier, output: buf.Discard, done: make(chan struct{}), phase: outputOpen}
|
||||
worker.Lock()
|
||||
admitted := worker.admitLocked(s)
|
||||
indexed := worker.sessions[4] == s
|
||||
worker.Unlock()
|
||||
if !admitted || !indexed || s.ID != 4 || worker.ActiveConnections() != 3 {
|
||||
t.Fatal("explicit wire identity not admitted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCarrierIdleRetirement(t *testing.T) {
|
||||
reader, writer := pipe.New(pipe.WithoutSizeLimit())
|
||||
worker := &ClientWorker{carrier: newCarrier(context.Background(), transport.Link{Reader: reader, Writer: buf.Discard}, 20*time.Millisecond, true)}
|
||||
go worker.run(context.Background(), nil)
|
||||
t.Cleanup(func() { worker.Close(); writer.Close() })
|
||||
ctx := testOutboundContext()
|
||||
s := NewSession(ctx, &transport.Link{Writer: buf.Discard})
|
||||
if !worker.TryAdmit(ctx, s) {
|
||||
t.Fatal("session not admitted")
|
||||
}
|
||||
select {
|
||||
case <-worker.WaitClosed():
|
||||
t.Fatal("active carrier retired")
|
||||
case <-time.After(65 * time.Millisecond):
|
||||
}
|
||||
s.Close()
|
||||
select {
|
||||
case <-worker.WaitClosed():
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("empty carrier did not retire")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
)
|
||||
|
||||
// encodeBatch moves up to four complete wire frames from raw caller custody.
|
||||
// An offer without buffers contains metadata only.
|
||||
func (s *Session) encodeBatch(mb *buf.MultiBuffer) (frames buf.MultiBuffer, err error) {
|
||||
stream := s.target.Network != net.Network_UDP
|
||||
if stream && (*mb).IsEmpty() {
|
||||
*mb = buf.ReleaseMulti(*mb)
|
||||
}
|
||||
for n := 0; n < 4 && (s.first || len(*mb) != 0); n++ {
|
||||
frame := buf.NewWithSize(1024)
|
||||
frames = append(frames, frame)
|
||||
meta := FrameMetadata{
|
||||
SessionID: s.ID, Target: s.target, GlobalID: s.globalID,
|
||||
Inbound: s.inbound, SessionStatus: SessionStatusKeep,
|
||||
}
|
||||
if s.first {
|
||||
s.first = false
|
||||
meta.SessionStatus = SessionStatusNew
|
||||
}
|
||||
if len(*mb) == 0 {
|
||||
return frames, meta.WriteTo(frame)
|
||||
}
|
||||
var chunk buf.MultiBuffer
|
||||
if stream {
|
||||
*mb, chunk = buf.SplitSize(*mb, 8*1024)
|
||||
} else {
|
||||
mb2, b := buf.SplitFirst(*mb)
|
||||
*mb = mb2
|
||||
chunk = buf.MultiBuffer{b}
|
||||
}
|
||||
if len(chunk) == 1 {
|
||||
frame.UDP = chunk[0].UDP
|
||||
}
|
||||
frames = append(frames, chunk...)
|
||||
meta.Option.Set(OptionData)
|
||||
if err := meta.WriteTo(frame); err != nil {
|
||||
return frames, err
|
||||
}
|
||||
if _, err := serial.WriteUint16(frame, uint16(chunk.Len())); err != nil {
|
||||
return frames, err
|
||||
}
|
||||
}
|
||||
return frames, nil
|
||||
}
|
||||
|
||||
func endFrame(id uint16, failed bool) buf.MultiBuffer {
|
||||
meta := FrameMetadata{SessionID: id, SessionStatus: SessionStatusEnd}
|
||||
if failed {
|
||||
meta.Option.Set(OptionError)
|
||||
}
|
||||
frame := buf.NewWithSize(1024)
|
||||
common.Must(meta.WriteTo(frame))
|
||||
return buf.MultiBuffer{frame}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"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/features/policy"
|
||||
"github.com/xtls/xray-core/features/stats"
|
||||
)
|
||||
|
||||
// inboundFlow owns native route input and persistent binding state. Its response
|
||||
// packet response mailbox retains native bytes until the physical sender claims them.
|
||||
// Locks nest association map -> flow -> one carrier; I/O is outside them.
|
||||
type inboundFlow struct {
|
||||
access sync.Mutex
|
||||
|
||||
requestWake, responseWake sync.Cond
|
||||
request, response buf.MultiBuffer
|
||||
requestErr, responseErr error
|
||||
uplinkCounter stats.Counter
|
||||
uplinkPending int64
|
||||
uplinkBound bool
|
||||
limit int32
|
||||
binding *Session
|
||||
GlobalID [8]byte
|
||||
Expire time.Time
|
||||
}
|
||||
|
||||
func newInboundFlow(ctx context.Context, id [8]byte) *inboundFlow {
|
||||
x := &inboundFlow{limit: policy.BufferPolicyFromContext(ctx).PerConnection, GlobalID: id}
|
||||
x.requestWake.L, x.responseWake.L = &x.access, &x.access
|
||||
return x
|
||||
}
|
||||
|
||||
// SetUplinkCounter binds attempted-input accounting once, including disabled stats.
|
||||
func (x *inboundFlow) SetUplinkCounter(counter stats.Counter) {
|
||||
x.access.Lock()
|
||||
if x.uplinkBound {
|
||||
x.access.Unlock()
|
||||
return
|
||||
}
|
||||
x.uplinkCounter, x.uplinkBound = counter, true
|
||||
pending := x.uplinkPending
|
||||
x.uplinkPending = 0
|
||||
x.access.Unlock()
|
||||
if counter != nil && pending != 0 {
|
||||
counter.Add(pending)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *inboundFlow) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
x.access.Lock()
|
||||
defer x.access.Unlock()
|
||||
return x.readLocked(nil)
|
||||
}
|
||||
|
||||
func (x *inboundFlow) ReadMultiBufferTimeout(duration time.Duration) (buf.MultiBuffer, error) {
|
||||
x.access.Lock()
|
||||
defer x.access.Unlock()
|
||||
if len(x.request) > 0 || x.requestErr != nil {
|
||||
return x.readLocked(nil)
|
||||
}
|
||||
timedOut := false
|
||||
timer := time.AfterFunc(duration, func() {
|
||||
x.access.Lock()
|
||||
timedOut = true
|
||||
x.requestWake.Broadcast()
|
||||
x.access.Unlock()
|
||||
})
|
||||
defer timer.Stop()
|
||||
return x.readLocked(&timedOut)
|
||||
}
|
||||
|
||||
// readLocked has no timeout closure or escaping flag on ordinary native reads.
|
||||
func (x *inboundFlow) readLocked(timedOut *bool) (buf.MultiBuffer, error) {
|
||||
for len(x.request) == 0 && x.requestErr == nil && (timedOut == nil || !*timedOut) {
|
||||
x.requestWake.Wait()
|
||||
}
|
||||
if len(x.request) > 0 {
|
||||
data := x.request
|
||||
x.request = nil
|
||||
x.requestWake.Broadcast()
|
||||
return data, nil
|
||||
}
|
||||
if x.requestErr != nil {
|
||||
return nil, x.requestErr
|
||||
}
|
||||
return nil, buf.ErrReadTimeout
|
||||
}
|
||||
|
||||
// accept leaves rejected data with the parser so a failed retained route can
|
||||
// restart with the very same first packet and destination.
|
||||
func (x *inboundFlow) accept(data buf.MultiBuffer, binding *Session) error {
|
||||
x.access.Lock()
|
||||
if !x.uplinkBound {
|
||||
x.uplinkPending += int64(data.Len())
|
||||
} else if counter := x.uplinkCounter; counter != nil {
|
||||
x.access.Unlock()
|
||||
counter.Add(int64(data.Len()))
|
||||
x.access.Lock()
|
||||
}
|
||||
defer x.access.Unlock()
|
||||
for {
|
||||
if x.requestErr != nil || x.binding != binding || binding.parent.Closed() {
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
if x.limit < 0 || x.request.Len() <= x.limit {
|
||||
if len(x.request) == 0 {
|
||||
x.request = data
|
||||
} else {
|
||||
x.request, _ = buf.MergeMulti(x.request, data)
|
||||
}
|
||||
x.requestWake.Broadcast()
|
||||
return nil
|
||||
}
|
||||
x.requestWake.Wait()
|
||||
}
|
||||
}
|
||||
|
||||
// Interrupt is native request abort. Ordinary wire EOF instead seals this
|
||||
// input in Session.close, preserving payload already accepted from the parser.
|
||||
func (x *inboundFlow) Interrupt() {
|
||||
x.access.Lock()
|
||||
x.requestErr = io.ErrClosedPipe
|
||||
x.request = buf.ReleaseMulti(x.request)
|
||||
x.requestWake.Broadcast()
|
||||
x.access.Unlock()
|
||||
}
|
||||
|
||||
type flowOutput struct{ *inboundFlow }
|
||||
|
||||
func (w *flowOutput) Interrupt() { w.finish(true) }
|
||||
func (w *flowOutput) Close() error { w.finish(false); return nil }
|
||||
func (x *inboundFlow) finish(abort bool) {
|
||||
x.access.Lock()
|
||||
if abort {
|
||||
x.responseErr = io.ErrClosedPipe
|
||||
x.response = buf.ReleaseMulti(x.response)
|
||||
} else if x.responseErr == nil {
|
||||
x.responseErr = io.EOF
|
||||
}
|
||||
if s := x.binding; s != nil {
|
||||
c := s.parent
|
||||
c.Lock()
|
||||
if abort && s.phase == outputOpen {
|
||||
s.closeLocked(x, true, true)
|
||||
} else {
|
||||
c.scheduleLocked(s)
|
||||
}
|
||||
c.Unlock()
|
||||
}
|
||||
x.responseWake.Broadcast()
|
||||
x.access.Unlock()
|
||||
}
|
||||
|
||||
func (x *inboundFlow) expire() {
|
||||
x.access.Lock()
|
||||
if x.requestErr == nil {
|
||||
x.requestErr = io.EOF
|
||||
x.requestWake.Broadcast()
|
||||
}
|
||||
x.access.Unlock()
|
||||
x.finish(true)
|
||||
}
|
||||
|
||||
// WriteMultiBuffer admits the whole raw offer under the original soft policy.
|
||||
// Response-capacity waiters are separate from request readers.
|
||||
func (w *flowOutput) WriteMultiBuffer(data buf.MultiBuffer) error {
|
||||
x := w.inboundFlow
|
||||
x.access.Lock()
|
||||
defer x.access.Unlock()
|
||||
for x.responseErr == nil && x.limit >= 0 && x.response.Len() > x.limit {
|
||||
x.responseWake.Wait()
|
||||
}
|
||||
if x.responseErr != nil {
|
||||
buf.ReleaseMulti(data)
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
if data.IsEmpty() {
|
||||
buf.ReleaseMulti(data)
|
||||
return nil
|
||||
}
|
||||
if len(x.response) == 0 {
|
||||
x.response = data
|
||||
} else {
|
||||
x.response, _ = buf.MergeMulti(x.response, data)
|
||||
}
|
||||
if s := x.binding; s != nil {
|
||||
s.parent.Lock()
|
||||
s.parent.scheduleLocked(s)
|
||||
s.parent.Unlock()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// packetReady is checked with the flow and carrier locked.
|
||||
func (s *Session) packetReady() bool {
|
||||
x := s.flow
|
||||
return x != nil && x.binding == s &&
|
||||
(s.phase == outputOpen && (len(x.response) != 0 || x.responseErr != nil) ||
|
||||
s.phase == outputStarting && x.requestErr == nil && len(x.response) != 0)
|
||||
}
|
||||
|
||||
// One gated actor claims packet data or retires one exact terminal identity.
|
||||
// It returns custody only; the sender encodes after both logical locks release.
|
||||
func (c *carrier) responseTurn(id uint16, s *Session) (buf.MultiBuffer, bool) {
|
||||
if s != nil && s.flow != nil {
|
||||
s.flow.access.Lock()
|
||||
defer s.flow.access.Unlock()
|
||||
}
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
if c.Closed() {
|
||||
return nil, false
|
||||
}
|
||||
if s == nil {
|
||||
return nil, c.invalidateUnknownLocked(id)
|
||||
}
|
||||
if c.sessions[id] != s {
|
||||
return nil, false
|
||||
}
|
||||
x := s.flow
|
||||
ready := s.packetReady()
|
||||
if ready && len(x.response) == 0 {
|
||||
s.closeLocked(x, x.responseErr == io.ErrClosedPipe, true)
|
||||
}
|
||||
if s.phase == outputDone {
|
||||
delete(c.ready, s.ID)
|
||||
delete(c.sessions, s.ID)
|
||||
return nil, true
|
||||
}
|
||||
if !ready {
|
||||
delete(c.ready, s.ID)
|
||||
return nil, false
|
||||
}
|
||||
n := min(4, len(x.response))
|
||||
data := x.response[:n:n]
|
||||
x.response = x.response[n:]
|
||||
if len(x.response) == 0 {
|
||||
x.response = nil
|
||||
}
|
||||
x.responseWake.Broadcast()
|
||||
// A terminal follow-up cannot run until this DATA turn completes physically.
|
||||
if !s.packetReady() {
|
||||
delete(c.ready, s.ID)
|
||||
}
|
||||
return data, false
|
||||
}
|
||||
|
||||
func (w *ServerWorker) bindXUDP(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
data, err := readPacket(reader, meta.Target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx = session.ContextWithTimeoutOnly(ctx, true)
|
||||
XUDPManager.Lock()
|
||||
for {
|
||||
x := XUDPManager.Map[meta.GlobalID]
|
||||
fresh := x == nil
|
||||
if fresh {
|
||||
x = newInboundFlow(ctx, meta.GlobalID)
|
||||
}
|
||||
x.access.Lock()
|
||||
if previous := x.binding; previous != nil {
|
||||
previous.parent.Lock()
|
||||
if previous.phase == outputStarting {
|
||||
previous.parent.Unlock()
|
||||
x.access.Unlock()
|
||||
XUDPManager.Unlock()
|
||||
buf.ReleaseMulti(data)
|
||||
errors.LogWarningInner(ctx, errors.New("conflict"), "XUDP hit ", meta.GlobalID)
|
||||
return nil
|
||||
}
|
||||
previous.closeLocked(x, true, true)
|
||||
previous.parent.Unlock()
|
||||
}
|
||||
w.Lock()
|
||||
if w.Closed() || w.sessions[meta.SessionID] != nil {
|
||||
w.Unlock()
|
||||
x.access.Unlock()
|
||||
XUDPManager.Unlock()
|
||||
buf.ReleaseMulti(data)
|
||||
return errors.New("failed to add new session")
|
||||
}
|
||||
s := &Session{
|
||||
parent: w.carrier, ID: meta.SessionID, phase: outputStarting,
|
||||
target: net.Destination{Network: net.Network_UDP}, flow: x,
|
||||
}
|
||||
w.invalidateUnknownLocked(s.ID)
|
||||
w.sessions[s.ID] = s
|
||||
XUDPManager.Map[meta.GlobalID] = x
|
||||
x.binding, x.Expire = s, time.Time{}
|
||||
w.scheduleLocked(s)
|
||||
w.Unlock()
|
||||
x.access.Unlock()
|
||||
XUDPManager.Unlock()
|
||||
if fresh {
|
||||
go w.dispatchFlow(ctx, meta.Target, x, &flowOutput{x})
|
||||
}
|
||||
err = x.accept(data, s)
|
||||
|
||||
XUDPManager.Lock()
|
||||
x.access.Lock()
|
||||
w.Lock()
|
||||
live := !w.Closed() && w.sessions[s.ID] == s && x.binding == s && s.phase == outputStarting
|
||||
current := XUDPManager.Map[meta.GlobalID]
|
||||
restart := err != nil && !fresh
|
||||
retry := restart && live && (current == x || current == nil)
|
||||
admitted := live && current == x
|
||||
if restart {
|
||||
s.closeLocked(x, false, false)
|
||||
if retry {
|
||||
x.responseErr = io.ErrClosedPipe
|
||||
x.response = buf.ReleaseMulti(x.response)
|
||||
x.responseWake.Broadcast()
|
||||
delete(XUDPManager.Map, meta.GlobalID)
|
||||
}
|
||||
} else if admitted {
|
||||
w.count++
|
||||
if x.responseErr == nil || len(x.response) != 0 {
|
||||
s.phase = outputOpen
|
||||
w.active++
|
||||
} else {
|
||||
s.closeLocked(x, x.responseErr == io.ErrClosedPipe, true)
|
||||
}
|
||||
w.scheduleLocked(s)
|
||||
}
|
||||
w.Unlock()
|
||||
x.access.Unlock()
|
||||
if retry {
|
||||
// Keep the manager lock until the replacement is registered.
|
||||
continue
|
||||
}
|
||||
XUDPManager.Unlock()
|
||||
if err != nil {
|
||||
buf.ReleaseMulti(data)
|
||||
}
|
||||
if restart {
|
||||
if !live {
|
||||
return nil
|
||||
}
|
||||
x.expire()
|
||||
}
|
||||
if restart || !admitted {
|
||||
s.abort()
|
||||
return errors.New("failed to add new session")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ package outbound
|
||||
|
||||
import (
|
||||
protocol "github.com/xtls/xray-core/common/protocol"
|
||||
vless "github.com/xtls/xray-core/proxy/vless"
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
@@ -25,6 +26,7 @@ const (
|
||||
type Config struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Vnext *protocol.ServerEndpoint `protobuf:"bytes,1,opt,name=vnext,proto3" json:"vnext,omitempty"`
|
||||
Multiplex *vless.Multiplex `protobuf:"bytes,2,opt,name=multiplex,proto3" json:"multiplex,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -66,13 +68,21 @@ func (x *Config) GetVnext() *protocol.ServerEndpoint {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Config) GetMultiplex() *vless.Multiplex {
|
||||
if x != nil {
|
||||
return x.Multiplex
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_proxy_vless_outbound_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_proxy_vless_outbound_config_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"!proxy/vless/outbound/config.proto\x12\x19xray.proxy.vless.outbound\x1a!common/protocol/server_spec.proto\"D\n" +
|
||||
"!proxy/vless/outbound/config.proto\x12\x19xray.proxy.vless.outbound\x1a!common/protocol/server_spec.proto\x1a\x19proxy/vless/account.proto\"\x7f\n" +
|
||||
"\x06Config\x12:\n" +
|
||||
"\x05vnext\x18\x01 \x01(\v2$.xray.common.protocol.ServerEndpointR\x05vnextBm\n" +
|
||||
"\x05vnext\x18\x01 \x01(\v2$.xray.common.protocol.ServerEndpointR\x05vnext\x129\n" +
|
||||
"\tmultiplex\x18\x02 \x01(\v2\x1b.xray.proxy.vless.MultiplexR\tmultiplexBm\n" +
|
||||
"\x1dcom.xray.proxy.vless.outboundP\x01Z.github.com/xtls/xray-core/proxy/vless/outbound\xaa\x02\x19Xray.Proxy.Vless.Outboundb\x06proto3"
|
||||
|
||||
var (
|
||||
@@ -91,14 +101,16 @@ var file_proxy_vless_outbound_config_proto_msgTypes = make([]protoimpl.MessageIn
|
||||
var file_proxy_vless_outbound_config_proto_goTypes = []any{
|
||||
(*Config)(nil), // 0: xray.proxy.vless.outbound.Config
|
||||
(*protocol.ServerEndpoint)(nil), // 1: xray.common.protocol.ServerEndpoint
|
||||
(*vless.Multiplex)(nil), // 2: xray.proxy.vless.Multiplex
|
||||
}
|
||||
var file_proxy_vless_outbound_config_proto_depIdxs = []int32{
|
||||
1, // 0: xray.proxy.vless.outbound.Config.vnext:type_name -> xray.common.protocol.ServerEndpoint
|
||||
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
|
||||
2, // 1: xray.proxy.vless.outbound.Config.multiplex:type_name -> xray.proxy.vless.Multiplex
|
||||
2, // [2:2] is the sub-list for method output_type
|
||||
2, // [2:2] is the sub-list for method input_type
|
||||
2, // [2:2] is the sub-list for extension type_name
|
||||
2, // [2:2] is the sub-list for extension extendee
|
||||
0, // [0:2] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_proxy_vless_outbound_config_proto_init() }
|
||||
|
||||
@@ -7,7 +7,9 @@ option java_package = "com.xray.proxy.vless.outbound";
|
||||
option java_multiple_files = true;
|
||||
|
||||
import "common/protocol/server_spec.proto";
|
||||
import "proxy/vless/account.proto";
|
||||
|
||||
message Config {
|
||||
xray.common.protocol.ServerEndpoint vnext = 1;
|
||||
xray.proxy.vless.Multiplex multiplex = 2;
|
||||
}
|
||||
|
||||
+182
-183
@@ -9,15 +9,11 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
utls "github.com/refraction-networking/utls"
|
||||
proxymanConfig "github.com/xtls/xray-core/app/proxyman"
|
||||
proxyman "github.com/xtls/xray-core/app/proxyman/outbound"
|
||||
"github.com/xtls/xray-core/app/reverse"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
xctx "github.com/xtls/xray-core/common/ctx"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/retry"
|
||||
@@ -32,12 +28,13 @@ import (
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/proxy/vless/encoding"
|
||||
"github.com/xtls/xray-core/proxy/vless/encryption"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/proxy/vless/reverse"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/internet/reality"
|
||||
"github.com/xtls/xray-core/transport/internet/stat"
|
||||
"github.com/xtls/xray-core/transport/internet/tls"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -51,7 +48,10 @@ type Handler struct {
|
||||
server *protocol.ServerSpec
|
||||
policyManager policy.Manager
|
||||
encryption *encryption.ClientInstance
|
||||
reverse *Reverse
|
||||
closeReverse func()
|
||||
ctx context.Context
|
||||
stop context.CancelFunc
|
||||
multiplex *multiplex.Client
|
||||
|
||||
testpre uint32
|
||||
initpre sync.Once
|
||||
@@ -73,13 +73,24 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
|
||||
return nil, errors.New("failed to get server spec").Base(err)
|
||||
}
|
||||
|
||||
muxConfig, err := multiplex.NormalizeConfig(config.Multiplex)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a := server.User.Account.(*vless.MemoryAccount)
|
||||
dialer, _ := session.FullHandlerFromContext(ctx).(internet.Dialer)
|
||||
if dialer == nil && (a.Reverse != nil || muxConfig != nil) {
|
||||
return nil, errors.New("VLESS Reverse or multiplex requires an outbound dialer")
|
||||
}
|
||||
|
||||
v := core.MustFromContext(ctx)
|
||||
handler := &Handler{
|
||||
server: server,
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
}
|
||||
|
||||
a := handler.server.User.Account.(*vless.MemoryAccount)
|
||||
handler.ctx, handler.stop = context.WithCancel(context.Background())
|
||||
|
||||
if a.Encryption != "" && a.Encryption != "none" {
|
||||
s := strings.Split(a.Encryption, ".")
|
||||
var nfsPKeysBytes [][]byte
|
||||
@@ -93,11 +104,14 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
|
||||
}
|
||||
}
|
||||
|
||||
if a.Reverse != nil {
|
||||
if a.Reverse == nil {
|
||||
handler.testpre = a.Testpre
|
||||
} else {
|
||||
rvsCtx := session.ContextWithInbound(ctx, &session.Inbound{
|
||||
Tag: a.Reverse.Tag,
|
||||
Name: "vless-reverse",
|
||||
User: handler.server.User, // TODO: email
|
||||
Tag: a.Reverse.Tag,
|
||||
Name: "vless-reverse",
|
||||
User: handler.server.User, // TODO: email
|
||||
CanSpliceCopy: 3,
|
||||
})
|
||||
if sc := a.Reverse.Sniffing; sc != nil && sc.Enabled {
|
||||
request, err := proxymanConfig.BuildSniffingRequest(sc)
|
||||
@@ -108,73 +122,106 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
|
||||
SniffingRequest: request,
|
||||
})
|
||||
}
|
||||
handler.reverse = &Reverse{
|
||||
tag: a.Reverse.Tag,
|
||||
dispatcher: v.GetFeature(routing.DispatcherType()).(routing.Dispatcher),
|
||||
ctx: rvsCtx,
|
||||
handler: handler,
|
||||
}
|
||||
handler.reverse.monitorTask = &task.Periodic{
|
||||
Execute: handler.reverse.monitor,
|
||||
Interval: time.Second * 2,
|
||||
}
|
||||
go func() {
|
||||
time.Sleep(2 * time.Second)
|
||||
handler.reverse.Start()
|
||||
}()
|
||||
handler.closeReverse = reverse.StartIntranet(rvsCtx,
|
||||
v.GetFeature(routing.DispatcherType()).(routing.Dispatcher).DispatchLink,
|
||||
func(ctx context.Context) (context.Context, *transport.Link, error) {
|
||||
return handler.process(ctx, nil, dialer, protocol.RequestCommandRvs)
|
||||
})
|
||||
}
|
||||
|
||||
handler.testpre = a.Testpre
|
||||
if muxConfig != nil {
|
||||
network := ""
|
||||
if settings, ok := session.StreamSettingsFromContext(ctx).(*internet.MemoryStreamConfig); ok {
|
||||
network = settings.ProtocolName
|
||||
}
|
||||
handler.multiplex = multiplex.NewClient(handler.ctx, muxConfig, network,
|
||||
func(ctx context.Context) (context.Context, *transport.Link, error) {
|
||||
return handler.process(ctx, nil, dialer, protocol.RequestCommandMux)
|
||||
})
|
||||
}
|
||||
|
||||
return handler, nil
|
||||
}
|
||||
|
||||
// Close implements common.Closable.Close().
|
||||
func (h *Handler) Close() error {
|
||||
if h.preConns != nil {
|
||||
close(h.preConns)
|
||||
}
|
||||
if h.reverse != nil {
|
||||
return h.reverse.Close()
|
||||
h.stop()
|
||||
if h.closeReverse != nil {
|
||||
h.closeReverse()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Process implements proxy.Outbound.Process().
|
||||
func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
|
||||
if handled, err := h.multiplex.Dispatch(ctx, link); handled {
|
||||
return err
|
||||
}
|
||||
_, _, err := h.process(ctx, link, dialer, 0)
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *Handler) process(ctx context.Context, link *transport.Link, dialer internet.Dialer, command protocol.RequestCommand) (nativeCtx context.Context, nativeLink *transport.Link, err error) {
|
||||
native := command != 0
|
||||
if native {
|
||||
ctx = session.ContextWithOutbounds(ctx, []*session.Outbound{{Target: h.server.Destination}})
|
||||
}
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
var rawConn stat.Connection
|
||||
var timer *signal.ActivityTimer
|
||||
defer func() {
|
||||
if !native || err != nil {
|
||||
if timer != nil {
|
||||
timer.SetTimeout(0)
|
||||
}
|
||||
cancel()
|
||||
if rawConn != nil {
|
||||
rawConn.Close()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
ob := outbounds[len(outbounds)-1]
|
||||
if !ob.Target.IsValid() && ob.Target.Address.String() != "v1.rvs.cool" {
|
||||
return errors.New("target not specified")
|
||||
if !ob.Target.IsValid() {
|
||||
return nil, nil, errors.New("target not specified")
|
||||
}
|
||||
ob.Name = "vless"
|
||||
|
||||
rec := h.server
|
||||
var conn stat.Connection
|
||||
|
||||
if h.testpre > 0 && h.reverse == nil {
|
||||
if h.testpre > 0 {
|
||||
h.initpre.Do(func() {
|
||||
h.preConns = make(chan *ConnExpire)
|
||||
for range h.testpre { // TODO: randomize
|
||||
go func() {
|
||||
defer func() { recover() }()
|
||||
ctx := xctx.ContextWithID(context.Background(), session.NewID())
|
||||
for {
|
||||
ctx := xctx.ContextWithID(h.ctx, session.NewID())
|
||||
for ctx.Err() == nil {
|
||||
conn, err := dialer.Dial(ctx, rec.Destination)
|
||||
if err != nil {
|
||||
errors.LogWarningInner(ctx, err, "pre-connect failed")
|
||||
continue
|
||||
}
|
||||
h.preConns <- &ConnExpire{Conn: conn, Expire: time.Now().Add(time.Minute * 2)} // TODO: customize & randomize
|
||||
time.Sleep(time.Millisecond * 200) // TODO: customize & randomize
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
conn.Close()
|
||||
return
|
||||
case h.preConns <- &ConnExpire{Conn: conn, Expire: time.Now().Add(time.Minute * 2)}:
|
||||
}
|
||||
time.Sleep(time.Millisecond * 200) // TODO: customize & randomize
|
||||
}
|
||||
}()
|
||||
}
|
||||
})
|
||||
for {
|
||||
connTime := <-h.preConns
|
||||
if connTime == nil {
|
||||
return errors.New("closed handler")
|
||||
var connTime *ConnExpire
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, nil, ctx.Err()
|
||||
case <-h.ctx.Done():
|
||||
return nil, nil, h.ctx.Err()
|
||||
case connTime = <-h.preConns:
|
||||
}
|
||||
if time.Now().Before(connTime.Expire) {
|
||||
conn = connTime.Conn
|
||||
@@ -193,10 +240,13 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.New("failed to find an available destination").Base(err)
|
||||
return nil, nil, errors.New("failed to find an available destination").Base(err)
|
||||
}
|
||||
}
|
||||
defer conn.Close()
|
||||
rawConn = conn
|
||||
if native {
|
||||
context.AfterFunc(ctx, func() { common.Interrupt(stat.TryUnwrapStatsConn(rawConn)) })
|
||||
}
|
||||
|
||||
iConn := stat.TryUnwrapStatsConn(conn)
|
||||
target := ob.Target
|
||||
@@ -205,23 +255,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
if h.encryption != nil {
|
||||
var err error
|
||||
if conn, err = h.encryption.Handshake(conn); err != nil {
|
||||
return errors.New("ML-KEM-768 handshake failed").Base(err)
|
||||
}
|
||||
}
|
||||
|
||||
command := protocol.RequestCommandTCP
|
||||
if target.Network == net.Network_UDP {
|
||||
command = protocol.RequestCommandUDP
|
||||
}
|
||||
if target.Address.Family().IsDomain() {
|
||||
switch target.Address.Domain() {
|
||||
case "v1.mux.cool":
|
||||
command = protocol.RequestCommandMux
|
||||
case "v1.rvs.cool":
|
||||
if target.Network != net.Network_Unknown {
|
||||
return errors.New("nice try baby")
|
||||
}
|
||||
command = protocol.RequestCommandRvs
|
||||
return nil, nil, errors.New("ML-KEM-768 handshake failed").Base(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,8 +263,13 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
Version: encoding.Version,
|
||||
User: rec.User,
|
||||
Command: command,
|
||||
Address: target.Address,
|
||||
Port: target.Port,
|
||||
}
|
||||
if !native {
|
||||
request.Command = protocol.RequestCommandTCP
|
||||
if target.Network == net.Network_UDP {
|
||||
request.Command = protocol.RequestCommandUDP
|
||||
}
|
||||
request.Address, request.Port = target.Address, target.Port
|
||||
}
|
||||
|
||||
account := request.User.Account.(*vless.MemoryAccount)
|
||||
@@ -252,11 +291,9 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
switch request.Command {
|
||||
case protocol.RequestCommandUDP:
|
||||
if !allowUDP443 && request.Port == 443 {
|
||||
return errors.New("XTLS rejected UDP/443 traffic")
|
||||
return nil, nil, errors.New("XTLS rejected UDP/443 traffic")
|
||||
}
|
||||
case protocol.RequestCommandMux:
|
||||
fallthrough // let server break Mux connections that contain TCP requests
|
||||
case protocol.RequestCommandTCP, protocol.RequestCommandRvs:
|
||||
case protocol.RequestCommandTCP, protocol.RequestCommandMux, protocol.RequestCommandRvs:
|
||||
var target net.Conn
|
||||
if commonConn, ok := conn.(*encryption.CommonConn); ok {
|
||||
if _, ok := commonConn.Conn.(*encryption.XorConn); ok || !proxy.IsRAWTransportWithoutSecurity(iConn) {
|
||||
@@ -270,7 +307,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
} else if realityConn, ok := iConn.(*reality.UConn); ok {
|
||||
target = realityConn.Conn
|
||||
} else {
|
||||
return errors.New("XTLS only supports TLS and REALITY directly for now.")
|
||||
return nil, nil, errors.New("XTLS only supports TLS and REALITY directly for now.")
|
||||
}
|
||||
input, rawInput = vless.AccessTLSBuffers(target)
|
||||
default:
|
||||
@@ -282,41 +319,95 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
|
||||
var newCtx context.Context
|
||||
var newCancel context.CancelFunc
|
||||
if session.TimeoutOnlyFromContext(ctx) {
|
||||
if !native && session.TimeoutOnlyFromContext(ctx) {
|
||||
newCtx, newCancel = context.WithCancel(context.Background())
|
||||
}
|
||||
|
||||
sessionPolicy := h.policyManager.ForLevel(request.User.Level)
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
timer := signal.CancelAfterInactivity(ctx, func() {
|
||||
timer = signal.CancelAfterInactivity(ctx, func() {
|
||||
cancel()
|
||||
if newCancel != nil {
|
||||
newCancel()
|
||||
}
|
||||
}, sessionPolicy.Timeouts.ConnectionIdle)
|
||||
|
||||
clientReader := link.Reader // .(*pipe.Reader)
|
||||
clientWriter := link.Writer // .(*pipe.Writer)
|
||||
if requestAddons.Flow == vless.XRV {
|
||||
if outerTLS, ok := iConn.(interface {
|
||||
tls.Interface
|
||||
ConnectionState() gotls.ConnectionState
|
||||
}); ok {
|
||||
if err := outerTLS.HandshakeContext(ctx); err != nil {
|
||||
return nil, nil, errors.New("failed outer TLS handshake for Vision").Base(err)
|
||||
}
|
||||
if version := outerTLS.ConnectionState().Version; version != gotls.VersionTLS13 {
|
||||
return nil, nil, errors.New("failed to use "+requestAddons.Flow+", found outer tls version ", version)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
trafficState := proxy.NewTrafficState(account.ID.Bytes())
|
||||
if request.Command == protocol.RequestCommandUDP && (requestAddons.Flow == vless.XRV || (request.Port != 53 && request.Port != 443)) {
|
||||
singleXUDP := request.Command == protocol.RequestCommandUDP && (requestAddons.Flow == vless.XRV || request.Port != 53 && request.Port != 443)
|
||||
if singleXUDP {
|
||||
request.Command = protocol.RequestCommandMux
|
||||
request.Address = net.DomainAddress("v1.mux.cool")
|
||||
request.Port = net.Port(666)
|
||||
}
|
||||
|
||||
bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
|
||||
if err := encoding.EncodeRequestHeader(bufferWriter, request, requestAddons); err != nil {
|
||||
return nil, nil, errors.New("failed to encode request header").Base(err)
|
||||
}
|
||||
|
||||
// default: serverWriter := bufferWriter
|
||||
serverWriter := encoding.EncodeBodyAddons(bufferWriter, request, requestAddons, trafficState, true, ctx, conn, ob)
|
||||
if singleXUDP {
|
||||
serverWriter = xudp.NewPacketWriter(serverWriter, target, xudp.GetGlobalID(ctx))
|
||||
}
|
||||
|
||||
openResponse := func() (buf.Reader, error) {
|
||||
responseAddons, err := encoding.DecodeResponseHeader(conn, request)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to decode response header").Base(err)
|
||||
}
|
||||
|
||||
// default: serverReader := buf.NewReader(conn)
|
||||
serverReader := encoding.DecodeBodyAddons(conn, request, responseAddons)
|
||||
if requestAddons.Flow == vless.XRV {
|
||||
serverReader = proxy.NewVisionReader(serverReader, trafficState, false, ctx, conn, input, rawInput, ob)
|
||||
}
|
||||
if singleXUDP {
|
||||
if requestAddons.Flow == vless.XRV {
|
||||
serverReader = xudp.NewPacketReader(&buf.BufferedReader{Reader: serverReader})
|
||||
} else {
|
||||
serverReader = xudp.NewPacketReader(conn)
|
||||
}
|
||||
}
|
||||
|
||||
return serverReader, nil
|
||||
}
|
||||
|
||||
if native {
|
||||
bufferWriter.SetFlushNext()
|
||||
if request.Command == protocol.RequestCommandRvs {
|
||||
timer.Update()
|
||||
if requestAddons.Flow == vless.XRV {
|
||||
if err := serverWriter.WriteMultiBuffer(buf.MultiBuffer{nil}); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
if err := bufferWriter.SetBuffered(false); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
directLink, openErr := multiplex.OpenLink(ctx, cancel, serverWriter, timer, openResponse)
|
||||
if openErr != nil {
|
||||
return nil, nil, openErr
|
||||
}
|
||||
return ctx, directLink, nil
|
||||
}
|
||||
|
||||
postRequest := func() error {
|
||||
clientReader := link.Reader
|
||||
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
|
||||
|
||||
bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
|
||||
if err := encoding.EncodeRequestHeader(bufferWriter, request, requestAddons); err != nil {
|
||||
return errors.New("failed to encode request header").Base(err)
|
||||
}
|
||||
|
||||
// default: serverWriter := bufferWriter
|
||||
serverWriter := encoding.EncodeBodyAddons(bufferWriter, request, requestAddons, trafficState, true, ctx, conn, ob)
|
||||
if request.Command == protocol.RequestCommandMux && request.Port == 666 {
|
||||
serverWriter = xudp.NewPacketWriter(serverWriter, target, xudp.GetGlobalID(ctx))
|
||||
}
|
||||
timeoutReader, ok := clientReader.(buf.TimeoutReader)
|
||||
if ok {
|
||||
multiBuffer, err1 := timeoutReader.ReadMultiBufferTimeout(time.Millisecond * 500)
|
||||
@@ -341,48 +432,20 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
return errors.New("failed to write A request payload").Base(err)
|
||||
}
|
||||
|
||||
if requestAddons.Flow == vless.XRV {
|
||||
if tlsConn, ok := iConn.(*tls.Conn); ok {
|
||||
if tlsConn.ConnectionState().Version != gotls.VersionTLS13 {
|
||||
return errors.New(`failed to use `+requestAddons.Flow+`, found outer tls version `, tlsConn.ConnectionState().Version)
|
||||
}
|
||||
} else if utlsConn, ok := iConn.(*tls.UConn); ok {
|
||||
if utlsConn.ConnectionState().Version != utls.VersionTLS13 {
|
||||
return errors.New(`failed to use `+requestAddons.Flow+`, found outer tls version `, utlsConn.ConnectionState().Version)
|
||||
}
|
||||
}
|
||||
}
|
||||
err := buf.Copy(clientReader, serverWriter, buf.UpdateActivity(timer))
|
||||
if err != nil {
|
||||
return errors.New("failed to transfer request payload").Base(err)
|
||||
}
|
||||
|
||||
// Indicates the end of request payload.
|
||||
switch requestAddons.Flow {
|
||||
default:
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
clientWriter := link.Writer
|
||||
getResponse := func() error {
|
||||
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
|
||||
|
||||
responseAddons, err := encoding.DecodeResponseHeader(conn, request)
|
||||
serverReader, err := openResponse()
|
||||
if err != nil {
|
||||
return errors.New("failed to decode response header").Base(err)
|
||||
}
|
||||
|
||||
// default: serverReader := buf.NewReader(conn)
|
||||
serverReader := encoding.DecodeBodyAddons(conn, request, responseAddons)
|
||||
if requestAddons.Flow == vless.XRV {
|
||||
serverReader = proxy.NewVisionReader(serverReader, trafficState, false, ctx, conn, input, rawInput, ob)
|
||||
}
|
||||
if request.Command == protocol.RequestCommandMux && request.Port == 666 {
|
||||
if requestAddons.Flow == vless.XRV {
|
||||
serverReader = xudp.NewPacketReader(&buf.BufferedReader{Reader: serverReader})
|
||||
} else {
|
||||
serverReader = xudp.NewPacketReader(conn)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if requestAddons.Flow == vless.XRV {
|
||||
@@ -404,72 +467,8 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
}
|
||||
|
||||
if err := task.Run(ctx, postRequest, task.OnSuccess(getResponse, task.Close(clientWriter))); err != nil {
|
||||
return errors.New("connection ends").Base(err)
|
||||
return nil, nil, errors.New("connection ends").Base(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type Reverse struct {
|
||||
tag string
|
||||
dispatcher routing.Dispatcher
|
||||
ctx context.Context
|
||||
handler *Handler
|
||||
workers []*reverse.BridgeWorker
|
||||
monitorTask *task.Periodic
|
||||
}
|
||||
|
||||
func (r *Reverse) monitor() error {
|
||||
var activeWorkers []*reverse.BridgeWorker
|
||||
for _, w := range r.workers {
|
||||
if w.IsActive() {
|
||||
activeWorkers = append(activeWorkers, w)
|
||||
}
|
||||
}
|
||||
if len(activeWorkers) != len(r.workers) {
|
||||
r.workers = activeWorkers
|
||||
}
|
||||
|
||||
var numConnections uint32
|
||||
var numWorker uint32
|
||||
for _, w := range r.workers {
|
||||
if w.IsActive() {
|
||||
numConnections += w.Connections()
|
||||
numWorker++
|
||||
}
|
||||
}
|
||||
if numWorker == 0 || numConnections/numWorker > 16 {
|
||||
reader1, writer1 := pipe.New(pipe.WithSizeLimit(2 * buf.Size))
|
||||
reader2, writer2 := pipe.New(pipe.WithSizeLimit(2 * buf.Size))
|
||||
link1 := &transport.Link{Reader: reader1, Writer: writer2}
|
||||
link2 := &transport.Link{Reader: reader2, Writer: writer1}
|
||||
w := &reverse.BridgeWorker{
|
||||
Tag: r.tag,
|
||||
Dispatcher: r.dispatcher,
|
||||
}
|
||||
worker, err := mux.NewServerWorker(session.ContextWithIsReverseMux(r.ctx, true), w, link1)
|
||||
if err != nil {
|
||||
errors.LogWarningInner(r.ctx, err, "failed to create mux server worker")
|
||||
return nil
|
||||
}
|
||||
w.Worker = worker
|
||||
r.workers = append(r.workers, w)
|
||||
go func() {
|
||||
ctx := session.ContextWithOutbounds(r.ctx, []*session.Outbound{{
|
||||
Target: net.Destination{Address: net.DomainAddress("v1.rvs.cool")},
|
||||
}})
|
||||
r.handler.Process(ctx, link2, session.FullHandlerFromContext(ctx).(*proxyman.Handler))
|
||||
common.Interrupt(reader1)
|
||||
common.Interrupt(reader2)
|
||||
}()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reverse) Start() error {
|
||||
return r.monitorTask.Start()
|
||||
}
|
||||
|
||||
func (r *Reverse) Close() error {
|
||||
return r.monitorTask.Close()
|
||||
return nil, nil, nil
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"io"
|
||||
|
||||
"github.com/xtls/xray-core/common/dice"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
)
|
||||
|
||||
func (c *Control) FillInRandom() {
|
||||
@@ -13,3 +14,9 @@ func (c *Control) FillInRandom() {
|
||||
c.Random = make([]byte, randomLength)
|
||||
io.ReadFull(rand.Reader, c.Random)
|
||||
}
|
||||
|
||||
const internalDomain = "reverse"
|
||||
|
||||
func isInternalDomain(dest net.Destination) bool {
|
||||
return dest.Address.Family().IsDomain() && dest.Address.Domain() == internalDomain
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.12
|
||||
// protoc (unknown)
|
||||
// source: proxy/vless/reverse/config.proto
|
||||
|
||||
package reverse
|
||||
|
||||
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 Control_State int32
|
||||
|
||||
const (
|
||||
Control_ACTIVE Control_State = 0
|
||||
Control_DRAIN Control_State = 1
|
||||
)
|
||||
|
||||
// Enum value maps for Control_State.
|
||||
var (
|
||||
Control_State_name = map[int32]string{
|
||||
0: "ACTIVE",
|
||||
1: "DRAIN",
|
||||
}
|
||||
Control_State_value = map[string]int32{
|
||||
"ACTIVE": 0,
|
||||
"DRAIN": 1,
|
||||
}
|
||||
)
|
||||
|
||||
func (x Control_State) Enum() *Control_State {
|
||||
p := new(Control_State)
|
||||
*p = x
|
||||
return p
|
||||
}
|
||||
|
||||
func (x Control_State) String() string {
|
||||
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
|
||||
}
|
||||
|
||||
func (Control_State) Descriptor() protoreflect.EnumDescriptor {
|
||||
return file_proxy_vless_reverse_config_proto_enumTypes[0].Descriptor()
|
||||
}
|
||||
|
||||
func (Control_State) Type() protoreflect.EnumType {
|
||||
return &file_proxy_vless_reverse_config_proto_enumTypes[0]
|
||||
}
|
||||
|
||||
func (x Control_State) Number() protoreflect.EnumNumber {
|
||||
return protoreflect.EnumNumber(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Control_State.Descriptor instead.
|
||||
func (Control_State) EnumDescriptor() ([]byte, []int) {
|
||||
return file_proxy_vless_reverse_config_proto_rawDescGZIP(), []int{0, 0}
|
||||
}
|
||||
|
||||
type Control struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
State Control_State `protobuf:"varint,1,opt,name=state,proto3,enum=xray.app.reverse.Control_State" json:"state,omitempty"`
|
||||
Random []byte `protobuf:"bytes,99,opt,name=random,proto3" json:"random,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Control) Reset() {
|
||||
*x = Control{}
|
||||
mi := &file_proxy_vless_reverse_config_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Control) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Control) ProtoMessage() {}
|
||||
|
||||
func (x *Control) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_proxy_vless_reverse_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 Control.ProtoReflect.Descriptor instead.
|
||||
func (*Control) Descriptor() ([]byte, []int) {
|
||||
return file_proxy_vless_reverse_config_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *Control) GetState() Control_State {
|
||||
if x != nil {
|
||||
return x.State
|
||||
}
|
||||
return Control_ACTIVE
|
||||
}
|
||||
|
||||
func (x *Control) GetRandom() []byte {
|
||||
if x != nil {
|
||||
return x.Random
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_proxy_vless_reverse_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_proxy_vless_reverse_config_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
" proxy/vless/reverse/config.proto\x12\x10xray.app.reverse\"x\n" +
|
||||
"\aControl\x125\n" +
|
||||
"\x05state\x18\x01 \x01(\x0e2\x1f.xray.app.reverse.Control.StateR\x05state\x12\x16\n" +
|
||||
"\x06random\x18c \x01(\fR\x06random\"\x1e\n" +
|
||||
"\x05State\x12\n" +
|
||||
"\n" +
|
||||
"\x06ACTIVE\x10\x00\x12\t\n" +
|
||||
"\x05DRAIN\x10\x01B^\n" +
|
||||
"\x16com.xray.proxy.reverseP\x01Z-github.com/xtls/xray-core/proxy/vless/reverse\xaa\x02\x12Xray.Proxy.Reverseb\x06proto3"
|
||||
|
||||
var (
|
||||
file_proxy_vless_reverse_config_proto_rawDescOnce sync.Once
|
||||
file_proxy_vless_reverse_config_proto_rawDescData []byte
|
||||
)
|
||||
|
||||
func file_proxy_vless_reverse_config_proto_rawDescGZIP() []byte {
|
||||
file_proxy_vless_reverse_config_proto_rawDescOnce.Do(func() {
|
||||
file_proxy_vless_reverse_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_vless_reverse_config_proto_rawDesc), len(file_proxy_vless_reverse_config_proto_rawDesc)))
|
||||
})
|
||||
return file_proxy_vless_reverse_config_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_proxy_vless_reverse_config_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
|
||||
var file_proxy_vless_reverse_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
|
||||
var file_proxy_vless_reverse_config_proto_goTypes = []any{
|
||||
(Control_State)(0), // 0: xray.app.reverse.Control.State
|
||||
(*Control)(nil), // 1: xray.app.reverse.Control
|
||||
}
|
||||
var file_proxy_vless_reverse_config_proto_depIdxs = []int32{
|
||||
0, // 0: xray.app.reverse.Control.state:type_name -> xray.app.reverse.Control.State
|
||||
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_vless_reverse_config_proto_init() }
|
||||
func file_proxy_vless_reverse_config_proto_init() {
|
||||
if File_proxy_vless_reverse_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_vless_reverse_config_proto_rawDesc), len(file_proxy_vless_reverse_config_proto_rawDesc)),
|
||||
NumEnums: 1,
|
||||
NumMessages: 1,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
GoTypes: file_proxy_vless_reverse_config_proto_goTypes,
|
||||
DependencyIndexes: file_proxy_vless_reverse_config_proto_depIdxs,
|
||||
EnumInfos: file_proxy_vless_reverse_config_proto_enumTypes,
|
||||
MessageInfos: file_proxy_vless_reverse_config_proto_msgTypes,
|
||||
}.Build()
|
||||
File_proxy_vless_reverse_config_proto = out.File
|
||||
file_proxy_vless_reverse_config_proto_goTypes = nil
|
||||
file_proxy_vless_reverse_config_proto_depIdxs = nil
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package xray.app.reverse;
|
||||
option csharp_namespace = "Xray.Proxy.Reverse";
|
||||
option go_package = "github.com/xtls/xray-core/proxy/vless/reverse";
|
||||
option java_package = "com.xray.proxy.reverse";
|
||||
option java_multiple_files = true;
|
||||
|
||||
message Control {
|
||||
enum State {
|
||||
ACTIVE = 0;
|
||||
DRAIN = 1;
|
||||
}
|
||||
|
||||
State state = 1;
|
||||
bytes random = 99;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package reverse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"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/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// StartIntranet maintains Reverse carriers until the returned cancellation function is called.
|
||||
// The opener derives each physical connection's context from the supplied context.
|
||||
func StartIntranet(ctx context.Context, dispatch func(context.Context, net.Destination, *transport.Link) error, open func(context.Context) (context.Context, *transport.Link, error)) func() {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
go func() {
|
||||
const interval = 2 * time.Second
|
||||
timer := time.NewTimer(interval)
|
||||
defer timer.Stop()
|
||||
var workers []*intranetWorker
|
||||
for ; ; timer.Reset(interval) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
var connections uint32
|
||||
active := workers[:0]
|
||||
for _, w := range workers {
|
||||
if w.state.Load() == int32(Control_ACTIVE) && !w.worker.Closed() {
|
||||
active = append(active, w)
|
||||
connections += w.worker.ActiveConnections()
|
||||
}
|
||||
}
|
||||
clear(workers[len(active):])
|
||||
workers = active
|
||||
if len(workers) != 0 && connections/uint32(len(workers)) <= 16 {
|
||||
continue
|
||||
}
|
||||
physical, link, err := open(ctx)
|
||||
if err != nil {
|
||||
errors.LogWarningInner(ctx, err, "failed to create intranet worker")
|
||||
continue
|
||||
}
|
||||
w := &intranetWorker{dispatch: dispatch}
|
||||
w.worker = multiplex.NewServerWorker(session.ContextWithIsReverseMux(physical, true), w.handle, link)
|
||||
workers = append(workers, w)
|
||||
}
|
||||
}()
|
||||
return cancel
|
||||
}
|
||||
|
||||
type intranetWorker struct {
|
||||
worker *multiplex.ServerWorker
|
||||
dispatch func(context.Context, net.Destination, *transport.Link) error
|
||||
state atomic.Int32
|
||||
}
|
||||
|
||||
// handle forwards user traffic or consumes the native Reverse control stream.
|
||||
func (w *intranetWorker) handle(ctx context.Context, dest net.Destination, link *transport.Link) error {
|
||||
if !isInternalDomain(dest) {
|
||||
return w.dispatch(ctx, dest, link)
|
||||
}
|
||||
defer common.Close(link.Writer)
|
||||
defer common.Interrupt(link.Reader)
|
||||
for {
|
||||
mb, readErr := link.Reader.ReadMultiBuffer()
|
||||
for _, b := range mb {
|
||||
var ctl Control
|
||||
if err := proto.Unmarshal(b.Bytes(), &ctl); err != nil {
|
||||
buf.ReleaseMulti(mb)
|
||||
errors.LogInfoInner(ctx, err, "failed to parse proto message")
|
||||
return nil
|
||||
}
|
||||
w.state.Store(int32(ctl.State))
|
||||
}
|
||||
buf.ReleaseMulti(mb)
|
||||
if readErr != nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package reverse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"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/common/signal"
|
||||
"github.com/xtls/xray-core/features"
|
||||
"github.com/xtls/xray-core/features/extension"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type PublicEndpoint struct {
|
||||
observer features.Feature
|
||||
tag string
|
||||
closed bool
|
||||
access sync.Mutex
|
||||
workers []*PublicWorker
|
||||
}
|
||||
|
||||
func NewPublicEndpoint(tag string, observer features.Feature) *PublicEndpoint {
|
||||
return &PublicEndpoint{tag: tag, observer: observer}
|
||||
}
|
||||
|
||||
func (p *PublicEndpoint) Tag() string { return p.tag }
|
||||
func (p *PublicEndpoint) SenderSettings() *serial.TypedMessage { return nil }
|
||||
func (p *PublicEndpoint) ProxySettings() *serial.TypedMessage { return nil }
|
||||
func (p *PublicEndpoint) Dispatch(ctx context.Context, link *transport.Link) {
|
||||
reader, writer := link.Reader, link.Writer
|
||||
if err := p.HandleConnection(ctx, link); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to process reverse connection")
|
||||
common.Interrupt(writer)
|
||||
common.Interrupt(reader)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *PublicEndpoint) Accept(ctx context.Context, link *transport.Link) error {
|
||||
client := multiplex.NewClientWorker(ctx, *link, multiplex.ClientStrategy{})
|
||||
target := net.UDPDestination(net.DomainAddress(internalDomain), 0)
|
||||
controlCtx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{Target: target}})
|
||||
s := multiplex.NewSession(controlCtx, &transport.Link{Writer: buf.Discard})
|
||||
if !client.TryAdmit(controlCtx, s) {
|
||||
client.Close()
|
||||
return errors.New("failed to admit reverse control session")
|
||||
}
|
||||
worker := &PublicWorker{
|
||||
client: client,
|
||||
timer: signal.CancelAfterInactivity(context.Background(), func() { client.Close() }, 24*time.Hour),
|
||||
}
|
||||
defer func() {
|
||||
worker.Close()
|
||||
p.access.Lock()
|
||||
p.workers = slices.DeleteFunc(p.workers, func(current *PublicWorker) bool { return current == worker })
|
||||
p.access.Unlock()
|
||||
}()
|
||||
p.access.Lock()
|
||||
if p.closed || ctx.Err() != nil || client.Closed() {
|
||||
p.access.Unlock()
|
||||
return client.Err()
|
||||
}
|
||||
p.workers = append(p.workers, worker)
|
||||
p.access.Unlock()
|
||||
if observer, ok := p.observer.(extension.BurstObservatory); ok {
|
||||
go observer.Check([]string{p.tag})
|
||||
}
|
||||
go p.heartbeat(worker, s)
|
||||
<-client.WaitClosed()
|
||||
return client.Err()
|
||||
}
|
||||
|
||||
func (p *PublicEndpoint) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *PublicEndpoint) Close() error {
|
||||
p.access.Lock()
|
||||
p.closed = true
|
||||
workers := p.workers
|
||||
p.workers = nil
|
||||
p.access.Unlock()
|
||||
for _, worker := range workers {
|
||||
worker.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *PublicEndpoint) HandleConnection(ctx context.Context, link *transport.Link) error {
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
ob := outbounds[len(outbounds)-1]
|
||||
if ob == nil {
|
||||
return errors.New("outbound metadata not found")
|
||||
}
|
||||
|
||||
reader, writer := link.Reader, link.Writer
|
||||
ctx = session.ContextWithIsReverseMux(ctx, true)
|
||||
|
||||
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
|
||||
link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
|
||||
link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
|
||||
}
|
||||
|
||||
return multiplex.Dispatch(ctx, link, p.Admit, func(physical context.Context) {
|
||||
stop := context.AfterFunc(physical, func() {
|
||||
common.Interrupt(writer)
|
||||
common.Interrupt(reader)
|
||||
})
|
||||
defer stop()
|
||||
common.Close(writer)
|
||||
common.Interrupt(reader)
|
||||
})
|
||||
}
|
||||
|
||||
func (p *PublicEndpoint) Admit(ctx context.Context, s *multiplex.Session) error {
|
||||
p.access.Lock()
|
||||
defer p.access.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.closed || len(p.workers) == 0 {
|
||||
return errors.New("empty worker list")
|
||||
}
|
||||
|
||||
// Failed reservations move out of this admission's candidate prefix.
|
||||
for remaining := len(p.workers); remaining > 0; {
|
||||
best, state := -1, Control_DRAIN
|
||||
var active uint32
|
||||
for i := 0; i < remaining; i++ {
|
||||
w := p.workers[i]
|
||||
a := w.client.ActiveConnections()
|
||||
if best == -1 || w.state < state || (w.state == state && a < active) {
|
||||
best, state, active = i, w.state, a
|
||||
}
|
||||
}
|
||||
if p.workers[best].client.TryAdmit(ctx, s) {
|
||||
return nil
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
remaining--
|
||||
p.workers[best], p.workers[remaining] = p.workers[remaining], p.workers[best]
|
||||
}
|
||||
|
||||
return errors.New("no mux client worker available")
|
||||
}
|
||||
|
||||
type PublicWorker struct {
|
||||
client *multiplex.ClientWorker
|
||||
state Control_State // guarded by PublicEndpoint.access; zero is ACTIVE
|
||||
timer *signal.ActivityTimer
|
||||
}
|
||||
|
||||
func (w *PublicWorker) Close() {
|
||||
w.client.Close()
|
||||
w.timer.SetTimeout(0)
|
||||
}
|
||||
|
||||
func (p *PublicEndpoint) heartbeat(w *PublicWorker, s *multiplex.Session) {
|
||||
var err error
|
||||
defer func() { s.CloseWithError(err) }()
|
||||
err = w.writeControl(s, Control_ACTIVE)
|
||||
if err != nil {
|
||||
w.client.Close()
|
||||
return
|
||||
}
|
||||
timer := time.NewTimer(2 * time.Second)
|
||||
defer timer.Stop()
|
||||
counter := uint32(1)
|
||||
for {
|
||||
select {
|
||||
case <-timer.C:
|
||||
case <-s.WaitClosed():
|
||||
err = io.ErrClosedPipe
|
||||
return
|
||||
case <-w.client.WaitClosed():
|
||||
err = io.ErrClosedPipe
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-s.WaitClosed():
|
||||
err = io.ErrClosedPipe
|
||||
return
|
||||
default:
|
||||
}
|
||||
if w.client.Closed() {
|
||||
err = io.ErrClosedPipe
|
||||
return
|
||||
}
|
||||
counter = (counter + 1) % 5
|
||||
if w.client.TotalConnections() > 256 {
|
||||
p.access.Lock()
|
||||
w.state = Control_DRAIN
|
||||
p.access.Unlock()
|
||||
err = w.writeControl(s, Control_DRAIN)
|
||||
return
|
||||
}
|
||||
if counter == 1 {
|
||||
if err = w.writeControl(s, Control_ACTIVE); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
timer.Reset(2 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *PublicWorker) writeControl(s *multiplex.Session, state Control_State) error {
|
||||
msg := &Control{State: state}
|
||||
msg.FillInRandom()
|
||||
b, err := proto.Marshal(msg)
|
||||
common.Must(err)
|
||||
w.timer.Update()
|
||||
return s.WriteMultiBuffer(buf.MergeBytes(nil, b))
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
feature_inbound "github.com/xtls/xray-core/features/inbound"
|
||||
"github.com/xtls/xray-core/features/policy"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/proxy/vmess"
|
||||
"github.com/xtls/xray-core/proxy/vmess/encoding"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
@@ -238,7 +239,6 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
|
||||
if err != nil {
|
||||
return errors.New("failed to start decoding").Base(err)
|
||||
}
|
||||
|
||||
writer := buf.NewBufferedWriter(buf.NewWriter(connection))
|
||||
response := &protocol.ResponseHeader{
|
||||
Command: h.generateCommand(ctx, request),
|
||||
@@ -249,12 +249,14 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
|
||||
return errors.New("failed to start decoding response").Base(err)
|
||||
}
|
||||
writer.SetFlushNext()
|
||||
link := &transport.Link{Reader: bodyReader, Writer: bodyWriter}
|
||||
|
||||
if err := dispatcher.DispatchLink(ctx, request.Destination(), &transport.Link{
|
||||
Reader: bodyReader,
|
||||
Writer: bodyWriter,
|
||||
},
|
||||
); err != nil {
|
||||
if request.Command == protocol.RequestCommandMux {
|
||||
worker := multiplex.NewServerWorker(ctx, dispatcher.DispatchLink, link)
|
||||
<-worker.WaitClosed()
|
||||
return worker.Err()
|
||||
}
|
||||
if err := dispatcher.DispatchLink(ctx, request.Destination(), link); err != nil {
|
||||
return errors.New("failed to dispatch request").Base(err)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
)
|
||||
|
||||
// As a stub command consumer.
|
||||
func (h *Handler) handleCommand(dest net.Destination, cmd protocol.ResponseCommand) {
|
||||
switch cmd.(type) {
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ package outbound
|
||||
|
||||
import (
|
||||
protocol "github.com/xtls/xray-core/common/protocol"
|
||||
vless "github.com/xtls/xray-core/proxy/vless"
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
@@ -25,6 +26,7 @@ const (
|
||||
type Config struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Receiver *protocol.ServerEndpoint `protobuf:"bytes,1,opt,name=Receiver,proto3" json:"Receiver,omitempty"`
|
||||
Multiplex *vless.Multiplex `protobuf:"bytes,2,opt,name=multiplex,proto3" json:"multiplex,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -66,13 +68,21 @@ func (x *Config) GetReceiver() *protocol.ServerEndpoint {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Config) GetMultiplex() *vless.Multiplex {
|
||||
if x != nil {
|
||||
return x.Multiplex
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_proxy_vmess_outbound_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_proxy_vmess_outbound_config_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"!proxy/vmess/outbound/config.proto\x12\x19xray.proxy.vmess.outbound\x1a!common/protocol/server_spec.proto\"J\n" +
|
||||
"!proxy/vmess/outbound/config.proto\x12\x19xray.proxy.vmess.outbound\x1a!common/protocol/server_spec.proto\x1a\x19proxy/vless/account.proto\"\x85\x01\n" +
|
||||
"\x06Config\x12@\n" +
|
||||
"\bReceiver\x18\x01 \x01(\v2$.xray.common.protocol.ServerEndpointR\bReceiverBm\n" +
|
||||
"\bReceiver\x18\x01 \x01(\v2$.xray.common.protocol.ServerEndpointR\bReceiver\x129\n" +
|
||||
"\tmultiplex\x18\x02 \x01(\v2\x1b.xray.proxy.vless.MultiplexR\tmultiplexBm\n" +
|
||||
"\x1dcom.xray.proxy.vmess.outboundP\x01Z.github.com/xtls/xray-core/proxy/vmess/outbound\xaa\x02\x19Xray.Proxy.Vmess.Outboundb\x06proto3"
|
||||
|
||||
var (
|
||||
@@ -91,14 +101,16 @@ var file_proxy_vmess_outbound_config_proto_msgTypes = make([]protoimpl.MessageIn
|
||||
var file_proxy_vmess_outbound_config_proto_goTypes = []any{
|
||||
(*Config)(nil), // 0: xray.proxy.vmess.outbound.Config
|
||||
(*protocol.ServerEndpoint)(nil), // 1: xray.common.protocol.ServerEndpoint
|
||||
(*vless.Multiplex)(nil), // 2: xray.proxy.vless.Multiplex
|
||||
}
|
||||
var file_proxy_vmess_outbound_config_proto_depIdxs = []int32{
|
||||
1, // 0: xray.proxy.vmess.outbound.Config.Receiver:type_name -> xray.common.protocol.ServerEndpoint
|
||||
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
|
||||
2, // 1: xray.proxy.vmess.outbound.Config.multiplex:type_name -> xray.proxy.vless.Multiplex
|
||||
2, // [2:2] is the sub-list for method output_type
|
||||
2, // [2:2] is the sub-list for method input_type
|
||||
2, // [2:2] is the sub-list for extension type_name
|
||||
2, // [2:2] is the sub-list for extension extendee
|
||||
0, // [0:2] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_proxy_vmess_outbound_config_proto_init() }
|
||||
|
||||
@@ -7,7 +7,9 @@ option java_package = "com.xray.proxy.vmess.outbound";
|
||||
option java_multiple_files = true;
|
||||
|
||||
import "common/protocol/server_spec.proto";
|
||||
import "proxy/vless/account.proto";
|
||||
|
||||
message Config {
|
||||
xray.common.protocol.ServerEndpoint Receiver = 1;
|
||||
xray.proxy.vless.Multiplex multiplex = 2;
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"github.com/xtls/xray-core/common/xudp"
|
||||
core "github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/features/policy"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/proxy/vmess"
|
||||
"github.com/xtls/xray-core/proxy/vmess/encoding"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
@@ -32,6 +33,8 @@ import (
|
||||
type Handler struct {
|
||||
server *protocol.ServerSpec
|
||||
policyManager policy.Manager
|
||||
multiplex *multiplex.Client
|
||||
stopMultiplex context.CancelFunc
|
||||
}
|
||||
|
||||
// New creates a new VMess outbound handler.
|
||||
@@ -44,21 +47,55 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
|
||||
return nil, errors.New("failed to get server spec").Base(err)
|
||||
}
|
||||
|
||||
muxConfig, err := multiplex.NormalizeConfig(config.Multiplex)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := core.MustFromContext(ctx)
|
||||
handler := &Handler{
|
||||
server: server,
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
}
|
||||
if muxConfig != nil {
|
||||
dialer, ok := session.FullHandlerFromContext(ctx).(internet.Dialer)
|
||||
if !ok {
|
||||
return nil, errors.New("VMess multiplex requires an outbound dialer")
|
||||
}
|
||||
poolCtx, stop := context.WithCancel(context.Background())
|
||||
handler.stopMultiplex = stop
|
||||
handler.multiplex = multiplex.NewClient(poolCtx, muxConfig, "", func(ctx context.Context) (context.Context, *transport.Link, error) {
|
||||
return handler.process(ctx, nil, dialer, protocol.RequestCommandMux)
|
||||
})
|
||||
}
|
||||
|
||||
return handler, nil
|
||||
}
|
||||
|
||||
func (h *Handler) Close() error {
|
||||
if h.stopMultiplex != nil {
|
||||
h.stopMultiplex()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Process implements proxy.Outbound.Process().
|
||||
func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
|
||||
if handled, err := h.multiplex.Dispatch(ctx, link); handled {
|
||||
return err
|
||||
}
|
||||
_, _, err := h.process(ctx, link, dialer, 0)
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *Handler) process(ctx context.Context, link *transport.Link, dialer internet.Dialer, command protocol.RequestCommand) (_ context.Context, _ *transport.Link, err error) {
|
||||
native := command == protocol.RequestCommandMux
|
||||
if native {
|
||||
ctx = session.ContextWithOutbounds(ctx, []*session.Outbound{{Target: h.server.Destination}})
|
||||
}
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
ob := outbounds[len(outbounds)-1]
|
||||
if !ob.Target.IsValid() {
|
||||
return errors.New("target not specified")
|
||||
return nil, nil, errors.New("target not specified")
|
||||
}
|
||||
ob.Name = "vmess"
|
||||
ob.CanSpliceCopy = 3
|
||||
@@ -66,7 +103,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
rec := h.server
|
||||
var conn stat.Connection
|
||||
|
||||
err := retry.ExponentialBackoff(5, 200).On(func() error {
|
||||
err = retry.ExponentialBackoff(5, 200).On(func() error {
|
||||
rawConn, err := dialer.Dial(ctx, rec.Destination)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -76,30 +113,30 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return errors.New("failed to find an available destination").Base(err)
|
||||
return nil, nil, errors.New("failed to find an available destination").Base(err)
|
||||
}
|
||||
if !native {
|
||||
defer conn.Close()
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
target := ob.Target
|
||||
errors.LogInfo(ctx, "tunneling request to ", target, " via ", rec.Destination.NetAddr())
|
||||
|
||||
command := protocol.RequestCommandTCP
|
||||
if target.Network == net.Network_UDP {
|
||||
command = protocol.RequestCommandUDP
|
||||
}
|
||||
if target.Address.Family().IsDomain() && target.Address.Domain() == "v1.mux.cool" {
|
||||
command = protocol.RequestCommandMux
|
||||
}
|
||||
|
||||
user := rec.User
|
||||
singleXUDP := target.Network == net.Network_UDP && target.Port != 53 && target.Port != 443
|
||||
request := &protocol.RequestHeader{
|
||||
Version: encoding.Version,
|
||||
User: user,
|
||||
Command: command,
|
||||
User: rec.User,
|
||||
Command: protocol.RequestCommandTCP,
|
||||
Address: target.Address,
|
||||
Port: target.Port,
|
||||
Option: protocol.RequestOptionChunkStream,
|
||||
}
|
||||
switch {
|
||||
case native || singleXUDP:
|
||||
request.Command = protocol.RequestCommandMux
|
||||
case target.Network == net.Network_UDP:
|
||||
request.Command = protocol.RequestCommandUDP
|
||||
}
|
||||
|
||||
account := request.User.Account.(*vmess.MemoryAccount)
|
||||
request.Security = account.Security
|
||||
@@ -107,7 +144,6 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
if request.Security == protocol.SecurityType_AES128_GCM || request.Security == protocol.SecurityType_CHACHA20_POLY1305 {
|
||||
request.Option.Set(protocol.RequestOptionChunkMasking)
|
||||
}
|
||||
|
||||
if shouldEnablePadding(request.Security) && request.Option.Has(protocol.RequestOptionChunkMasking) {
|
||||
request.Option.Set(protocol.RequestOptionGlobalPadding)
|
||||
}
|
||||
@@ -116,54 +152,60 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
request.Option.Set(protocol.RequestOptionAuthenticatedLength)
|
||||
}
|
||||
|
||||
input := link.Reader
|
||||
output := link.Writer
|
||||
|
||||
hashkdf := hmac.New(sha256.New, []byte("VMessBF"))
|
||||
hashkdf.Write(account.ID.Bytes())
|
||||
|
||||
behaviorSeed := crc64.Checksum(hashkdf.Sum(nil), crc64.MakeTable(crc64.ISO))
|
||||
|
||||
var newCtx context.Context
|
||||
var newCancel context.CancelFunc
|
||||
clientSession := encoding.NewClientSession(ctx, int64(behaviorSeed))
|
||||
sessionPolicy := h.policyManager.ForLevel(request.User.Level)
|
||||
if session.TimeoutOnlyFromContext(ctx) {
|
||||
newCtx, newCancel = context.WithCancel(context.Background())
|
||||
ctx = context.Background()
|
||||
}
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
|
||||
if native {
|
||||
context.AfterFunc(ctx, func() { common.Interrupt(stat.TryUnwrapStatsConn(conn)) })
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
timer.SetTimeout(0)
|
||||
}
|
||||
}()
|
||||
|
||||
writer := buf.NewBufferedWriter(buf.NewWriter(conn))
|
||||
if err := clientSession.EncodeRequestHeader(request, writer); err != nil {
|
||||
return nil, nil, errors.New("failed to encode request").Base(err)
|
||||
}
|
||||
|
||||
session := encoding.NewClientSession(ctx, int64(behaviorSeed))
|
||||
sessionPolicy := h.policyManager.ForLevel(request.User.Level)
|
||||
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
timer := signal.CancelAfterInactivity(ctx, func() {
|
||||
cancel()
|
||||
if newCancel != nil {
|
||||
newCancel()
|
||||
bodyWriter, err := clientSession.EncodeRequestBody(request, writer)
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("failed to start encoding").Base(err)
|
||||
}
|
||||
openResponse := func() (buf.Reader, error) {
|
||||
reader := &buf.BufferedReader{Reader: buf.NewReader(conn)}
|
||||
if _, err := clientSession.DecodeResponseHeader(reader); err != nil {
|
||||
return nil, errors.New("failed to read header").Base(err)
|
||||
}
|
||||
}, sessionPolicy.Timeouts.ConnectionIdle)
|
||||
return clientSession.DecodeResponseBody(request, reader)
|
||||
}
|
||||
|
||||
if request.Command == protocol.RequestCommandUDP && request.Port != 53 && request.Port != 443 {
|
||||
request.Command = protocol.RequestCommandMux
|
||||
request.Address = net.DomainAddress("v1.mux.cool")
|
||||
request.Port = net.Port(666)
|
||||
if native {
|
||||
if err := writer.SetBuffered(false); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
physical, err := multiplex.OpenLink(ctx, cancel, bodyWriter, timer, openResponse)
|
||||
return ctx, physical, err
|
||||
}
|
||||
|
||||
requestDone := func() error {
|
||||
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
|
||||
|
||||
writer := buf.NewBufferedWriter(buf.NewWriter(conn))
|
||||
if err := session.EncodeRequestHeader(request, writer); err != nil {
|
||||
return errors.New("failed to encode request").Base(err)
|
||||
stream := bodyWriter
|
||||
if singleXUDP {
|
||||
stream = xudp.NewPacketWriter(bodyWriter, target, xudp.GetGlobalID(ctx))
|
||||
}
|
||||
|
||||
bodyWriter, err := session.EncodeRequestBody(request, writer)
|
||||
if err != nil {
|
||||
return errors.New("failed to start encoding").Base(err)
|
||||
}
|
||||
bodyWriter2 := bodyWriter
|
||||
if request.Command == protocol.RequestCommandMux && request.Port == 666 {
|
||||
bodyWriter = xudp.NewPacketWriter(bodyWriter, target, xudp.GetGlobalID(ctx))
|
||||
}
|
||||
if err := buf.CopyOnceTimeout(input, bodyWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
|
||||
if err := buf.CopyOnceTimeout(link.Reader, stream, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
|
||||
return errors.New("failed to write first payload").Base(err)
|
||||
}
|
||||
|
||||
@@ -171,50 +213,33 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
return err
|
||||
}
|
||||
|
||||
if err := buf.Copy(input, bodyWriter, buf.UpdateActivity(timer)); err != nil {
|
||||
err := buf.Copy(link.Reader, stream, buf.UpdateActivity(timer))
|
||||
if err != nil || account.NoTerminationSignal {
|
||||
return err
|
||||
}
|
||||
|
||||
if request.Option.Has(protocol.RequestOptionChunkStream) && !account.NoTerminationSignal {
|
||||
if err := bodyWriter2.WriteMultiBuffer(buf.MultiBuffer{}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
return bodyWriter.WriteMultiBuffer(buf.MultiBuffer{})
|
||||
}
|
||||
|
||||
responseDone := func() error {
|
||||
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
|
||||
|
||||
reader := &buf.BufferedReader{Reader: buf.NewReader(conn)}
|
||||
header, err := session.DecodeResponseHeader(reader)
|
||||
bodyReader, err := openResponse()
|
||||
if err != nil {
|
||||
return errors.New("failed to read header").Base(err)
|
||||
return err
|
||||
}
|
||||
h.handleCommand(rec.Destination, header.Command)
|
||||
|
||||
bodyReader, err := session.DecodeResponseBody(request, reader)
|
||||
if err != nil {
|
||||
return errors.New("failed to start encoding response").Base(err)
|
||||
}
|
||||
if request.Command == protocol.RequestCommandMux && request.Port == 666 {
|
||||
if singleXUDP {
|
||||
bodyReader = xudp.NewPacketReader(&buf.BufferedReader{Reader: bodyReader})
|
||||
}
|
||||
|
||||
return buf.Copy(bodyReader, output, buf.UpdateActivity(timer))
|
||||
return buf.Copy(bodyReader, link.Writer, buf.UpdateActivity(timer))
|
||||
}
|
||||
|
||||
if newCtx != nil {
|
||||
ctx = newCtx
|
||||
}
|
||||
|
||||
responseDonePost := task.OnSuccess(responseDone, task.Close(output))
|
||||
responseDonePost := task.OnSuccess(responseDone, task.Close(link.Writer))
|
||||
if err := task.Run(ctx, requestDone, responseDonePost); err != nil {
|
||||
return errors.New("connection ends").Base(err)
|
||||
return nil, nil, errors.New("connection ends").Base(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
return nil, nil, nil
|
||||
}
|
||||
|
||||
var enablePadding atomic.Bool
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
// Code generated by MockGen. DO NOT EDIT.
|
||||
// Source: github.com/xtls/xray-core/common/mux (interfaces: ClientWorkerFactory)
|
||||
|
||||
// Package mocks is a generated GoMock package.
|
||||
package mocks
|
||||
|
||||
import (
|
||||
reflect "reflect"
|
||||
|
||||
gomock "github.com/golang/mock/gomock"
|
||||
mux "github.com/xtls/xray-core/common/mux"
|
||||
)
|
||||
|
||||
// MuxClientWorkerFactory is a mock of ClientWorkerFactory interface
|
||||
type MuxClientWorkerFactory struct {
|
||||
ctrl *gomock.Controller
|
||||
recorder *MuxClientWorkerFactoryMockRecorder
|
||||
}
|
||||
|
||||
// MuxClientWorkerFactoryMockRecorder is the mock recorder for MuxClientWorkerFactory
|
||||
type MuxClientWorkerFactoryMockRecorder struct {
|
||||
mock *MuxClientWorkerFactory
|
||||
}
|
||||
|
||||
// NewMuxClientWorkerFactory creates a new mock instance
|
||||
func NewMuxClientWorkerFactory(ctrl *gomock.Controller) *MuxClientWorkerFactory {
|
||||
mock := &MuxClientWorkerFactory{ctrl: ctrl}
|
||||
mock.recorder = &MuxClientWorkerFactoryMockRecorder{mock}
|
||||
return mock
|
||||
}
|
||||
|
||||
// EXPECT returns an object that allows the caller to indicate expected use
|
||||
func (m *MuxClientWorkerFactory) EXPECT() *MuxClientWorkerFactoryMockRecorder {
|
||||
return m.recorder
|
||||
}
|
||||
|
||||
// Create mocks base method
|
||||
func (m *MuxClientWorkerFactory) Create() (*mux.ClientWorker, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "Create")
|
||||
ret0, _ := ret[0].(*mux.ClientWorker)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// Create indicates an expected call of Create
|
||||
func (mr *MuxClientWorkerFactoryMockRecorder) Create() *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MuxClientWorkerFactory)(nil).Create))
|
||||
}
|
||||
@@ -4,24 +4,20 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/app/log"
|
||||
"github.com/xtls/xray-core/app/policy"
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
"github.com/xtls/xray-core/app/reverse"
|
||||
"github.com/xtls/xray-core/app/router"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
clog "github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/retry"
|
||||
"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/dokodemo"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
"github.com/xtls/xray-core/proxy/vmess"
|
||||
"github.com/xtls/xray-core/proxy/vmess/inbound"
|
||||
"github.com/xtls/xray-core/proxy/vmess/outbound"
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/proxy/vless/inbound"
|
||||
"github.com/xtls/xray-core/proxy/vless/outbound"
|
||||
"github.com/xtls/xray-core/testing/servers/tcp"
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
@@ -41,24 +37,8 @@ func TestReverseProxy(t *testing.T) {
|
||||
|
||||
serverConfig := &core.Config{
|
||||
App: []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&reverse.Config{
|
||||
PortalConfig: []*reverse.PortalConfig{
|
||||
{
|
||||
Tag: "portal",
|
||||
Domain: "test.example.com",
|
||||
},
|
||||
},
|
||||
}),
|
||||
serial.ToTypedMessage(&router.Config{
|
||||
Rule: []*router.RoutingRule{
|
||||
{
|
||||
Domain: []*geodata.DomainRule{
|
||||
{Value: &geodata.DomainRule_Custom{Custom: &geodata.Domain{Type: geodata.Domain_Full, Value: "test.example.com"}}},
|
||||
},
|
||||
TargetTag: &router.RoutingRule_Tag{
|
||||
Tag: "portal",
|
||||
},
|
||||
},
|
||||
{
|
||||
InboundTag: []string{"external"},
|
||||
TargetTag: &router.RoutingRule_Tag{
|
||||
@@ -87,10 +67,11 @@ func TestReverseProxy(t *testing.T) {
|
||||
Listen: net.NewIPOrDomain(net.LocalHostIP),
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&inbound.Config{
|
||||
User: []*protocol.User{
|
||||
Users: []*protocol.User{
|
||||
{
|
||||
Account: serial.ToTypedMessage(&vmess.Account{
|
||||
Id: userID.String(),
|
||||
Account: serial.ToTypedMessage(&vless.Account{
|
||||
Id: userID.String(),
|
||||
Reverse: &vless.Reverse{Tag: "portal"},
|
||||
}),
|
||||
},
|
||||
},
|
||||
@@ -107,24 +88,8 @@ func TestReverseProxy(t *testing.T) {
|
||||
clientPort := tcp.PickPort()
|
||||
clientConfig := &core.Config{
|
||||
App: []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&reverse.Config{
|
||||
BridgeConfig: []*reverse.BridgeConfig{
|
||||
{
|
||||
Tag: "bridge",
|
||||
Domain: "test.example.com",
|
||||
},
|
||||
},
|
||||
}),
|
||||
serial.ToTypedMessage(&router.Config{
|
||||
Rule: []*router.RoutingRule{
|
||||
{
|
||||
Domain: []*geodata.DomainRule{
|
||||
{Value: &geodata.DomainRule_Custom{Custom: &geodata.Domain{Type: geodata.Domain_Full, Value: "test.example.com"}}},
|
||||
},
|
||||
TargetTag: &router.RoutingRule_Tag{
|
||||
Tag: "reverse",
|
||||
},
|
||||
},
|
||||
{
|
||||
InboundTag: []string{"bridge"},
|
||||
TargetTag: &router.RoutingRule_Tag{
|
||||
@@ -155,15 +120,13 @@ func TestReverseProxy(t *testing.T) {
|
||||
{
|
||||
Tag: "reverse",
|
||||
ProxySettings: serial.ToTypedMessage(&outbound.Config{
|
||||
Receiver: &protocol.ServerEndpoint{
|
||||
Vnext: &protocol.ServerEndpoint{
|
||||
Address: net.NewIPOrDomain(net.LocalHostIP),
|
||||
Port: uint32(reversePort),
|
||||
User: &protocol.User{
|
||||
Account: serial.ToTypedMessage(&vmess.Account{
|
||||
Id: userID.String(),
|
||||
SecuritySettings: &protocol.SecurityConfig{
|
||||
Type: protocol.SecurityType_AES128_GCM,
|
||||
},
|
||||
Account: serial.ToTypedMessage(&vless.Account{
|
||||
Id: userID.String(),
|
||||
Reverse: &vless.Reverse{Tag: "bridge"},
|
||||
}),
|
||||
},
|
||||
},
|
||||
@@ -177,198 +140,16 @@ func TestReverseProxy(t *testing.T) {
|
||||
|
||||
defer CloseAllServers(servers)
|
||||
|
||||
if err := retry.Timed(20, 100).On(testTCPConn(externalPort, 1, time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var errg errgroup.Group
|
||||
for range 32 {
|
||||
errg.Go(testTCPConn(externalPort, 10240*1024, time.Second*40))
|
||||
for range 4 {
|
||||
errg.Go(testTCPConn(externalPort, 64*1024, time.Second*10))
|
||||
}
|
||||
|
||||
if err := errg.Wait(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReverseProxyLongRunning(t *testing.T) {
|
||||
tcpServer := tcp.Server{
|
||||
MsgProcessor: xor,
|
||||
}
|
||||
dest, err := tcpServer.Start()
|
||||
common.Must(err)
|
||||
|
||||
defer tcpServer.Close()
|
||||
|
||||
userID := protocol.NewID(uuid.New())
|
||||
externalPort := tcp.PickPort()
|
||||
reversePort := tcp.PickPort()
|
||||
|
||||
serverConfig := &core.Config{
|
||||
App: []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&log.Config{
|
||||
ErrorLogLevel: clog.Severity_Warning,
|
||||
ErrorLogType: log.LogType_Console,
|
||||
}),
|
||||
serial.ToTypedMessage(&policy.Config{
|
||||
Level: map[uint32]*policy.Policy{
|
||||
0: {
|
||||
Timeout: &policy.Policy_Timeout{
|
||||
UplinkOnly: &policy.Second{Value: 0},
|
||||
DownlinkOnly: &policy.Second{Value: 0},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
serial.ToTypedMessage(&reverse.Config{
|
||||
PortalConfig: []*reverse.PortalConfig{
|
||||
{
|
||||
Tag: "portal",
|
||||
Domain: "test.example.com",
|
||||
},
|
||||
},
|
||||
}),
|
||||
serial.ToTypedMessage(&router.Config{
|
||||
Rule: []*router.RoutingRule{
|
||||
{
|
||||
Domain: []*geodata.DomainRule{
|
||||
{Value: &geodata.DomainRule_Custom{Custom: &geodata.Domain{Type: geodata.Domain_Full, Value: "test.example.com"}}},
|
||||
},
|
||||
TargetTag: &router.RoutingRule_Tag{
|
||||
Tag: "portal",
|
||||
},
|
||||
},
|
||||
{
|
||||
InboundTag: []string{"external"},
|
||||
TargetTag: &router.RoutingRule_Tag{
|
||||
Tag: "portal",
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
Inbound: []*core.InboundHandlerConfig{
|
||||
{
|
||||
Tag: "external",
|
||||
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(externalPort)}},
|
||||
Listen: net.NewIPOrDomain(net.LocalHostIP),
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
|
||||
RewriteAddress: net.NewIPOrDomain(dest.Address),
|
||||
RewritePort: uint32(dest.Port),
|
||||
AllowedNetworks: []net.Network{net.Network_TCP},
|
||||
}),
|
||||
},
|
||||
{
|
||||
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(reversePort)}},
|
||||
Listen: net.NewIPOrDomain(net.LocalHostIP),
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&inbound.Config{
|
||||
User: []*protocol.User{
|
||||
{
|
||||
Account: serial.ToTypedMessage(&vmess.Account{
|
||||
Id: userID.String(),
|
||||
}),
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
clientPort := tcp.PickPort()
|
||||
clientConfig := &core.Config{
|
||||
App: []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&log.Config{
|
||||
ErrorLogLevel: clog.Severity_Warning,
|
||||
ErrorLogType: log.LogType_Console,
|
||||
}),
|
||||
serial.ToTypedMessage(&policy.Config{
|
||||
Level: map[uint32]*policy.Policy{
|
||||
0: {
|
||||
Timeout: &policy.Policy_Timeout{
|
||||
UplinkOnly: &policy.Second{Value: 0},
|
||||
DownlinkOnly: &policy.Second{Value: 0},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
serial.ToTypedMessage(&reverse.Config{
|
||||
BridgeConfig: []*reverse.BridgeConfig{
|
||||
{
|
||||
Tag: "bridge",
|
||||
Domain: "test.example.com",
|
||||
},
|
||||
},
|
||||
}),
|
||||
serial.ToTypedMessage(&router.Config{
|
||||
Rule: []*router.RoutingRule{
|
||||
{
|
||||
Domain: []*geodata.DomainRule{
|
||||
{Value: &geodata.DomainRule_Custom{Custom: &geodata.Domain{Type: geodata.Domain_Full, Value: "test.example.com"}}},
|
||||
},
|
||||
TargetTag: &router.RoutingRule_Tag{
|
||||
Tag: "reverse",
|
||||
},
|
||||
},
|
||||
{
|
||||
InboundTag: []string{"bridge"},
|
||||
TargetTag: &router.RoutingRule_Tag{
|
||||
Tag: "freedom",
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
Inbound: []*core.InboundHandlerConfig{
|
||||
{
|
||||
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(clientPort)}},
|
||||
Listen: net.NewIPOrDomain(net.LocalHostIP),
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
|
||||
RewriteAddress: net.NewIPOrDomain(dest.Address),
|
||||
RewritePort: uint32(dest.Port),
|
||||
AllowedNetworks: []net.Network{net.Network_TCP},
|
||||
}),
|
||||
},
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
Tag: "freedom",
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
|
||||
},
|
||||
{
|
||||
Tag: "reverse",
|
||||
ProxySettings: serial.ToTypedMessage(&outbound.Config{
|
||||
Receiver: &protocol.ServerEndpoint{
|
||||
Address: net.NewIPOrDomain(net.LocalHostIP),
|
||||
Port: uint32(reversePort),
|
||||
User: &protocol.User{
|
||||
Account: serial.ToTypedMessage(&vmess.Account{
|
||||
Id: userID.String(),
|
||||
SecuritySettings: &protocol.SecurityConfig{
|
||||
Type: protocol.SecurityType_AES128_GCM,
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
|
||||
common.Must(err)
|
||||
|
||||
defer CloseAllServers(servers)
|
||||
|
||||
for range 4096 {
|
||||
if err := testTCPConn(externalPort, 1024, time.Second*20)(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,103 +290,3 @@ func TestShadowsocksAES128GCMUDP(t *testing.T) {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShadowsocksAES128GCMUDPMux(t *testing.T) {
|
||||
udpServer := udp.Server{
|
||||
MsgProcessor: xor,
|
||||
}
|
||||
dest, err := udpServer.Start()
|
||||
common.Must(err)
|
||||
defer udpServer.Close()
|
||||
|
||||
account := serial.ToTypedMessage(&shadowsocks.Account{
|
||||
Password: "shadowsocks-password",
|
||||
CipherType: shadowsocks.CipherType_AES_128_GCM,
|
||||
})
|
||||
|
||||
serverPort := tcp.PickPort()
|
||||
serverConfig := &core.Config{
|
||||
App: []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&log.Config{
|
||||
ErrorLogLevel: clog.Severity_Debug,
|
||||
ErrorLogType: log.LogType_Console,
|
||||
}),
|
||||
},
|
||||
Inbound: []*core.InboundHandlerConfig{
|
||||
{
|
||||
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(serverPort)}},
|
||||
Listen: net.NewIPOrDomain(net.LocalHostIP),
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&shadowsocks.ServerConfig{
|
||||
Users: []*protocol.User{{
|
||||
Account: account,
|
||||
Level: 1,
|
||||
}},
|
||||
Network: []net.Network{net.Network_TCP},
|
||||
}),
|
||||
},
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
|
||||
}),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
clientPort := udp.PickPort()
|
||||
clientConfig := &core.Config{
|
||||
App: []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&log.Config{
|
||||
ErrorLogLevel: clog.Severity_Debug,
|
||||
ErrorLogType: log.LogType_Console,
|
||||
}),
|
||||
},
|
||||
Inbound: []*core.InboundHandlerConfig{
|
||||
{
|
||||
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(clientPort)}},
|
||||
Listen: net.NewIPOrDomain(net.LocalHostIP),
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
|
||||
RewriteAddress: net.NewIPOrDomain(dest.Address),
|
||||
RewritePort: uint32(dest.Port),
|
||||
AllowedNetworks: []net.Network{net.Network_UDP},
|
||||
}),
|
||||
},
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
|
||||
MultiplexSettings: &proxyman.MultiplexingConfig{
|
||||
Enabled: true,
|
||||
Concurrency: 8,
|
||||
},
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&shadowsocks.ClientConfig{
|
||||
Server: &protocol.ServerEndpoint{
|
||||
Address: net.NewIPOrDomain(net.LocalHostIP),
|
||||
Port: uint32(serverPort),
|
||||
User: &protocol.User{
|
||||
Account: account,
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
|
||||
common.Must(err)
|
||||
defer CloseAllServers(servers)
|
||||
|
||||
var errGroup errgroup.Group
|
||||
for range 3 {
|
||||
errGroup.Go(testUDPConn(clientPort, 1024, time.Second*5))
|
||||
}
|
||||
if err := errGroup.Wait(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -33,7 +34,47 @@ import (
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
func countTCPCarriers(t *testing.T, target net.Port) (net.Port, *atomic.Int32) {
|
||||
t.Helper()
|
||||
addr := &net.TCPAddr{IP: net.LocalHostIP.IP()}
|
||||
listener, err := net.ListenTCP("tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { listener.Close() })
|
||||
count := new(atomic.Int32)
|
||||
go func() {
|
||||
for {
|
||||
conn, err := listener.AcceptTCP()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
count.Add(1)
|
||||
go func() {
|
||||
defer conn.Close()
|
||||
server, err := net.DialTCP("tcp", nil, &net.TCPAddr{IP: addr.IP, Port: int(target)})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer server.Close()
|
||||
go func() {
|
||||
io.Copy(server, conn)
|
||||
server.CloseWrite()
|
||||
}()
|
||||
io.Copy(conn, server)
|
||||
}()
|
||||
}
|
||||
}()
|
||||
return net.Port(listener.Addr().(*net.TCPAddr).Port), count
|
||||
}
|
||||
|
||||
func TestVless(t *testing.T) {
|
||||
t.Run("direct", func(t *testing.T) { testVlessTCP(t, false) })
|
||||
t.Run("native-multiplex", func(t *testing.T) { testVlessTCP(t, true) })
|
||||
}
|
||||
|
||||
func testVlessTCP(t *testing.T, nativeMux bool) {
|
||||
t.Helper()
|
||||
tcpServer := tcp.Server{
|
||||
MsgProcessor: xor,
|
||||
}
|
||||
@@ -76,6 +117,14 @@ func TestVless(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
outboundPort := serverPort
|
||||
var carrierCount func() int32
|
||||
var multiplex *vless.Multiplex
|
||||
if nativeMux {
|
||||
port, count := countTCPCarriers(t, serverPort)
|
||||
outboundPort, carrierCount = port, count.Load
|
||||
multiplex = &vless.Multiplex{Concurrency: 4}
|
||||
}
|
||||
clientPort := tcp.PickPort()
|
||||
clientConfig := &core.Config{
|
||||
App: []*serial.TypedMessage{
|
||||
@@ -100,9 +149,10 @@ func TestVless(t *testing.T) {
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&outbound.Config{
|
||||
Multiplex: multiplex,
|
||||
Vnext: &protocol.ServerEndpoint{
|
||||
Address: net.NewIPOrDomain(net.LocalHostIP),
|
||||
Port: uint32(serverPort),
|
||||
Port: uint32(outboundPort),
|
||||
User: &protocol.User{
|
||||
Account: serial.ToTypedMessage(&vless.Account{
|
||||
Id: userID.String(),
|
||||
@@ -118,6 +168,11 @@ func TestVless(t *testing.T) {
|
||||
common.Must(err)
|
||||
defer CloseAllServers(servers)
|
||||
|
||||
if nativeMux {
|
||||
if err := testTCPConn(clientPort, 64*1024, time.Second*10)(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var errg errgroup.Group
|
||||
for range 3 {
|
||||
errg.Go(testTCPConn(clientPort, 1024*1024, time.Second*30))
|
||||
@@ -125,6 +180,11 @@ func TestVless(t *testing.T) {
|
||||
if err := errg.Wait(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if nativeMux {
|
||||
if got := carrierCount(); got != 1 {
|
||||
t.Errorf("connections used %d physical carriers, want 1", got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVlessTls(t *testing.T) {
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
core "github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/proxy/dokodemo"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/proxy/vmess"
|
||||
"github.com/xtls/xray-core/proxy/vmess/inbound"
|
||||
"github.com/xtls/xray-core/proxy/vmess/outbound"
|
||||
@@ -680,6 +681,7 @@ func TestVMessGCMMux(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
carrierPort, carriers := countTCPCarriers(t, serverPort)
|
||||
clientPort := tcp.PickPort()
|
||||
clientConfig := &core.Config{
|
||||
App: []*serial.TypedMessage{
|
||||
@@ -703,16 +705,11 @@ func TestVMessGCMMux(t *testing.T) {
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
|
||||
MultiplexSettings: &proxyman.MultiplexingConfig{
|
||||
Enabled: true,
|
||||
Concurrency: 4,
|
||||
},
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&outbound.Config{
|
||||
Multiplex: &vless.Multiplex{Concurrency: 4},
|
||||
Receiver: &protocol.ServerEndpoint{
|
||||
Address: net.NewIPOrDomain(net.LocalHostIP),
|
||||
Port: uint32(serverPort),
|
||||
Port: uint32(carrierPort),
|
||||
User: &protocol.User{
|
||||
Account: serial.ToTypedMessage(&vmess.Account{
|
||||
Id: userID.String(),
|
||||
@@ -731,7 +728,10 @@ func TestVMessGCMMux(t *testing.T) {
|
||||
common.Must(err)
|
||||
defer CloseAllServers(servers)
|
||||
|
||||
for range "abcd" {
|
||||
if err := testTCPConn(clientPort, 10240, 10*time.Second)(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for range 4 {
|
||||
var errg errgroup.Group
|
||||
for range 3 {
|
||||
errg.Go(testTCPConn(clientPort, 10240, time.Second*20))
|
||||
@@ -739,7 +739,9 @@ func TestVMessGCMMux(t *testing.T) {
|
||||
if err := errg.Wait(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
if got := carriers.Load(); got != 1 {
|
||||
t.Errorf("connections used %d physical carriers, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -793,6 +795,7 @@ func TestVMessGCMMuxUDP(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
carrierPort, carriers := countTCPCarriers(t, serverPort)
|
||||
clientPort := tcp.PickPort()
|
||||
clientUDPPort := udp.PickPort()
|
||||
clientConfig := &core.Config{
|
||||
@@ -828,16 +831,11 @@ func TestVMessGCMMuxUDP(t *testing.T) {
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
|
||||
MultiplexSettings: &proxyman.MultiplexingConfig{
|
||||
Enabled: true,
|
||||
Concurrency: 4,
|
||||
},
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&outbound.Config{
|
||||
Multiplex: &vless.Multiplex{Concurrency: 16},
|
||||
Receiver: &protocol.ServerEndpoint{
|
||||
Address: net.NewIPOrDomain(net.LocalHostIP),
|
||||
Port: uint32(serverPort),
|
||||
Port: uint32(carrierPort),
|
||||
User: &protocol.User{
|
||||
Account: serial.ToTypedMessage(&vmess.Account{
|
||||
Id: userID.String(),
|
||||
@@ -867,6 +865,10 @@ func TestVMessGCMMuxUDP(t *testing.T) {
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
|
||||
if got := carriers.Load(); got != 1 {
|
||||
t.Errorf("TCP and UDP used %d physical carriers, want 1", got)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
<-time.After(5 * time.Second)
|
||||
CloseAllServers(servers)
|
||||
|
||||
Reference in New Issue
Block a user