mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-10-13 19:14:02 +00:00
Compare commits
19
Commits
CA
..
lua-sandbox
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
590a5236bb | ||
|
|
1aae252fc3 | ||
|
|
20c4c8f956 | ||
|
|
4c571f5e06 | ||
|
|
c77a4d0e49 | ||
|
|
5a64db009b | ||
|
|
2bea2df6a1 | ||
|
|
fb2dcedbb7 | ||
|
|
7c2e05dc47 | ||
|
|
1dd2a0bd3c | ||
|
|
70ef97d564 | ||
|
|
701af60772 | ||
|
|
8855145e58 | ||
|
|
c7dbfd5e1e | ||
|
|
aa7aa9ad0a | ||
|
|
2cc08769a5 | ||
|
|
5af2e9c228 | ||
|
|
836a6fed38 | ||
|
|
2a14c50775 |
@@ -470,6 +470,9 @@ func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *transport.
|
||||
return // DO NOT CHANGE: the traffic shouldn't be processed by default outbound if the specified outbound tag doesn't exist (yet), e.g., VLESS Reverse Proxy
|
||||
}
|
||||
} else {
|
||||
if err != common.ErrNoClue {
|
||||
errors.LogErrorInner(ctx, err, "failed to pick route for ", destination)
|
||||
}
|
||||
errors.LogInfo(ctx, "default route for ", destination)
|
||||
}
|
||||
}
|
||||
|
||||
+22
-4
@@ -93,6 +93,7 @@ type NameServer struct {
|
||||
UnexpectedIp []*geodata.IPRule `protobuf:"bytes,13,rep,name=unexpected_ip,json=unexpectedIp,proto3" json:"unexpected_ip,omitempty"`
|
||||
ActUnprior bool `protobuf:"varint,14,opt,name=actUnprior,proto3" json:"actUnprior,omitempty"`
|
||||
PolicyID uint32 `protobuf:"varint,17,opt,name=policyID,proto3" json:"policyID,omitempty"`
|
||||
Id string `protobuf:"bytes,18,opt,name=id,proto3" json:"id,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -239,6 +240,13 @@ func (x *NameServer) GetPolicyID() uint32 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *NameServer) GetId() string {
|
||||
if x != nil {
|
||||
return x.Id
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
// NameServer list used by this DNS client.
|
||||
@@ -258,6 +266,7 @@ type Config struct {
|
||||
DisableFallback bool `protobuf:"varint,10,opt,name=disableFallback,proto3" json:"disableFallback,omitempty"`
|
||||
DisableFallbackIfMatch bool `protobuf:"varint,11,opt,name=disableFallbackIfMatch,proto3" json:"disableFallbackIfMatch,omitempty"`
|
||||
EnableParallelQuery bool `protobuf:"varint,14,opt,name=enableParallelQuery,proto3" json:"enableParallelQuery,omitempty"`
|
||||
Script string `protobuf:"bytes,15,opt,name=script,proto3" json:"script,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -369,6 +378,13 @@ func (x *Config) GetEnableParallelQuery() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *Config) GetScript() string {
|
||||
if x != nil {
|
||||
return x.Script
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type Config_HostMapping struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Domain *geodata.DomainRule `protobuf:"bytes,2,opt,name=domain,proto3" json:"domain,omitempty"`
|
||||
@@ -435,7 +451,7 @@ var File_app_dns_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_app_dns_config_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"\x14app/dns/config.proto\x12\fxray.app.dns\x1a\x1ccommon/net/destination.proto\x1a\x1bcommon/geodata/geodat.proto\"\xde\x05\n" +
|
||||
"\x14app/dns/config.proto\x12\fxray.app.dns\x1a\x1ccommon/net/destination.proto\x1a\x1bcommon/geodata/geodat.proto\"\xee\x05\n" +
|
||||
"\n" +
|
||||
"NameServer\x123\n" +
|
||||
"\aaddress\x18\x01 \x01(\v2\x19.xray.common.net.EndpointR\aaddress\x12\x1b\n" +
|
||||
@@ -461,10 +477,11 @@ const file_app_dns_config_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"actUnprior\x18\x0e \x01(\bR\n" +
|
||||
"actUnprior\x12\x1a\n" +
|
||||
"\bpolicyID\x18\x11 \x01(\rR\bpolicyIDB\x0f\n" +
|
||||
"\bpolicyID\x18\x11 \x01(\rR\bpolicyID\x12\x0e\n" +
|
||||
"\x02id\x18\x12 \x01(\tR\x02idB\x0f\n" +
|
||||
"\r_disableCacheB\r\n" +
|
||||
"\v_serveStaleB\x12\n" +
|
||||
"\x10_serveExpiredTTLJ\x04\b\x04\x10\x05\"\x82\x05\n" +
|
||||
"\x10_serveExpiredTTLJ\x04\b\x04\x10\x05\"\x9a\x05\n" +
|
||||
"\x06Config\x129\n" +
|
||||
"\vname_server\x18\x05 \x03(\v2\x18.xray.app.dns.NameServerR\n" +
|
||||
"nameServer\x12\x1b\n" +
|
||||
@@ -480,7 +497,8 @@ const file_app_dns_config_proto_rawDesc = "" +
|
||||
"\x0fdisableFallback\x18\n" +
|
||||
" \x01(\bR\x0fdisableFallback\x126\n" +
|
||||
"\x16disableFallbackIfMatch\x18\v \x01(\bR\x16disableFallbackIfMatch\x120\n" +
|
||||
"\x13enableParallelQuery\x18\x0e \x01(\bR\x13enableParallelQuery\x1a}\n" +
|
||||
"\x13enableParallelQuery\x18\x0e \x01(\bR\x13enableParallelQuery\x12\x16\n" +
|
||||
"\x06script\x18\x0f \x01(\tR\x06script\x1a}\n" +
|
||||
"\vHostMapping\x127\n" +
|
||||
"\x06domain\x18\x02 \x01(\v2\x1f.xray.common.geodata.DomainRuleR\x06domain\x12\x0e\n" +
|
||||
"\x02ip\x18\x03 \x03(\fR\x02ip\x12%\n" +
|
||||
|
||||
@@ -27,6 +27,7 @@ message NameServer {
|
||||
repeated xray.common.geodata.IPRule unexpected_ip = 13;
|
||||
bool actUnprior = 14;
|
||||
uint32 policyID = 17;
|
||||
string id = 18;
|
||||
}
|
||||
|
||||
enum QueryStrategy {
|
||||
@@ -73,4 +74,6 @@ message Config {
|
||||
bool disableFallbackIfMatch = 11;
|
||||
|
||||
bool enableParallelQuery = 14;
|
||||
|
||||
string script = 15;
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ type DNS struct {
|
||||
domainMatcher geodata.DomainMatcher
|
||||
matcherInfos []*DomainMatcherInfo
|
||||
checkSystem bool
|
||||
script *scriptEngine
|
||||
}
|
||||
|
||||
// DomainMatcherInfo contains information attached to index returned by Server.domainMatcher.
|
||||
@@ -169,6 +170,13 @@ func New(ctx context.Context, config *Config) (*DNS, error) {
|
||||
clients = append(clients, NewLocalDNSClient(ipOption))
|
||||
}
|
||||
|
||||
var script *scriptEngine
|
||||
if config.Script != "" {
|
||||
if script, err = newScriptEngine(config.Script); err != nil {
|
||||
return nil, errors.New("failed to prepare DNS script").Base(err)
|
||||
}
|
||||
}
|
||||
|
||||
return &DNS{
|
||||
hosts: hosts,
|
||||
ipOption: &ipOption,
|
||||
@@ -180,6 +188,7 @@ func New(ctx context.Context, config *Config) (*DNS, error) {
|
||||
disableFallbackIfMatch: config.DisableFallbackIfMatch,
|
||||
enableParallelQuery: config.EnableParallelQuery,
|
||||
checkSystem: checkSystem,
|
||||
script: script,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -190,11 +199,19 @@ func (*DNS) Type() interface{} {
|
||||
|
||||
// Start implements common.Runnable.
|
||||
func (s *DNS) Start() error {
|
||||
if s.script != nil {
|
||||
if err := s.script.start(s); err != nil {
|
||||
return errors.New("failed to initialize DNS script").Base(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close implements common.Closable.
|
||||
func (s *DNS) Close() error {
|
||||
if s.script != nil {
|
||||
s.script.close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -279,6 +296,9 @@ func (s *DNS) LookupIP(domain string, option dns.IPOption) ([]net.IP, uint32, er
|
||||
}
|
||||
|
||||
// Name servers lookup
|
||||
if s.script != nil {
|
||||
return s.script.query(domain, option)
|
||||
}
|
||||
if s.enableParallelQuery {
|
||||
return s.parallelQuery(domain, option)
|
||||
} else {
|
||||
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
xlua "github.com/xtls/xray-core/common/lua"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
featureDNS "github.com/xtls/xray-core/features/dns"
|
||||
"github.com/xtls/xray-core/features/dns/localdns"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
// luaDNSServer adapts configured and local DNS to the same Lua API.
|
||||
type luaDNSServer struct {
|
||||
id string
|
||||
name string
|
||||
query func(context.Context, string, featureDNS.IPOption) ([]net.IP, uint32, error)
|
||||
}
|
||||
|
||||
// RegisterLua makes xray.dns available to scripts backed by client.
|
||||
func RegisterLua(L *lua.LState, client featureDNS.Client) {
|
||||
var servers []luaDNSServer
|
||||
switch client := client.(type) {
|
||||
case *DNS:
|
||||
servers = luaServers(client)
|
||||
case *localdns.Client:
|
||||
servers = []luaDNSServer{{
|
||||
id: "localhost",
|
||||
name: "localhost",
|
||||
query: func(_ context.Context, domain string, option featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||
return client.LookupIP(domain, option)
|
||||
},
|
||||
}}
|
||||
}
|
||||
registerLua(L, servers, client)
|
||||
}
|
||||
|
||||
// registerLua makes xray.dns available to DNS scripts.
|
||||
func (s *DNS) registerLua(L *lua.LState) {
|
||||
registerLua(L, luaServers(s), nil)
|
||||
}
|
||||
|
||||
func luaServers(s *DNS) []luaDNSServer {
|
||||
servers := make([]luaDNSServer, len(s.clients))
|
||||
for i, client := range s.clients {
|
||||
servers[i] = luaDNSServer{id: client.id, name: client.Name(), query: client.QueryIP}
|
||||
}
|
||||
return servers
|
||||
}
|
||||
|
||||
func registerLua(L *lua.LState, servers []luaDNSServer, client featureDNS.Client) {
|
||||
L.PreloadModule("xray.dns", func(L *lua.LState) int {
|
||||
pushIPs := xlua.NewSlicePusher[net.IP](L)
|
||||
|
||||
serverList := L.CreateTable(len(servers), 0)
|
||||
for i, client := range servers {
|
||||
server := L.CreateTable(0, 2)
|
||||
|
||||
server.RawSetString("ID", lua.LString(client.id))
|
||||
|
||||
server.RawSetString("Query", L.NewFunction(func(L *lua.LState) int {
|
||||
domain, ok := L.Get(2).(lua.LString)
|
||||
if !ok {
|
||||
L.RaiseError("server:Query requires a domain")
|
||||
return 0
|
||||
}
|
||||
option := featureDNS.IPOption{
|
||||
IPv4Enable: L.CheckBool(3),
|
||||
IPv6Enable: L.CheckBool(4),
|
||||
FakeEnable: L.CheckBool(5),
|
||||
}
|
||||
ctx := L.Context()
|
||||
if ctx == nil {
|
||||
L.RaiseError("server:Query requires an active DNS query")
|
||||
return 0
|
||||
}
|
||||
var ips []net.IP
|
||||
var ttl uint32
|
||||
var err error
|
||||
if !option.FakeEnable && strings.EqualFold(client.name, "FakeDNS") {
|
||||
err = featureDNS.ErrEmptyResponse
|
||||
} else {
|
||||
ips, ttl, err = client.query(ctx, string(domain), option)
|
||||
}
|
||||
pushIPs(L, ips)
|
||||
xlua.PushNumber(L, ttl)
|
||||
xlua.PushError(L, err)
|
||||
return 3
|
||||
}))
|
||||
serverList.RawSetInt(i+1, server)
|
||||
}
|
||||
|
||||
module := L.CreateTable(0, 2)
|
||||
if servers != nil {
|
||||
module.RawSetString("Servers", serverList)
|
||||
}
|
||||
if client != nil {
|
||||
module.RawSetString("Query", newLuaClientQuery(L, client, pushIPs))
|
||||
}
|
||||
L.Push(module)
|
||||
return 1
|
||||
})
|
||||
}
|
||||
|
||||
func newLuaClientQuery(L *lua.LState, client featureDNS.Client, pushIPs func(*lua.LState, []net.IP)) *lua.LFunction {
|
||||
return L.NewFunction(func(L *lua.LState) int {
|
||||
domain, ok := L.Get(1).(lua.LString)
|
||||
if !ok {
|
||||
L.RaiseError("dns.Query requires a domain")
|
||||
return 0
|
||||
}
|
||||
option := featureDNS.IPOption{
|
||||
IPv4Enable: L.CheckBool(2),
|
||||
IPv6Enable: L.CheckBool(3),
|
||||
FakeEnable: L.CheckBool(4),
|
||||
}
|
||||
if L.Context() == nil {
|
||||
L.RaiseError("dns.Query requires an active DNS query")
|
||||
return 0
|
||||
}
|
||||
ips, ttl, err := client.LookupIP(string(domain), option)
|
||||
pushIPs(L, ips)
|
||||
xlua.PushNumber(L, ttl)
|
||||
xlua.PushError(L, err)
|
||||
return 3
|
||||
})
|
||||
}
|
||||
|
||||
// callLuaQuery runs HandleDNSQuery and leaves (ips, ttl, err) on the stack.
|
||||
func callLuaQuery(L *lua.LState, domain string, option featureDNS.IPOption) error {
|
||||
fn := L.GetGlobal("HandleDNSQuery")
|
||||
if fn.Type() != lua.LTFunction {
|
||||
return errors.New("DNS script must define HandleDNSQuery(...)")
|
||||
}
|
||||
|
||||
return L.CallByParam(lua.P{Fn: fn, NRet: 3, Protect: true},
|
||||
lua.LString(strings.ToLower(domain)),
|
||||
lua.LBool(option.IPv4Enable),
|
||||
lua.LBool(option.IPv6Enable),
|
||||
lua.LBool(option.FakeEnable))
|
||||
}
|
||||
|
||||
// readLuaQueryResult reads (ips, ttl, err) from the stack without copying the IPs.
|
||||
func readLuaQueryResult(L *lua.LState) ([]net.IP, uint32, error) {
|
||||
if err := xlua.ReadError(L.Get(-1), "DNS script error must be an error or string"); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
ttl, err := xlua.ReadUint32(L.Get(-2), "DNS script returned invalid TTL")
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
addresses := L.Get(-3)
|
||||
if addresses == lua.LNil {
|
||||
return nil, 0, featureDNS.ErrEmptyResponse
|
||||
}
|
||||
ips, err := xlua.ReadUserData[[]net.IP](addresses, "DNS script IPs must be native IP slice userdata")
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if len(ips) == 0 {
|
||||
return nil, 0, featureDNS.ErrEmptyResponse
|
||||
}
|
||||
|
||||
return ips, ttl, nil
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
featureDNS "github.com/xtls/xray-core/features/dns"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
// BenchmarkLuaDNSHook isolates scalar argument bridging and a fixed return.
|
||||
// It excludes upstream queries, result decoding, and state pool management.
|
||||
func BenchmarkLuaDNSHook(b *testing.B) {
|
||||
L := lua.NewState()
|
||||
b.Cleanup(L.Close)
|
||||
if err := L.DoString(`
|
||||
function HandleDNSQuery(domain, ipv4, ipv6, fake)
|
||||
return true
|
||||
end
|
||||
`); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
L.SetContext(context.Background())
|
||||
option := featureDNS.IPOption{IPv4Enable: true}
|
||||
if err := callLuaQuery(L, "example.com", option); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
if L.Get(-3) != lua.LTrue {
|
||||
b.Fatal("hook did not return true")
|
||||
}
|
||||
L.Pop(3)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
if err := callLuaQuery(L, "example.com", option); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
L.Pop(3)
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkLuaDNSQuery queries the same preselected, in-memory upstream.
|
||||
// client_query compares Client.QueryIP to a preloaded server:Query hook.
|
||||
// script_query additionally measures production pool and timeout management.
|
||||
// These cases do not measure DNS.LookupIP server selection or network latency.
|
||||
func BenchmarkLuaDNSQuery(b *testing.B) {
|
||||
ctx := context.Background()
|
||||
option := featureDNS.IPOption{IPv4Enable: true}
|
||||
ip := net.ParseIP("127.0.0.1")
|
||||
upstream := &benchmarkLuaNameServer{ips: []net.IP{ip}}
|
||||
client := &Client{server: upstream, ipOption: &option, timeoutMs: time.Second}
|
||||
server := &DNS{ctx: ctx, clients: []*Client{client}}
|
||||
const script = `
|
||||
local server = require("xray.dns").Servers[1]
|
||||
function HandleDNSQuery(domain, ipv4, ipv6, fake)
|
||||
return server:Query(domain, ipv4, ipv6, fake)
|
||||
end
|
||||
`
|
||||
L := lua.NewState()
|
||||
b.Cleanup(L.Close)
|
||||
server.registerLua(L)
|
||||
if err := L.DoString(script); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
L.SetContext(ctx)
|
||||
|
||||
path := filepath.Join(b.TempDir(), "query.lua")
|
||||
if err := os.WriteFile(path, []byte(script), 0o600); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
engine, err := newScriptEngine(path)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
if err := engine.start(server); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
b.Cleanup(engine.close)
|
||||
for _, bench := range []struct {
|
||||
name string
|
||||
query func() ([]net.IP, uint32, error)
|
||||
}{
|
||||
{"client_query/native", func() ([]net.IP, uint32, error) {
|
||||
return client.QueryIP(ctx, "example.com", option)
|
||||
}},
|
||||
{"client_query/lua", func() ([]net.IP, uint32, error) {
|
||||
if err := callLuaQuery(L, "example.com", option); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
ips, ttl, err := readLuaQueryResult(L)
|
||||
L.Pop(3)
|
||||
return ips, ttl, err
|
||||
}},
|
||||
{"script_query/lua", func() ([]net.IP, uint32, error) {
|
||||
return engine.query("example.com", option)
|
||||
}},
|
||||
} {
|
||||
b.Run(bench.name, func(b *testing.B) {
|
||||
ips, ttl, err := bench.query()
|
||||
if err != nil || ttl != 60 || len(ips) != 1 || !ips[0].Equal(ip) {
|
||||
b.Fatalf("query() = %v, TTL %d, %v; want %v, TTL 60", ips, ttl, err, ip)
|
||||
}
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
ips, ttl, err = bench.query()
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
b.StopTimer()
|
||||
if ttl != 60 || len(ips) != 1 || !ips[0].Equal(ip) {
|
||||
b.Fatalf("query() = %v, TTL %d; want %v, TTL 60", ips, ttl, ip)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
go_errors "errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
featureDNS "github.com/xtls/xray-core/features/dns"
|
||||
"github.com/xtls/xray-core/features/dns/localdns"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
func TestReadLuaQueryResult(t *testing.T) {
|
||||
wantIPs := []net.IP{net.ParseIP("8.8.8.8"), {127, 0, 0, 1}, net.ParseIP("::1")}
|
||||
nativeErr := go_errors.New("upstream failed")
|
||||
for _, tc := range []struct {
|
||||
name, values string
|
||||
wantIPs []net.IP
|
||||
wantTTL uint32
|
||||
wantErr error
|
||||
wantMessage string
|
||||
}{
|
||||
{name: "IPs", values: `ips, 45`, wantIPs: wantIPs, wantTTL: 45},
|
||||
{name: "nil IPs", values: `nil, 0`, wantErr: featureDNS.ErrEmptyResponse},
|
||||
{name: "empty IPs", values: `emptyIPs, 0`, wantErr: featureDNS.ErrEmptyResponse},
|
||||
{name: "native error", values: `nil, nil, nativeError`, wantErr: nativeErr},
|
||||
{name: "string error", values: `nil, nil, "blocked"`, wantMessage: "blocked"},
|
||||
{name: "fractional TTL", values: `ips, 1.5`, wantMessage: "invalid TTL"},
|
||||
{name: "oversized TTL", values: `ips, 4294967296`, wantMessage: "invalid TTL"},
|
||||
{name: "negative TTL", values: `ips, -1`, wantMessage: "invalid TTL"},
|
||||
{name: "NaN TTL", values: `ips, 0/0`, wantMessage: "invalid TTL"},
|
||||
{name: "missing TTL", values: `ips`, wantMessage: "invalid TTL"},
|
||||
{name: "string IPs", values: `"127.0.0.1", 60`, wantMessage: "native IP slice"},
|
||||
{name: "wrong userdata", values: `ip, 60`, wantMessage: "native IP slice"},
|
||||
{name: "invalid error", values: `ips, 60, false`, wantMessage: "error or string"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
L := lua.NewState()
|
||||
defer L.Close()
|
||||
for name, value := range map[string]any{"ips": wantIPs, "ip": wantIPs[0], "emptyIPs": []net.IP(nil), "nativeError": nativeErr} {
|
||||
ud := L.NewUserData()
|
||||
ud.Value = value
|
||||
L.SetGlobal(name, ud)
|
||||
}
|
||||
fn, err := L.LoadString("return " + tc.values)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := L.CallByParam(lua.P{Fn: fn, NRet: 3, Protect: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ips, ttl, err := readLuaQueryResult(L)
|
||||
switch {
|
||||
case tc.wantErr != nil:
|
||||
if err != tc.wantErr {
|
||||
t.Fatalf("error = %v, want original error %v", err, tc.wantErr)
|
||||
}
|
||||
case tc.wantMessage != "":
|
||||
if err == nil || !strings.Contains(err.Error(), tc.wantMessage) {
|
||||
t.Fatalf("error = %v, want %q", err, tc.wantMessage)
|
||||
}
|
||||
case err != nil:
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ttl != tc.wantTTL || len(ips) != len(tc.wantIPs) {
|
||||
t.Fatalf("result = %v, TTL %d; want %v, TTL %d", ips, ttl, tc.wantIPs, tc.wantTTL)
|
||||
}
|
||||
for i := range ips {
|
||||
if !ips[i].Equal(tc.wantIPs[i]) {
|
||||
t.Fatalf("IP %d = %v, want %v", i, ips[i], tc.wantIPs[i])
|
||||
}
|
||||
}
|
||||
if len(ips) != 0 && &ips[0] != &tc.wantIPs[0] {
|
||||
t.Fatal("result copied the IP slice")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallLuaQueryCancellation(t *testing.T) {
|
||||
L := lua.NewState()
|
||||
defer L.Close()
|
||||
if err := L.DoString(`function HandleDNSQuery(domain, ipv4, ipv6, fake) while true do end end`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
L.SetContext(ctx)
|
||||
err := callLuaQuery(L, "example.com", featureDNS.IPOption{IPv4Enable: true})
|
||||
if err == nil {
|
||||
t.Fatal("callLuaQuery did not stop after context cancellation")
|
||||
}
|
||||
if L.Context() != ctx {
|
||||
t.Fatal("callLuaQuery changed the Lua state's context")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallLuaQuery(t *testing.T) {
|
||||
L := lua.NewState()
|
||||
defer L.Close()
|
||||
addresses := L.NewUserData()
|
||||
addresses.Value = []net.IP{net.ParseIP("127.0.0.1")}
|
||||
L.SetGlobal("ips", addresses)
|
||||
if err := L.DoString(`
|
||||
function HandleDNSQuery(domain, ipv4, ipv6, fake)
|
||||
assert(domain == "example.com")
|
||||
assert(ipv4 and not ipv6 and not fake)
|
||||
return ips, 60, nil
|
||||
end
|
||||
`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := callLuaQuery(L, "ExAmPlE.CoM", featureDNS.IPOption{IPv4Enable: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if L.GetTop() != 3 || L.Get(1) != addresses || L.Get(2) != lua.LNumber(60) || L.Get(3) != lua.LNil {
|
||||
t.Fatal("callLuaQuery did not leave the three query results on the stack")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLuaDNSServerQuery(t *testing.T) {
|
||||
L := lua.NewState()
|
||||
defer L.Close()
|
||||
geodata.RegisterLua(L)
|
||||
option := featureDNS.IPOption{IPv4Enable: true}
|
||||
ips := []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("8.8.8.8")}
|
||||
server := &DNS{clients: []*Client{{server: &benchmarkLuaNameServer{ips: ips}, ipOption: &option, timeoutMs: time.Second}}}
|
||||
server.registerLua(L)
|
||||
if err := L.DoString(`
|
||||
local server = require("xray.dns").Servers[1]
|
||||
local matcher = require("xray.geodata").BuildIPMatcher("127.0.0.0/8")
|
||||
function HandleDNSQuery(domain, ipv4, ipv6, fake)
|
||||
local ips, ttl, err = server:Query(domain, ipv4, ipv6, fake)
|
||||
assert(type(ips) == "userdata" and not err)
|
||||
assert(#ips == 2 and ips[1]:String() == "127.0.0.1" and ips[2]:String() == "8.8.8.8")
|
||||
assert(matcher:Match(ips[1]) and not matcher:Match(ips[2]))
|
||||
assert(matcher:AnyMatch(ips))
|
||||
local matched, unmatched = matcher:FilterIPs(ips)
|
||||
assert(#matched == 1 and #unmatched == 1)
|
||||
assert(matched[1]:Equal(ips[1]) and unmatched[1]:Equal(ips[2]))
|
||||
return matched, ttl, err
|
||||
end
|
||||
`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
L.SetContext(context.Background())
|
||||
if err := callLuaQuery(L, "example.com", option); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, ttl, err := readLuaQueryResult(L)
|
||||
if err != nil || ttl != 60 || len(got) != 1 || !got[0].Equal(ips[0]) {
|
||||
t.Fatalf("server query = %v, TTL %d, %v", got, ttl, err)
|
||||
}
|
||||
}
|
||||
|
||||
type luaDNSClient struct {
|
||||
featureDNS.Client
|
||||
lookup func(string, featureDNS.IPOption) ([]net.IP, uint32, error)
|
||||
}
|
||||
|
||||
func (c *luaDNSClient) LookupIP(domain string, option featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||
return c.lookup(domain, option)
|
||||
}
|
||||
|
||||
func TestLuaDNSClientQuery(t *testing.T) {
|
||||
L := lua.NewState()
|
||||
defer L.Close()
|
||||
L.SetContext(context.Background())
|
||||
geodata.RegisterLua(L)
|
||||
want := []net.IP{{127, 0, 0, 1}, net.ParseIP("::1")}
|
||||
client := &luaDNSClient{lookup: func(domain string, option featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||
if domain != "MiXeD.Example." || !option.IPv4Enable || option.IPv6Enable || !option.FakeEnable {
|
||||
t.Fatalf("dns.Query arguments = %q, %+v", domain, option)
|
||||
}
|
||||
return want, 42, nil
|
||||
}}
|
||||
RegisterLua(L, client)
|
||||
if err := L.DoString(`
|
||||
local dns = require("xray.dns")
|
||||
local matcher = require("xray.geodata").BuildIPMatcher("127.0.0.1")
|
||||
assert(dns.Servers == nil)
|
||||
ips, ttl, err = dns.Query("MiXeD.Example.", true, false, true)
|
||||
assert(not err and ttl == 42 and matcher:AnyMatch(ips))
|
||||
assert(#ips == 2 and ips[1]:String() == "127.0.0.1" and ips[2]:String() == "::1")
|
||||
assert(matcher:Match(ips[1]) and not matcher:Match(ips[2]))
|
||||
`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := L.GetGlobal("ips").(*lua.LUserData).Value.([]net.IP)
|
||||
if &got[0] != &want[0] {
|
||||
t.Fatal("dns.Query copied the IP slice")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLuaDNSLocalClient(t *testing.T) {
|
||||
L := lua.NewState()
|
||||
defer L.Close()
|
||||
L.SetContext(context.Background())
|
||||
RegisterLua(L, localdns.New())
|
||||
if err := L.DoString(`
|
||||
local dns = require("xray.dns")
|
||||
assert(dns.Servers[1].ID == "localhost")
|
||||
serverIPs, _, serverErr = dns.Servers[1]:Query("127.0.0.1", true, false, false)
|
||||
clientIPs, _, clientErr = dns.Query("127.0.0.1", true, false, false)
|
||||
assert(not serverErr and not clientErr)
|
||||
assert(#serverIPs == 1 and #clientIPs == 1)
|
||||
assert(serverIPs[1]:String() == "127.0.0.1" and serverIPs[1]:Equal(clientIPs[1]))
|
||||
`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range []string{"serverIPs", "clientIPs"} {
|
||||
ips := L.GetGlobal(name).(*lua.LUserData).Value.([]net.IP)
|
||||
if len(ips) != 1 || !ips[0].Equal(net.ParseIP("127.0.0.1")) {
|
||||
t.Fatalf("%s = %v", name, ips)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLuaDNSQueryEmptyIPs(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
ips []net.IP
|
||||
}{
|
||||
{"nil", nil},
|
||||
{"empty", []net.IP{}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
L := lua.NewState()
|
||||
defer L.Close()
|
||||
L.SetContext(context.Background())
|
||||
L.SetGlobal("expectNil", lua.LBool(tc.ips == nil))
|
||||
client := &luaDNSClient{lookup: func(string, featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||
return tc.ips, 0, featureDNS.ErrEmptyResponse
|
||||
}}
|
||||
registerLua(L, []luaDNSServer{{query: func(_ context.Context, domain string, option featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||
return client.LookupIP(domain, option)
|
||||
}}}, client)
|
||||
if err := L.DoString(`
|
||||
local dns = require("xray.dns")
|
||||
for _, query in ipairs({
|
||||
function() return dns.Servers[1]:Query("empty.example", true, false, false) end,
|
||||
function() return dns.Query("empty.example", true, false, false) end,
|
||||
}) do
|
||||
local ips, ttl, err = query()
|
||||
assert(ttl == 0 and err)
|
||||
if expectNil then
|
||||
assert(ips == nil)
|
||||
else
|
||||
assert(type(ips) == "userdata" and #ips == 0)
|
||||
assert(not pcall(function() return ips[1] end))
|
||||
end
|
||||
end
|
||||
`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type benchmarkLuaNameServer struct {
|
||||
ips []net.IP
|
||||
}
|
||||
|
||||
func (*benchmarkLuaNameServer) Name() string { return "benchmark" }
|
||||
func (*benchmarkLuaNameServer) IsDisableCache() bool { return true }
|
||||
func (s *benchmarkLuaNameServer) QueryIP(context.Context, string, featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||
return s.ips, 60, nil
|
||||
}
|
||||
@@ -29,6 +29,7 @@ type Server interface {
|
||||
|
||||
// Client is the interface for DNS client.
|
||||
type Client struct {
|
||||
id string
|
||||
server Server
|
||||
skipFallback bool
|
||||
expectedIPs geodata.IPMatcher
|
||||
@@ -97,7 +98,7 @@ func NewClient(
|
||||
ipOption dns.IPOption,
|
||||
updateRules func(bool),
|
||||
) (*Client, error) {
|
||||
client := &Client{}
|
||||
client := &Client{id: ns.Id}
|
||||
err := core.RequireFeatures(ctx, func(dispatcher routing.Dispatcher) error {
|
||||
// Create a new server for each client for now
|
||||
server, err := NewServer(ctx, ns.Address.AsDestination(), dispatcher, disableCache, serveStale, serveExpiredTTL, clientIP)
|
||||
|
||||
@@ -49,5 +49,5 @@ func NewLocalNameServer() *LocalNameServer {
|
||||
|
||||
// NewLocalDNSClient creates localdns client object for directly lookup in system DNS.
|
||||
func NewLocalDNSClient(ipOption dns.IPOption) *Client {
|
||||
return &Client{server: NewLocalNameServer(), ipOption: &ipOption}
|
||||
return &Client{id: "localhost", server: NewLocalNameServer(), ipOption: &ipOption}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
xlua "github.com/xtls/xray-core/common/lua"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/features/dns"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
const scriptExecutionTimeout = 6 * time.Second
|
||||
|
||||
type scriptEngine struct {
|
||||
program *xlua.Program
|
||||
pool *xlua.Pool
|
||||
}
|
||||
|
||||
func newScriptEngine(script string) (*scriptEngine, error) {
|
||||
program, err := xlua.Compile(script)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &scriptEngine{program: program}, nil
|
||||
}
|
||||
|
||||
func (e *scriptEngine) start(server *DNS) error {
|
||||
pool, err := xlua.NewPool(server.ctx, scriptExecutionTimeout, e.program.NewStateFactory(
|
||||
scriptExecutionTimeout*20,
|
||||
func(L *lua.LState) {
|
||||
geodata.RegisterLua(L)
|
||||
log.RegisterLua(L)
|
||||
server.registerLua(L)
|
||||
},
|
||||
func(L *lua.LState) error {
|
||||
if L.GetGlobal("HandleDNSQuery").Type() != lua.LTFunction {
|
||||
return errors.New("DNS script must define HandleDNSQuery(...)")
|
||||
}
|
||||
return nil
|
||||
}))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
e.pool = pool
|
||||
errors.LogInfo(server.ctx, "DNS script initialized")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *scriptEngine) close() {
|
||||
if e.pool != nil {
|
||||
e.pool.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (e *scriptEngine) query(domain string, option dns.IPOption) (ips []net.IP, ttl uint32, queryErr error) {
|
||||
if err := e.pool.WithState(nil, 0, func(L *lua.LState) error {
|
||||
if err := callLuaQuery(L, domain, option); err != nil {
|
||||
return err
|
||||
}
|
||||
ips, ttl, queryErr = readLuaQueryResult(L)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return ips, ttl, queryErr
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
go_errors "errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
featureDNS "github.com/xtls/xray-core/features/dns"
|
||||
)
|
||||
|
||||
type scriptNameServer struct {
|
||||
name string
|
||||
answers map[string]net.IP
|
||||
errors map[string]error
|
||||
ttl uint32
|
||||
calls int
|
||||
}
|
||||
|
||||
func (s *scriptNameServer) Name() string { return s.name }
|
||||
func (s *scriptNameServer) IsDisableCache() bool { return true }
|
||||
|
||||
func (s *scriptNameServer) QueryIP(ctx context.Context, domain string, _ featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
s.calls++
|
||||
if err := s.errors[domain]; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
ip, ok := s.answers[domain]
|
||||
if !ok {
|
||||
return nil, 0, featureDNS.ErrEmptyResponse
|
||||
}
|
||||
return []net.IP{ip}, s.ttl, nil
|
||||
}
|
||||
|
||||
func TestDNSScriptQuery(t *testing.T) {
|
||||
wantIP := net.ParseIP("127.0.0.1")
|
||||
upstreamErr := go_errors.New("upstream failed")
|
||||
for _, tc := range []struct {
|
||||
name, body string
|
||||
wantIPs []net.IP
|
||||
wantTTL uint32
|
||||
wantErr error
|
||||
wantMessage string
|
||||
wantCalls uint32
|
||||
}{
|
||||
{name: "IPs", body: `return server:Query(domain, ipv4, ipv6, fake)`, wantIPs: []net.IP{wantIP}, wantTTL: 60, wantCalls: 2},
|
||||
{name: "empty result", body: `return nil, 0`, wantErr: featureDNS.ErrEmptyResponse, wantCalls: 2},
|
||||
{name: "upstream error", body: `return server:Query("failed.example", ipv4, ipv6, fake)`, wantErr: upstreamErr, wantCalls: 2},
|
||||
{name: "string error", body: `return nil, nil, "blocked"`, wantMessage: "blocked", wantCalls: 2},
|
||||
{name: "invalid result", body: `return false, 0`, wantMessage: "native IP slice", wantCalls: 2},
|
||||
{name: "execution error", body: `error("execution failed")`, wantMessage: "execution failed", wantCalls: 1},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
script := `
|
||||
local server = require("xray.dns").Servers[1]
|
||||
local calls = 0
|
||||
function HandleDNSQuery(domain, ipv4, ipv6, fake)
|
||||
calls = calls + 1
|
||||
if domain == "count.example" then
|
||||
local ips, _, err = server:Query("good.example", ipv4, ipv6, fake)
|
||||
return ips, calls, err
|
||||
end
|
||||
` + tc.body + `
|
||||
end
|
||||
`
|
||||
path := filepath.Join(t.TempDir(), "query.lua")
|
||||
if err := os.WriteFile(path, []byte(script), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
option := featureDNS.IPOption{IPv4Enable: true}
|
||||
upstream := &scriptNameServer{
|
||||
name: "test",
|
||||
answers: map[string]net.IP{"good.example": wantIP},
|
||||
errors: map[string]error{"failed.example": upstreamErr},
|
||||
ttl: 60,
|
||||
}
|
||||
server := &DNS{
|
||||
ctx: context.Background(),
|
||||
clients: []*Client{{server: upstream, ipOption: &option, timeoutMs: time.Second}},
|
||||
}
|
||||
engine, err := newScriptEngine(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := engine.start(server); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer engine.close()
|
||||
|
||||
ips, ttl, err := engine.query("good.example", option)
|
||||
switch {
|
||||
case tc.wantErr != nil:
|
||||
if err != tc.wantErr {
|
||||
t.Fatalf("query error = %v, want original error %v", err, tc.wantErr)
|
||||
}
|
||||
case tc.wantMessage != "":
|
||||
if err == nil || !strings.Contains(err.Error(), tc.wantMessage) {
|
||||
t.Fatalf("query error = %v, want %q", err, tc.wantMessage)
|
||||
}
|
||||
case err != nil:
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ttl != tc.wantTTL || len(ips) != len(tc.wantIPs) {
|
||||
t.Fatalf("query = %v, TTL %d; want %v, TTL %d", ips, ttl, tc.wantIPs, tc.wantTTL)
|
||||
}
|
||||
for i := range ips {
|
||||
if !ips[i].Equal(tc.wantIPs[i]) {
|
||||
t.Fatalf("IP %d = %v, want %v", i, ips[i], tc.wantIPs[i])
|
||||
}
|
||||
}
|
||||
|
||||
ips, calls, err := engine.query("count.example", option)
|
||||
if err != nil || calls != tc.wantCalls || len(ips) != 1 || !ips[0].Equal(wantIP) {
|
||||
t.Fatalf("next query = %v, calls %d, %v; want %v, calls %d", ips, calls, err, wantIP, tc.wantCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSScriptGeoIPFallback(t *testing.T) {
|
||||
t.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
||||
script := `
|
||||
local servers = require("xray.dns").Servers
|
||||
local us_ips = require("xray.geodata").BuildIPMatcher("geoip:us")
|
||||
|
||||
local by_id = {}
|
||||
for _, server in ipairs(servers) do
|
||||
by_id[server.ID] = server
|
||||
end
|
||||
assert(by_id.primary and by_id.fallback, "primary and fallback DNS servers are required")
|
||||
|
||||
function HandleDNSQuery(domain, ipv4, ipv6, fake)
|
||||
local ips, ttl, err = by_id.primary:Query(domain, ipv4, ipv6, fake)
|
||||
if not err and us_ips:AnyMatch(ips) then
|
||||
return ips, ttl, nil
|
||||
end
|
||||
return by_id.fallback:Query(domain, ipv4, ipv6, fake)
|
||||
end
|
||||
`
|
||||
scriptPath := filepath.Join(t.TempDir(), "geoip_fallback.lua")
|
||||
if err := os.WriteFile(scriptPath, []byte(script), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
primary := &scriptNameServer{
|
||||
name: "primary",
|
||||
answers: map[string]net.IP{
|
||||
"us.example": net.ParseIP("2001:4860:4860::8888"),
|
||||
"other.example": net.ParseIP("127.0.0.1"),
|
||||
},
|
||||
ttl: 30,
|
||||
}
|
||||
fallback := &scriptNameServer{
|
||||
name: "fallback",
|
||||
answers: map[string]net.IP{"other.example": net.ParseIP("9.9.9.9")},
|
||||
ttl: 60,
|
||||
}
|
||||
option := featureDNS.IPOption{IPv4Enable: true, IPv6Enable: true}
|
||||
hosts, err := NewStaticHosts(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
engine, err := newScriptEngine(scriptPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := &DNS{
|
||||
ctx: context.Background(),
|
||||
hosts: hosts,
|
||||
ipOption: &option,
|
||||
script: engine,
|
||||
clients: []*Client{
|
||||
{id: "primary", server: primary, ipOption: &option, timeoutMs: 2 * time.Second},
|
||||
{id: "fallback", server: fallback, ipOption: &option, timeoutMs: 2 * time.Second},
|
||||
},
|
||||
}
|
||||
if err := server.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer server.Close()
|
||||
|
||||
for _, tc := range []struct {
|
||||
domain string
|
||||
ip net.IP
|
||||
ttl uint32
|
||||
}{
|
||||
{"Us.Example.", net.ParseIP("2001:4860:4860::8888"), 30},
|
||||
{"other.example", net.ParseIP("9.9.9.9"), 60},
|
||||
} {
|
||||
ips, ttl, err := server.LookupIP(tc.domain, option)
|
||||
if err != nil {
|
||||
t.Fatalf("LookupIP(%q): %v", tc.domain, err)
|
||||
}
|
||||
if ttl != tc.ttl || len(ips) != 1 || !ips[0].Equal(tc.ip) {
|
||||
t.Fatalf("LookupIP(%q) = %v, TTL %d; want %v, TTL %d", tc.domain, ips, ttl, tc.ip, tc.ttl)
|
||||
}
|
||||
}
|
||||
if primary.calls != 2 || fallback.calls != 1 {
|
||||
t.Fatalf("upstream calls: primary %d, fallback %d; want 2 and 1", primary.calls, fallback.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSScriptRejectsInvalidStartup(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, script string
|
||||
compileError bool
|
||||
}{
|
||||
{"syntax", "function HandleDNSQuery(", true},
|
||||
{"missing hook", "value = 1", false},
|
||||
{"invalid hook", "HandleDNSQuery = true", false},
|
||||
{"top-level error", `error("setup failed")`, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "script.lua")
|
||||
if err := os.WriteFile(path, []byte(tc.script), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server, err := New(context.Background(), &Config{Script: path})
|
||||
if tc.compileError {
|
||||
if server != nil || err == nil || !strings.Contains(err.Error(), "failed to prepare DNS script") {
|
||||
t.Fatalf("New = %v, %v; want nil server and script preparation error", server, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer server.Close()
|
||||
if server.script.program == nil || server.script.pool != nil {
|
||||
t.Fatal("New did not compile the script without starting its pool")
|
||||
}
|
||||
if err := server.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := server.Start(); err == nil {
|
||||
t.Fatal("Start accepted an invalid DNS script")
|
||||
}
|
||||
if server.script.pool != nil {
|
||||
t.Fatal("Start retained a script pool after failure")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSScriptProgramSnapshot(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "script.lua")
|
||||
if err := os.WriteFile(path, []byte(`function HandleDNSQuery() return nil, nil, "compiled" end`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
engine, err := newScriptEngine(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer engine.close()
|
||||
if err := os.Remove(path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := engine.start(&DNS{ctx: context.Background()}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := engine.query("example.com", featureDNS.IPOption{}); err == nil || !strings.Contains(err.Error(), "compiled") {
|
||||
t.Fatalf("query error = %v, want compiled", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSScriptFakeDNSOption(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "script.lua")
|
||||
script := `
|
||||
local server = require("xray.dns").Servers[1]
|
||||
local log = require("xray.log")
|
||||
log.Info("DNS script loaded")
|
||||
function HandleDNSQuery(domain, ipv4, ipv6, fake)
|
||||
log.Debug("DNS query: ", domain)
|
||||
local ips, ttl, err = server:Query(domain, ipv4, ipv6, fake)
|
||||
if err then log.Error("DNS failed: ", err) end
|
||||
return ips, ttl, err
|
||||
end
|
||||
`
|
||||
if err := os.WriteFile(path, []byte(script), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
option := featureDNS.IPOption{IPv4Enable: true}
|
||||
hosts, err := NewStaticHosts(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
upstream := &scriptNameServer{
|
||||
name: "FakeDNS",
|
||||
answers: map[string]net.IP{"good.example": net.ParseIP("198.18.0.1")},
|
||||
ttl: 30,
|
||||
}
|
||||
engine, err := newScriptEngine(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := &DNS{
|
||||
ctx: context.Background(),
|
||||
hosts: hosts,
|
||||
ipOption: &option,
|
||||
script: engine,
|
||||
clients: []*Client{{id: "fake", server: upstream, ipOption: &option, timeoutMs: time.Second}},
|
||||
}
|
||||
if err := server.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer server.Close()
|
||||
|
||||
if _, _, err := server.LookupIP("good.example", option); err != featureDNS.ErrEmptyResponse {
|
||||
t.Fatalf("FakeDNS without FakeEnable = %v, want ErrEmptyResponse", err)
|
||||
}
|
||||
if upstream.calls != 0 {
|
||||
t.Fatalf("FakeDNS was queried without FakeEnable: %d calls", upstream.calls)
|
||||
}
|
||||
withFake := featureDNS.IPOption{IPv4Enable: true, FakeEnable: true}
|
||||
ips, ttl, err := server.LookupIP("good.example", withFake)
|
||||
if err != nil || ttl != 30 || len(ips) != 1 || !ips[0].Equal(net.ParseIP("198.18.0.1")) {
|
||||
t.Fatalf("FakeDNS with FakeEnable = %v, TTL %d, %v", ips, ttl, err)
|
||||
}
|
||||
if upstream.calls != 1 {
|
||||
t.Fatalf("FakeDNS query count = %d, want 1", upstream.calls)
|
||||
}
|
||||
}
|
||||
@@ -174,7 +174,7 @@ func NewHandler(ctx context.Context, config *core.InboundHandlerConfig) (inbound
|
||||
Mark: streamSettings.SocketSettings.Mark,
|
||||
})
|
||||
}
|
||||
if streamSettings != nil && streamSettings.ProtocolName == "splithttp" {
|
||||
if streamSettings != nil && (streamSettings.ProtocolName == "splithttp" || streamSettings.ProtocolName == "masque") {
|
||||
ctx = session.ContextWithAllowedNetwork(ctx, net.Network_UDP)
|
||||
}
|
||||
|
||||
|
||||
+11
-2
@@ -587,6 +587,7 @@ type Config struct {
|
||||
DomainStrategy Config_DomainStrategy `protobuf:"varint,1,opt,name=domain_strategy,json=domainStrategy,proto3,enum=xray.app.router.Config_DomainStrategy" json:"domain_strategy,omitempty"`
|
||||
Rule []*RoutingRule `protobuf:"bytes,2,rep,name=rule,proto3" json:"rule,omitempty"`
|
||||
BalancingRule []*BalancingRule `protobuf:"bytes,3,rep,name=balancing_rule,json=balancingRule,proto3" json:"balancing_rule,omitempty"`
|
||||
Script string `protobuf:"bytes,4,opt,name=script,proto3" json:"script,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -642,6 +643,13 @@ func (x *Config) GetBalancingRule() []*BalancingRule {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Config) GetScript() string {
|
||||
if x != nil {
|
||||
return x.Script
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var File_app_router_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_app_router_config_proto_rawDesc = "" +
|
||||
@@ -699,11 +707,12 @@ const file_app_router_config_proto_rawDesc = "" +
|
||||
"\tbaselines\x18\x03 \x03(\x03R\tbaselines\x12\x1a\n" +
|
||||
"\bexpected\x18\x04 \x01(\x05R\bexpected\x12\x16\n" +
|
||||
"\x06maxRTT\x18\x05 \x01(\x03R\x06maxRTT\x12\x1c\n" +
|
||||
"\ttolerance\x18\x06 \x01(\x02R\ttolerance\"\x96\x02\n" +
|
||||
"\ttolerance\x18\x06 \x01(\x02R\ttolerance\"\xae\x02\n" +
|
||||
"\x06Config\x12O\n" +
|
||||
"\x0fdomain_strategy\x18\x01 \x01(\x0e2&.xray.app.router.Config.DomainStrategyR\x0edomainStrategy\x120\n" +
|
||||
"\x04rule\x18\x02 \x03(\v2\x1c.xray.app.router.RoutingRuleR\x04rule\x12E\n" +
|
||||
"\x0ebalancing_rule\x18\x03 \x03(\v2\x1e.xray.app.router.BalancingRuleR\rbalancingRule\"B\n" +
|
||||
"\x0ebalancing_rule\x18\x03 \x03(\v2\x1e.xray.app.router.BalancingRuleR\rbalancingRule\x12\x16\n" +
|
||||
"\x06script\x18\x04 \x01(\tR\x06script\"B\n" +
|
||||
"\x0eDomainStrategy\x12\b\n" +
|
||||
"\x04AsIs\x10\x00\x12\x10\n" +
|
||||
"\fIpIfNonMatch\x10\x02\x12\x0e\n" +
|
||||
|
||||
@@ -110,4 +110,5 @@ message Config {
|
||||
DomainStrategy domain_strategy = 1;
|
||||
repeated RoutingRule rule = 2;
|
||||
repeated BalancingRule balancing_rule = 3;
|
||||
string script = 4;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
xlua "github.com/xtls/xray-core/common/lua"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
const (
|
||||
luaContextType = "xray.router.Context"
|
||||
luaAttributesType = "xray.router.Attributes"
|
||||
)
|
||||
|
||||
// RegisterLua makes xray.router available to routing scripts.
|
||||
func (r *Router) RegisterLua(L *lua.LState) {
|
||||
registerLuaContext(L)
|
||||
|
||||
L.PreloadModule("xray.router", func(L *lua.LState) int {
|
||||
module := L.CreateTable(0, 7)
|
||||
|
||||
module.RawSetString("NetworkUnknown", lua.LNumber(net.Network_Unknown))
|
||||
module.RawSetString("NetworkTCP", lua.LNumber(net.Network_TCP))
|
||||
module.RawSetString("NetworkUDP", lua.LNumber(net.Network_UDP))
|
||||
module.RawSetString("NetworkUNIX", lua.LNumber(net.Network_UNIX))
|
||||
module.RawSetString("LocalOS", lua.LString(runtime.GOOS))
|
||||
|
||||
module.RawSetString("PickOutbound", L.NewFunction(func(L *lua.LState) int {
|
||||
tag, ok := L.Get(1).(lua.LString)
|
||||
if !ok {
|
||||
L.ArgError(1, "balancer tag must be a string")
|
||||
return 0
|
||||
}
|
||||
balancer, found := (*r.balancers.Load())[string(tag)]
|
||||
if !found {
|
||||
xlua.PushNil(L)
|
||||
xlua.PushError(L, errors.New("balancer ", tag, " not found"))
|
||||
return 2
|
||||
}
|
||||
outboundTag, err := balancer.PickOutbound()
|
||||
xlua.PushString(L, outboundTag)
|
||||
xlua.PushError(L, err)
|
||||
return 2
|
||||
}))
|
||||
|
||||
module.RawSetString("FindProcess", L.NewFunction(func(L *lua.LState) int {
|
||||
pid, name, path, err := findProcess(checkLuaContext(L), net.FindProcess)
|
||||
xlua.PushNumber(L, pid)
|
||||
xlua.PushString(L, name)
|
||||
xlua.PushString(L, path)
|
||||
xlua.PushError(L, err)
|
||||
return 4
|
||||
}))
|
||||
|
||||
L.Push(module)
|
||||
return 1
|
||||
})
|
||||
}
|
||||
|
||||
func registerLuaContext(L *lua.LState) {
|
||||
pushIPs := xlua.NewSlicePusher[net.IP](L)
|
||||
attributes := L.NewTypeMetatable(luaAttributesType)
|
||||
L.SetField(attributes, "__index", L.NewFunction(func(L *lua.LState) int {
|
||||
values := L.CheckUserData(1).Value.(map[string]string)
|
||||
key := L.CheckString(2)
|
||||
if value, found := values[key]; found {
|
||||
xlua.PushString(L, value)
|
||||
} else {
|
||||
xlua.PushNil(L)
|
||||
}
|
||||
return 1
|
||||
}))
|
||||
methods := L.CreateTable(0, 4)
|
||||
L.SetFuncs(methods, map[string]lua.LGFunction{
|
||||
"GetSourceIPs": func(L *lua.LState) int {
|
||||
pushIPs(L, checkLuaContext(L).GetSourceIPs())
|
||||
return 1
|
||||
},
|
||||
"GetTargetIPs": func(L *lua.LState) int {
|
||||
pushIPs(L, checkLuaContext(L).GetTargetIPs())
|
||||
return 1
|
||||
},
|
||||
"GetLocalIPs": func(L *lua.LState) int {
|
||||
pushIPs(L, checkLuaContext(L).GetLocalIPs())
|
||||
return 1
|
||||
},
|
||||
"GetAttributes": func(L *lua.LState) int {
|
||||
values := L.NewUserData()
|
||||
values.Value = checkLuaContext(L).GetAttributes()
|
||||
L.SetMetatable(values, attributes)
|
||||
L.Push(values)
|
||||
return 1
|
||||
},
|
||||
})
|
||||
L.SetField(L.NewTypeMetatable(luaContextType), "__index", methods)
|
||||
}
|
||||
|
||||
func checkLuaContext(L *lua.LState) routing.Context {
|
||||
ctx, ok := L.CheckUserData(1).Value.(routing.Context)
|
||||
if !ok {
|
||||
L.ArgError(1, "routing context expected")
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
// callLuaRoute runs HandleRoute and leaves (outboundTag, ruleTag, err) on the stack.
|
||||
func callLuaRoute(L *lua.LState, ctx routing.Context) error {
|
||||
fn := L.GetGlobal("HandleRoute")
|
||||
if fn.Type() != lua.LTFunction {
|
||||
return errors.New("routing script must define HandleRoute(...)")
|
||||
}
|
||||
|
||||
value := L.NewUserData()
|
||||
value.Value = ctx
|
||||
L.SetMetatable(value, L.GetTypeMetatable(luaContextType))
|
||||
|
||||
return L.CallByParam(lua.P{Fn: fn, NRet: 3, Protect: true},
|
||||
value,
|
||||
lua.LString(ctx.GetInboundTag()),
|
||||
lua.LNumber(ctx.GetSourcePort()),
|
||||
lua.LNumber(ctx.GetTargetPort()),
|
||||
lua.LNumber(ctx.GetLocalPort()),
|
||||
lua.LString(strings.ToLower(ctx.GetTargetDomain())),
|
||||
lua.LNumber(ctx.GetNetwork()),
|
||||
lua.LString(ctx.GetProtocol()),
|
||||
lua.LString(ctx.GetUser()),
|
||||
lua.LNumber(ctx.GetVlessRoute()),
|
||||
lua.LBool(ctx.GetSkipDNSResolve()))
|
||||
}
|
||||
|
||||
// readLuaRouteResult reads (outboundTag, ruleTag, err) from the stack.
|
||||
func readLuaRouteResult(L *lua.LState) (string, string, error) {
|
||||
if err := xlua.ReadError(L.Get(-1), "routing script error must be an error or string"); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
outboundTag, err := xlua.ReadOptionalString(L.Get(-3), "routing script outboundTag must be a string or nil")
|
||||
if err != nil || outboundTag == "" {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
ruleTag, err := xlua.ReadOptionalString(L.Get(-2), "routing script ruleTag must be a string")
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
return outboundTag, ruleTag, nil
|
||||
}
|
||||
|
||||
type processFinder func(string, string, uint16, string, uint16) (int, string, string, error)
|
||||
|
||||
func findProcess(ctx routing.Context, finder processFinder) (int, string, string, error) {
|
||||
sources := ctx.GetSourceIPs()
|
||||
if len(sources) == 0 {
|
||||
return 0, "", "", errors.New("process lookup requires a source IP")
|
||||
}
|
||||
var network string
|
||||
switch ctx.GetNetwork() {
|
||||
case net.Network_TCP:
|
||||
network = "tcp"
|
||||
case net.Network_UDP:
|
||||
network = "udp"
|
||||
default:
|
||||
return 0, "", "", errors.New("process lookup requires TCP or UDP")
|
||||
}
|
||||
targetIP, targetPort := "", uint16(0)
|
||||
if targets := ctx.GetTargetIPs(); len(targets) > 0 {
|
||||
targetIP, targetPort = targets[0].String(), uint16(ctx.GetTargetPort())
|
||||
}
|
||||
return finder(network, sources[0].String(), uint16(ctx.GetSourcePort()), targetIP, targetPort)
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
routing_session "github.com/xtls/xray-core/features/routing/session"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
func benchmarkRouteContext(target net.Destination) *routing_session.Context {
|
||||
// Use the production context: its IP getters construct a slice per call.
|
||||
// The cached IP slices in luaRouteTestContext would undercount this cost.
|
||||
return &routing_session.Context{
|
||||
Inbound: &session.Inbound{
|
||||
Tag: "in",
|
||||
Source: net.TCPDestination(net.LocalHostIP, 1234),
|
||||
Local: net.TCPDestination(net.LocalHostIP, 5678),
|
||||
},
|
||||
Outbound: &session.Outbound{Target: target},
|
||||
Content: &session.Content{Protocol: "tls"},
|
||||
}
|
||||
}
|
||||
|
||||
func benchmarkRouteState(b *testing.B, r *Router, script string) *lua.LState {
|
||||
b.Helper()
|
||||
L := lua.NewState()
|
||||
b.Cleanup(L.Close)
|
||||
r.RegisterLua(L)
|
||||
geodata.RegisterLua(L)
|
||||
if err := L.DoString(script); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
L.SetContext(context.Background())
|
||||
return L
|
||||
}
|
||||
|
||||
// BenchmarkLuaRouteHook isolates argument bridging and a fixed-return hook.
|
||||
// It excludes rules, result decoding, the state pool, and Route construction.
|
||||
func BenchmarkLuaRouteHook(b *testing.B) {
|
||||
L := benchmarkRouteState(b, new(Router), `
|
||||
function HandleRoute(ctx, inboundTag, sourcePort, targetPort, localPort,
|
||||
targetDomain, network, protocol, user, vlessRoute, skipDNSResolve)
|
||||
return "out", "rule"
|
||||
end
|
||||
`)
|
||||
ctx := benchmarkRouteContext(net.TCPDestination(net.LocalHostIP, 443))
|
||||
if err := callLuaRoute(L, ctx); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
outboundTag, ruleTag, err := readLuaRouteResult(L)
|
||||
L.Pop(3)
|
||||
if err != nil || outboundTag != "out" || ruleTag != "rule" {
|
||||
b.Fatalf("hook() = %q, %q, %v", outboundTag, ruleTag, err)
|
||||
}
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
if err := callLuaRoute(L, ctx); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
L.Pop(3)
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkLuaRoute compares equivalent ordered rules on the same session.
|
||||
// rules returns tags only; pick_route uses Router.PickRoute on both sides.
|
||||
// All compilation, matcher construction, and pool startup are outside timing.
|
||||
func BenchmarkLuaRoute(b *testing.B) {
|
||||
for _, name := range []string{"scalar", "ip", "domain", "domain_32_last"} {
|
||||
b.Run(name, func(b *testing.B) {
|
||||
config, script, ctx, wantTag, wantRule := benchmarkRouteFixture(b, name)
|
||||
native := new(Router)
|
||||
if err := native.Init(context.Background(), config, nil, nil, nil); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
L := benchmarkRouteState(b, native, script)
|
||||
|
||||
path := filepath.Join(b.TempDir(), "route.lua")
|
||||
if err := os.WriteFile(path, []byte(script), 0o600); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
scripted := new(Router)
|
||||
if err := scripted.Init(context.Background(), &Config{Script: path}, nil, nil, nil); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
if err := scripted.Start(); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
b.Cleanup(func() {
|
||||
if err := scripted.Close(); err != nil {
|
||||
b.Error(err)
|
||||
}
|
||||
})
|
||||
|
||||
for _, bench := range []struct {
|
||||
name string
|
||||
route func() (string, string, error)
|
||||
}{
|
||||
{"rules/native", func() (string, string, error) {
|
||||
rule, _, err := native.pickRouteInternal(ctx)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
tag, err := rule.GetTag()
|
||||
return tag, rule.RuleTag, err
|
||||
}},
|
||||
{"rules/lua", func() (string, string, error) {
|
||||
if err := callLuaRoute(L, ctx); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
tag, ruleTag, err := readLuaRouteResult(L)
|
||||
L.Pop(3)
|
||||
return tag, ruleTag, err
|
||||
}},
|
||||
{"pick_route/native", func() (string, string, error) {
|
||||
return benchmarkPickRoute(native, ctx)
|
||||
}},
|
||||
{"pick_route/lua", func() (string, string, error) {
|
||||
return benchmarkPickRoute(scripted, ctx)
|
||||
}},
|
||||
} {
|
||||
b.Run(bench.name, func(b *testing.B) {
|
||||
// Validate and warm both paths before measuring steady state.
|
||||
tag, ruleTag, err := bench.route()
|
||||
if err != nil || tag != wantTag || ruleTag != wantRule {
|
||||
b.Fatalf("route() = %q, %q, %v; want %q, %q", tag, ruleTag, err, wantTag, wantRule)
|
||||
}
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
tag, ruleTag, err = bench.route()
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
b.StopTimer()
|
||||
if tag != wantTag || ruleTag != wantRule {
|
||||
b.Fatalf("route() = %q, %q; want %q, %q", tag, ruleTag, wantTag, wantRule)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func benchmarkPickRoute(r *Router, ctx routing.Context) (string, string, error) {
|
||||
route, err := r.PickRoute(ctx)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return route.GetOutboundTag(), route.GetRuleTag(), nil
|
||||
}
|
||||
|
||||
func benchmarkRouteFixture(b *testing.B, name string) (*Config, string, routing.Context, string, string) {
|
||||
b.Helper()
|
||||
config := new(Config)
|
||||
ctx := benchmarkRouteContext(net.TCPDestination(net.LocalHostIP, 443))
|
||||
prelude := `local router = require("xray.router")
|
||||
local geodata = require("xray.geodata")
|
||||
`
|
||||
body := `if inboundTag == "in" and network == router.NetworkTCP then return "out", "rule" end`
|
||||
wantTag, wantRule := "out", "rule"
|
||||
if name == "scalar" || name == "ip" {
|
||||
rule := &RoutingRule{
|
||||
TargetTag: &RoutingRule_Tag{Tag: wantTag},
|
||||
RuleTag: wantRule,
|
||||
InboundTag: []string{"in"},
|
||||
Networks: []net.Network{net.Network_TCP},
|
||||
}
|
||||
if name == "ip" {
|
||||
var err error
|
||||
rule.Ip, err = geodata.ParseIPRules([]string{"127.0.0.0/8"})
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
prelude += `local matcher = geodata.BuildIPMatcher("127.0.0.0/8")` + "\n"
|
||||
body = `if inboundTag == "in" and network == router.NetworkTCP and matcher:AnyMatch(ctx:GetTargetIPs()) then return "out", "rule" end`
|
||||
}
|
||||
config.Rule = []*RoutingRule{rule}
|
||||
} else {
|
||||
count := 1
|
||||
if name == "domain_32_last" {
|
||||
count = 32
|
||||
}
|
||||
var rules strings.Builder
|
||||
rules.WriteString("local rules = {\n")
|
||||
for i := 0; i < count; i++ {
|
||||
domain := fmt.Sprintf("route-%d.example.com", i)
|
||||
tag, ruleTag := fmt.Sprintf("out-%d", i), fmt.Sprintf("rule-%d", i)
|
||||
domains, err := geodata.ParseDomainRules([]string{"full:" + domain}, geodata.Domain_Domain)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
config.Rule = append(config.Rule, &RoutingRule{
|
||||
TargetTag: &RoutingRule_Tag{Tag: tag}, RuleTag: ruleTag, Domain: domains,
|
||||
})
|
||||
fmt.Fprintf(&rules, "{geodata.BuildDomainMatcher(%q), %q, %q},\n", "full:"+domain, tag, ruleTag)
|
||||
if i == count-1 {
|
||||
ctx.Outbound.Target = net.TCPDestination(net.DomainAddress(domain), 443)
|
||||
wantTag, wantRule = tag, ruleTag
|
||||
}
|
||||
}
|
||||
rules.WriteString("}\n")
|
||||
prelude += rules.String()
|
||||
body = `for i = 1, #rules do
|
||||
local rule = rules[i]
|
||||
if rule[1]:MatchAny(targetDomain) then return rule[2], rule[3] end
|
||||
end`
|
||||
}
|
||||
script := prelude + `function HandleRoute(ctx, inboundTag, sourcePort, targetPort, localPort,
|
||||
targetDomain, network, protocol, user, vlessRoute, skipDNSResolve)
|
||||
` + body + "\nend\n"
|
||||
return config, script, ctx, wantTag, wantRule
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"context"
|
||||
go_errors "errors"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
"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/features/routing"
|
||||
routing_session "github.com/xtls/xray-core/features/routing/session"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
type luaRouteTestContext struct {
|
||||
*routing_session.Context
|
||||
sourceIPs, targetIPs, localIPs []net.IP
|
||||
}
|
||||
|
||||
func (c *luaRouteTestContext) GetSourceIPs() []net.IP { return c.sourceIPs }
|
||||
func (c *luaRouteTestContext) GetTargetIPs() []net.IP { return c.targetIPs }
|
||||
func (c *luaRouteTestContext) GetLocalIPs() []net.IP { return c.localIPs }
|
||||
|
||||
func newLuaRouteTestContext() *luaRouteTestContext {
|
||||
return &luaRouteTestContext{
|
||||
Context: &routing_session.Context{
|
||||
Inbound: &session.Inbound{
|
||||
Tag: "in", VlessRoute: 4321,
|
||||
Source: net.TCPDestination(net.LocalHostIP, 1234),
|
||||
Local: net.TCPDestination(net.LocalHostIP, 5678),
|
||||
User: &protocol.MemoryUser{Email: "user@example.com"},
|
||||
},
|
||||
Outbound: &session.Outbound{
|
||||
Target: net.TCPDestination(net.LocalHostIP, 443),
|
||||
RouteTarget: net.TCPDestination(net.DomainAddress("MiXeD.Example."), 443),
|
||||
},
|
||||
Content: &session.Content{
|
||||
Protocol: "tls", Attributes: map[string]string{"key": "value"}, SkipDNSResolve: true,
|
||||
},
|
||||
},
|
||||
sourceIPs: []net.IP{{127, 0, 0, 2}},
|
||||
targetIPs: []net.IP{{127, 0, 0, 3}},
|
||||
localIPs: []net.IP{{127, 0, 0, 1}},
|
||||
}
|
||||
}
|
||||
|
||||
func newLuaRouterState(t *testing.T, script string) *lua.LState {
|
||||
t.Helper()
|
||||
r := new(Router)
|
||||
if err := r.Init(context.Background(), &Config{}, nil, nil, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
L := lua.NewState()
|
||||
t.Cleanup(L.Close)
|
||||
r.RegisterLua(L)
|
||||
geodata.RegisterLua(L)
|
||||
if err := L.DoString(script); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return L
|
||||
}
|
||||
|
||||
func TestLuaRouteBinding(t *testing.T) {
|
||||
L := newLuaRouterState(t, `
|
||||
local router = require("xray.router")
|
||||
local matcher = require("xray.geodata").BuildIPMatcher("127.0.0.0/8")
|
||||
assert(router.NetworkUnknown == 0 and router.NetworkTCP == 2)
|
||||
assert(router.NetworkUDP == 3 and router.NetworkUNIX == 4)
|
||||
assert(router.BuildIPMatcher == nil and router.BuildDomainMatcher == nil)
|
||||
function HandleRoute(ctx, inboundTag, sourcePort, targetPort, localPort,
|
||||
targetDomain, network, protocol, user, vlessRoute, skipDNSResolve, ...)
|
||||
assert(select("#", ...) == 0)
|
||||
assert(inboundTag == "in" and sourcePort == 1234 and targetPort == 443 and localPort == 5678)
|
||||
assert(targetDomain == "mixed.example." and network == router.NetworkTCP)
|
||||
assert(protocol == "tls" and user == "user@example.com" and vlessRoute == 4321 and skipDNSResolve)
|
||||
assert(ctx.GetNetwork == nil and ctx.Context == nil)
|
||||
savedContext = ctx
|
||||
sourceIPs, targetIPs, localIPs = ctx:GetSourceIPs(), ctx:GetTargetIPs(), ctx:GetLocalIPs()
|
||||
attributes = ctx:GetAttributes()
|
||||
assert(#sourceIPs == 1 and #targetIPs == 1 and #localIPs == 1)
|
||||
assert(sourceIPs[1]:String() == "127.0.0.2" and targetIPs[1]:String() == "127.0.0.3")
|
||||
assert(localIPs[1]:String() == "127.0.0.1")
|
||||
assert(matcher:Match(sourceIPs[1]) and matcher:Match(targetIPs[1]) and matcher:Match(localIPs[1]))
|
||||
assert(matcher:AnyMatch(sourceIPs) and matcher:AnyMatch(targetIPs) and matcher:AnyMatch(localIPs))
|
||||
local matched = matcher:FilterIPs(targetIPs)
|
||||
assert(#matched == 1 and matched[1]:Equal(targetIPs[1]))
|
||||
assert(attributes.key == "value" and attributes.missing == nil)
|
||||
assert(not pcall(function() attributes.key = "changed" end))
|
||||
return "out", "rule"
|
||||
end`)
|
||||
|
||||
ctx := newLuaRouteTestContext()
|
||||
if err := callLuaRoute(L, ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if L.GetTop() != 3 || L.Get(1) != lua.LString("out") || L.Get(2) != lua.LString("rule") || L.Get(3) != lua.LNil {
|
||||
t.Fatal("callLuaRoute did not leave the three route results on the stack")
|
||||
}
|
||||
if L.GetGlobal("savedContext").(*lua.LUserData).Value != ctx {
|
||||
t.Fatal("routing context was copied")
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
want []net.IP
|
||||
}{
|
||||
{"sourceIPs", ctx.sourceIPs},
|
||||
{"targetIPs", ctx.targetIPs},
|
||||
{"localIPs", ctx.localIPs},
|
||||
} {
|
||||
got := L.GetGlobal(tc.name).(*lua.LUserData).Value.([]net.IP)
|
||||
if &got[0] != &tc.want[0] {
|
||||
t.Fatalf("%s storage was copied", tc.name)
|
||||
}
|
||||
}
|
||||
ctx.Content.Attributes["key"] = "updated"
|
||||
L.SetGlobal("expectedOS", lua.LString(runtime.GOOS))
|
||||
if err := L.DoString(`
|
||||
assert(attributes.key == "updated")
|
||||
assert(require("xray.router").LocalOS == expectedOS)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLuaRouteEmptyIPs(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
ips []net.IP
|
||||
}{
|
||||
{"nil", nil},
|
||||
{"empty", []net.IP{}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
L := newLuaRouterState(t, `
|
||||
function HandleRoute(ctx)
|
||||
for _, name in ipairs({"GetSourceIPs", "GetTargetIPs", "GetLocalIPs"}) do
|
||||
local ips = ctx[name](ctx)
|
||||
if expectNil then
|
||||
assert(ips == nil)
|
||||
else
|
||||
assert(type(ips) == "userdata" and #ips == 0)
|
||||
assert(not pcall(function() return ips[1] end))
|
||||
end
|
||||
end
|
||||
return "out"
|
||||
end
|
||||
`)
|
||||
L.SetGlobal("expectNil", lua.LBool(tc.ips == nil))
|
||||
ctx := newLuaRouteTestContext()
|
||||
ctx.sourceIPs, ctx.targetIPs, ctx.localIPs = tc.ips, tc.ips, tc.ips
|
||||
if err := callLuaRoute(L, ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadLuaRouteResult(t *testing.T) {
|
||||
nativeErr := go_errors.New("native failure")
|
||||
for _, tc := range []struct {
|
||||
name, values string
|
||||
wantTag, wantRule string
|
||||
wantErr error
|
||||
wantMessage string
|
||||
}{
|
||||
{name: "route", values: `"out", "rule"`, wantTag: "out", wantRule: "rule"},
|
||||
{name: "no match", values: `nil`},
|
||||
{name: "empty tag", values: `""`},
|
||||
{name: "no match ignores rule", values: `nil, false`},
|
||||
{name: "empty tag ignores rule", values: `"", false`},
|
||||
{name: "missing rule", values: `"out"`, wantTag: "out"},
|
||||
{name: "invalid tag", values: `1`, wantMessage: "outboundTag"},
|
||||
{name: "invalid rule", values: `"out", false`, wantMessage: "ruleTag"},
|
||||
{name: "string error", values: `nil, nil, "script failure"`, wantMessage: "script failure"},
|
||||
{name: "native error", values: `nil, nil, nativeError`, wantErr: nativeErr},
|
||||
{name: "error overrides invalid tags", values: `false, false, nativeError`, wantErr: nativeErr},
|
||||
{name: "invalid error", values: `"out", "rule", false`, wantMessage: "error or string"},
|
||||
{name: "wrong error userdata", values: `"out", "rule", wrongError`, wantMessage: "error or string"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
L := lua.NewState()
|
||||
defer L.Close()
|
||||
for name, value := range map[string]any{"nativeError": nativeErr, "wrongError": "not a native error"} {
|
||||
ud := L.NewUserData()
|
||||
ud.Value = value
|
||||
L.SetGlobal(name, ud)
|
||||
}
|
||||
fn, err := L.LoadString("return " + tc.values)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := L.CallByParam(lua.P{Fn: fn, NRet: 3, Protect: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outboundTag, ruleTag, err := readLuaRouteResult(L)
|
||||
if outboundTag != tc.wantTag || ruleTag != tc.wantRule {
|
||||
t.Fatalf("result = %q, %q, %v; want %q, %q", outboundTag, ruleTag, err, tc.wantTag, tc.wantRule)
|
||||
}
|
||||
switch {
|
||||
case tc.wantErr != nil:
|
||||
if err != tc.wantErr {
|
||||
t.Fatalf("error = %v, want original error", err)
|
||||
}
|
||||
case tc.wantMessage != "":
|
||||
if err == nil || !strings.Contains(err.Error(), tc.wantMessage) {
|
||||
t.Fatalf("error = %v, want %q", err, tc.wantMessage)
|
||||
}
|
||||
case err != nil:
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallLuaRouteCancellation(t *testing.T) {
|
||||
L := newLuaRouterState(t, `function HandleRoute() while true do end end`)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
L.SetContext(ctx)
|
||||
if err := callLuaRoute(L, &routing_session.Context{}); err == nil {
|
||||
t.Fatal("callLuaRoute did not stop after context cancellation")
|
||||
}
|
||||
if L.Context() != ctx {
|
||||
t.Fatal("callLuaRoute changed the Lua state's context")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindProcess(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, network, target string
|
||||
targetPort uint16
|
||||
modify func(*luaRouteTestContext)
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "TCP", network: "tcp", target: "127.0.0.3", targetPort: 443},
|
||||
{name: "UDP", network: "udp", target: "127.0.0.3", targetPort: 443, modify: func(c *luaRouteTestContext) {
|
||||
c.Outbound.Target.Network = net.Network_UDP
|
||||
}},
|
||||
{name: "domain target", network: "tcp", modify: func(c *luaRouteTestContext) { c.targetIPs = nil }},
|
||||
{name: "missing source", modify: func(c *luaRouteTestContext) { c.sourceIPs = nil }, wantErr: true},
|
||||
{name: "unsupported network", modify: func(c *luaRouteTestContext) {
|
||||
c.Outbound.Target.Network = net.Network_UNIX
|
||||
}, wantErr: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx := newLuaRouteTestContext()
|
||||
if tc.modify != nil {
|
||||
tc.modify(ctx)
|
||||
}
|
||||
called := false
|
||||
pid, name, path, err := findProcess(ctx, func(network, source string, sourcePort uint16, target string, targetPort uint16) (int, string, string, error) {
|
||||
called = true
|
||||
if network != tc.network || source != "127.0.0.2" || sourcePort != 1234 || target != tc.target || targetPort != tc.targetPort {
|
||||
t.Fatalf("endpoints = %s %s:%d -> %s:%d", network, source, sourcePort, target, targetPort)
|
||||
}
|
||||
return 42, "process", "/path/process", nil
|
||||
})
|
||||
if tc.wantErr {
|
||||
if err == nil || called {
|
||||
t.Fatalf("findProcess = %d, %q, %q, %v", pid, name, path, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || !called || pid != 42 || name != "process" || path != "/path/process" {
|
||||
t.Fatalf("findProcess = %d, %q, %q, %v", pid, name, path, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var _ routing.Context = (*luaRouteTestContext)(nil)
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
type Router struct {
|
||||
domainStrategy Config_DomainStrategy
|
||||
rules atomic.Pointer[[]*Rule]
|
||||
script *scriptEngine
|
||||
balancers atomic.Pointer[map[string]*Balancer]
|
||||
dns dns.Client
|
||||
|
||||
@@ -45,6 +46,14 @@ func (r *Router) Init(ctx context.Context, config *Config, d dns.Client, ohm out
|
||||
r.ohm = ohm
|
||||
r.dispatcher = dispatcher
|
||||
|
||||
if config.Script != "" {
|
||||
script, err := newScriptEngine(config.Script)
|
||||
if err != nil {
|
||||
return errors.New("failed to prepare routing script").Base(err)
|
||||
}
|
||||
r.script = script
|
||||
}
|
||||
|
||||
r.rules.Store(new([]*Rule))
|
||||
r.balancers.Store(&map[string]*Balancer{})
|
||||
return r.ReloadRules(config, false)
|
||||
@@ -52,6 +61,10 @@ func (r *Router) Init(ctx context.Context, config *Config, d dns.Client, ohm out
|
||||
|
||||
// PickRoute implements routing.Router.
|
||||
func (r *Router) PickRoute(ctx routing.Context) (routing.Route, error) {
|
||||
if r.script != nil {
|
||||
return r.script.pickRoute(ctx)
|
||||
}
|
||||
|
||||
originalCtx := ctx
|
||||
rule, ctx, err := r.pickRouteInternal(ctx)
|
||||
if err != nil {
|
||||
@@ -221,6 +234,11 @@ func (r *Router) pickRouteInternal(ctx routing.Context) (*Rule, routing.Context,
|
||||
|
||||
// Start implements common.Runnable.
|
||||
func (r *Router) Start() error {
|
||||
if r.script != nil {
|
||||
if err := r.script.start(r); err != nil {
|
||||
return errors.New("failed to initialize routing script").Base(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -235,6 +253,9 @@ func closeWebhooks(rules []*Rule) {
|
||||
|
||||
// Close implements common.Closable.
|
||||
func (r *Router) Close() error {
|
||||
if r.script != nil {
|
||||
r.script.close()
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
closeWebhooks(*r.rules.Load())
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/app/dns"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
xlua "github.com/xtls/xray-core/common/lua"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
const scriptExecutionTimeout = 6 * time.Second
|
||||
|
||||
type scriptEngine struct {
|
||||
program *xlua.Program
|
||||
pool *xlua.Pool
|
||||
}
|
||||
|
||||
func newScriptEngine(script string) (*scriptEngine, error) {
|
||||
program, err := xlua.Compile(script)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &scriptEngine{program: program}, nil
|
||||
}
|
||||
|
||||
func (e *scriptEngine) start(router *Router) error {
|
||||
pool, err := xlua.NewPool(router.ctx, scriptExecutionTimeout, e.program.NewStateFactory(
|
||||
scriptExecutionTimeout*20,
|
||||
func(L *lua.LState) {
|
||||
geodata.RegisterLua(L)
|
||||
log.RegisterLua(L)
|
||||
router.RegisterLua(L)
|
||||
dns.RegisterLua(L, router.dns)
|
||||
},
|
||||
func(L *lua.LState) error {
|
||||
if L.GetGlobal("HandleRoute").Type() != lua.LTFunction {
|
||||
return errors.New("routing script must define HandleRoute(...)")
|
||||
}
|
||||
return nil
|
||||
}))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
e.pool = pool
|
||||
errors.LogInfo(router.ctx, "routing script initialized")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *scriptEngine) close() {
|
||||
if e.pool != nil {
|
||||
e.pool.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (e *scriptEngine) pickRoute(ctx routing.Context) (routing.Route, error) {
|
||||
var outboundTag, ruleTag string
|
||||
var routeErr error
|
||||
|
||||
if err := e.pool.WithState(nil, 0, func(L *lua.LState) error {
|
||||
if err := callLuaRoute(L, ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
outboundTag, ruleTag, routeErr = readLuaRouteResult(L)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if routeErr != nil {
|
||||
return nil, routeErr
|
||||
}
|
||||
if outboundTag == "" {
|
||||
return nil, common.ErrNoClue
|
||||
}
|
||||
|
||||
return &Route{Context: ctx, outboundTag: outboundTag, ruleTag: ruleTag}, nil
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"context"
|
||||
stdnet "net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
wireDNS "github.com/miekg/dns"
|
||||
"github.com/xtls/xray-core/app/dispatcher"
|
||||
appdns "github.com/xtls/xray-core/app/dns"
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
_ "github.com/xtls/xray-core/app/proxyman/outbound"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/core"
|
||||
featureDNS "github.com/xtls/xray-core/features/dns"
|
||||
"github.com/xtls/xray-core/features/outbound"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
routing_session "github.com/xtls/xray-core/features/routing/session"
|
||||
"github.com/xtls/xray-core/proxy/blackhole"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
)
|
||||
|
||||
type luaRouteDNSClient struct {
|
||||
featureDNS.Client
|
||||
lookup func(string, featureDNS.IPOption) ([]net.IP, uint32, error)
|
||||
}
|
||||
|
||||
func (d *luaRouteDNSClient) LookupIP(domain string, option featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||
return d.lookup(domain, option)
|
||||
}
|
||||
|
||||
type luaRouteOutboundManager struct{ outbound.Manager }
|
||||
|
||||
func (*luaRouteOutboundManager) Select(selectors []string) []string { return selectors }
|
||||
|
||||
func writeRouteScript(t *testing.T, script string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "route.lua")
|
||||
if err := os.WriteFile(path, []byte(script), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func startLuaRouter(t *testing.T, script string, d featureDNS.Client, config *Config) *Router {
|
||||
t.Helper()
|
||||
if config == nil {
|
||||
config = &Config{}
|
||||
}
|
||||
config.Script = writeRouteScript(t, script)
|
||||
r := new(Router)
|
||||
if err := r.Init(context.Background(), config, d, &luaRouteOutboundManager{}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := r.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
return r
|
||||
}
|
||||
|
||||
func TestRouterScriptStartup(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, script string
|
||||
compileError bool
|
||||
}{
|
||||
{"syntax error", "function HandleRoute(", true},
|
||||
{"missing hook", "value = 1", false},
|
||||
{"invalid hook", "HandleRoute = true", false},
|
||||
{"initialization error", `error("setup failed")`, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
r := new(Router)
|
||||
err := r.Init(context.Background(), &Config{Script: writeRouteScript(t, tc.script)}, nil, nil, nil)
|
||||
if tc.compileError {
|
||||
if r.script != nil || err == nil || !strings.Contains(err.Error(), "failed to prepare routing script") {
|
||||
t.Fatalf("Init = %v; want no engine and script preparation error", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Close()
|
||||
if r.script.program == nil || r.script.pool != nil {
|
||||
t.Fatal("Init did not compile the script without starting its pool")
|
||||
}
|
||||
if err := r.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.Start(); err == nil {
|
||||
t.Fatal("Start accepted an invalid routing script")
|
||||
}
|
||||
if r.script.pool != nil {
|
||||
t.Fatal("Start retained a script pool after failure")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouterScriptProgramSnapshot(t *testing.T) {
|
||||
path := writeRouteScript(t, `function HandleRoute() return "compiled", "compiled-rule" end`)
|
||||
engine, err := newScriptEngine(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer engine.close()
|
||||
if err := os.Remove(path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := engine.start(&Router{ctx: context.Background()}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
route, err := engine.pickRoute(newLuaRouteTestContext())
|
||||
if err != nil || route == nil || route.GetOutboundTag() != "compiled" || route.GetRuleTag() != "compiled-rule" {
|
||||
t.Fatalf("route = %v, %v; want compiled, compiled-rule", route, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouterScriptRouting(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, body string
|
||||
wantTag, wantRule string
|
||||
wantErr error
|
||||
wantMessage string
|
||||
wantCalls string
|
||||
}{
|
||||
{name: "route", body: `return "lua-out", "lua-rule"`, wantTag: "lua-out", wantRule: "lua-rule", wantCalls: "2"},
|
||||
{name: "no match", body: `return nil`, wantErr: common.ErrNoClue, wantCalls: "2"},
|
||||
{name: "empty tag", body: `return ""`, wantErr: common.ErrNoClue, wantCalls: "2"},
|
||||
{name: "balancer error", body: `local tag, err = router.PickOutbound("missing"); return tag, nil, err`, wantMessage: "not found", wantCalls: "2"},
|
||||
{name: "string error", body: `return nil, nil, "blocked"`, wantMessage: "blocked", wantCalls: "2"},
|
||||
{name: "invalid tag", body: `return false`, wantMessage: "outboundTag", wantCalls: "2"},
|
||||
{name: "invalid rule", body: `return "lua-out", false`, wantMessage: "ruleTag", wantCalls: "2"},
|
||||
{name: "execution error", body: `error("execution failed")`, wantMessage: "execution failed", wantCalls: "1"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var dnsCalls atomic.Int32
|
||||
d := &luaRouteDNSClient{lookup: func(string, featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||
dnsCalls.Add(1)
|
||||
return []net.IP{{1, 2, 3, 4}}, 60, nil
|
||||
}}
|
||||
script := `
|
||||
local router = require("xray.router")
|
||||
local calls = 0
|
||||
function HandleRoute(ctx, inbound)
|
||||
calls = calls + 1
|
||||
if inbound == "count" then return "lua-out", tostring(calls) end
|
||||
` + tc.body + `
|
||||
end
|
||||
`
|
||||
r := startLuaRouter(t, script, d, &Config{
|
||||
DomainStrategy: Config_IpOnDemand,
|
||||
Rule: []*RoutingRule{{
|
||||
TargetTag: &RoutingRule_Tag{Tag: "json-out"},
|
||||
Networks: []net.Network{net.Network_TCP},
|
||||
}},
|
||||
})
|
||||
ctx := newLuaRouteTestContext()
|
||||
ctx.Content.SkipDNSResolve = false
|
||||
route, err := r.PickRoute(ctx)
|
||||
switch {
|
||||
case tc.wantErr != nil:
|
||||
if err != tc.wantErr {
|
||||
t.Fatalf("route error = %v, want %v", err, tc.wantErr)
|
||||
}
|
||||
case tc.wantMessage != "":
|
||||
if err == nil || !strings.Contains(err.Error(), tc.wantMessage) {
|
||||
t.Fatalf("route error = %v, want %q", err, tc.wantMessage)
|
||||
}
|
||||
case err != nil:
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tc.wantTag == "" {
|
||||
if route != nil {
|
||||
t.Fatalf("route = %v, want nil", route)
|
||||
}
|
||||
} else if route == nil || route.GetOutboundTag() != tc.wantTag || route.GetRuleTag() != tc.wantRule || route.(*Route).Context != ctx {
|
||||
t.Fatalf("route = %v; want %q, %q and original context", route, tc.wantTag, tc.wantRule)
|
||||
}
|
||||
|
||||
ctx.Inbound.Tag = "count"
|
||||
route, err = r.PickRoute(ctx)
|
||||
if err != nil || route == nil || route.GetOutboundTag() != "lua-out" || route.GetRuleTag() != tc.wantCalls {
|
||||
t.Fatalf("next route = %v, %v; want lua-out, calls %s", route, err, tc.wantCalls)
|
||||
}
|
||||
if dnsCalls.Load() != 0 {
|
||||
t.Fatal("script routing implicitly resolved DNS")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouterScriptModules(t *testing.T) {
|
||||
ips := []net.IP{{127, 0, 0, 7}}
|
||||
calls := 0
|
||||
d := &luaRouteDNSClient{lookup: func(domain string, option featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||
calls++
|
||||
if domain != "mixed.example." || !option.IPv4Enable || option.IPv6Enable || !option.FakeEnable {
|
||||
t.Fatalf("dns.Query arguments = %q, %+v", domain, option)
|
||||
}
|
||||
return ips, 17, nil
|
||||
}}
|
||||
r := startLuaRouter(t, `
|
||||
local dns = require("xray.dns")
|
||||
local matcher = require("xray.geodata").BuildIPMatcher("127.0.0.0/8")
|
||||
assert(dns.Servers == nil and type(dns.Query) == "function")
|
||||
assert(type(require("xray.log").Info) == "function")
|
||||
function HandleRoute(ctx, inbound, sourcePort, targetPort, localPort, domain)
|
||||
local ips, ttl, err = dns.Query(domain, true, false, true)
|
||||
assert(not err and ttl == 17)
|
||||
assert(matcher:AnyMatch(ips) and matcher:AnyMatch(ctx:GetTargetIPs()))
|
||||
return "out"
|
||||
end`, d, nil)
|
||||
if _, err := r.PickRoute(newLuaRouteTestContext()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatalf("DNS calls = %d, want 1", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouterScriptBalancerReload(t *testing.T) {
|
||||
config := func(tag string) *Config {
|
||||
return &Config{BalancingRule: []*BalancingRule{{
|
||||
Tag: "balance", Strategy: "roundrobin", OutboundSelector: []string{tag},
|
||||
}}}
|
||||
}
|
||||
r := startLuaRouter(t, `
|
||||
local router = require("xray.router")
|
||||
function HandleRoute()
|
||||
local tag, err = router.PickOutbound("balance")
|
||||
return tag, "balanced", err
|
||||
end`, nil, config("old"))
|
||||
pick := func(want string) {
|
||||
t.Helper()
|
||||
route, err := r.PickRoute(&routing_session.Context{})
|
||||
if err != nil || route.GetOutboundTag() != want || route.GetRuleTag() != "balanced" {
|
||||
t.Fatalf("route = %v, %v, want %q", route, err, want)
|
||||
}
|
||||
}
|
||||
|
||||
pick("old")
|
||||
if err := r.SetOverrideTarget("balance", "override"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pick("override")
|
||||
if err := r.SetOverrideTarget("balance", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.ReloadRules(config("new"), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pick("new")
|
||||
}
|
||||
|
||||
func TestRouterScriptConcurrentBalancerReload(t *testing.T) {
|
||||
config := func(tag string) *Config {
|
||||
return &Config{BalancingRule: []*BalancingRule{{
|
||||
Tag: "balance", Strategy: "roundrobin", OutboundSelector: []string{tag},
|
||||
}}}
|
||||
}
|
||||
r := startLuaRouter(t, `
|
||||
local router = require("xray.router")
|
||||
function HandleRoute()
|
||||
local tag, err = router.PickOutbound("balance")
|
||||
return tag, nil, err
|
||||
end`, nil, config("a"))
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for range 4 {
|
||||
wg.Go(func() {
|
||||
for range 20 {
|
||||
route, err := r.PickRoute(&routing_session.Context{})
|
||||
if err != nil {
|
||||
t.Errorf("PickRoute: %v", err)
|
||||
return
|
||||
}
|
||||
if tag := route.GetOutboundTag(); tag != "a" && tag != "b" {
|
||||
t.Errorf("unexpected tag %q", tag)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Go(func() {
|
||||
for range 20 {
|
||||
for _, tag := range []string{"a", "b"} {
|
||||
if err := r.ReloadRules(config(tag), false); err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestRouterScriptDNSDispatcherReentry(t *testing.T) {
|
||||
conn, err := stdnet.ListenPacket("udp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
port := conn.LocalAddr().(*stdnet.UDPAddr).Port
|
||||
ready, stopped := make(chan struct{}), make(chan error, 1)
|
||||
var queries atomic.Int32
|
||||
server := &wireDNS.Server{
|
||||
PacketConn: conn,
|
||||
NotifyStartedFunc: func() {
|
||||
close(ready)
|
||||
},
|
||||
Handler: wireDNS.HandlerFunc(func(w wireDNS.ResponseWriter, query *wireDNS.Msg) {
|
||||
queries.Add(1)
|
||||
response := new(wireDNS.Msg).SetReply(query)
|
||||
for _, question := range query.Question {
|
||||
if question.Name == "nested.example." && question.Qtype == wireDNS.TypeA {
|
||||
response.Answer = append(response.Answer, &wireDNS.A{
|
||||
Hdr: wireDNS.RR_Header{Name: question.Name, Rrtype: wireDNS.TypeA, Class: wireDNS.ClassINET, Ttl: 60},
|
||||
A: stdnet.IP{127, 0, 0, 7},
|
||||
})
|
||||
}
|
||||
}
|
||||
if err := w.WriteMsg(response); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}),
|
||||
}
|
||||
go func() { stopped <- server.ActivateAndServe() }()
|
||||
defer func() {
|
||||
server.Shutdown()
|
||||
select {
|
||||
case err := <-stopped:
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Error("DNS server did not stop")
|
||||
}
|
||||
}()
|
||||
select {
|
||||
case <-ready:
|
||||
case err := <-stopped:
|
||||
t.Fatalf("DNS server startup: %v", err)
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("DNS server did not start")
|
||||
}
|
||||
|
||||
dnsScript := writeRouteScript(t, `
|
||||
local server = require("xray.dns").Servers[1]
|
||||
function HandleDNSQuery(domain, ipv4, ipv6, fake)
|
||||
return server:Query(domain, ipv4, ipv6, fake)
|
||||
end`)
|
||||
routerScript := writeRouteScript(t, `
|
||||
local router = require("xray.router")
|
||||
local dns = require("xray.dns")
|
||||
local matcher = require("xray.geodata").BuildIPMatcher("127.0.0.7")
|
||||
local active = false
|
||||
function HandleRoute(ctx, inbound, sourcePort, targetPort, localPort, domain, network,
|
||||
protocol, user, vlessRoute, skipDNSResolve)
|
||||
assert(not active, "borrowed Router VM reentered")
|
||||
if inbound == "dns" then
|
||||
assert(network == router.NetworkUDP and skipDNSResolve == false)
|
||||
return "direct", "dns-route"
|
||||
end
|
||||
active = true
|
||||
local ips, ttl, err = dns.Query("nested.example", true, false, false)
|
||||
assert(not err and matcher:AnyMatch(ips) and active)
|
||||
active = false
|
||||
return "direct", "outer-route"
|
||||
end`)
|
||||
instance, err := core.New(&core.Config{
|
||||
App: []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&appdns.Config{
|
||||
Tag: "dns", Script: dnsScript, DisableCache: true,
|
||||
NameServer: []*appdns.NameServer{{
|
||||
Id: "upstream", TimeoutMs: 1000,
|
||||
Address: &net.Endpoint{
|
||||
Network: net.Network_UDP,
|
||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Ip{Ip: []byte{127, 0, 0, 1}}},
|
||||
Port: uint32(port),
|
||||
},
|
||||
}},
|
||||
}),
|
||||
serial.ToTypedMessage(&Config{Script: routerScript}),
|
||||
serial.ToTypedMessage(&dispatcher.Config{}),
|
||||
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{Tag: "default", ProxySettings: serial.ToTypedMessage(&blackhole.Config{})},
|
||||
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||
})},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := instance.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer instance.Close()
|
||||
r := instance.GetFeature(routing.RouterType()).(*Router)
|
||||
route, err := r.PickRoute(newLuaRouteTestContext())
|
||||
if err != nil || route.GetOutboundTag() != "direct" || route.GetRuleTag() != "outer-route" {
|
||||
t.Fatalf("nested DNS routing = %v, %v", route, err)
|
||||
}
|
||||
if queries.Load() == 0 {
|
||||
t.Fatal("DNS query did not pass through the dispatcher")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package base64
|
||||
|
||||
const (
|
||||
Prefix = "base64:"
|
||||
GzipPrefix = "base64+gzip:"
|
||||
)
|
||||
@@ -0,0 +1,38 @@
|
||||
package base64
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
)
|
||||
|
||||
// Decode decodes Base64 text with an optional [Prefix] or [GzipPrefix].
|
||||
func Decode(value string) ([]byte, error) {
|
||||
value, zip := strings.CutPrefix(value, GzipPrefix)
|
||||
if !zip {
|
||||
value = strings.TrimPrefix(value, Prefix)
|
||||
}
|
||||
|
||||
data, err := base64.StdEncoding.DecodeString(value)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to decode base64").Base(err)
|
||||
}
|
||||
if !zip {
|
||||
return data, nil
|
||||
}
|
||||
|
||||
reader, err := gzip.NewReader(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to decompress gzip").Base(err)
|
||||
}
|
||||
defer reader.Close()
|
||||
data, err = io.ReadAll(reader)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to decompress gzip").Base(err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package base64
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDecodeFormats(t *testing.T) {
|
||||
compressed, err := Encode([]byte("x"), true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name, value, want string
|
||||
}{
|
||||
{"unprefixed", "eA==", "x"},
|
||||
{"base64", Prefix + "eA==", "x"},
|
||||
{"gzip", compressed, "x"},
|
||||
{"empty", Prefix, ""},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
data, err := Decode(tc.value)
|
||||
if err != nil || !bytes.Equal(data, []byte(tc.want)) {
|
||||
t.Fatalf("Decode = %q, %v; want %q", data, err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package base64
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"encoding/base64"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
)
|
||||
|
||||
// Encode returns prefixed Base64 text, optionally compressed with gzip at the highest level.
|
||||
func Encode(data []byte, zip bool) (string, error) {
|
||||
if !zip {
|
||||
return Prefix + base64.StdEncoding.EncodeToString(data), nil
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
writer, err := gzip.NewWriterLevel(&buf, gzip.BestCompression)
|
||||
if err != nil {
|
||||
return "", errors.New("failed to compress gzip").Base(err)
|
||||
}
|
||||
if _, err := writer.Write(data); err != nil {
|
||||
return "", errors.New("failed to compress gzip").Base(err)
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
return "", errors.New("failed to compress gzip").Base(err)
|
||||
}
|
||||
return GzipPrefix + base64.StdEncoding.EncodeToString(buf.Bytes()), nil
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package base64
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEncodeFormats(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
data []byte
|
||||
}{
|
||||
{"empty", nil},
|
||||
{"bytes", []byte("ä˝ ĺĄ˝\r\n\x00\xff")},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
for _, zip := range []bool{false, true} {
|
||||
prefix := Prefix
|
||||
if zip {
|
||||
prefix = GzipPrefix
|
||||
}
|
||||
t.Run(prefix, func(t *testing.T) {
|
||||
value, err := Encode(tc.data, zip)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
payload, ok := strings.CutPrefix(value, prefix)
|
||||
if !ok {
|
||||
t.Fatalf("encoded value does not start with %q", prefix)
|
||||
}
|
||||
// Read the output independently of Decode so matching bugs cannot hide.
|
||||
data, err := base64.StdEncoding.DecodeString(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if zip {
|
||||
// gzip's XFL byte identifies the compression level we selected.
|
||||
if len(data) < 10 || data[8] != 2 {
|
||||
t.Fatal("gzip output does not use the highest compression level")
|
||||
}
|
||||
reader, err := gzip.NewReader(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer reader.Close()
|
||||
data, err = io.ReadAll(reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if !bytes.Equal(data, tc.data) {
|
||||
t.Fatal("encoded output does not preserve the input bytes")
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package geodata
|
||||
|
||||
import (
|
||||
xlua "github.com/xtls/xray-core/common/lua"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
// RegisterLua makes xray.geodata available to require in an LState.
|
||||
func RegisterLua(L *lua.LState) {
|
||||
L.PreloadModule("xray.geodata", func(L *lua.LState) int {
|
||||
module := L.CreateTable(0, 2)
|
||||
|
||||
module.RawSetString("BuildDomainMatcher", L.NewFunction(func(L *lua.LState) int {
|
||||
parsed, err := ParseDomainRules(luaRules(L), Domain_Domain)
|
||||
if err != nil {
|
||||
L.RaiseError("%v", err)
|
||||
return 0
|
||||
}
|
||||
matcher, err := DomainReg.BuildDomainMatcher(parsed)
|
||||
if err != nil {
|
||||
L.RaiseError("%v", err)
|
||||
return 0
|
||||
}
|
||||
xlua.PushWithDirectMethods(L, matcher, map[string]xlua.DirectMethod{
|
||||
"Match": newLuaDomainMatch(xlua.NewSlicePusher[uint32](L)),
|
||||
"MatchAny": luaDomainMatchAny,
|
||||
})
|
||||
return 1
|
||||
}))
|
||||
|
||||
module.RawSetString("BuildIPMatcher", L.NewFunction(func(L *lua.LState) int {
|
||||
parsed, err := ParseIPRules(luaRules(L))
|
||||
if err != nil {
|
||||
L.RaiseError("%v", err)
|
||||
return 0
|
||||
}
|
||||
matcher, err := IPReg.BuildIPMatcher(parsed)
|
||||
if err != nil {
|
||||
L.RaiseError("%v", err)
|
||||
return 0
|
||||
}
|
||||
xlua.PushWithDirectMethods(L, matcher, map[string]xlua.DirectMethod{
|
||||
"Match": luaIPMatch,
|
||||
"AnyMatch": luaIPAnyMatch,
|
||||
"Matches": luaIPMatches,
|
||||
"FilterIPs": newLuaIPFilterIPs(xlua.NewSlicePusher[net.IP](L)),
|
||||
})
|
||||
return 1
|
||||
}))
|
||||
|
||||
L.Push(module)
|
||||
return 1
|
||||
})
|
||||
}
|
||||
|
||||
// Read native Go values by type assertion; slices keep their original storage.
|
||||
func readLuaIPMatcherArgs[T any](L *lua.LState) (IPMatcher, T, bool) {
|
||||
var input T
|
||||
if L.GetTop() != 2 {
|
||||
return nil, input, false
|
||||
}
|
||||
value, ok := L.Get(1).(*lua.LUserData)
|
||||
if !ok {
|
||||
return nil, input, false
|
||||
}
|
||||
matcher, ok := value.Value.(IPMatcher)
|
||||
if !ok {
|
||||
return nil, input, false
|
||||
}
|
||||
if L.Get(2) == lua.LNil {
|
||||
return matcher, input, true
|
||||
}
|
||||
value, ok = L.Get(2).(*lua.LUserData)
|
||||
if !ok {
|
||||
return nil, input, false
|
||||
}
|
||||
input, ok = value.Value.(T)
|
||||
return matcher, input, ok
|
||||
}
|
||||
|
||||
func luaIPMatch(L *lua.LState) (int, bool) {
|
||||
matcher, ip, ok := readLuaIPMatcherArgs[net.IP](L)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
L.Push(lua.LBool(matcher.Match(ip)))
|
||||
return 1, true
|
||||
}
|
||||
|
||||
func luaIPAnyMatch(L *lua.LState) (int, bool) {
|
||||
matcher, ips, ok := readLuaIPMatcherArgs[[]net.IP](L)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
L.Push(lua.LBool(matcher.AnyMatch(ips)))
|
||||
return 1, true
|
||||
}
|
||||
|
||||
func luaIPMatches(L *lua.LState) (int, bool) {
|
||||
matcher, ips, ok := readLuaIPMatcherArgs[[]net.IP](L)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
L.Push(lua.LBool(matcher.Matches(ips)))
|
||||
return 1, true
|
||||
}
|
||||
|
||||
func newLuaIPFilterIPs(pushIPs func(*lua.LState, []net.IP)) xlua.DirectMethod {
|
||||
return func(L *lua.LState) (int, bool) {
|
||||
matcher, ips, ok := readLuaIPMatcherArgs[[]net.IP](L)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
matched, unmatched := matcher.FilterIPs(ips)
|
||||
pushIPs(L, matched)
|
||||
pushIPs(L, unmatched)
|
||||
return 2, true
|
||||
}
|
||||
}
|
||||
|
||||
func newLuaDomainMatch(pushMatches func(*lua.LState, []uint32)) xlua.DirectMethod {
|
||||
return func(L *lua.LState) (int, bool) {
|
||||
if L.GetTop() == 2 {
|
||||
if value, ok := L.Get(1).(*lua.LUserData); ok {
|
||||
matcher, validMatcher := value.Value.(DomainMatcher)
|
||||
domain, validDomain := L.Get(2).(lua.LString)
|
||||
if validMatcher && validDomain {
|
||||
pushMatches(L, matcher.Match(string(domain)))
|
||||
return 1, true
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func luaDomainMatchAny(L *lua.LState) (int, bool) {
|
||||
if L.GetTop() == 2 {
|
||||
if value, ok := L.Get(1).(*lua.LUserData); ok {
|
||||
matcher, validMatcher := value.Value.(DomainMatcher)
|
||||
domain, validDomain := L.Get(2).(lua.LString)
|
||||
if validMatcher && validDomain {
|
||||
L.Push(lua.LBool(matcher.MatchAny(string(domain))))
|
||||
return 1, true
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func luaRules(L *lua.LState) []string {
|
||||
rules := make([]string, L.GetTop())
|
||||
for i := range rules {
|
||||
value, ok := L.Get(i + 1).(lua.LString)
|
||||
if !ok {
|
||||
L.RaiseError("geodata rules must be strings")
|
||||
return nil
|
||||
}
|
||||
rules[i] = string(value)
|
||||
}
|
||||
return rules
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package geodata
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
func TestLuaIPMatcher(t *testing.T) {
|
||||
L := lua.NewState()
|
||||
defer L.Close()
|
||||
RegisterLua(L)
|
||||
ip := L.NewUserData()
|
||||
ip.Value = net.ParseIP("127.0.0.1")
|
||||
L.SetGlobal("ip", ip)
|
||||
ips := L.NewUserData()
|
||||
ips.Value = []net.IP{ip.Value.(net.IP), net.ParseIP("8.8.8.8")}
|
||||
L.SetGlobal("ips", ips)
|
||||
if err := L.DoString(`
|
||||
local matcher = require("xray.geodata").BuildIPMatcher("127.0.0.0/8", "::1")
|
||||
assert(matcher:Match(ip))
|
||||
assert(matcher:AnyMatch(ips))
|
||||
assert(not matcher:Matches(ips))
|
||||
local matched, unmatched = matcher:FilterIPs(ips)
|
||||
assert(type(matched) == "userdata" and type(unmatched) == "userdata")
|
||||
assert(#matched == 1 and #unmatched == 1)
|
||||
`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLuaDomainMatcher(t *testing.T) {
|
||||
L := lua.NewState()
|
||||
defer L.Close()
|
||||
RegisterLua(L)
|
||||
if err := L.DoString(`
|
||||
local matcher = require("xray.geodata").BuildDomainMatcher("example.com", "full:other.com")
|
||||
assert(matcher:MatchAny("example.com"))
|
||||
assert(matcher:MatchAny("www.example.com"))
|
||||
assert(matcher:MatchAny("other.com"))
|
||||
assert(not matcher:MatchAny("www.other.com"))
|
||||
assert(#(matcher:Match("www.example.com")) == 1)
|
||||
`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLuaMatchersRejectInvalidRules(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
script string
|
||||
}{
|
||||
{"IP rule", `require("xray.geodata").BuildIPMatcher("not-an-ip")`},
|
||||
{"non-string domain rule", `require("xray.geodata").BuildDomainMatcher("example.com", true)`},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
L := lua.NewState()
|
||||
defer L.Close()
|
||||
RegisterLua(L)
|
||||
if err := L.DoString(tc.script); err == nil {
|
||||
t.Fatal("invalid geodata rule was accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLuaMatcherArgumentsAndAliases(t *testing.T) {
|
||||
L := lua.NewState()
|
||||
defer L.Close()
|
||||
RegisterLua(L)
|
||||
ip := L.NewUserData()
|
||||
ip.Value = net.ParseIP("127.0.0.1")
|
||||
L.SetGlobal("ip", ip)
|
||||
if err := L.DoString(`
|
||||
local geodata = require("xray.geodata")
|
||||
local matcher = geodata.BuildIPMatcher("127.0.0.0/8")
|
||||
assert(matcher.Match == matcher.match and matcher.AnyMatch == matcher.anyMatch)
|
||||
assert(matcher.Matches == matcher.matches and matcher.FilterIPs == matcher.filterIPs)
|
||||
assert(matcher:match(ip))
|
||||
assert(matcher:anyMatch({ip}) and matcher:matches({ip}))
|
||||
assert(not matcher:AnyMatch(nil))
|
||||
assert(matcher:Matches(nil) == matcher:Matches({}))
|
||||
local matched, unmatched = matcher:FilterIPs({ip})
|
||||
assert(#matched == 1 and matched[1]:Equal(ip))
|
||||
assert(matcher:AnyMatch(matched) and matcher:Matches(matched))
|
||||
local filtered, excluded = matcher:filterIPs(matched)
|
||||
assert(#filtered == 1 and #excluded == 0 and filtered[1]:Equal(ip))
|
||||
local emptyMatched, emptyUnmatched = matcher:FilterIPs(nil)
|
||||
assert(#emptyMatched == 0 and #emptyUnmatched == 0)
|
||||
matcher:SetReverse(true)
|
||||
assert(not matcher:Match(ip) and not matcher:AnyMatch(matched))
|
||||
matcher:ToggleReverse()
|
||||
assert(matcher:Match(ip) and matcher:AnyMatch(matched))
|
||||
assert(matcher.missing == nil)
|
||||
|
||||
local domain = geodata.BuildDomainMatcher("full:example.com")
|
||||
assert(domain.Match == domain.match and domain.MatchAny == domain.matchAny)
|
||||
assert(domain:matchAny("example.com"))
|
||||
assert(#domain:Match("example.com") == 1)
|
||||
assert(domain:match("example.com")[1] == 0)
|
||||
assert(not pcall(function() matcher:AnyMatch() end))
|
||||
assert(not pcall(function() matcher:AnyMatch(matched, true) end))
|
||||
assert(not pcall(function() matcher.AnyMatch(ip, matched) end))
|
||||
assert(not pcall(function() matcher:Match(true) end))
|
||||
assert(not pcall(function() domain:MatchAny(123) end))
|
||||
assert(not pcall(function() domain:MatchAny("example.com", true) end))
|
||||
assert(not pcall(function() matcher:FilterIPs(true) end))
|
||||
assert(not pcall(function() matcher:FilterIPs(matched, true) end))
|
||||
assert(not pcall(function() domain:Match(123) end))
|
||||
assert(not pcall(function() domain:Match("example.com", true) end))
|
||||
`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkLuaMatcherCall measures repeated calls with prebuilt matchers and inputs.
|
||||
func BenchmarkLuaMatcherCall(b *testing.B) {
|
||||
L := lua.NewState()
|
||||
defer L.Close()
|
||||
RegisterLua(L)
|
||||
ip := net.ParseIP("127.0.0.1")
|
||||
for name, value := range map[string]any{"ip": ip, "ips": []net.IP{ip}} {
|
||||
ud := L.NewUserData()
|
||||
ud.Value = value
|
||||
L.SetGlobal(name, ud)
|
||||
}
|
||||
if err := L.DoString(`
|
||||
local geodata = require("xray.geodata")
|
||||
ipMatcher = geodata.BuildIPMatcher("127.0.0.0/8")
|
||||
domainMatcher = geodata.BuildDomainMatcher("full:example.com")
|
||||
`); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
for _, benchmark := range []struct {
|
||||
name, expression string
|
||||
}{
|
||||
{"ip_match", "ipMatcher:Match(ip)"},
|
||||
{"ip_match_lower", "ipMatcher:match(ip)"},
|
||||
{"ip_any_match", "ipMatcher:AnyMatch(ips)"},
|
||||
{"ip_any_match_lower", "ipMatcher:anyMatch(ips)"},
|
||||
{"ip_matches", "ipMatcher:Matches(ips)"},
|
||||
{"ip_matches_lower", "ipMatcher:matches(ips)"},
|
||||
{"domain_match_any", `domainMatcher:MatchAny("example.com")`},
|
||||
{"domain_match_any_lower", `domainMatcher:matchAny("example.com")`},
|
||||
{"ip_filter", "select(1, ipMatcher:FilterIPs(ips)) ~= nil"},
|
||||
{"ip_filter_lower", "select(1, ipMatcher:filterIPs(ips)) ~= nil"},
|
||||
{"domain_match", `#domainMatcher:Match("example.com") == 1`},
|
||||
{"domain_match_lower", `#domainMatcher:match("example.com") == 1`},
|
||||
{"ip_lua_table", "ipMatcher:AnyMatch({ip})"},
|
||||
{"ip_lua_table_lower", "ipMatcher:anyMatch({ip})"},
|
||||
} {
|
||||
b.Run(benchmark.name, func(b *testing.B) {
|
||||
if err := L.DoString(fmt.Sprintf("function benchmarkMatch() return %s end", benchmark.expression)); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
fn := L.GetGlobal("benchmarkMatch")
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
if err := L.CallByParam(lua.P{Fn: fn, NRet: 1, Protect: true}); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
if L.Get(-1) != lua.LTrue {
|
||||
b.Fatal("matcher returned false")
|
||||
}
|
||||
L.Pop(1)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
// RegisterLua makes xray.log available to require in an LState.
|
||||
func RegisterLua(L *lua.LState) {
|
||||
L.PreloadModule("xray.log", func(L *lua.LState) int {
|
||||
module := L.CreateTable(0, 4)
|
||||
var source, prefix string // cache
|
||||
for name, severity := range map[string]Severity{
|
||||
"Debug": Severity_Debug,
|
||||
"Info": Severity_Info,
|
||||
"Warning": Severity_Warning,
|
||||
"Error": Severity_Error,
|
||||
} {
|
||||
module.RawSetString(name, L.NewFunction(func(L *lua.LState) int {
|
||||
if GetSeverity() < severity {
|
||||
return 0
|
||||
}
|
||||
var content strings.Builder
|
||||
// Prefix with the calling script's filename.
|
||||
if caller, ok := L.GetStack(1); ok {
|
||||
if _, err := L.GetInfo("S", caller, lua.LNil); err == nil && caller.Source != "" {
|
||||
if caller.Source != source {
|
||||
source = caller.Source
|
||||
prefix = filepath.Base(strings.TrimPrefix(source, "@")) + ": "
|
||||
}
|
||||
content.WriteString(prefix)
|
||||
}
|
||||
}
|
||||
for i := 1; i <= L.GetTop(); i++ {
|
||||
content.WriteString(luaLogString(L, L.Get(i)))
|
||||
}
|
||||
Record(&GeneralMessage{
|
||||
Severity: severity,
|
||||
Content: content.String(),
|
||||
})
|
||||
return 0
|
||||
}))
|
||||
}
|
||||
L.Push(module)
|
||||
return 1
|
||||
})
|
||||
}
|
||||
|
||||
func luaLogString(L *lua.LState, value lua.LValue) string {
|
||||
if ud, ok := value.(*lua.LUserData); ok {
|
||||
if err, ok := ud.Value.(error); ok {
|
||||
return err.Error()
|
||||
}
|
||||
}
|
||||
if _, ok := L.GetMetaField(value, "__tostring").(*lua.LFunction); ok {
|
||||
return L.ToStringMeta(value).String()
|
||||
}
|
||||
return value.String()
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
type luaLogHandler struct {
|
||||
messages []Message
|
||||
}
|
||||
|
||||
func (h *luaLogHandler) Handle(msg Message) {
|
||||
h.messages = append(h.messages, msg)
|
||||
}
|
||||
|
||||
func TestLuaLog(t *testing.T) {
|
||||
previous := logHandler.Load()
|
||||
t.Cleanup(func() { logHandler.Store(previous) })
|
||||
handler := &luaLogHandler{}
|
||||
RegisterHandler(handler)
|
||||
|
||||
L := lua.NewState()
|
||||
defer L.Close()
|
||||
RegisterLua(L)
|
||||
nativeError := L.NewUserData()
|
||||
nativeError.Value = fmt.Errorf("lookup failed: %w", errors.New("upstream timeout"))
|
||||
L.SetGlobal("nativeError", nativeError)
|
||||
path := filepath.Join(t.TempDir(), "logging.lua")
|
||||
if err := os.WriteFile(path, []byte(`
|
||||
local log = require("xray.log")
|
||||
assert(log == require("xray.log"))
|
||||
log.Debug("query: ", "example.com")
|
||||
log.Info("count=", 42, ", enabled=", true, ", value=", nil)
|
||||
log.Warning(setmetatable({}, {
|
||||
__tostring = function() return "fallback" end
|
||||
}))
|
||||
assert(select("#", log.Error("failed")) == 0)
|
||||
log.Error("DNS failed: ", nativeError)
|
||||
log.Warning(nativeError)
|
||||
local ok, err = pcall(function() error("Lua failure", 0) end)
|
||||
assert(not ok)
|
||||
log.Error(err)
|
||||
local calls = 0
|
||||
local custom = setmetatable({}, {
|
||||
__tostring = function() calls = calls + 1; return "custom" end
|
||||
})
|
||||
log.Info(custom, custom)
|
||||
assert(calls == 2)
|
||||
log.Info("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l")
|
||||
log.Info()
|
||||
function logHook()
|
||||
log.Info("hook")
|
||||
end
|
||||
`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := L.DoFile(path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := L.DoString(`
|
||||
logHook()
|
||||
require("xray.log").Info("anonymous")
|
||||
`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
other := filepath.Join(t.TempDir(), "other.lua")
|
||||
if err := os.WriteFile(other, []byte(`
|
||||
local log = require("xray.log")
|
||||
log.Info("other")
|
||||
logHook()
|
||||
log.Info("other again")
|
||||
`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := L.DoFile(other); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
want := []struct {
|
||||
severity Severity
|
||||
message string
|
||||
}{
|
||||
{Severity_Debug, "[Debug] logging.lua: query: example.com"},
|
||||
{Severity_Info, "[Info] logging.lua: count=42, enabled=true, value=nil"},
|
||||
{Severity_Warning, "[Warning] logging.lua: fallback"},
|
||||
{Severity_Error, "[Error] logging.lua: failed"},
|
||||
{Severity_Error, "[Error] logging.lua: DNS failed: lookup failed: upstream timeout"},
|
||||
{Severity_Warning, "[Warning] logging.lua: lookup failed: upstream timeout"},
|
||||
{Severity_Error, "[Error] logging.lua: Lua failure"},
|
||||
{Severity_Info, "[Info] logging.lua: customcustom"},
|
||||
{Severity_Info, "[Info] logging.lua: abcdefghijkl"},
|
||||
{Severity_Info, "[Info] logging.lua: "},
|
||||
{Severity_Info, "[Info] logging.lua: hook"},
|
||||
{Severity_Info, "[Info] <string>: anonymous"},
|
||||
{Severity_Info, "[Info] other.lua: other"},
|
||||
{Severity_Info, "[Info] logging.lua: hook"},
|
||||
{Severity_Info, "[Info] other.lua: other again"},
|
||||
}
|
||||
if len(handler.messages) != len(want) {
|
||||
t.Fatalf("logged %d messages, want %d", len(handler.messages), len(want))
|
||||
}
|
||||
for i, expected := range want {
|
||||
msg, ok := handler.messages[i].(*GeneralMessage)
|
||||
if !ok {
|
||||
t.Fatalf("message %d has type %T, want *GeneralMessage", i, handler.messages[i])
|
||||
}
|
||||
if msg.Severity != expected.severity || msg.String() != expected.message {
|
||||
t.Errorf("message %d = %q with severity %v, want %q with severity %v", i, msg.String(), msg.Severity, expected.message, expected.severity)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type luaSeverityLogHandler struct {
|
||||
luaLogHandler
|
||||
level Severity
|
||||
}
|
||||
|
||||
func (h *luaSeverityLogHandler) Severity() Severity { return h.level }
|
||||
|
||||
func TestLuaLogSeverity(t *testing.T) {
|
||||
previous := logHandler.Load()
|
||||
t.Cleanup(func() { logHandler.Store(previous) })
|
||||
L := lua.NewState()
|
||||
defer L.Close()
|
||||
RegisterLua(L)
|
||||
for _, level := range []Severity{Severity_Unknown, Severity_Error, Severity_Warning, Severity_Info, Severity_Debug, Severity_Warning} {
|
||||
t.Run(level.String(), func(t *testing.T) {
|
||||
handler := &luaSeverityLogHandler{level: level}
|
||||
RegisterHandler(handler)
|
||||
want := []Severity{}
|
||||
for _, severity := range []Severity{Severity_Error, Severity_Warning, Severity_Info, Severity_Debug} {
|
||||
if severity <= level {
|
||||
want = append(want, severity)
|
||||
}
|
||||
}
|
||||
if err := L.DoString(fmt.Sprintf(`
|
||||
local log = require("xray.log")
|
||||
local calls = 0
|
||||
local value = setmetatable({}, {
|
||||
__tostring = function() calls = calls + 1; return "message" end
|
||||
})
|
||||
for _, write in ipairs({log.Error, log.Warning, log.Info, log.Debug}) do
|
||||
assert(select("#", write(value)) == 0)
|
||||
end
|
||||
assert(calls == %d)
|
||||
`, len(want))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(handler.messages) != len(want) {
|
||||
t.Fatalf("logged %d messages, want %d", len(handler.messages), len(want))
|
||||
}
|
||||
for i, severity := range want {
|
||||
msg := handler.messages[i].(*GeneralMessage)
|
||||
if msg.Severity != severity || msg.Content != "<string>: message" {
|
||||
t.Errorf("message %d = %v, want severity %v and content %q", i, msg, severity, "<string>: message")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type luaDiscardLogHandler struct{ level Severity }
|
||||
|
||||
func (luaDiscardLogHandler) Handle(Message) {}
|
||||
func (h luaDiscardLogHandler) Severity() Severity { return h.level }
|
||||
|
||||
func BenchmarkLuaLog(b *testing.B) {
|
||||
benchmarkLuaLog(b, Severity_Debug)
|
||||
}
|
||||
|
||||
func BenchmarkLuaLogFiltered(b *testing.B) {
|
||||
benchmarkLuaLog(b, Severity_Warning)
|
||||
}
|
||||
|
||||
func benchmarkLuaLog(b *testing.B, level Severity) {
|
||||
previous := logHandler.Load()
|
||||
b.Cleanup(func() { logHandler.Store(previous) })
|
||||
RegisterHandler(luaDiscardLogHandler{level: level})
|
||||
L := lua.NewState()
|
||||
defer L.Close()
|
||||
RegisterLua(L)
|
||||
if err := L.DoString(`custom = setmetatable({}, {__tostring = function() return "custom" end})`); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
for _, benchmark := range []struct {
|
||||
name, arguments string
|
||||
}{
|
||||
{"strings", `"query: ", "example.com"`},
|
||||
{"mixed", `"count=", 42, ", enabled=", true, ", value=", nil`},
|
||||
{"many_arguments", `"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"`},
|
||||
{"tostring", "custom"},
|
||||
} {
|
||||
b.Run(benchmark.name, func(b *testing.B) {
|
||||
if err := L.DoString(fmt.Sprintf(`local log = require("xray.log")
|
||||
function benchmarkLog() log.Info(%s) end`, benchmark.arguments)); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
fn := L.GetGlobal("benchmarkLog")
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
if err := L.CallByParam(lua.P{Fn: fn, NRet: 0, Protect: true}); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
// Package lua provides shared GopherLua programs, state management, and value
|
||||
// conversion and validation helpers for Xray scripts.
|
||||
package lua
|
||||
@@ -0,0 +1,65 @@
|
||||
package lua
|
||||
|
||||
import (
|
||||
glua "github.com/yuin/gopher-lua"
|
||||
luar "layeh.com/gopher-luar"
|
||||
)
|
||||
|
||||
// NewSlicePusher captures luar's slice metatable during state initialization.
|
||||
// The returned function wraps slices without reflection or metatable lookup,
|
||||
// and pushes nil for nil slices. Use it with this state or its coroutines.
|
||||
func NewSlicePusher[T any](L *glua.LState) func(*glua.LState, []T) {
|
||||
metatable := luar.New(L, []T{}).(*glua.LUserData).Metatable
|
||||
return func(L *glua.LState, values []T) {
|
||||
if values == nil {
|
||||
L.Push(glua.LNil)
|
||||
return
|
||||
}
|
||||
userdata := L.NewUserData()
|
||||
userdata.Value = values
|
||||
userdata.Metatable = metatable
|
||||
L.Push(userdata)
|
||||
}
|
||||
}
|
||||
|
||||
// DirectMethod handles a Lua call without luar's reflected method invocation.
|
||||
// It returns the result count and whether it handled the arguments. On false,
|
||||
// it must leave the stack unchanged for the original luar wrapper.
|
||||
type DirectMethod func(L *glua.LState) (nresults int, handled bool)
|
||||
|
||||
// PushWithDirectMethods pushes a luar userdata with typed Go method bindings.
|
||||
// Handled calls bypass luar's argument conversion and reflect.Call; method lookup
|
||||
// uses the methods table directly instead of luar's reflected __index handler.
|
||||
// value must expose methods only. Bindings and their closures are installed once
|
||||
// per Go type per LState, outside the method-call hot path.
|
||||
func PushWithDirectMethods(L *glua.LState, value any, directMethods map[string]DirectMethod) {
|
||||
userdata := luar.New(L, value).(*glua.LUserData)
|
||||
metatable := userdata.Metatable.(*glua.LTable)
|
||||
methods := metatable.RawGetString("methods").(*glua.LTable)
|
||||
if metatable.RawGetString("__index") != methods {
|
||||
for name, direct := range directMethods {
|
||||
original := methods.RawGetString(name)
|
||||
fn := L.NewFunction(func(L *glua.LState) int {
|
||||
if nresults, handled := direct(L); handled {
|
||||
return nresults
|
||||
}
|
||||
return callLuarMethod(L, original)
|
||||
})
|
||||
// Keep luar's method aliases on the same direct binding.
|
||||
for key, method := methods.Next(glua.LNil); key != glua.LNil; key, method = methods.Next(key) {
|
||||
if method == original {
|
||||
methods.RawSet(key, fn)
|
||||
}
|
||||
}
|
||||
}
|
||||
metatable.RawSetString("__index", methods)
|
||||
}
|
||||
L.Push(userdata)
|
||||
}
|
||||
|
||||
func callLuarMethod(L *glua.LState, method glua.LValue) int {
|
||||
nargs := L.GetTop()
|
||||
L.Insert(method, 1)
|
||||
L.Call(nargs, glua.MultRet)
|
||||
return L.GetTop()
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package lua
|
||||
|
||||
import (
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
glua "github.com/yuin/gopher-lua"
|
||||
luar "layeh.com/gopher-luar"
|
||||
)
|
||||
|
||||
func TestSlicePusher(t *testing.T) {
|
||||
L := glua.NewState()
|
||||
defer L.Close()
|
||||
push := NewSlicePusher[int](L)
|
||||
values := []int{3, 5}
|
||||
L.SetGlobal("getValues", L.NewFunction(func(L *glua.LState) int {
|
||||
push(L, values)
|
||||
return 1
|
||||
}))
|
||||
if err := L.DoString(`
|
||||
local values = getValues()
|
||||
assert(#values == 2 and values[1] == 3 and values[2] == 5)
|
||||
values[2] = 7
|
||||
local co = coroutine.create(function()
|
||||
local values = getValues()
|
||||
assert(#values == 2 and values[1] == 3 and values[2] == 7)
|
||||
return true
|
||||
end)
|
||||
local ok, result = coroutine.resume(co)
|
||||
assert(ok and result == true)
|
||||
`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if values[1] != 7 {
|
||||
t.Fatal("slice storage was copied")
|
||||
}
|
||||
push(L, nil)
|
||||
if L.Get(-1) != glua.LNil {
|
||||
t.Fatal("nil slice must push Lua nil")
|
||||
}
|
||||
L.Pop(1)
|
||||
push(L, []int{})
|
||||
L.SetGlobal("empty", L.Get(-1))
|
||||
L.Pop(1)
|
||||
if err := L.DoString(`assert(type(empty) == "userdata" and #empty == 0)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlicePusherMetatablePerState(t *testing.T) {
|
||||
first := glua.NewState()
|
||||
defer first.Close()
|
||||
second := glua.NewState()
|
||||
defer second.Close()
|
||||
NewSlicePusher[int](first)(first, []int{1})
|
||||
NewSlicePusher[int](second)(second, []int{1})
|
||||
if first.Get(-1).(*glua.LUserData).Metatable == second.Get(-1).(*glua.LUserData).Metatable {
|
||||
t.Fatal("independent states share a slice metatable")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkSlicePusher(b *testing.B) {
|
||||
L := glua.NewState()
|
||||
defer L.Close()
|
||||
ips := []net.IP{net.ParseIP("127.0.0.1")}
|
||||
pushIPs := NewSlicePusher[net.IP](L)
|
||||
for _, benchmark := range []struct {
|
||||
name string
|
||||
push func(*glua.LState, []net.IP)
|
||||
}{
|
||||
{"bare", func(L *glua.LState, ips []net.IP) { PushUserData(L, ips) }},
|
||||
{"luar", func(L *glua.LState, ips []net.IP) { L.Push(luar.New(L, ips)) }},
|
||||
{"cached", pushIPs},
|
||||
} {
|
||||
b.Run(benchmark.name, func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
benchmark.push(L, ips)
|
||||
L.Pop(1)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package lua
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
glua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
const maxIdleStates = 16
|
||||
|
||||
// Pool lends each state to one caller at a time. It grows on contention and
|
||||
// keeps up to maxIdleStates idle states until Close. Acquire/Release callers
|
||||
// decide reusability; WithState uses its callback's error.
|
||||
type Pool struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
timeout time.Duration
|
||||
|
||||
factory LStateFactory
|
||||
idle []*glua.LState
|
||||
top int
|
||||
|
||||
mu sync.Mutex
|
||||
active sync.WaitGroup
|
||||
closed bool
|
||||
}
|
||||
|
||||
// NewPool tests the factory by creating one state during initialization.
|
||||
func NewPool(ctx context.Context, timeout time.Duration, factory LStateFactory) (*Pool, error) {
|
||||
if timeout <= 0 {
|
||||
return nil, errors.New("Lua pool timeout must be positive")
|
||||
}
|
||||
|
||||
poolCtx, cancel := context.WithCancel(ctx)
|
||||
|
||||
state, err := factory(poolCtx)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Pool{ctx: poolCtx, cancel: cancel, timeout: timeout, factory: factory, idle: []*glua.LState{state}, top: state.GetTop()}, nil
|
||||
}
|
||||
|
||||
// Acquire returns an initialized exclusive state, growing the pool if necessary.
|
||||
// ctx is passed to the factory for state creation; nil uses the pool context.
|
||||
func (p *Pool) Acquire(ctx context.Context) (*glua.LState, error) {
|
||||
p.mu.Lock()
|
||||
if p.closed {
|
||||
p.mu.Unlock()
|
||||
return nil, errors.New("Lua pool is closed")
|
||||
}
|
||||
if err := p.ctx.Err(); err != nil {
|
||||
p.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = p.ctx
|
||||
} else if err := ctx.Err(); err != nil {
|
||||
p.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
p.active.Add(1)
|
||||
|
||||
n := len(p.idle)
|
||||
if n != 0 {
|
||||
state := p.idle[n-1]
|
||||
p.idle[n-1] = nil
|
||||
p.idle = p.idle[:n-1]
|
||||
p.mu.Unlock()
|
||||
return state, nil
|
||||
}
|
||||
p.mu.Unlock()
|
||||
|
||||
// TODO: Limit the total number of states. When the limit is reached, wait
|
||||
// for a Release instead of creating another state; allow the wait to be
|
||||
// cancelled by the caller or by Close.
|
||||
state, err := p.factory(ctx)
|
||||
if err != nil {
|
||||
p.active.Done()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return state, nil
|
||||
}
|
||||
|
||||
// WithState runs work on an exclusive state and releases it afterward.
|
||||
// Nil ctx and zero timeout use pool defaults. The timeout starts after acquisition.
|
||||
func (p *Pool) WithState(ctx context.Context, timeout time.Duration, work func(*glua.LState) error) error {
|
||||
state, err := p.Acquire(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = p.ctx
|
||||
}
|
||||
if timeout == 0 {
|
||||
timeout = p.timeout
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
state.SetContext(ctx)
|
||||
reusable := false
|
||||
defer func() {
|
||||
cancel()
|
||||
p.Release(state, reusable)
|
||||
}()
|
||||
err = work(state)
|
||||
reusable = err == nil
|
||||
return err
|
||||
}
|
||||
|
||||
// Release resets a state for reuse or closes it.
|
||||
func (p *Pool) Release(state *glua.LState, reusable bool) {
|
||||
if reusable {
|
||||
state.RemoveContext()
|
||||
state.SetTop(p.top)
|
||||
p.mu.Lock()
|
||||
if !p.closed && p.ctx.Err() == nil && len(p.idle) < maxIdleStates {
|
||||
p.idle = append(p.idle, state)
|
||||
} else {
|
||||
reusable = false
|
||||
}
|
||||
p.mu.Unlock()
|
||||
}
|
||||
|
||||
if !reusable {
|
||||
state.Close()
|
||||
}
|
||||
|
||||
p.active.Done()
|
||||
}
|
||||
|
||||
// Close cancels the pool context, closes idle states, and waits for borrowed states.
|
||||
func (p *Pool) Close() {
|
||||
p.mu.Lock()
|
||||
if !p.closed {
|
||||
p.closed = true
|
||||
p.cancel()
|
||||
for _, state := range p.idle {
|
||||
state.Close()
|
||||
}
|
||||
p.idle = nil
|
||||
}
|
||||
p.mu.Unlock()
|
||||
|
||||
p.active.Wait()
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
package lua
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
glua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
func newTestPool(t testing.TB, ctx context.Context, timeout time.Duration, factory LStateFactory) *Pool {
|
||||
t.Helper()
|
||||
pool, err := NewPool(ctx, timeout, factory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
return pool
|
||||
}
|
||||
|
||||
func assertPoolCloseBlocked(t *testing.T, done <-chan struct{}) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-done:
|
||||
t.Fatal("Close returned while work was still active")
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolTimeoutValidation(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
timeout time.Duration
|
||||
wantErr bool
|
||||
}{
|
||||
{"zero", 0, true},
|
||||
{"negative", -time.Nanosecond, true},
|
||||
{"positive", time.Nanosecond, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
called := false
|
||||
pool, err := NewPool(context.Background(), tc.timeout, func(context.Context) (*glua.LState, error) {
|
||||
called = true
|
||||
return glua.NewState(), nil
|
||||
})
|
||||
if pool != nil {
|
||||
t.Cleanup(pool.Close)
|
||||
}
|
||||
if (err != nil) != tc.wantErr {
|
||||
t.Fatalf("NewPool error = %v, want error %t", err, tc.wantErr)
|
||||
}
|
||||
if tc.wantErr && (pool != nil || called) {
|
||||
t.Fatal("invalid timeout created a pool or called the factory")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolFactoryFailure(t *testing.T) {
|
||||
failure := errors.New("factory failed")
|
||||
_, err := NewPool(context.Background(), time.Second, func(context.Context) (*glua.LState, error) {
|
||||
return nil, failure
|
||||
})
|
||||
if !errors.Is(err, failure) {
|
||||
t.Fatalf("NewPool error = %v, want original factory error", err)
|
||||
}
|
||||
|
||||
calls := 0
|
||||
pool := newTestPool(t, context.Background(), time.Second, func(context.Context) (*glua.LState, error) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
return glua.NewState(), nil
|
||||
}
|
||||
return nil, failure
|
||||
})
|
||||
state, err := pool.Acquire(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Release(state, true)
|
||||
err = pool.WithState(nil, 0, func(*glua.LState) error {
|
||||
t.Error("work ran after factory failure")
|
||||
return nil
|
||||
})
|
||||
if !errors.Is(err, failure) {
|
||||
t.Fatalf("WithState error = %v, want original factory error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolReusesStatesAndLimitsIdle(t *testing.T) {
|
||||
created := 0
|
||||
pool := newTestPool(t, context.Background(), time.Second, func(context.Context) (*glua.LState, error) {
|
||||
created++
|
||||
return glua.NewState(), nil
|
||||
})
|
||||
var borrowed []*glua.LState
|
||||
defer func() {
|
||||
for _, state := range borrowed {
|
||||
pool.Release(state, false)
|
||||
}
|
||||
}()
|
||||
for range maxIdleStates + 3 {
|
||||
state, err := pool.Acquire(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
borrowed = append(borrowed, state)
|
||||
state.SetContext(context.Background())
|
||||
}
|
||||
states := borrowed
|
||||
for _, state := range states {
|
||||
pool.Release(state, true)
|
||||
}
|
||||
borrowed = nil
|
||||
open := 0
|
||||
for _, state := range states {
|
||||
if !state.IsClosed() {
|
||||
if state.Context() != nil {
|
||||
t.Fatal("Release left a context on a reusable state")
|
||||
}
|
||||
open++
|
||||
}
|
||||
}
|
||||
if open != maxIdleStates {
|
||||
t.Fatalf("retained %d states, want %d", open, maxIdleStates)
|
||||
}
|
||||
if err := pool.WithState(nil, 0, func(*glua.LState) error { return nil }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if created != len(states) {
|
||||
t.Fatalf("created %d states, want %d", created, len(states))
|
||||
}
|
||||
pool.Close()
|
||||
for _, state := range states {
|
||||
if !state.IsClosed() {
|
||||
t.Fatal("Close left an idle state open")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolWithStateOptions(t *testing.T) {
|
||||
key := struct{}{}
|
||||
parent := context.WithValue(context.Background(), key, "pool")
|
||||
caller := context.WithValue(context.Background(), key, "caller")
|
||||
pool := newTestPool(t, parent, time.Second, func(context.Context) (*glua.LState, error) {
|
||||
return glua.NewState(), nil
|
||||
})
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
ctx context.Context
|
||||
timeout time.Duration
|
||||
wantValue string
|
||||
wantTimeout time.Duration
|
||||
}{
|
||||
{"defaults", nil, 0, "pool", time.Second},
|
||||
{"context", caller, 0, "caller", time.Second},
|
||||
{"timeout", nil, 2 * time.Second, "pool", 2 * time.Second},
|
||||
{"both", caller, 2 * time.Second, "caller", 2 * time.Second},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
started := time.Now()
|
||||
err := pool.WithState(tc.ctx, tc.timeout, func(L *glua.LState) error {
|
||||
ctx := L.Context()
|
||||
if ctx.Value(key) != tc.wantValue {
|
||||
t.Errorf("context value = %v, want %q", ctx.Value(key), tc.wantValue)
|
||||
}
|
||||
deadline, ok := ctx.Deadline()
|
||||
if !ok || deadline.Before(started.Add(tc.wantTimeout)) || deadline.After(time.Now().Add(tc.wantTimeout)) {
|
||||
t.Errorf("deadline = %v, want timeout %v", deadline, tc.wantTimeout)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolFactoryContext(t *testing.T) {
|
||||
caller, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
ctx context.Context
|
||||
}{
|
||||
{"default", nil},
|
||||
{"caller", caller},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var contexts []context.Context
|
||||
pool := newTestPool(t, context.Background(), time.Second, func(ctx context.Context) (*glua.LState, error) {
|
||||
contexts = append(contexts, ctx)
|
||||
return glua.NewState(), nil
|
||||
})
|
||||
state, err := pool.Acquire(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Release(state, true)
|
||||
if err := pool.WithState(tc.ctx, 2*time.Second, func(*glua.LState) error { return nil }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := tc.ctx
|
||||
if want == nil {
|
||||
want = pool.ctx
|
||||
}
|
||||
if len(contexts) != 2 || contexts[0] != pool.ctx || contexts[1] != want {
|
||||
t.Fatal("factory did not receive the initialization and acquisition contexts unchanged")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolWithStateLifecycle(t *testing.T) {
|
||||
failure := errors.New("work failed")
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
work func(*glua.LState, context.CancelFunc) error
|
||||
reusable bool
|
||||
wantPanic bool
|
||||
wantErr error
|
||||
}{
|
||||
{"success", func(*glua.LState, context.CancelFunc) error { return nil }, true, false, nil},
|
||||
{"canceled success", func(_ *glua.LState, cancel context.CancelFunc) error {
|
||||
cancel()
|
||||
return nil
|
||||
}, true, false, nil},
|
||||
{"error", func(*glua.LState, context.CancelFunc) error { return failure }, false, false, failure},
|
||||
{"timeout", func(L *glua.LState, _ context.CancelFunc) error { return L.DoString("while true do end") }, false, false, nil},
|
||||
{"panic", func(*glua.LState, context.CancelFunc) error { panic(failure) }, false, true, nil},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
pool := newTestPool(t, context.Background(), 10*time.Millisecond, func(context.Context) (*glua.LState, error) {
|
||||
state := glua.NewState()
|
||||
state.Push(glua.LTrue)
|
||||
return state, nil
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
var state *glua.LState
|
||||
var workCtx context.Context
|
||||
var recovered any
|
||||
err := func() (err error) {
|
||||
defer func() { recovered = recover() }()
|
||||
return pool.WithState(ctx, 0, func(L *glua.LState) error {
|
||||
state, workCtx = L, L.Context()
|
||||
L.Push(glua.LFalse)
|
||||
return tc.work(L, cancel)
|
||||
})
|
||||
}()
|
||||
if tc.wantPanic {
|
||||
if recovered != failure {
|
||||
t.Fatalf("panic = %v, want original panic", recovered)
|
||||
}
|
||||
} else {
|
||||
if recovered != nil || (err == nil) != tc.reusable {
|
||||
t.Fatalf("WithState error = %v, panic = %v", err, recovered)
|
||||
}
|
||||
if tc.wantErr != nil && !errors.Is(err, tc.wantErr) {
|
||||
t.Fatalf("WithState error = %v, want %v", err, tc.wantErr)
|
||||
}
|
||||
}
|
||||
if workCtx.Err() == nil {
|
||||
t.Fatal("WithState did not cancel the execution context")
|
||||
}
|
||||
if closed := state.IsClosed(); closed == tc.reusable {
|
||||
t.Fatalf("state closed = %t, want %t", closed, !tc.reusable)
|
||||
}
|
||||
if tc.reusable && (state.Context() != nil || state.GetTop() != 1 || state.Get(1) != glua.LTrue) {
|
||||
t.Fatal("WithState did not reset the state for reuse")
|
||||
}
|
||||
if err := pool.WithState(nil, 0, func(L *glua.LState) error {
|
||||
if (L == state) != tc.reusable {
|
||||
t.Error("unexpected state reuse")
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolClose(t *testing.T) {
|
||||
pool := newTestPool(t, context.Background(), time.Second, func(context.Context) (*glua.LState, error) {
|
||||
return glua.NewState(), nil
|
||||
})
|
||||
finishCtx, finish := context.WithCancel(context.Background())
|
||||
t.Cleanup(finish)
|
||||
started, done := make(chan *glua.LState, 1), make(chan error, 1)
|
||||
var workCtx context.Context
|
||||
go func() {
|
||||
done <- pool.WithState(nil, 0, func(L *glua.LState) error {
|
||||
workCtx = L.Context()
|
||||
started <- L
|
||||
<-finishCtx.Done()
|
||||
return nil
|
||||
})
|
||||
}()
|
||||
var state *glua.LState
|
||||
select {
|
||||
case state = <-started:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("WithState did not start")
|
||||
}
|
||||
closed := make(chan struct{})
|
||||
go func() {
|
||||
pool.Close()
|
||||
close(closed)
|
||||
}()
|
||||
select {
|
||||
case <-workCtx.Done():
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("Close did not cancel work using the pool context")
|
||||
}
|
||||
if !errors.Is(workCtx.Err(), context.Canceled) {
|
||||
t.Fatalf("work context error = %v, want context.Canceled", workCtx.Err())
|
||||
}
|
||||
assertPoolCloseBlocked(t, closed)
|
||||
finish()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("successful work returned an error: %v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("WithState did not finish")
|
||||
}
|
||||
select {
|
||||
case <-closed:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("Close did not finish after WithState")
|
||||
}
|
||||
if !state.IsClosed() {
|
||||
t.Fatal("Release returned a state to a closed pool")
|
||||
}
|
||||
if state, err := pool.Acquire(nil); state != nil || err == nil || errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Acquire after Close = %v, %v; want closed pool error", state, err)
|
||||
}
|
||||
pool.Close()
|
||||
}
|
||||
|
||||
func TestPoolCloseWaitsForFactory(t *testing.T) {
|
||||
finishCtx, finish := context.WithCancel(context.Background())
|
||||
started, canceled := make(chan struct{}), make(chan struct{})
|
||||
first := true
|
||||
pool := newTestPool(t, context.Background(), time.Second, func(ctx context.Context) (*glua.LState, error) {
|
||||
if first {
|
||||
first = false
|
||||
return glua.NewState(), nil
|
||||
}
|
||||
close(started)
|
||||
<-ctx.Done()
|
||||
close(canceled)
|
||||
<-finishCtx.Done()
|
||||
return nil, ctx.Err()
|
||||
})
|
||||
t.Cleanup(finish)
|
||||
state, err := pool.Acquire(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pool.Release(state, false)
|
||||
acquireDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := pool.Acquire(nil)
|
||||
acquireDone <- err
|
||||
}()
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("state creation did not start")
|
||||
}
|
||||
closed := make(chan struct{})
|
||||
go func() {
|
||||
pool.Close()
|
||||
close(closed)
|
||||
}()
|
||||
select {
|
||||
case <-canceled:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("Close did not cancel state creation")
|
||||
}
|
||||
assertPoolCloseBlocked(t, closed)
|
||||
finish()
|
||||
select {
|
||||
case err := <-acquireDone:
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Acquire error = %v, want context.Canceled", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("state creation did not finish")
|
||||
}
|
||||
select {
|
||||
case <-closed:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("Close did not finish after state creation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolCloseWaitsForCallerContext(t *testing.T) {
|
||||
pool := newTestPool(t, context.Background(), time.Minute, func(context.Context) (*glua.LState, error) {
|
||||
return glua.NewState(), nil
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
started, done := make(chan context.Context, 1), make(chan error, 1)
|
||||
go func() {
|
||||
done <- pool.WithState(ctx, 0, func(L *glua.LState) error {
|
||||
started <- L.Context()
|
||||
<-L.Context().Done()
|
||||
return L.Context().Err()
|
||||
})
|
||||
}()
|
||||
var workCtx context.Context
|
||||
select {
|
||||
case workCtx = <-started:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("WithState did not start")
|
||||
}
|
||||
closed := make(chan struct{})
|
||||
go func() {
|
||||
pool.Close()
|
||||
close(closed)
|
||||
}()
|
||||
select {
|
||||
case <-pool.ctx.Done():
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("Close did not cancel the pool context")
|
||||
}
|
||||
assertPoolCloseBlocked(t, closed)
|
||||
if workCtx.Err() != nil || ctx.Err() != nil {
|
||||
t.Fatal("Close canceled the caller's execution context")
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("WithState error = %v, want context.Canceled", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("WithState did not stop after caller cancellation")
|
||||
}
|
||||
select {
|
||||
case <-closed:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("Close did not finish after WithState")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkPoolAcquireRelease(b *testing.B) {
|
||||
pool := newTestPool(b, context.Background(), time.Second, func(context.Context) (*glua.LState, error) {
|
||||
return glua.NewState(), nil
|
||||
})
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
state, err := pool.Acquire(nil)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
pool.Release(state, true)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package lua
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/base64"
|
||||
"github.com/xtls/xray-core/common/platform"
|
||||
glua "github.com/yuin/gopher-lua"
|
||||
"github.com/yuin/gopher-lua/parse"
|
||||
)
|
||||
|
||||
// Program holds immutable bytecode that can be run by independent LStates.
|
||||
type Program struct {
|
||||
proto *glua.FunctionProto
|
||||
privileged bool
|
||||
}
|
||||
|
||||
// LStateFactory returns a fully initialized state or nil and an error.
|
||||
// Implementations must close partial states on failure; callers own successful states.
|
||||
type LStateFactory func(context.Context) (*glua.LState, error)
|
||||
|
||||
// Compile reads a Lua file or decodes an inline script and compiles it into an immutable program.
|
||||
func Compile(script string) (*Program, error) {
|
||||
var code []byte
|
||||
var err error
|
||||
name := "[inline]"
|
||||
privileged := false
|
||||
if strings.HasPrefix(script, base64.GzipPrefix) || strings.HasPrefix(script, base64.Prefix) {
|
||||
code, err = base64.Decode(script)
|
||||
} else if name, err = platform.ResolveLuaFile(script); err == nil {
|
||||
code, err = os.ReadFile(name)
|
||||
privileged = hasPrivilegedPSK(code)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
chunk, err := parse.Parse(bytes.NewReader(code), name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
proto, err := glua.Compile(chunk, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Program{proto: proto, privileged: privileged}, nil
|
||||
}
|
||||
|
||||
func hasPrivilegedPSK(code []byte) bool {
|
||||
expected := strings.TrimSpace(platform.NewEnvFlag(platform.LuaPrivilegedPSK).GetValue(func() string { return "" }))
|
||||
if expected == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
for len(code) != 0 {
|
||||
line, rest, _ := bytes.Cut(code, []byte{'\n'})
|
||||
code = rest
|
||||
line = bytes.TrimSuffix(line, []byte{'\r'})
|
||||
if len(bytes.TrimSpace(line)) == 0 {
|
||||
continue
|
||||
}
|
||||
line, found := bytes.CutPrefix(bytes.TrimLeft(line, " \t"), []byte("--"))
|
||||
if !found {
|
||||
return false
|
||||
}
|
||||
key, found := bytes.CutPrefix(bytes.TrimLeft(line, " \t"), []byte("@xray:privileged-psk="))
|
||||
key = bytes.TrimSpace(key)
|
||||
return found && len(key) != 0 && string(key) == expected
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// NewState creates a state, runs register, executes the program under ctx, and
|
||||
// runs validate. It removes the initialization context before returning a state
|
||||
// owned by the caller.
|
||||
func (p *Program) NewState(ctx context.Context, register func(*glua.LState), validate func(*glua.LState) error) (*glua.LState, error) {
|
||||
var L *glua.LState
|
||||
if p.privileged {
|
||||
L = glua.NewState()
|
||||
} else {
|
||||
L = newSandboxedState()
|
||||
}
|
||||
valid := false
|
||||
defer func() {
|
||||
if !valid {
|
||||
L.Close()
|
||||
}
|
||||
}()
|
||||
L.SetContext(ctx)
|
||||
defer L.RemoveContext()
|
||||
if register != nil {
|
||||
register(L)
|
||||
}
|
||||
if !p.privileged {
|
||||
// Host registration needs package.preload; scripts must not access the cache or loaders.
|
||||
L.SetGlobal(glua.LoadLibName, glua.LNil)
|
||||
}
|
||||
L.Push(L.NewFunctionFromProto(p.proto))
|
||||
// Execute the Lua script's top level.
|
||||
if err := L.PCall(0, 0, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if validate != nil {
|
||||
if err := validate(L); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
valid = true
|
||||
return L, nil
|
||||
}
|
||||
|
||||
func newSandboxedState() *glua.LState {
|
||||
L := glua.NewState(glua.Options{SkipOpenLibs: true})
|
||||
|
||||
for _, lib := range []struct {
|
||||
name string
|
||||
open glua.LGFunction
|
||||
}{
|
||||
{glua.LoadLibName, glua.OpenPackage},
|
||||
{glua.BaseLibName, glua.OpenBase},
|
||||
{glua.TabLibName, glua.OpenTable},
|
||||
{glua.StringLibName, glua.OpenString},
|
||||
{glua.MathLibName, glua.OpenMath},
|
||||
{glua.CoroutineLibName, glua.OpenCoroutine},
|
||||
} {
|
||||
L.Push(L.NewFunction(lib.open))
|
||||
L.Push(glua.LString(lib.name))
|
||||
L.Call(1, 0)
|
||||
}
|
||||
|
||||
for _, name := range []string{
|
||||
"dofile", "loadfile", "load", "loadstring", "getfenv", "setfenv",
|
||||
"collectgarbage", "module", "newproxy", "print", "_printregs",
|
||||
} {
|
||||
L.SetGlobal(name, glua.LNil)
|
||||
}
|
||||
|
||||
// Capture preload before package is hidden; require() reads loaders from the registry.
|
||||
module := L.GetGlobal(glua.LoadLibName).(*glua.LTable)
|
||||
preload := module.RawGetString("preload").(*glua.LTable)
|
||||
loaders := L.CreateTable(1, 0)
|
||||
loaders.RawSetInt(1, L.NewFunction(func(L *glua.LState) int {
|
||||
name := L.CheckString(1)
|
||||
loader := preload.RawGetString(name)
|
||||
if loader == glua.LNil {
|
||||
loader = glua.LString("no preloaded module: " + name)
|
||||
}
|
||||
L.Push(loader)
|
||||
return 1
|
||||
}))
|
||||
module.RawSetString("loaders", loaders)
|
||||
L.SetField(L.Get(glua.RegistryIndex), "_LOADERS", loaders)
|
||||
for _, name := range []string{"loadlib", "seeall", "path", "cpath", "config"} {
|
||||
module.RawSetString(name, glua.LNil)
|
||||
}
|
||||
|
||||
return L
|
||||
}
|
||||
|
||||
// NewStateFactory returns a factory that gives each state an initialization timeout.
|
||||
func (p *Program) NewStateFactory(initTimeout time.Duration, register func(*glua.LState), validate func(*glua.LState) error) LStateFactory {
|
||||
return func(ctx context.Context) (*glua.LState, error) {
|
||||
initCtx, cancel := context.WithTimeout(ctx, initTimeout)
|
||||
defer cancel()
|
||||
return p.NewState(initCtx, register, validate)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,553 @@
|
||||
package lua
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
"weak"
|
||||
|
||||
xbase64 "github.com/xtls/xray-core/common/base64"
|
||||
"github.com/xtls/xray-core/common/platform"
|
||||
glua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
func TestProgramStatesAreIndependent(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "state.lua")
|
||||
if err := os.WriteFile(path, []byte("value = (value or 0) + 1"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
program, err := Compile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if program.proto.SourceName != path {
|
||||
t.Fatalf("program source = %q, want %q", program.proto.SourceName, path)
|
||||
}
|
||||
first, err := program.NewState(context.Background(), nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer first.Close()
|
||||
first.SetGlobal("value", glua.LNumber(42))
|
||||
second, err := program.NewState(context.Background(), nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer second.Close()
|
||||
if got := second.GetGlobal("value"); got != glua.LNumber(1) {
|
||||
t.Fatalf("second state value = %v, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProgramInitializationObservesCancellation(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "loop.lua")
|
||||
if err := os.WriteFile(path, []byte("while true do end"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
program, err := Compile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
state, err := program.NewState(ctx, nil, nil)
|
||||
if err == nil || state != nil {
|
||||
if state != nil {
|
||||
state.Close()
|
||||
}
|
||||
t.Fatalf("NewState with canceled context = %v, %v; want nil state and error", state, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewStateClosesFailedValidation(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "state.lua")
|
||||
if err := os.WriteFile(path, []byte("value = 1"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
program, err := Compile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantErr := errors.New("invalid script")
|
||||
var checked *glua.LState
|
||||
L, err := program.NewState(context.Background(), nil, func(L *glua.LState) error {
|
||||
checked = L
|
||||
return wantErr
|
||||
})
|
||||
if L != nil || !errors.Is(err, wantErr) || checked == nil || !checked.IsClosed() {
|
||||
t.Fatalf("state = %v, error = %v, checked state closed = %t", L, err, checked != nil && checked.IsClosed())
|
||||
}
|
||||
}
|
||||
|
||||
func compressSource(t *testing.T, code string) []byte {
|
||||
t.Helper()
|
||||
var data bytes.Buffer
|
||||
writer := gzip.NewWriter(&data)
|
||||
if _, err := writer.Write([]byte(code)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return data.Bytes()
|
||||
}
|
||||
|
||||
func TestCompileInline(t *testing.T) {
|
||||
const code = `value = "ä˝ ĺĄ˝"`
|
||||
for _, tc := range []struct {
|
||||
name, script string
|
||||
value glua.LValue
|
||||
}{
|
||||
{"base64", xbase64.Prefix + base64.StdEncoding.EncodeToString([]byte(code)), glua.LString("ä˝ ĺĄ˝")},
|
||||
{"base64+gzip", xbase64.GzipPrefix + base64.StdEncoding.EncodeToString(compressSource(t, code)), glua.LString("ä˝ ĺĄ˝")},
|
||||
{"empty base64", xbase64.Prefix, glua.LNil},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
program, err := Compile(tc.script)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if program.proto.SourceName != "[inline]" {
|
||||
t.Fatalf("program source = %q, want [inline]", program.proto.SourceName)
|
||||
}
|
||||
state, err := program.NewState(context.Background(), nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer state.Close()
|
||||
if got := state.GetGlobal("value"); got != tc.value {
|
||||
t.Fatalf("value = %v, want %v", got, tc.value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompileRejectsInvalidInline(t *testing.T) {
|
||||
corrupt := compressSource(t, "value = 1")
|
||||
corrupt[len(corrupt)-8] ^= 0xff
|
||||
for _, tc := range []struct {
|
||||
name, script string
|
||||
wantErr error
|
||||
wantMessage string
|
||||
}{
|
||||
{"base64", xbase64.Prefix + "%", base64.CorruptInputError(0), "failed to decode base64"},
|
||||
{"gzip base64", xbase64.GzipPrefix + "%", base64.CorruptInputError(0), "failed to decode base64"},
|
||||
{"gzip header", xbase64.GzipPrefix + base64.StdEncoding.EncodeToString([]byte("value = 'uncompressed'")), gzip.ErrHeader, "failed to decompress gzip"},
|
||||
{"gzip checksum", xbase64.GzipPrefix + base64.StdEncoding.EncodeToString(corrupt), gzip.ErrChecksum, "failed to decompress gzip"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
program, err := Compile(tc.script)
|
||||
if program != nil || !errors.Is(err, tc.wantErr) || !strings.Contains(err.Error(), tc.wantMessage) {
|
||||
t.Fatalf("Compile = %v, %v; want nil program and %q error wrapping %v", program, err, tc.wantMessage, tc.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompileInlineDiagnostics(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
code string
|
||||
compileError bool
|
||||
wantMessage string
|
||||
}{
|
||||
{"function broken(", true, ""},
|
||||
{`error("initialization failed")`, false, ""},
|
||||
{"\n-- @xray:privileged-psk=secret\n\nerror('failure')", false, "[inline]:4: failure"},
|
||||
} {
|
||||
program, err := Compile(xbase64.Prefix + base64.StdEncoding.EncodeToString([]byte(tc.code)))
|
||||
if tc.compileError {
|
||||
if program != nil || err == nil {
|
||||
t.Fatalf("Compile = %v, %v; want nil program and syntax error", program, err)
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, initErr := program.NewState(context.Background(), nil, nil)
|
||||
if state != nil {
|
||||
state.Close()
|
||||
t.Fatal("NewState returned a state after failed initialization")
|
||||
}
|
||||
err = initErr
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), "[inline]") {
|
||||
t.Fatalf("Lua error = %v, want [inline] diagnostic", err)
|
||||
}
|
||||
if tc.wantMessage != "" && (!strings.Contains(err.Error(), tc.wantMessage) || strings.Contains(err.Error(), "secret")) {
|
||||
t.Fatalf("Lua error = %v, want %q without the PSK", err, tc.wantMessage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompileRejectsReadFailure(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "unreadable.lua")
|
||||
if err := os.WriteFile(path, []byte("value = 42"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chmod(path, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { os.Chmod(path, 0o600) })
|
||||
if _, err := os.ReadFile(path); !errors.Is(err, os.ErrPermission) {
|
||||
t.Skip("file read permissions are not enforced")
|
||||
}
|
||||
if program, err := Compile(path); program != nil || !errors.Is(err, os.ErrPermission) {
|
||||
t.Fatalf("Compile = %v, %v; want nil program and permission error", program, err)
|
||||
}
|
||||
}
|
||||
|
||||
func compileTestProgram(t *testing.T, code string) *Program {
|
||||
t.Helper()
|
||||
program, err := Compile(xbase64.Prefix + base64.StdEncoding.EncodeToString([]byte(code)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return program
|
||||
}
|
||||
|
||||
func TestProgramPrivilegedPSK(t *testing.T) {
|
||||
const header = "-- @xray:privileged-psk="
|
||||
for _, tc := range []struct {
|
||||
name, psk, code string
|
||||
privileged bool
|
||||
}{
|
||||
{"match", "secret", header + "secret", true},
|
||||
{"no comment space", "secret", "--@xray:privileged-psk=secret", true},
|
||||
{"comment whitespace", "secret", "-- \t @xray:privileged-psk=secret", true},
|
||||
{"mismatch", "secret", header + "other", false},
|
||||
{"both empty", "", header, false},
|
||||
{"missing header", "secret", "value = 1", false},
|
||||
{"empty header", "secret", header, false},
|
||||
{"blank lines and indentation", "secret", " \t\n\n \t" + header + "secret", true},
|
||||
{"CRLF", "secret", "\r\n" + header + "secret\r\nvalue = 1\r\n", true},
|
||||
{"key whitespace", " \tsecret \t", header + " secret ", true},
|
||||
{"whitespace-only keys", " \t", header + " \t", false},
|
||||
{"after comment", "secret", "-- ordinary comment\n" + header + "secret", false},
|
||||
{"after code", "secret", "value = 1\n" + header + "secret", false},
|
||||
{"inside string", "secret", `value = "-- @xray:privileged-psk=secret"`, false},
|
||||
{"wrong marker", "secret", "-- xray:privileged-psk=secret", false},
|
||||
{"later match", "secret", header + "other\n" + header + "secret", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Setenv(platform.LuaPrivilegedPSK, tc.psk)
|
||||
path := filepath.Join(t.TempDir(), "psk.lua")
|
||||
if err := os.WriteFile(path, []byte(tc.code), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, source := range []struct {
|
||||
name, script string
|
||||
privileged bool
|
||||
}{
|
||||
{"file", path, tc.privileged},
|
||||
{"base64", xbase64.Prefix + base64.StdEncoding.EncodeToString([]byte(tc.code)), false},
|
||||
{"gzip", xbase64.GzipPrefix + base64.StdEncoding.EncodeToString(compressSource(t, tc.code)), false},
|
||||
} {
|
||||
t.Run(source.name, func(t *testing.T) {
|
||||
program, err := Compile(source.script)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if program.privileged != source.privileged {
|
||||
t.Fatalf("privileged = %t, want %t", program.privileged, source.privileged)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProgramSandbox(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "escape.lua"), []byte(`disk_loaded = true; return "escaped"`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("LUA_PATH", filepath.ToSlash(filepath.Join(dir, "?.lua")))
|
||||
program := compileTestProgram(t, `
|
||||
local function check()
|
||||
assert(package == nil)
|
||||
assert(require("_G") == _G)
|
||||
for _, name in ipairs({"io", "os", "debug", "channel", "dofile", "loadfile",
|
||||
"load", "loadstring", "getfenv", "setfenv", "collectgarbage", "module",
|
||||
"newproxy", "print", "_printregs"}) do
|
||||
assert(_G[name] == nil, name)
|
||||
end
|
||||
for _, name in ipairs({"io", "os", "debug", "channel", "package", "escape"}) do
|
||||
assert(not pcall(require, name), name)
|
||||
end
|
||||
for _, name in ipairs({"math", "string", "table", "coroutine"}) do
|
||||
assert(require(name) == _G[name], name)
|
||||
end
|
||||
local helper = require("xray.test")
|
||||
assert(helper.value == "ok" and helper == require("xray.test"))
|
||||
assert(math.abs(-2) == 2 and string.upper("ok") == "OK")
|
||||
assert(table.concat({"a", "b"}) == "ab")
|
||||
end
|
||||
check()
|
||||
function CheckSandbox()
|
||||
local thread = coroutine.create(check)
|
||||
assert(coroutine.resume(thread))
|
||||
local injected = false
|
||||
package = {
|
||||
preload = {
|
||||
escape = function() injected = true; return "escaped" end,
|
||||
["xray.late"] = function() injected = true; return "injected" end,
|
||||
},
|
||||
loaded = {escape = "escaped", ["cached.only"] = "injected"},
|
||||
loaders = {function() injected = true; return function() return "escaped" end end},
|
||||
path = testPath,
|
||||
cpath = testPath,
|
||||
}
|
||||
assert(not pcall(require, "escape") and disk_loaded == nil)
|
||||
assert(not pcall(require, "cached.only") and not pcall(require, "package"))
|
||||
assert(require("xray.late") == "host" and require("xray.late") == "host")
|
||||
assert(require("xray.test").value == "ok" and not injected)
|
||||
package = nil
|
||||
end`)
|
||||
var helperLoads, lateLoads int
|
||||
L, err := program.NewState(context.Background(), func(L *glua.LState) {
|
||||
if L.GetGlobal("io") != glua.LNil || L.GetGlobal("loadfile") != glua.LNil {
|
||||
t.Fatal("sandbox was not configured before module registration")
|
||||
}
|
||||
L.SetGlobal("testPath", glua.LString(filepath.ToSlash(filepath.Join(dir, "?.lua"))))
|
||||
L.PreloadModule("xray.test", func(L *glua.LState) int {
|
||||
helperLoads++
|
||||
module := L.NewTable()
|
||||
module.RawSetString("value", glua.LString("ok"))
|
||||
L.Push(module)
|
||||
return 1
|
||||
})
|
||||
L.PreloadModule("xray.late", func(L *glua.LState) int {
|
||||
lateLoads++
|
||||
L.Push(glua.LString("host"))
|
||||
return 1
|
||||
})
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer L.Close()
|
||||
if L.GetTop() != 0 {
|
||||
t.Fatalf("stack top = %d, want 0", L.GetTop())
|
||||
}
|
||||
if err := L.CallByParam(glua.P{Fn: L.GetGlobal("CheckSandbox"), Protect: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if helperLoads != 1 || lateLoads != 1 {
|
||||
t.Fatalf("module initialization calls = (%d, %d), want (1, 1)", helperLoads, lateLoads)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProgramSandboxModuleFailures(t *testing.T) {
|
||||
program := compileTestProgram(t, `
|
||||
assert(package == nil)
|
||||
local ok, err = pcall(require, "xray.failure")
|
||||
assert(not ok and string.find(err, "module initialization failed", 1, true))
|
||||
package = {loaded = {["xray.failure"] = "injected"}}
|
||||
ok, err = pcall(require, "xray.failure")
|
||||
assert(not ok and string.find(err, "loop or previous error loading module", 1, true))
|
||||
for i = 1, 2 do
|
||||
ok, err = pcall(require, "xray.cycle")
|
||||
assert(not ok and string.find(err, "loop or previous error loading module", 1, true))
|
||||
end
|
||||
package = nil
|
||||
`)
|
||||
var failedLoads, cycleLoads int
|
||||
L, err := program.NewState(context.Background(), func(L *glua.LState) {
|
||||
L.PreloadModule("xray.failure", func(L *glua.LState) int {
|
||||
failedLoads++
|
||||
L.RaiseError("module initialization failed")
|
||||
return 0
|
||||
})
|
||||
L.PreloadModule("xray.cycle", func(L *glua.LState) int {
|
||||
cycleLoads++
|
||||
L.Push(L.GetGlobal("require"))
|
||||
L.Push(glua.LString("xray.cycle"))
|
||||
L.Call(1, 1)
|
||||
return 1
|
||||
})
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer L.Close()
|
||||
if failedLoads != 1 || cycleLoads != 1 {
|
||||
t.Fatalf("module initialization calls = (%d, %d), want (1, 1)", failedLoads, cycleLoads)
|
||||
}
|
||||
if L.GetTop() != 0 {
|
||||
t.Fatalf("stack top = %d, want 0", L.GetTop())
|
||||
}
|
||||
}
|
||||
|
||||
func TestProgramSandboxModulesAreCollected(t *testing.T) {
|
||||
for _, fail := range []bool{false, true} {
|
||||
name := "success"
|
||||
if fail {
|
||||
name = "failure"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
ref := func() weak.Pointer[glua.LTable] {
|
||||
program := compileTestProgram(t, `payload = string.rep("x", 1024 * 1024); assert(pcall(require, "xray.test") == expectedSuccess)`)
|
||||
L, err := program.NewState(context.Background(), func(L *glua.LState) {
|
||||
L.SetGlobal("expectedSuccess", glua.LBool(!fail))
|
||||
L.PreloadModule("xray.test", func(L *glua.LState) int {
|
||||
if fail {
|
||||
L.RaiseError("module initialization failed")
|
||||
}
|
||||
L.Push(L.NewTable())
|
||||
return 1
|
||||
})
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref := weak.Make(L.G.Global)
|
||||
L.Close()
|
||||
return ref
|
||||
}()
|
||||
runtime.GC()
|
||||
runtime.GC()
|
||||
if ref.Value() != nil {
|
||||
t.Fatal("closed sandbox's global table was not collected")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProgramSandboxClosesFailedInitialization(t *testing.T) {
|
||||
program := compileTestProgram(t, `require("xray.failure")`)
|
||||
var partial *glua.LState
|
||||
L, err := program.NewState(context.Background(), func(L *glua.LState) {
|
||||
partial = L
|
||||
L.PreloadModule("xray.failure", func(L *glua.LState) int {
|
||||
L.RaiseError("module initialization failed")
|
||||
return 0
|
||||
})
|
||||
}, func(*glua.LState) error {
|
||||
t.Error("validation ran after failed initialization")
|
||||
return nil
|
||||
})
|
||||
if L != nil {
|
||||
L.Close()
|
||||
t.Fatal("sandbox initialization returned a state")
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), "module initialization failed") || partial == nil || !partial.IsClosed() {
|
||||
t.Fatalf("error = %v, partial state closed = %t", err, partial != nil && partial.IsClosed())
|
||||
}
|
||||
}
|
||||
|
||||
func TestProgramPrivilegedLibraries(t *testing.T) {
|
||||
t.Setenv(platform.LuaPrivilegedPSK, "secret")
|
||||
const code = `-- @xray:privileged-psk=secret
|
||||
assert(require("io") == io and require("os") == os)
|
||||
assert(require("debug") == debug and require("channel") == channel)
|
||||
assert(type(coroutine.create) == "function" and require("coroutine") == coroutine)
|
||||
assert(type(dofile) == "function" and type(loadfile) == "function")
|
||||
assert(type(getfenv) == "function" and type(setfenv) == "function")
|
||||
assert(type(collectgarbage) == "function" and type(print) == "function")
|
||||
assert(type(package.loaders[2]) == "function" and type(package.path) == "string")
|
||||
assert(type(debug.traceback()) == "string" and type(os.time()) == "number")
|
||||
assert(assert(loadstring("return 42"))() == 42)
|
||||
local file = assert(io.open(testPath, "w"))
|
||||
file:write("privileged")
|
||||
file:close()`
|
||||
path := filepath.Join(t.TempDir(), "privileged.lua")
|
||||
if err := os.WriteFile(path, []byte(code), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name, script string
|
||||
privileged bool
|
||||
}{
|
||||
{"file", path, true},
|
||||
{"base64", xbase64.Prefix + base64.StdEncoding.EncodeToString([]byte(code)), false},
|
||||
{"gzip", xbase64.GzipPrefix + base64.StdEncoding.EncodeToString(compressSource(t, code)), false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
program, err := Compile(tc.script)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := filepath.Join(t.TempDir(), "privileged.txt")
|
||||
L, err := program.NewState(context.Background(), func(L *glua.LState) {
|
||||
L.SetGlobal("testPath", glua.LString(output))
|
||||
}, nil)
|
||||
if !tc.privileged {
|
||||
if L != nil {
|
||||
L.Close()
|
||||
t.Fatal("inline script with a matching PSK accessed privileged libraries")
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), "no preloaded module: io") {
|
||||
t.Fatalf("NewState error = %v, want io module unavailable", err)
|
||||
}
|
||||
if _, err := os.Stat(output); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("inline script output stat error = %v, want file not found", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer L.Close()
|
||||
data, err := os.ReadFile(output)
|
||||
if err != nil || string(data) != "privileged" {
|
||||
t.Fatalf("privileged file contents = %q, error = %v", data, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProgramPrivilegesAreCompileTimeSnapshot(t *testing.T) {
|
||||
for _, privileged := range []bool{false, true} {
|
||||
name := "sandboxed"
|
||||
if privileged {
|
||||
name = "privileged"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
before, after := "other", "secret"
|
||||
if privileged {
|
||||
before, after = after, before
|
||||
}
|
||||
t.Setenv(platform.LuaPrivilegedPSK, before)
|
||||
const code = "-- @xray:privileged-psk=secret\nvalue = 1"
|
||||
path := filepath.Join(t.TempDir(), "snapshot.lua")
|
||||
if err := os.WriteFile(path, []byte(code), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
program, err := Compile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv(platform.LuaPrivilegedPSK, after)
|
||||
check := func(L *glua.LState) {
|
||||
t.Helper()
|
||||
if got := L.GetGlobal("os").Type() == glua.LTTable; got != privileged {
|
||||
t.Fatalf("os available = %t, want compile-time value %t", got, privileged)
|
||||
}
|
||||
}
|
||||
factory := program.NewStateFactory(time.Second, nil, nil)
|
||||
for range 2 {
|
||||
L, err := factory(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer L.Close()
|
||||
check(L)
|
||||
}
|
||||
recompiled, err := Compile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if recompiled.privileged == privileged {
|
||||
t.Fatal("recompilation did not observe the changed environment")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package lua
|
||||
|
||||
import (
|
||||
"math"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
glua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
type number interface {
|
||||
~int | ~int8 | ~int16 | ~int32 | ~int64 |
|
||||
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
|
||||
~float32 | ~float64
|
||||
}
|
||||
|
||||
// PushNumber converts a Go number to a Lua number and pushes it.
|
||||
func PushNumber[T number](L *glua.LState, value T) {
|
||||
L.Push(glua.LNumber(value))
|
||||
}
|
||||
|
||||
// PushString converts a Go string to a Lua string and pushes it.
|
||||
func PushString(L *glua.LState, value string) {
|
||||
L.Push(glua.LString(value))
|
||||
}
|
||||
|
||||
// PushNil pushes Lua nil.
|
||||
func PushNil(L *glua.LState) {
|
||||
L.Push(glua.LNil)
|
||||
}
|
||||
|
||||
// PushUserData pushes a native Go value without copying it.
|
||||
func PushUserData(L *glua.LState, value any) {
|
||||
ud := L.NewUserData()
|
||||
ud.Value = value
|
||||
L.Push(ud)
|
||||
}
|
||||
|
||||
// PushError pushes nil or the original Go error as userdata.
|
||||
func PushError(L *glua.LState, err error) {
|
||||
if err == nil {
|
||||
L.Push(glua.LNil)
|
||||
return
|
||||
}
|
||||
PushUserData(L, err)
|
||||
}
|
||||
|
||||
// ReadUserData reads a native Go value of type T without copying it.
|
||||
// Other Lua values or userdata containing a different type return invalidMessage.
|
||||
func ReadUserData[T any](value glua.LValue, invalidMessage string) (T, error) {
|
||||
if ud, ok := value.(*glua.LUserData); ok {
|
||||
if result, ok := ud.Value.(T); ok {
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
var zero T
|
||||
return zero, errors.New(invalidMessage)
|
||||
}
|
||||
|
||||
// ReadError accepts nil, a native Go error, or a Lua string.
|
||||
// Native errors retain their identity; other values return invalidMessage.
|
||||
func ReadError(value glua.LValue, invalidMessage string) error {
|
||||
if value == glua.LNil {
|
||||
return nil
|
||||
}
|
||||
if ud, ok := value.(*glua.LUserData); ok {
|
||||
if err, ok := ud.Value.(error); ok {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if message, ok := value.(glua.LString); ok {
|
||||
return errors.New(string(message))
|
||||
}
|
||||
return errors.New(invalidMessage)
|
||||
}
|
||||
|
||||
// ReadUint32 accepts only integral Lua numbers in the uint32 range.
|
||||
func ReadUint32(value glua.LValue, invalidMessage string) (uint32, error) {
|
||||
number, ok := value.(glua.LNumber)
|
||||
if !ok || number < 0 || number > math.MaxUint32 || math.Trunc(float64(number)) != float64(number) {
|
||||
return 0, errors.New(invalidMessage)
|
||||
}
|
||||
return uint32(number), nil
|
||||
}
|
||||
|
||||
// ReadOptionalString accepts a Lua string or nil, which becomes an empty string.
|
||||
// It does not coerce other values to strings.
|
||||
func ReadOptionalString(value glua.LValue, invalidMessage string) (string, error) {
|
||||
if value == glua.LNil {
|
||||
return "", nil
|
||||
}
|
||||
if result, ok := value.(glua.LString); ok {
|
||||
return string(result), nil
|
||||
}
|
||||
return "", errors.New(invalidMessage)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package lua
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
glua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
func TestReadUint32(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
value glua.LValue
|
||||
want uint32
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "zero", value: glua.LNumber(0)},
|
||||
{name: "integer", value: glua.LNumber(45), want: 45},
|
||||
{name: "maximum", value: glua.LNumber(math.MaxUint32), want: math.MaxUint32},
|
||||
{name: "fraction", value: glua.LNumber(1.5), wantErr: true},
|
||||
{name: "negative", value: glua.LNumber(-1), wantErr: true},
|
||||
{name: "overflow", value: glua.LNumber(math.MaxUint32 + 1), wantErr: true},
|
||||
{name: "NaN", value: glua.LNumber(math.NaN()), wantErr: true},
|
||||
{name: "positive infinity", value: glua.LNumber(math.Inf(1)), wantErr: true},
|
||||
{name: "negative infinity", value: glua.LNumber(math.Inf(-1)), wantErr: true},
|
||||
{name: "nil", value: glua.LNil, wantErr: true},
|
||||
{name: "numeric string", value: glua.LString("45"), wantErr: true},
|
||||
{name: "boolean", value: glua.LTrue, wantErr: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, err := ReadUint32(tc.value, "invalid number")
|
||||
if got != tc.want || (err != nil) != tc.wantErr {
|
||||
t.Fatalf("ReadUint32() = %d, %v; want %d, error %t", got, err, tc.want, tc.wantErr)
|
||||
}
|
||||
if err != nil && !strings.Contains(err.Error(), "invalid number") {
|
||||
t.Fatalf("error = %v, want invalid number", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadOptionalString(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
value glua.LValue
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "nil", value: glua.LNil},
|
||||
{name: "empty", value: glua.LString("")},
|
||||
{name: "string", value: glua.LString("out"), want: "out"},
|
||||
{name: "number", value: glua.LNumber(1), wantErr: true},
|
||||
{name: "boolean", value: glua.LFalse, wantErr: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, err := ReadOptionalString(tc.value, "invalid string")
|
||||
if got != tc.want || (err != nil) != tc.wantErr {
|
||||
t.Fatalf("ReadOptionalString() = %q, %v; want %q, error %t", got, err, tc.want, tc.wantErr)
|
||||
}
|
||||
if err != nil && !strings.Contains(err.Error(), "invalid string") {
|
||||
t.Fatalf("error = %v, want invalid string", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserDataRoundTrip(t *testing.T) {
|
||||
L := glua.NewState()
|
||||
defer L.Close()
|
||||
want := []int{1, 2}
|
||||
PushUserData(L, want)
|
||||
if L.GetTop() != 1 {
|
||||
t.Fatalf("stack top = %d, want 1", L.GetTop())
|
||||
}
|
||||
got, err := ReadUserData[[]int](L.Get(-1), "invalid userdata")
|
||||
if err != nil || len(got) != len(want) || &got[0] != &want[0] {
|
||||
t.Fatalf("userdata = %v, %v; want original slice", got, err)
|
||||
}
|
||||
PushUserData(L, []int(nil))
|
||||
if got, err := ReadUserData[[]int](L.Get(-1), "invalid userdata"); err != nil || got != nil {
|
||||
t.Fatalf("nil slice userdata = %v, %v", got, err)
|
||||
}
|
||||
for _, value := range []glua.LValue{glua.LNil, glua.LString("1"), L.NewTable(), L.Get(1)} {
|
||||
if got, err := ReadUserData[int](value, "invalid userdata"); got != 0 || err == nil || !strings.Contains(err.Error(), "invalid userdata") {
|
||||
t.Fatalf("ReadUserData(%v) = %d, %v; want invalid userdata", value, got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorRoundTrip(t *testing.T) {
|
||||
L := glua.NewState()
|
||||
defer L.Close()
|
||||
want := errors.New("upstream failed")
|
||||
for _, err := range []error{nil, want} {
|
||||
PushError(L, err)
|
||||
if L.GetTop() != 1 {
|
||||
t.Fatalf("stack top = %d, want 1", L.GetTop())
|
||||
}
|
||||
if err == nil && L.Get(-1) != glua.LNil {
|
||||
t.Fatalf("nil error pushed as %v", L.Get(-1))
|
||||
}
|
||||
if got := ReadError(L.Get(-1), "invalid error"); got != err {
|
||||
t.Fatalf("ReadError() = %v, want original error %v", got, err)
|
||||
}
|
||||
L.Pop(1)
|
||||
}
|
||||
for _, message := range []string{"script failed", ""} {
|
||||
if err := ReadError(glua.LString(message), "invalid error"); err == nil || !strings.Contains(err.Error(), message) {
|
||||
t.Fatalf("string error = %v, want %q", err, message)
|
||||
}
|
||||
}
|
||||
wrong := L.NewUserData()
|
||||
wrong.Value = "not a native error"
|
||||
for _, value := range []glua.LValue{glua.LTrue, glua.LNumber(1), L.NewTable(), wrong, L.NewUserData()} {
|
||||
if err := ReadError(value, "invalid error"); err == nil || !strings.Contains(err.Error(), "invalid error") {
|
||||
t.Fatalf("ReadError(%v) = %v, want invalid error", value, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,11 @@ import (
|
||||
|
||||
"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"
|
||||
@@ -114,3 +116,48 @@ func TestClientWorkerClose(t *testing.T) {
|
||||
|
||||
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])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,15 +14,16 @@ import (
|
||||
type PacketReader struct {
|
||||
reader io.Reader
|
||||
eof bool
|
||||
dest *net.Destination
|
||||
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,
|
||||
dest: *dest,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,8 +48,8 @@ func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
return nil, err
|
||||
}
|
||||
r.eof = true
|
||||
if r.dest != nil && r.dest.Network == net.Network_UDP {
|
||||
b.UDP = r.dest
|
||||
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
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package platform // import "github.com/xtls/xray-core/common/platform"
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
@@ -23,6 +25,7 @@ const (
|
||||
BrowserDialerAddress = "xray.browser.dialer"
|
||||
XUDPLog = "xray.xudp.show"
|
||||
XUDPBaseKey = "xray.xudp.basekey"
|
||||
LuaPrivilegedPSK = "xray.lua.privileged.psk"
|
||||
|
||||
TunFdKey = "xray.tun.fd"
|
||||
)
|
||||
@@ -90,3 +93,49 @@ func GetConfDirPath() string {
|
||||
configPath := NewEnvFlag(ConfdirLocation).GetValue(func() string { return "" })
|
||||
return configPath
|
||||
}
|
||||
|
||||
// ResolveLuaFile finds a local Lua script and returns its absolute path.
|
||||
// Relative paths: XRAY_LOCATION_CONFDIR > XRAY_LOCATION_CONFIG > working dir > executable dir.
|
||||
func ResolveLuaFile(path string) (string, error) {
|
||||
if path == "" {
|
||||
return "", errors.New("Lua file path is empty")
|
||||
}
|
||||
paths := []string{path}
|
||||
if !filepath.IsAbs(path) {
|
||||
paths = nil
|
||||
for _, dir := range []string{
|
||||
GetConfDirPath(),
|
||||
NewEnvFlag(ConfigLocation).GetValue(func() string { return "" }),
|
||||
".",
|
||||
getExecutableDir(),
|
||||
} {
|
||||
if dir != "" {
|
||||
paths = append(paths, filepath.Join(dir, path))
|
||||
}
|
||||
}
|
||||
}
|
||||
return resolveFile(paths)
|
||||
}
|
||||
|
||||
func resolveFile(paths []string) (string, error) {
|
||||
var tried []string
|
||||
for _, path := range paths {
|
||||
path, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to resolve file path: %w", err)
|
||||
}
|
||||
tried = append(tried, path)
|
||||
info, err := os.Stat(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to inspect file %q: %w", path, err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return "", fmt.Errorf("file is not a regular file: %s", path)
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
return "", fmt.Errorf("file not found; tried %q: %w", tried, os.ErrNotExist)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package platform_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
@@ -64,3 +65,53 @@ func TestGetAssetLocation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveLuaFile(t *testing.T) {
|
||||
workingDir := t.TempDir()
|
||||
t.Chdir(workingDir)
|
||||
executable, err := os.Executable()
|
||||
common.Must(err)
|
||||
file, err := os.CreateTemp(filepath.Dir(executable), "lua-*.lua")
|
||||
common.Must(err)
|
||||
common.Must(file.Close())
|
||||
defer os.Remove(file.Name())
|
||||
|
||||
name := filepath.Base(file.Name())
|
||||
paths := []string{
|
||||
filepath.Join(t.TempDir(), name),
|
||||
filepath.Join(t.TempDir(), name),
|
||||
filepath.Join(workingDir, name),
|
||||
file.Name(),
|
||||
}
|
||||
t.Setenv(ConfdirLocation, filepath.Dir(paths[0]))
|
||||
t.Setenv(ConfigLocation, filepath.Dir(paths[1]))
|
||||
for _, path := range paths[:3] {
|
||||
common.Must(os.WriteFile(path, nil, 0o600))
|
||||
}
|
||||
if got, err := ResolveLuaFile(paths[2]); err != nil || got != paths[2] {
|
||||
t.Fatalf("absolute path = %q, %v; want %q", got, err, paths[2])
|
||||
}
|
||||
for i, want := range paths {
|
||||
if i == 2 {
|
||||
t.Setenv(ConfdirLocation, "")
|
||||
t.Setenv(ConfigLocation, "")
|
||||
}
|
||||
if got, err := ResolveLuaFile(name); err != nil || got != want {
|
||||
t.Fatalf("resolved path = %q, %v; want %q", got, err, want)
|
||||
}
|
||||
common.Must(os.Remove(want))
|
||||
}
|
||||
if _, err := ResolveLuaFile(name); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("missing file error = %v", err)
|
||||
}
|
||||
|
||||
t.Setenv(ConfdirLocation, filepath.Dir(paths[0]))
|
||||
t.Setenv(ConfigLocation, filepath.Dir(paths[1]))
|
||||
common.Must(os.Mkdir(paths[0], 0o700))
|
||||
common.Must(os.WriteFile(paths[1], nil, 0o600))
|
||||
for _, path := range []string{"", name, filepath.Join(t.TempDir(), name)} {
|
||||
if _, err := ResolveLuaFile(path); err == nil {
|
||||
t.Fatalf("accepted invalid path %q", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -19,8 +19,8 @@ import (
|
||||
|
||||
var (
|
||||
Version_x byte = 26
|
||||
Version_y byte = 9
|
||||
Version_z byte = 30
|
||||
Version_y byte = 10
|
||||
Version_z byte = 10
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
+3
-1
@@ -92,6 +92,8 @@ type Instance struct {
|
||||
|
||||
// Instance state
|
||||
func (server *Instance) IsRunning() bool {
|
||||
server.statusLock.Lock()
|
||||
defer server.statusLock.Unlock()
|
||||
return server.running
|
||||
}
|
||||
|
||||
@@ -320,7 +322,7 @@ func (s *Instance) RequireFeatures(callback interface{}, optional bool) error {
|
||||
|
||||
// AddFeature registers a feature into current Instance.
|
||||
func (s *Instance) AddFeature(feature features.Feature) error {
|
||||
if s.running {
|
||||
if s.IsRunning() {
|
||||
if err := feature.Start(); err != nil {
|
||||
errors.LogInfoInner(s.ctx, err, "failed to start feature")
|
||||
}
|
||||
|
||||
@@ -21,10 +21,12 @@ require (
|
||||
github.com/stretchr/testify v1.12.1
|
||||
github.com/vishvananda/netlink v1.3.1
|
||||
github.com/xtls/reality v0.0.0-20260908062103-8cdf7bf9c7f0
|
||||
github.com/yuin/gopher-lua v1.1.2
|
||||
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba
|
||||
golang.org/x/crypto v0.57.0
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20261005185213-c3db4df58582
|
||||
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842
|
||||
golang.org/x/net v0.59.0
|
||||
golang.org/x/net v0.60.0
|
||||
golang.org/x/sync v0.23.0
|
||||
golang.org/x/sys v0.48.0
|
||||
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2
|
||||
@@ -34,6 +36,7 @@ require (
|
||||
google.golang.org/protobuf v1.36.12
|
||||
gvisor.dev/gvisor v0.0.0-20260122175437-89a5d21be8f0
|
||||
h12.io/socks v1.0.3
|
||||
layeh.com/gopher-luar v1.0.11
|
||||
lukechampine.com/blake3 v1.4.1
|
||||
mvdan.cc/gofumpt v0.12.0
|
||||
)
|
||||
@@ -55,7 +58,6 @@ require (
|
||||
github.com/vishvananda/netns v0.0.5 // indirect
|
||||
github.com/wlynxg/anet v0.0.5 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20261005185213-c3db4df58582 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
golang.org/x/time v0.14.0 // indirect
|
||||
golang.org/x/tools v0.49.0 // indirect
|
||||
|
||||
@@ -2,6 +2,9 @@ github.com/andybalholm/brotli v1.0.6 h1:Yf9fFpf49Zrxb9NlQaluyE92/+X7UVHlhMNJN2sx
|
||||
github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
|
||||
github.com/apernet/quic-go v0.61.1-0.20260806010916-184d081eef3e h1:5mgtR5gwIgBKMiGI1QdXldZZ+SNor06Nbu1wCBulQBg=
|
||||
github.com/apernet/quic-go v0.61.1-0.20260806010916-184d081eef3e/go.mod h1:x7qxEvX6MCVtDuBKHj3E+88+BtrbEMuAL5qGUKItjW8=
|
||||
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
||||
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
|
||||
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
|
||||
github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA=
|
||||
github.com/cloudflare/circl v1.6.5/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c=
|
||||
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 h1:Arcl6UOIS/kgO2nW3A65HN+7CMjSDP/gofXL4CZt1V4=
|
||||
@@ -81,6 +84,9 @@ github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguH
|
||||
github.com/xtls/reality v0.0.0-20260908062103-8cdf7bf9c7f0 h1:rb+fKQFhz+5I2PPuQsNYxI5mUU840XWYtRF0ZBjvkws=
|
||||
github.com/xtls/reality v0.0.0-20260908062103-8cdf7bf9c7f0/go.mod h1:DsJblcWDGt76+FVqBVwbwRhxyyNJsGV48gJLch0OOWI=
|
||||
github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
||||
github.com/yuin/gopher-lua v0.0.0-20190206043414-8bfc7677f583/go.mod h1:gqRgreBUhTSL0GeU64rtZ3Uq3wtjOa/TB2YfrtkCbVQ=
|
||||
github.com/yuin/gopher-lua v1.1.2 h1:yF/FjE3hD65tBbt0VXLE13HWS9h34fdzJmrWRXwobGA=
|
||||
github.com/yuin/gopher-lua v1.1.2/go.mod h1:7aRmXIWl37SqRf0koeyylBEzJ+aPt8A+mmkQ4f1ntR8=
|
||||
go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=
|
||||
go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
@@ -101,12 +107,13 @@ golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
|
||||
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
|
||||
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@@ -157,6 +164,8 @@ gvisor.dev/gvisor v0.0.0-20260122175437-89a5d21be8f0 h1:Lk6hARj5UPY47dBep70OD/TI
|
||||
gvisor.dev/gvisor v0.0.0-20260122175437-89a5d21be8f0/go.mod h1:QkHjoMIBaYtpVufgwv3keYAbln78mBoCuShZrPrer1Q=
|
||||
h12.io/socks v1.0.3 h1:Ka3qaQewws4j4/eDQnOdpr4wXsC//dXtWvftlIcCQUo=
|
||||
h12.io/socks v1.0.3/go.mod h1:AIhxy1jOId/XCz9BO+EIgNL2rQiPTBNnOfnVnQ+3Eck=
|
||||
layeh.com/gopher-luar v1.0.11 h1:8zJudpKI6HWkoh9eyyNFaTM79PY6CAPcIr6X/KTiliw=
|
||||
layeh.com/gopher-luar v1.0.11/go.mod h1:TPnIVCZ2RJBndm7ohXyaqfhzjlZ+OA2SZR/YwL8tECk=
|
||||
lukechampine.com/blake3 v1.4.1 h1:I3Smz7gso8w4/TunLKec6K2fn+kyKtDxr/xcQEN84Wg=
|
||||
lukechampine.com/blake3 v1.4.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo=
|
||||
mvdan.cc/gofumpt v0.12.0 h1:1Lbudkz2kpM9Cjz2pL4M19u7q+GaEhCTNf7N9mfpcho=
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
)
|
||||
|
||||
type NameServerConfig struct {
|
||||
ID string `json:"id"`
|
||||
Address *Address `json:"address"`
|
||||
ClientIP *Address `json:"clientIp"`
|
||||
Port uint16 `json:"port"`
|
||||
@@ -43,6 +44,7 @@ func (c *NameServerConfig) UnmarshalJSON(data []byte) error {
|
||||
}
|
||||
|
||||
var advanced struct {
|
||||
ID string `json:"id"`
|
||||
Address *Address `json:"address"`
|
||||
ClientIP *Address `json:"clientIp"`
|
||||
Port uint16 `json:"port"`
|
||||
@@ -60,6 +62,7 @@ func (c *NameServerConfig) UnmarshalJSON(data []byte) error {
|
||||
UnexpectedIPs StringList `json:"unexpectedIPs"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &advanced); err == nil {
|
||||
c.ID = advanced.ID
|
||||
c.Address = advanced.Address
|
||||
c.ClientIP = advanced.ClientIP
|
||||
c.Port = advanced.Port
|
||||
@@ -134,6 +137,7 @@ func (c *NameServerConfig) Build() (*dns.NameServer, error) {
|
||||
}
|
||||
|
||||
return &dns.NameServer{
|
||||
Id: c.ID,
|
||||
Address: &net.Endpoint{
|
||||
Network: net.Network_UDP,
|
||||
Address: c.Address.Build(),
|
||||
@@ -159,6 +163,7 @@ func (c *NameServerConfig) Build() (*dns.NameServer, error) {
|
||||
// DNSConfig is a JSON serializable object for dns.Config
|
||||
type DNSConfig struct {
|
||||
Servers []*NameServerConfig `json:"servers"`
|
||||
Script string `json:"script"`
|
||||
Hosts *HostsWrapper `json:"hosts"`
|
||||
ClientIP *Address `json:"clientIp"`
|
||||
Tag string `json:"tag"`
|
||||
@@ -267,6 +272,17 @@ func (m *HostsWrapper) Build() ([]*dns.Config_HostMapping, error) {
|
||||
|
||||
// Build implements Buildable
|
||||
func (c *DNSConfig) Build() (*dns.Config, error) {
|
||||
if c.Script != "" {
|
||||
if c.DisableFallback || c.DisableFallbackIfMatch || c.EnableParallelQuery {
|
||||
return nil, errors.New("DNS script cannot be used with disableFallback, disableFallbackIfMatch or enableParallelQuery")
|
||||
}
|
||||
for i, server := range c.Servers {
|
||||
if len(server.Domains) > 0 || server.SkipFallback || server.FinalQuery {
|
||||
return nil, errors.New("DNS script cannot be used with domains, skipFallback or finalQuery in server ", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
config := &dns.Config{
|
||||
Tag: c.Tag,
|
||||
DisableCache: c.DisableCache,
|
||||
@@ -276,6 +292,7 @@ func (c *DNSConfig) Build() (*dns.Config, error) {
|
||||
DisableFallbackIfMatch: c.DisableFallbackIfMatch,
|
||||
EnableParallelQuery: c.EnableParallelQuery,
|
||||
QueryStrategy: resolveQueryStrategy(c.QueryStrategy),
|
||||
Script: c.Script,
|
||||
}
|
||||
|
||||
if c.ClientIP != nil {
|
||||
|
||||
@@ -2,6 +2,7 @@ package conf_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
@@ -122,3 +123,57 @@ func TestDNSConfigParsing(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSNameServerID(t *testing.T) {
|
||||
var parsed DNSConfig
|
||||
if err := json.Unmarshal([]byte(`{"servers":[{"id":"primary","address":"1.1.1.1"}]}`), &parsed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
built, err := parsed.Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(built.NameServer) != 1 || built.NameServer[0].Id != "primary" {
|
||||
t.Fatalf("nameserver IDs = %v, want primary", built.NameServer)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSScriptConfig(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
input string
|
||||
wantError string
|
||||
}{
|
||||
{name: "script only", input: `{"script":"script.lua"}`},
|
||||
{name: "compatible fields", input: `{"script":"script.lua","servers":["1.1.1.1",{"id":"primary","address":"8.8.8.8","expectedIPs":["8.8.8.8"],"queryStrategy":"UseIPv4","disableCache":true}],"hosts":{"example.com":"127.0.0.1"},"disableCache":true}`},
|
||||
{name: "disabled options", input: `{"script":"script.lua","disableFallback":false,"disableFallbackIfMatch":false,"enableParallelQuery":false,"servers":[{"address":"1.1.1.1","domains":[],"skipFallback":false,"finalQuery":false}]}`},
|
||||
{name: "domains", input: `{"script":"script.lua","servers":[{"address":"1.1.1.1","domains":["domain:example.com"]}]}`, wantError: "domains"},
|
||||
{name: "skip fallback", input: `{"script":"script.lua","servers":[{"address":"1.1.1.1","skipFallback":true}]}`, wantError: "skipFallback"},
|
||||
{name: "final query", input: `{"script":"script.lua","servers":[{"address":"1.1.1.1","finalQuery":true}]}`, wantError: "finalQuery"},
|
||||
{name: "later server", input: `{"script":"script.lua","servers":["1.1.1.1",{"address":"8.8.8.8","finalQuery":true}]}`, wantError: "server 1"},
|
||||
{name: "disable fallback", input: `{"script":"script.lua","disableFallback":true}`, wantError: "disableFallback"},
|
||||
{name: "disable fallback if match", input: `{"script":"script.lua","disableFallbackIfMatch":true}`, wantError: "disableFallbackIfMatch"},
|
||||
{name: "parallel query", input: `{"script":"script.lua","enableParallelQuery":true}`, wantError: "enableParallelQuery"},
|
||||
{name: "empty script", input: `{"script":"","disableFallback":true,"disableFallbackIfMatch":true,"enableParallelQuery":true,"servers":[{"address":"1.1.1.1","domains":["example.com"],"skipFallback":true,"finalQuery":true}]}`},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var config DNSConfig
|
||||
if err := json.Unmarshal([]byte(test.input), &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
built, err := config.Build()
|
||||
if test.wantError != "" {
|
||||
if built != nil || err == nil || !strings.Contains(err.Error(), "DNS script cannot be used with ") || !strings.Contains(err.Error(), test.wantError) {
|
||||
t.Fatalf("Build() = %v, %v; want nil config and script conflict error mentioning %s", built, err, test.wantError)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if built.Script != config.Script || len(built.NameServer) != len(config.Servers) {
|
||||
t.Fatalf("Build() did not preserve script or servers: %v", built)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+68
-11
@@ -16,8 +16,61 @@ import (
|
||||
. "github.com/xtls/xray-core/infra/conf"
|
||||
masqueproxy "github.com/xtls/xray-core/proxy/masque"
|
||||
"github.com/xtls/xray-core/transport/internet/masque"
|
||||
"github.com/xtls/xray-core/transport/internet/splithttp"
|
||||
)
|
||||
|
||||
func defaultMasqueXmux() *splithttp.XmuxConfig {
|
||||
return &splithttp.XmuxConfig{
|
||||
MaxConcurrency: &splithttp.RangeConfig{},
|
||||
MaxConnections: &splithttp.RangeConfig{From: 1, To: 1},
|
||||
CMaxReuseTimes: &splithttp.RangeConfig{},
|
||||
HMaxRequestTimes: &splithttp.RangeConfig{},
|
||||
HMaxReusableSecs: &splithttp.RangeConfig{From: 1800, To: 3000},
|
||||
}
|
||||
}
|
||||
|
||||
func TestMasqueXmuxConfig(t *testing.T) {
|
||||
creator := func() Buildable {
|
||||
return new(MasqueConfig)
|
||||
}
|
||||
|
||||
runMultiTestCase(t, []TestCase{
|
||||
{
|
||||
Input: `{"xmux": {"maxConnections": "2-4", "hMaxReusableSecs": 60, "hKeepAlivePeriod": -1}}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &masque.Config{
|
||||
Path: "/.well-known/masque/ip/*/*/",
|
||||
Xmux: &splithttp.XmuxConfig{
|
||||
MaxConcurrency: &splithttp.RangeConfig{},
|
||||
MaxConnections: &splithttp.RangeConfig{From: 2, To: 4},
|
||||
CMaxReuseTimes: &splithttp.RangeConfig{},
|
||||
HMaxRequestTimes: &splithttp.RangeConfig{},
|
||||
HMaxReusableSecs: &splithttp.RangeConfig{From: 60, To: 60},
|
||||
HKeepAlivePeriod: -1,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Input: `{"xmux": {"maxConcurrency": 8}}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &masque.Config{
|
||||
Path: "/.well-known/masque/ip/*/*/",
|
||||
Xmux: &splithttp.XmuxConfig{
|
||||
MaxConcurrency: &splithttp.RangeConfig{From: 8, To: 8},
|
||||
MaxConnections: &splithttp.RangeConfig{},
|
||||
CMaxReuseTimes: &splithttp.RangeConfig{},
|
||||
HMaxRequestTimes: &splithttp.RangeConfig{},
|
||||
HMaxReusableSecs: &splithttp.RangeConfig{},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if _, err := loadJSON(creator)(`{"xmux": {"maxConnections": 2, "maxConcurrency": 8}}`); err == nil {
|
||||
t.Error("expected an error for maxConnections with maxConcurrency")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMasqueConfig(t *testing.T) {
|
||||
creator := func() Buildable {
|
||||
return new(MasqueConfig)
|
||||
@@ -27,7 +80,7 @@ func TestMasqueConfig(t *testing.T) {
|
||||
{
|
||||
Input: `{}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &masque.Config{Path: "/.well-known/masque/ip/*/*/"},
|
||||
Output: &masque.Config{Path: "/.well-known/masque/ip/*/*/", Xmux: defaultMasqueXmux()},
|
||||
},
|
||||
{
|
||||
Input: `{
|
||||
@@ -40,12 +93,13 @@ func TestMasqueConfig(t *testing.T) {
|
||||
Host: "example.com:8443",
|
||||
Path: "/.well-known/masque/ip/*/*/",
|
||||
Headers: map[string]string{"Authorization": "Basic dTpw"},
|
||||
Xmux: defaultMasqueXmux(),
|
||||
},
|
||||
},
|
||||
{
|
||||
Input: `{"path": "/masque/ip{?target,ipproto}"}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &masque.Config{Path: "/masque/ip?target=*&ipproto=*"},
|
||||
Output: &masque.Config{Path: "/masque/ip?target=*&ipproto=*", Xmux: defaultMasqueXmux()},
|
||||
},
|
||||
{
|
||||
Input: `{"user": "u", "pass": "p:q", "headers": {"X-Token": "a"}}`,
|
||||
@@ -53,6 +107,7 @@ func TestMasqueConfig(t *testing.T) {
|
||||
Output: &masque.Config{
|
||||
Path: "/.well-known/masque/ip/*/*/",
|
||||
Headers: map[string]string{"Authorization": "Basic dTpwOnE=", "X-Token": "a"},
|
||||
Xmux: defaultMasqueXmux(),
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -122,6 +177,7 @@ func TestMasqueWarpConfig(t *testing.T) {
|
||||
Host: "cloudflareaccess.com",
|
||||
Path: "/",
|
||||
Warp: &masque.Warp{PrivateKey: pkcs8, PublicKey: publicKey, Address: address},
|
||||
Xmux: defaultMasqueXmux(),
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -134,6 +190,7 @@ func TestMasqueWarpConfig(t *testing.T) {
|
||||
Host: "example.com",
|
||||
Path: "/warp",
|
||||
Warp: &masque.Warp{PrivateKey: pkcs8, PublicKey: publicKey, Address: address},
|
||||
Xmux: defaultMasqueXmux(),
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -164,6 +221,7 @@ func TestMasqueWarpConfig(t *testing.T) {
|
||||
Host: "cloudflareaccess.com",
|
||||
Path: "/",
|
||||
Warp: &masque.Warp{PrivateKey: pkcs8, PublicKey: publicKey, Address: []string{"172.16.0.2/32"}},
|
||||
Xmux: defaultMasqueXmux(),
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -199,18 +257,17 @@ func TestMasqueOutboundConfig(t *testing.T) {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := build(`{
|
||||
"protocol": "masque",
|
||||
"settings": {"address": "example.com", "port": 443},
|
||||
"streamSettings": {"network": "masque", "security": "tls"},
|
||||
"mux": {"enabled": false, "concurrency": -1}
|
||||
}`); err != nil {
|
||||
t.Error(err)
|
||||
for _, input := range []string{
|
||||
`{"protocol": "masque", "settings": {"address": "example.com", "port": 443}, "streamSettings": {"network": "masque", "security": "tls"}, "mux": {"enabled": false, "concurrency": -1}}`,
|
||||
`{"protocol": "masque", "settings": {"address": "example.com", "port": 443}, "streamSettings": {"network": "masque", "security": "tls"}, "mux": {"enabled": true}}`,
|
||||
`{"protocol": "masque", "settings": {"address": "example.com", "port": 443}, "streamSettings": {"network": "masque", "security": "tls"}, "mux": {"enabled": true, "concurrency": -1, "xudpConcurrency": 8}}`,
|
||||
} {
|
||||
if err := build(input); err != nil {
|
||||
t.Errorf("%s: %v", input, err)
|
||||
}
|
||||
}
|
||||
for _, input := range []string{
|
||||
`{"protocol": "masque", "settings": {"address": "example.com"}, "streamSettings": {"network": "masque", "security": "tls"}}`,
|
||||
`{"protocol": "masque", "settings": {"address": "example.com", "port": 443}, "streamSettings": {"network": "masque", "security": "tls"}, "mux": {"enabled": true}}`,
|
||||
`{"protocol": "masque", "settings": {"address": "example.com", "port": 443}, "streamSettings": {"network": "masque", "security": "tls"}, "mux": {"enabled": true, "concurrency": -1}}`,
|
||||
`{"protocol": "freedom", "streamSettings": {"network": "masque", "security": "tls"}}`,
|
||||
} {
|
||||
if err := build(input); err == nil {
|
||||
|
||||
@@ -72,6 +72,7 @@ type RouterConfig struct {
|
||||
RuleList []json.RawMessage `json:"rules"`
|
||||
DomainStrategy *string `json:"domainStrategy"`
|
||||
Balancers []*BalancingRule `json:"balancers"`
|
||||
Script string `json:"script"`
|
||||
}
|
||||
|
||||
func (c *RouterConfig) getDomainStrategy() router.Config_DomainStrategy {
|
||||
@@ -92,6 +93,12 @@ func (c *RouterConfig) getDomainStrategy() router.Config_DomainStrategy {
|
||||
|
||||
func (c *RouterConfig) Build() (*router.Config, error) {
|
||||
config := new(router.Config)
|
||||
|
||||
if c.Script != "" && (c.DomainStrategy != nil || len(c.RuleList) > 0) {
|
||||
return nil, errors.New("routing script cannot be used with domainStrategy or rules")
|
||||
}
|
||||
config.Script = c.Script
|
||||
|
||||
config.DomainStrategy = c.getDomainStrategy()
|
||||
|
||||
var rawRuleList []json.RawMessage
|
||||
|
||||
@@ -2,6 +2,7 @@ package conf_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
_ "unsafe"
|
||||
@@ -236,3 +237,40 @@ func TestRouterConfig(t *testing.T) {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestRouterScriptConfig(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
input string
|
||||
wantError bool
|
||||
}{
|
||||
{name: "script only", input: `{"script":"missing.lua"}`},
|
||||
{name: "empty rules", input: `{"script":"missing.lua","rules":[]}`},
|
||||
{name: "balancers", input: `{"script":"missing.lua","balancers":[{"tag":"b1","selector":["direct"]}]}`},
|
||||
{name: "default domain strategy", input: `{"script":"missing.lua","domainStrategy":"AsIs"}`, wantError: true},
|
||||
{name: "IP domain strategy", input: `{"script":"missing.lua","domainStrategy":"IPIfNonMatch"}`, wantError: true},
|
||||
{name: "empty domain strategy", input: `{"script":"missing.lua","domainStrategy":""}`, wantError: true},
|
||||
{name: "rules", input: `{"script":"missing.lua","rules":[{"outboundTag":"direct","domain":["example.com"]}]}`, wantError: true},
|
||||
{name: "empty script", input: `{"script":"","domainStrategy":"IPOnDemand","rules":[{"outboundTag":"direct","domain":["example.com"]}]}`},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var config RouterConfig
|
||||
if err := json.Unmarshal([]byte(test.input), &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
built, err := config.Build()
|
||||
if test.wantError {
|
||||
if built != nil || err == nil || !strings.Contains(err.Error(), "routing script cannot be used with domainStrategy or rules") {
|
||||
t.Fatalf("Build() = %v, %v; want nil config and script conflict error", built, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if built.Script != config.Script || len(built.Rule) != len(config.RuleList) || len(built.BalancingRule) != len(config.Balancers) {
|
||||
t.Fatalf("Build() did not preserve script, rules or balancers: %v", built)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -808,6 +808,7 @@ type MasqueConfig struct {
|
||||
Pass string `json:"pass"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
Warp *MasqueWarpConfig `json:"warp"`
|
||||
Xmux XmuxConfig `json:"xmux"`
|
||||
}
|
||||
|
||||
func (c *MasqueConfig) Build() (proto.Message, error) {
|
||||
@@ -878,11 +879,28 @@ func (c *MasqueConfig) Build() (proto.Message, error) {
|
||||
}
|
||||
headers["Authorization"] = "Basic " + base64.StdEncoding.EncodeToString([]byte(c.User+":"+c.Pass))
|
||||
}
|
||||
if c.Xmux.MaxConnections.To > 0 && c.Xmux.MaxConcurrency.To > 0 {
|
||||
return nil, errors.New("maxConnections cannot be specified together with maxConcurrency")
|
||||
}
|
||||
if c.Xmux == (XmuxConfig{}) {
|
||||
c.Xmux.MaxConnections.From = 1
|
||||
c.Xmux.MaxConnections.To = 1
|
||||
c.Xmux.HMaxReusableSecs.From = 1800
|
||||
c.Xmux.HMaxReusableSecs.To = 3000
|
||||
}
|
||||
return &masque.Config{
|
||||
Host: host,
|
||||
Path: path,
|
||||
Headers: headers,
|
||||
Warp: warp,
|
||||
Xmux: &splithttp.XmuxConfig{
|
||||
MaxConcurrency: newRangeConfig(c.Xmux.MaxConcurrency),
|
||||
MaxConnections: newRangeConfig(c.Xmux.MaxConnections),
|
||||
CMaxReuseTimes: newRangeConfig(c.Xmux.CMaxReuseTimes),
|
||||
HMaxRequestTimes: newRangeConfig(c.Xmux.HMaxRequestTimes),
|
||||
HMaxReusableSecs: newRangeConfig(c.Xmux.HMaxReusableSecs),
|
||||
HKeepAlivePeriod: c.Xmux.HKeepAlivePeriod,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -59,7 +59,7 @@ func (v *TunConfig) Build() (proto.Message, error) {
|
||||
if slices.Contains(config.AutoSystemWfpBlockLeak, "dns") && len(v.DNS) == 0 {
|
||||
return nil, errors.New(`autoSystemWfpBlockLeak "dns" needs dns to be set`)
|
||||
}
|
||||
case "linux":
|
||||
case "linux", "freebsd":
|
||||
if v.AutoSystemDnsToGateway && len(v.Gateway) == 0 {
|
||||
return nil, errors.New("autoSystemDnsToGateway needs gateway to be set")
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package conf_test
|
||||
import (
|
||||
"encoding/json"
|
||||
"runtime"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
. "github.com/xtls/xray-core/infra/conf"
|
||||
@@ -43,18 +44,18 @@ func TestTunConfigAutoSystem(t *testing.T) {
|
||||
func TestTunConfigAutoSystemNeeds(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
input string
|
||||
goos string // where it is rejected
|
||||
goos []string // where it is rejected
|
||||
}{
|
||||
{`{"name": "xray0", "autoSystemWfpBlockLeak": ["misconfigtun"]}`, "windows"},
|
||||
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["misconfigtun"]}`, ""},
|
||||
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["dns"]}`, "windows"},
|
||||
{`{"name": "xray0", "autoSystemDnsToGateway": true}`, "linux"},
|
||||
{`{"name": "xray0", "autoSystemWfpBlockLeak": ["misconfigtun"]}`, []string{"windows"}},
|
||||
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["misconfigtun"]}`, nil},
|
||||
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["dns"]}`, []string{"windows"}},
|
||||
{`{"name": "xray0", "autoSystemDnsToGateway": true}`, []string{"linux", "freebsd"}},
|
||||
} {
|
||||
config := new(TunConfig)
|
||||
if err := json.Unmarshal([]byte(c.input), config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := config.Build(); (err != nil) != (runtime.GOOS == c.goos) {
|
||||
if _, err := config.Build(); (err != nil) != slices.Contains(c.goos, runtime.GOOS) {
|
||||
t.Errorf("%s on %s: error = %v", c.input, runtime.GOOS, err)
|
||||
}
|
||||
}
|
||||
|
||||
+1
-5
@@ -344,11 +344,7 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, ok := ts.(*masque.ClientConfig); ok {
|
||||
if ms := senderSettings.MultiplexSettings; ms != nil && ms.Enabled {
|
||||
return nil, errors.New(`masque outbound does not support "mux"`)
|
||||
}
|
||||
} else if senderSettings.StreamSettings != nil && senderSettings.StreamSettings.ProtocolName == "masque" {
|
||||
if _, ok := ts.(*masque.ClientConfig); !ok && senderSettings.StreamSettings != nil && senderSettings.StreamSettings.ProtocolName == "masque" {
|
||||
return nil, errors.New("the masque transport can only be used by the masque outbound")
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package base64
|
||||
|
||||
import "github.com/xtls/xray-core/main/commands/base"
|
||||
|
||||
// CmdBase64 holds all Base64 subcommands.
|
||||
var CmdBase64 = &base.Command{
|
||||
UsageLine: "{{.Exec}} base64",
|
||||
Short: "Encode and decode Base64",
|
||||
Long: "{{.Exec}} {{.LongName}} provides tools to encode and decode arbitrary bytes.",
|
||||
Commands: []*base.Command{
|
||||
cmdEncode,
|
||||
cmdDecode,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package base64
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
xbase64 "github.com/xtls/xray-core/common/base64"
|
||||
"github.com/xtls/xray-core/main/commands/base"
|
||||
)
|
||||
|
||||
var cmdDecode = &base.Command{
|
||||
UsageLine: "{{.Exec}} base64 decode [-gzip] <value | - | stdin:> [output-file]",
|
||||
Short: "Decode Base64",
|
||||
Long: fmt.Sprintf(`
|
||||
Decode a Base64 value, or pass "-" or "stdin:" to read stdin.
|
||||
Write to output-file, or stdout if omitted.
|
||||
Accepts %s, %s, or no prefix; gzip is enabled by %s or -gzip.
|
||||
|
||||
Examples:
|
||||
|
||||
{{.Exec}} base64 decode eA== out.bin
|
||||
{{.Exec}} base64 decode -gzip H4sIAAAAAAAC/6sAAIMW3IwBAAAA out.bin
|
||||
`, xbase64.Prefix, xbase64.GzipPrefix, xbase64.GzipPrefix),
|
||||
}
|
||||
|
||||
var decodeGzipEnabled = cmdDecode.Flag.Bool("gzip", false, "Decompress the decoded bytes with gzip.")
|
||||
|
||||
func init() {
|
||||
cmdDecode.Run = executeDecode
|
||||
}
|
||||
|
||||
func executeDecode(cmd *base.Command, args []string) {
|
||||
if len(args) == 0 || len(args) > 2 {
|
||||
cmd.Usage()
|
||||
}
|
||||
|
||||
value := args[0]
|
||||
if value == "-" || value == "stdin:" {
|
||||
input, err := io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
base.Fatalf("failed to read input: %s", err)
|
||||
}
|
||||
value = string(input)
|
||||
}
|
||||
|
||||
value = strings.TrimSpace(value)
|
||||
if *decodeGzipEnabled && !strings.HasPrefix(value, xbase64.GzipPrefix) {
|
||||
value = xbase64.GzipPrefix + strings.TrimPrefix(value, xbase64.Prefix)
|
||||
}
|
||||
|
||||
data, err := xbase64.Decode(value)
|
||||
if err != nil {
|
||||
base.Fatalf("failed to decode input: %s", err)
|
||||
}
|
||||
|
||||
if len(args) == 2 && args[1] != "-" {
|
||||
err = os.WriteFile(args[1], data, 0o666)
|
||||
} else {
|
||||
_, err = os.Stdout.Write(data)
|
||||
}
|
||||
if err != nil {
|
||||
base.Fatalf("failed to write decoded output: %s", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package base64
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
xbase64 "github.com/xtls/xray-core/common/base64"
|
||||
"github.com/xtls/xray-core/main/commands/base"
|
||||
)
|
||||
|
||||
var cmdEncode = &base.Command{
|
||||
UsageLine: "{{.Exec}} base64 encode [-gzip] <input-file | - | stdin:>",
|
||||
Short: "Encode as Base64",
|
||||
Long: fmt.Sprintf(`
|
||||
Encode input-file as Base64 with the %s prefix.
|
||||
Pass "-" or "stdin:" to read stdin.
|
||||
Use -gzip to compress and output %s.
|
||||
|
||||
Examples:
|
||||
|
||||
{{.Exec}} base64 encode input.bin
|
||||
{{.Exec}} base64 encode -gzip input.bin
|
||||
`, xbase64.Prefix, xbase64.GzipPrefix),
|
||||
}
|
||||
|
||||
var gzipEnabled = cmdEncode.Flag.Bool("gzip", false, "Compress the input with gzip.")
|
||||
|
||||
func init() {
|
||||
cmdEncode.Run = executeEncode
|
||||
}
|
||||
|
||||
func executeEncode(cmd *base.Command, args []string) {
|
||||
if len(args) != 1 {
|
||||
cmd.Usage()
|
||||
}
|
||||
|
||||
var data []byte
|
||||
var err error
|
||||
if args[0] == "-" || args[0] == "stdin:" {
|
||||
data, err = io.ReadAll(os.Stdin)
|
||||
} else {
|
||||
data, err = os.ReadFile(args[0])
|
||||
}
|
||||
if err != nil {
|
||||
base.Fatalf("failed to read input: %s", err)
|
||||
}
|
||||
|
||||
value, err := xbase64.Encode(data, *gzipEnabled)
|
||||
if err != nil {
|
||||
base.Fatalf("failed to encode input: %s", err)
|
||||
}
|
||||
|
||||
if _, err := fmt.Fprintln(os.Stdout, value); err != nil {
|
||||
base.Fatalf("failed to write encoded output: %s", err)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package all
|
||||
|
||||
import (
|
||||
"github.com/xtls/xray-core/main/commands/all/api"
|
||||
"github.com/xtls/xray-core/main/commands/all/base64"
|
||||
"github.com/xtls/xray-core/main/commands/all/convert"
|
||||
"github.com/xtls/xray-core/main/commands/all/tls"
|
||||
"github.com/xtls/xray-core/main/commands/base"
|
||||
@@ -11,6 +12,7 @@ func init() {
|
||||
base.RootCommand.Commands = append(
|
||||
base.RootCommand.Commands,
|
||||
api.CmdAPI,
|
||||
base64.CmdBase64,
|
||||
convert.CmdConvert,
|
||||
tls.CmdTLS,
|
||||
cmdUUID,
|
||||
|
||||
+103
-34
@@ -7,7 +7,6 @@ import (
|
||||
"net/netip"
|
||||
"slices"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"golang.zx2c4.com/wireguard/tun"
|
||||
@@ -26,6 +25,7 @@ import (
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/internet/masque"
|
||||
"github.com/xtls/xray-core/transport/internet/splithttp"
|
||||
"github.com/xtls/xray-core/transport/internet/stat"
|
||||
"github.com/xtls/xray-core/transport/internet/tls"
|
||||
)
|
||||
@@ -43,11 +43,15 @@ type Client struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
|
||||
tunnel atomic.Pointer[tunnel]
|
||||
|
||||
mu sync.Mutex
|
||||
xmux *splithttp.XmuxManager
|
||||
dialCtx context.Context
|
||||
dialer internet.Dialer
|
||||
lastErr error
|
||||
lastErrAt time.Time
|
||||
|
||||
tunnelsMu sync.Mutex
|
||||
tunnels map[*tunnel]struct{}
|
||||
}
|
||||
|
||||
func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
|
||||
@@ -55,7 +59,8 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
|
||||
p := v.GetFeature(policy.ManagerType()).(policy.Manager)
|
||||
|
||||
streamSettings := session.StreamSettingsFromContext(ctx).(*internet.MemoryStreamConfig)
|
||||
if _, ok := streamSettings.ProtocolSettings.(*masque.Config); !ok {
|
||||
transportConfig, ok := streamSettings.ProtocolSettings.(*masque.Config)
|
||||
if !ok {
|
||||
return nil, errors.New("not masque transport")
|
||||
}
|
||||
if tls.ConfigFromStreamSettings(streamSettings) == nil {
|
||||
@@ -86,7 +91,13 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
|
||||
server: server,
|
||||
policyManager: p,
|
||||
remoteDNS: remoteDNS,
|
||||
tunnels: make(map[*tunnel]struct{}),
|
||||
}
|
||||
xmuxConfig := transportConfig.Xmux
|
||||
if xmuxConfig == nil {
|
||||
xmuxConfig = &splithttp.XmuxConfig{}
|
||||
}
|
||||
c.xmux = splithttp.NewXmuxManager(*xmuxConfig, c.newXmuxConn)
|
||||
c.ctx, c.cancel = context.WithCancel(context.Background())
|
||||
return c, nil
|
||||
}
|
||||
@@ -100,10 +111,11 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
|
||||
ob.Name = "masque"
|
||||
ob.CanSpliceCopy = 3
|
||||
|
||||
t, err := c.getTunnel(ctx, dialer)
|
||||
xmuxClient, t, err := c.getTunnel(ctx, dialer)
|
||||
if err != nil {
|
||||
return errors.New("failed to establish CONNECT-IP tunnel").Base(err)
|
||||
}
|
||||
defer xmuxClient.DoneRunning()
|
||||
|
||||
var newCtx context.Context
|
||||
var newCancel context.CancelFunc
|
||||
@@ -180,40 +192,63 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) getTunnel(ctx context.Context, dialer internet.Dialer) (*tunnel, error) {
|
||||
func (c *Client) getTunnel(ctx context.Context, dialer internet.Dialer) (*splithttp.XmuxClient, *tunnel, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.ctx.Err() != nil {
|
||||
return nil, errors.New("closed")
|
||||
}
|
||||
if t := c.tunnel.Load(); t != nil {
|
||||
select {
|
||||
case <-t.done:
|
||||
default:
|
||||
return t, nil
|
||||
}
|
||||
return nil, nil, errors.New("closed")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
var xmuxClient *splithttp.XmuxClient
|
||||
if c.lastErr != nil && time.Since(c.lastErrAt) < retryInterval {
|
||||
return nil, c.lastErr
|
||||
if xmuxClient = c.xmux.GetExistingXmuxClient(ctx); xmuxClient == nil {
|
||||
return nil, nil, c.lastErr
|
||||
}
|
||||
} else {
|
||||
c.dialCtx, c.dialer = ctx, dialer
|
||||
xmuxClient = c.xmux.GetXmuxClient(ctx)
|
||||
c.dialCtx, c.dialer = nil, nil
|
||||
if err := xmuxClient.XmuxConn.(*tunnel).err; err != nil {
|
||||
if xmuxClient = c.xmux.GetExistingXmuxClient(ctx); xmuxClient == nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
t := xmuxClient.XmuxConn.(*tunnel)
|
||||
if c.ctx.Err() != nil {
|
||||
return nil, nil, errors.New("closed")
|
||||
}
|
||||
xmuxClient.AddRunning()
|
||||
return xmuxClient, t, nil
|
||||
}
|
||||
|
||||
t, err := c.establish(ctx, dialer)
|
||||
func (c *Client) newXmuxConn() splithttp.XmuxConn {
|
||||
t, err := c.establish(c.dialCtx, c.dialer)
|
||||
if err != nil {
|
||||
c.lastErr, c.lastErrAt = err, time.Now()
|
||||
return nil, err
|
||||
return failedTunnel(err)
|
||||
}
|
||||
c.lastErr = nil
|
||||
c.tunnel.Store(t)
|
||||
if c.ctx.Err() != nil {
|
||||
if c.tunnel.CompareAndSwap(t, nil) {
|
||||
t.close()
|
||||
}
|
||||
return nil, errors.New("closed")
|
||||
c.tunnelsMu.Lock()
|
||||
if c.tunnels == nil {
|
||||
c.tunnelsMu.Unlock()
|
||||
t.close()
|
||||
return failedTunnel(errors.New("closed"))
|
||||
}
|
||||
return t, nil
|
||||
c.tunnels[t] = struct{}{}
|
||||
c.tunnelsMu.Unlock()
|
||||
if t.IsClosed() {
|
||||
c.removeTunnel(t)
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func (c *Client) removeTunnel(t *tunnel) {
|
||||
c.tunnelsMu.Lock()
|
||||
delete(c.tunnels, t)
|
||||
c.tunnelsMu.Unlock()
|
||||
}
|
||||
|
||||
func (c *Client) establish(ctx context.Context, dialer internet.Dialer) (*tunnel, error) {
|
||||
@@ -229,7 +264,7 @@ func (c *Client) establish(ctx context.Context, dialer internet.Dialer) (*tunnel
|
||||
conn.Close()
|
||||
return nil, errors.New("not a CONNECT-IP connection")
|
||||
}
|
||||
t, err := newTunnel(conn, mconn.LocalAddrs(), c.remoteDNS)
|
||||
t, err := newTunnel(conn, mconn.LocalAddrs(), c.remoteDNS, c.removeTunnel)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
@@ -240,7 +275,11 @@ func (c *Client) establish(ctx context.Context, dialer internet.Dialer) (*tunnel
|
||||
|
||||
func (c *Client) Close() error {
|
||||
c.cancel()
|
||||
if t := c.tunnel.Swap(nil); t != nil {
|
||||
c.tunnelsMu.Lock()
|
||||
tunnels := c.tunnels
|
||||
c.tunnels = nil
|
||||
c.tunnelsMu.Unlock()
|
||||
for t := range tunnels {
|
||||
t.close()
|
||||
}
|
||||
return nil
|
||||
@@ -252,9 +291,31 @@ type tunnel struct {
|
||||
tnet *wireguard.Net
|
||||
done chan struct{}
|
||||
closeOnce sync.Once
|
||||
onClose func(*tunnel)
|
||||
err error
|
||||
}
|
||||
|
||||
func newTunnel(conn stat.Connection, local []netip.Addr, remoteDNS []netip.Addr) (*tunnel, error) {
|
||||
func failedTunnel(err error) *tunnel {
|
||||
t := &tunnel{err: err, done: make(chan struct{})}
|
||||
t.close()
|
||||
return t
|
||||
}
|
||||
|
||||
func (t *tunnel) IsClosed() bool {
|
||||
select {
|
||||
case <-t.done:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (t *tunnel) Close() error {
|
||||
t.close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func newTunnel(conn stat.Connection, local []netip.Addr, remoteDNS []netip.Addr, onClose func(*tunnel)) (*tunnel, error) {
|
||||
var dns []netip.Addr
|
||||
for _, addr := range remoteDNS {
|
||||
if slices.ContainsFunc(local, func(l netip.Addr) bool { return l.Is4() == addr.Is4() }) {
|
||||
@@ -271,10 +332,11 @@ func newTunnel(conn stat.Connection, local []netip.Addr, remoteDNS []netip.Addr)
|
||||
return nil, err
|
||||
}
|
||||
t := &tunnel{
|
||||
conn: conn,
|
||||
dev: dev,
|
||||
tnet: tnet,
|
||||
done: make(chan struct{}),
|
||||
conn: conn,
|
||||
dev: dev,
|
||||
tnet: tnet,
|
||||
done: make(chan struct{}),
|
||||
onClose: onClose,
|
||||
}
|
||||
go t.readFromTunnel()
|
||||
go t.writeToTunnel()
|
||||
@@ -316,8 +378,15 @@ func (t *tunnel) writeToTunnel() {
|
||||
func (t *tunnel) close() {
|
||||
t.closeOnce.Do(func() {
|
||||
close(t.done)
|
||||
t.conn.Close()
|
||||
t.dev.Close()
|
||||
if t.conn != nil {
|
||||
t.conn.Close()
|
||||
}
|
||||
if t.dev != nil {
|
||||
t.dev.Close()
|
||||
}
|
||||
if t.onClose != nil {
|
||||
t.onClose(t)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package masque
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/transport/internet/splithttp"
|
||||
)
|
||||
|
||||
func newTestClient(newConn func(c *Client) splithttp.XmuxConn) *Client {
|
||||
c := &Client{ctx: context.Background()}
|
||||
c.xmux = splithttp.NewXmuxManager(splithttp.XmuxConfig{
|
||||
MaxConnections: &splithttp.RangeConfig{From: 3, To: 3},
|
||||
}, func() splithttp.XmuxConn {
|
||||
return newConn(c)
|
||||
})
|
||||
return c
|
||||
}
|
||||
|
||||
func TestGetTunnelFallsBack(t *testing.T) {
|
||||
refused := errors.New("refused")
|
||||
healthy := &tunnel{done: make(chan struct{})}
|
||||
dials := 0
|
||||
c := newTestClient(func(c *Client) splithttp.XmuxConn {
|
||||
if dials++; dials == 1 {
|
||||
return healthy
|
||||
}
|
||||
c.lastErr, c.lastErrAt = refused, time.Now()
|
||||
return failedTunnel(refused)
|
||||
})
|
||||
for i := 0; i < 5; i++ {
|
||||
if _, got, err := c.getTunnel(context.Background(), nil); err != nil || got != healthy {
|
||||
t.Fatalf("flow %d: got %p, %v instead of the healthy tunnel", i, got, err)
|
||||
}
|
||||
}
|
||||
if dials != 2 {
|
||||
t.Errorf("dialed %d times, a failed tunnel should not be retried within %v", dials, retryInterval)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetTunnelFailsWithoutTunnels(t *testing.T) {
|
||||
refused := errors.New("refused")
|
||||
c := newTestClient(func(c *Client) splithttp.XmuxConn {
|
||||
c.lastErr, c.lastErrAt = refused, time.Now()
|
||||
return failedTunnel(refused)
|
||||
})
|
||||
for i := 0; i < 2; i++ {
|
||||
if _, _, err := c.getTunnel(context.Background(), nil); err != refused {
|
||||
t.Fatalf("flow %d: got %v instead of %v", i, err, refused)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -170,9 +170,17 @@ func (s *Server) processTCP(ctx context.Context, conn stat.Connection, dispatche
|
||||
return errors.New("UDP associate with listen port failed")
|
||||
}
|
||||
tempUDPConn.SetTimeout(plcy.Timeouts.ConnectionIdle)
|
||||
var udpConn stat.Connection = tempUDPConn
|
||||
if counters, ok := conn.(*stat.CounterConnection); ok {
|
||||
udpConn = &stat.CounterConnection{
|
||||
Connection: tempUDPConn,
|
||||
ReadCounter: counters.ReadCounter,
|
||||
WriteCounter: counters.WriteCounter,
|
||||
}
|
||||
}
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- s.handleUDPPayload(ctx, tempUDPConn, dispatcher)
|
||||
errCh <- s.handleUDPPayload(ctx, udpConn, dispatcher)
|
||||
}()
|
||||
// Associated TCP keeps the UDP alive
|
||||
// Close UDP if TCP connection is closed
|
||||
|
||||
+31
-9
@@ -15,17 +15,17 @@ Plainly enabling it in the config probably will result nothing, or lock your rou
|
||||
## DETAILS
|
||||
|
||||
By default, enabling the feature will only bring the tun interface up. \
|
||||
When configured explicitly, Windows and Linux can apply interface addresses from `gateway`, while macOS and FreeBSD use the first IPv4 prefix from `gateway` for the point-to-point address. \
|
||||
When configured explicitly, Windows and Linux can apply interface addresses from `gateway`, while macOS uses the first IPv4 prefix from `gateway` for the point-to-point address and FreeBSD for the interface address, the one after the gateway. \
|
||||
Without `gateway`, the systems differ: Xray assigns no address on Linux, Windows gives the interface link-local addresses itself (an IPv6 one at once, an IPv4 one from `169.254.0.0/16` after a few seconds), and macOS and FreeBSD use `169.254.10.1/30`. \
|
||||
Windows, Linux and macOS can also apply system routes from `autoSystemRoutingTable`.
|
||||
macOS does not configure system DNS from the `dns` field, and neither does Linux by default; system DNS remains managed by the OS or distribution-specific network services. \
|
||||
Windows, Linux, macOS and FreeBSD can also apply system routes from `autoSystemRoutingTable`.
|
||||
macOS does not configure system DNS from the `dns` field, and neither do Linux and FreeBSD by default; system DNS remains managed by the OS or distribution-specific network services. \
|
||||
For more advanced routing policies or rules, OS level configuration can still manage the named interface (e.g. xray0) when it appears.
|
||||
This keeps complex system level routing and rules in a single place of responsibility - the OS itself. \
|
||||
Examples of how to achieve this on a simple Linux system (Ubuntu with systemd-networkd) can be found at the end of this README.
|
||||
|
||||
### SYSTEM DNS ON LINUX (`autoSystemDnsToGateway`)
|
||||
### SYSTEM DNS ON LINUX AND FREEBSD (`autoSystemDnsToGateway`)
|
||||
|
||||
On Linux, setting `autoSystemDnsToGateway` to `true` lets the inbound point the system resolver at the tun interface, so name lookups resolve through Xray instead of going out over the physical link. It is off by default, and it is Linux-only.
|
||||
On Linux and FreeBSD, setting `autoSystemDnsToGateway` to `true` lets the inbound point the system resolver at the tun interface, so name lookups resolve through Xray instead of going out over the physical link. It is off by default, and it exists only on those two systems. This section describes Linux; the FreeBSD differences follow in [SYSTEM DNS ON FREEBSD](#system-dns-on-freebsd).
|
||||
|
||||
It uses `resolvectl`, which means it only works when all of these hold. Where Xray can tell that one does not, it does not start:
|
||||
|
||||
@@ -66,6 +66,24 @@ Where it cannot apply, Xray does not start, rather than run with the leak descri
|
||||
|
||||
On `Close()` the setting is reverted. It is **not** reverted if the process is killed with `SIGKILL`, since a process cannot handle that signal; run `resolvectl revert <iface>` to clean up by hand. An application that brings its own DNS endpoint is unaffected either way — this only covers the system resolver.
|
||||
|
||||
### SYSTEM DNS ON FREEBSD
|
||||
|
||||
On FreeBSD the same option goes through `resolvconf(8)`, the openresolv that ships in the base system, instead of `resolvectl`. The checks on Xray's own `dns` and routing configuration above apply unchanged, as does the loop through a `dns` upstream that bootstraps over the system resolver.
|
||||
|
||||
The address handed over is the gateway itself, not the next address: on FreeBSD the interface gets the address after the first IPv4 `gateway` (as on macOS), and the gateway, which nothing owns, is routed into the TUN, so a query to it is what Xray answers (e.g. `169.254.10.1/30` -> resolver `169.254.10.1`, local address `169.254.10.2`). Without `gateway` the config is rejected, as on Linux.
|
||||
|
||||
The entry is added with `resolvconf -a <iface> -x`, which makes the TUN's nameserver the only one in use, the equivalent of `domain ~.` plus `default-route true` above; without `-x` the nameservers DHCP supplied stay listed alongside it, and the system falls back to them. `resolvconf` exits successfully, and still records the entry, when `resolvconf=NO` is set in `resolvconf.conf`, but then runs none of the subscribers that write the resolver files, so Xray confirms the takeover in those files and does not start when the nameserver reached none of them: `/etc/resolv.conf` first, where it also has to be the only nameserver besides loopback ones (`inclusive_interfaces` in `resolvconf.conf` makes `resolvconf` ignore `-x` and keep the DHCP nameservers listed, which would be the leak again), and then, when `resolvconf.conf` names an `unbound_conf` file, that file. The latter is the `local_unbound` layout, where `local-unbound-setup` turns the `libc` subscriber off and has `resolvconf` write unbound's forwarders instead, with `resolv.conf` left pointed at loopback; the system then resolves through unbound, which forwards into the TUN. That only works with unbound's DNSSEC validation turned off, which `local_unbound` has on by default: the extra queries validation makes get no answer through the `dns` outbound, and resolution times out. A drop-in such as `/var/unbound/conf.d/xray.conf` with `server:` and `module-config: "iterator"`, followed by `service local_unbound restart`, turns it off (verified on FreeBSD 15.1).
|
||||
|
||||
| Environment | Behaviour |
|
||||
|---|---|
|
||||
| default FreeBSD, `resolv.conf` managed by `resolvconf` (DHCP or static) | applies |
|
||||
| `local_unbound` enabled | applies, through unbound's forwarders; needs validation off (see above) |
|
||||
| `resolvconf=NO` in `resolvconf.conf` | no resolver file changes, does not start |
|
||||
| `inclusive_interfaces` covering the TUN in `resolvconf.conf` | DHCP nameservers stay listed, does not start |
|
||||
| another resolver in front of `resolv.conf` that `resolvconf` is not configured to feed | nameserver reaches no resolver file, does not start |
|
||||
|
||||
On `Close()` the entry is removed with `resolvconf -d <iface>`. It is **not** removed if the process is killed with `SIGKILL`; run `resolvconf -d <iface>` to clean up by hand. The next start with the same interface name replaces the stale entry on its own.
|
||||
|
||||
Due to this inbound not actually being a proxy, the configuration ignore required listen and port options, and never listen on any port. \
|
||||
Here is simple Xray config snippet to enable the inbound:
|
||||
```
|
||||
@@ -245,10 +263,10 @@ So everything applicable for ipv4 above also works for ipv6, you only need to gi
|
||||
FreeBSD support of the same functionality is implemented through tun(4).
|
||||
|
||||
Interface name in the configuration must comply to the scheme "tunN", where N is some number. \
|
||||
It's necessary to set an IP address to the interface, ex.:
|
||||
```
|
||||
ifconfig tun0 inet 169.254.10.1/30
|
||||
```
|
||||
FreeBSD requires the tun interface to have an IPv4 address before IPv4 routes can use it. \
|
||||
By default Xray uses `169.254.10.1/30` as the gateway and assigns the next address in the prefix to the tun interface; the gateway itself belongs to nothing and is routed into the TUN. \
|
||||
You can override this by setting `gateway`; FreeBSD uses the first IPv4 prefix in the list, and IPv6 `gateway` entries are not used for addressing.
|
||||
|
||||
To attach routing to the interface, route command like following can be executed:
|
||||
```
|
||||
route add -net 1.1.1.0/24 -iface tun10
|
||||
@@ -257,6 +275,10 @@ route add -net 1.1.1.0/24 -iface tun10
|
||||
route add -inet6 -host 2606:4700:4700::1111 -iface tun10
|
||||
route add -inet6 -host 2606:4700:4700::1001 -iface tun10
|
||||
```
|
||||
Alternatively, configure `autoSystemRoutingTable` and Xray will add and remove those system routes while it is running. \
|
||||
With `autoSystemRoutingTable`, Xray's own connections are kept out of the TUN through `autoOutboundsInterface` (the default), which on FreeBSD switches them to a second routing table (FIB 1) that mirrors the physical default route; this needs the boot tunable `net.fibs` set to at least 2, and Xray does not start otherwise. \
|
||||
`autoSystemDnsToGateway` points the system resolver at the TUN through `resolvconf(8)`, see [SYSTEM DNS ON FREEBSD](#system-dns-on-freebsd).
|
||||
|
||||
Important to remember that everything written above about Linux routing concept, also apply to FreeBSD. If you simply route default route through tun interface, that will result network loop and immediate network failure.
|
||||
|
||||
## MAC OS X SUPPORT
|
||||
|
||||
+26
-22
@@ -56,6 +56,24 @@ func (w *tunUDPStatsWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// tunTCPWriter is the writing side of a TCP connection for the dispatcher. It has no Close: the outbound closes
|
||||
// its writer when the other side has no more to send, and the system may still be sending
|
||||
type tunTCPWriter struct {
|
||||
writer buf.Writer
|
||||
counter stats.Counter
|
||||
}
|
||||
|
||||
func (w *tunTCPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
size := mb.Len()
|
||||
if err := w.writer.WriteMultiBuffer(mb); err != nil {
|
||||
return err
|
||||
}
|
||||
if w.counter != nil {
|
||||
w.counter.Add(int64(size))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ConnectionHandler interface with the only method that stack is going to push new connections to
|
||||
type ConnectionHandler interface {
|
||||
HandleConnection(conn net.Conn, destination net.Destination)
|
||||
@@ -143,6 +161,7 @@ func (t *Handler) Start() error {
|
||||
|
||||
tunStackOptions := StackOptions{
|
||||
Tun: tunInterface,
|
||||
MTU: t.config.MTU,
|
||||
IdleTimeout: t.policyManager.ForLevel(t.config.UserLevel).Timeouts.ConnectionIdle,
|
||||
}
|
||||
tunStack, err := NewStack(t.ctx, tunStackOptions, t)
|
||||
@@ -194,22 +213,7 @@ func (t *Handler) HandleConnection(conn net.Conn, destination net.Destination) {
|
||||
defer cancel()
|
||||
ctx = c.ContextWithID(ctx, session.NewID())
|
||||
|
||||
// if the connection is already closed, conn.RemoteAddr() will be nil
|
||||
// due to gvisor weird behavior
|
||||
remote := conn.RemoteAddr()
|
||||
if remote == nil {
|
||||
errors.LogInfo(t.ctx, "dropped quickly closed connection")
|
||||
return
|
||||
}
|
||||
source := net.DestinationFromAddr(remote)
|
||||
isUDP := destination.Network == net.Network_UDP
|
||||
if !isUDP && (t.uplinkCounter != nil || t.downlinkCounter != nil) {
|
||||
conn = &stat.CounterConnection{
|
||||
Connection: conn,
|
||||
ReadCounter: t.uplinkCounter,
|
||||
WriteCounter: t.downlinkCounter,
|
||||
}
|
||||
}
|
||||
source := net.DestinationFromAddr(conn.RemoteAddr())
|
||||
|
||||
inbound := session.Inbound{
|
||||
Name: "tun",
|
||||
@@ -235,13 +239,13 @@ func (t *Handler) HandleConnection(conn net.Conn, destination net.Destination) {
|
||||
})
|
||||
errors.LogInfo(ctx, "processing from ", source, " to ", destination)
|
||||
|
||||
reader := &buf.TimeoutWrapperReader{Reader: buf.NewReader(conn)}
|
||||
// both kinds of connection are buf.Reader and buf.Writer, what they carry is counted on the way
|
||||
reader := &buf.TimeoutWrapperReader{Reader: buf.NewReader(conn), Counter: t.uplinkCounter}
|
||||
writer := buf.NewWriter(conn)
|
||||
if isUDP {
|
||||
reader.Counter = t.uplinkCounter
|
||||
if t.downlinkCounter != nil {
|
||||
writer = &tunUDPStatsWriter{writer: writer, counter: t.downlinkCounter}
|
||||
}
|
||||
if destination.Network != net.Network_UDP {
|
||||
writer = &tunTCPWriter{writer: writer, counter: t.downlinkCounter}
|
||||
} else if t.downlinkCounter != nil {
|
||||
writer = &tunUDPStatsWriter{writer: writer, counter: t.downlinkCounter}
|
||||
}
|
||||
|
||||
link := &transport.Link{
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
xnet "github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
@@ -103,6 +104,53 @@ func (d *testDispatcher) DispatchLink(ctx context.Context, dest xnet.Destination
|
||||
return link.Writer.WriteMultiBuffer(buf.MultiBuffer{buf.FromBytes(d.writePayload)})
|
||||
}
|
||||
|
||||
// closableConn is a connection that is its own writer, as the ones of the stack are
|
||||
type closableConn struct {
|
||||
*testConn
|
||||
closed int32
|
||||
}
|
||||
|
||||
func (c *closableConn) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
buf.ReleaseMulti(mb)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *closableConn) Close() error {
|
||||
atomic.AddInt32(&c.closed, 1)
|
||||
return nil
|
||||
}
|
||||
|
||||
// closingDispatcher does what an outbound does when the other side has no more to send
|
||||
type closingDispatcher struct {
|
||||
testDispatcher
|
||||
conn *closableConn
|
||||
closed int32
|
||||
}
|
||||
|
||||
func (d *closingDispatcher) DispatchLink(_ context.Context, _ xnet.Destination, link *transport.Link) error {
|
||||
common.Close(link.Writer)
|
||||
d.closed = atomic.LoadInt32(&d.conn.closed)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestHandlerClosesTunConnectionWhenBothSidesAreDone(t *testing.T) {
|
||||
conn := &closableConn{testConn: newTestConn(nil)}
|
||||
dispatcher := &closingDispatcher{conn: conn}
|
||||
handler := &Handler{
|
||||
ctx: context.Background(),
|
||||
config: &Config{},
|
||||
dispatcher: dispatcher,
|
||||
}
|
||||
handler.HandleConnection(conn, xnet.TCPDestination(xnet.LocalHostIP, 443))
|
||||
|
||||
if dispatcher.closed != 0 {
|
||||
t.Fatal("the connection was closed with its writer, while the system may still be sending")
|
||||
}
|
||||
if got := atomic.LoadInt32(&conn.closed); got != 1 {
|
||||
t.Fatalf("connection closed %d times, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandlerCountsTunConnectionTraffic(t *testing.T) {
|
||||
uplinkCounter := new(testCounter)
|
||||
downlinkCounter := new(testCounter)
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"math/bits"
|
||||
"net/netip"
|
||||
)
|
||||
|
||||
const (
|
||||
ipv4HeaderSize = 20
|
||||
ipv6HeaderSize = 40
|
||||
tcpHeaderSize = 20
|
||||
udpHeaderSize = 8
|
||||
|
||||
protoICMPv4 = 1
|
||||
protoTCP = 6
|
||||
protoUDP = 17
|
||||
protoICMPv6 = 58
|
||||
)
|
||||
|
||||
// packet is an IP packet with its header read
|
||||
type packet struct {
|
||||
proto byte
|
||||
src, dst netip.Addr
|
||||
// payload is what follows the IP header
|
||||
payload []byte
|
||||
}
|
||||
|
||||
// parsePacket reads the IP header of b. Fragments are not accepted: what the system sends to the tun fits its MTU
|
||||
func parsePacket(b []byte) (p packet, ok bool) {
|
||||
if len(b) < ipv4HeaderSize {
|
||||
return p, false
|
||||
}
|
||||
switch b[0] >> 4 {
|
||||
case 4:
|
||||
size := int(b[0]&0xf) * 4
|
||||
total := int(binary.BigEndian.Uint16(b[2:]))
|
||||
if size < ipv4HeaderSize || total < size || total > len(b) || binary.BigEndian.Uint16(b[6:])&0x3fff != 0 {
|
||||
return p, false
|
||||
}
|
||||
p.proto = b[9]
|
||||
p.src = netip.AddrFrom4([4]byte(b[12:16]))
|
||||
p.dst = netip.AddrFrom4([4]byte(b[16:20]))
|
||||
p.payload = b[size:total]
|
||||
case 6:
|
||||
if len(b) < ipv6HeaderSize {
|
||||
return p, false
|
||||
}
|
||||
total := ipv6HeaderSize + int(binary.BigEndian.Uint16(b[4:]))
|
||||
if total > len(b) {
|
||||
return p, false
|
||||
}
|
||||
p.proto = b[6]
|
||||
p.src = netip.AddrFrom16([16]byte(b[8:24]))
|
||||
p.dst = netip.AddrFrom16([16]byte(b[24:40]))
|
||||
p.payload = b[ipv6HeaderSize:total]
|
||||
// hop-by-hop options, routing, destination options
|
||||
for p.proto == 0 || p.proto == 43 || p.proto == 60 {
|
||||
if len(p.payload) < 8 {
|
||||
return p, false
|
||||
}
|
||||
size := int(p.payload[1])*8 + 8
|
||||
if size > len(p.payload) {
|
||||
return p, false
|
||||
}
|
||||
p.proto, p.payload = p.payload[0], p.payload[size:]
|
||||
}
|
||||
default:
|
||||
return p, false
|
||||
}
|
||||
return p, true
|
||||
}
|
||||
|
||||
// putIPHeader writes the header of a packet from src to dst into b, without its length, and returns the size of the header
|
||||
func putIPHeader(b []byte, proto byte, src, dst netip.Addr) int {
|
||||
if src.Is4() {
|
||||
s, d := src.As4(), dst.As4()
|
||||
clear(b[:ipv4HeaderSize])
|
||||
b[0] = 0x45
|
||||
if proto == protoTCP {
|
||||
b[6] = 0x40 // don't fragment
|
||||
}
|
||||
b[8] = 64
|
||||
b[9] = proto
|
||||
copy(b[12:], s[:])
|
||||
copy(b[16:], d[:])
|
||||
return ipv4HeaderSize
|
||||
}
|
||||
s, d := src.As16(), dst.As16()
|
||||
clear(b[:ipv6HeaderSize])
|
||||
b[0] = 0x60
|
||||
b[6] = proto
|
||||
b[7] = 64
|
||||
copy(b[8:], s[:])
|
||||
copy(b[24:], d[:])
|
||||
return ipv6HeaderSize
|
||||
}
|
||||
|
||||
// setIPLength completes the header ip of a packet that is size bytes long with it
|
||||
func setIPLength(ip []byte, size int) {
|
||||
if len(ip) == ipv4HeaderSize {
|
||||
binary.BigEndian.PutUint16(ip[2:], uint16(size))
|
||||
ip[10], ip[11] = 0, 0
|
||||
binary.BigEndian.PutUint16(ip[10:], checksum(sum(ip, 0)))
|
||||
return
|
||||
}
|
||||
binary.BigEndian.PutUint16(ip[4:], uint16(size-ipv6HeaderSize))
|
||||
}
|
||||
|
||||
// transportChecksum is the checksum of a TCP or UDP segment, header and payload, of a packet with the header ip.
|
||||
// The checksum field of header is zero
|
||||
func transportChecksum(ip []byte, proto byte, header, payload []byte) uint16 {
|
||||
return checksum(sum(payload, sum(header, pseudoSum(ip, proto, len(header)+len(payload)))))
|
||||
}
|
||||
|
||||
// pseudoSum is what the header ip of a packet adds to the checksum of its TCP or UDP segment of size bytes
|
||||
func pseudoSum(ip []byte, proto byte, size int) uint64 {
|
||||
addresses := ip[12:ipv4HeaderSize]
|
||||
if len(ip) == ipv6HeaderSize {
|
||||
addresses = ip[8:]
|
||||
}
|
||||
return sum(addresses, uint64(proto)+uint64(size))
|
||||
}
|
||||
|
||||
// sum adds the 16-bit words of b to s, with the carry of every addition added back
|
||||
func sum(b []byte, s uint64) uint64 {
|
||||
var c uint64
|
||||
for len(b) >= 32 {
|
||||
s, c = bits.Add64(s, binary.BigEndian.Uint64(b), c)
|
||||
s, c = bits.Add64(s, binary.BigEndian.Uint64(b[8:]), c)
|
||||
s, c = bits.Add64(s, binary.BigEndian.Uint64(b[16:]), c)
|
||||
s, c = bits.Add64(s, binary.BigEndian.Uint64(b[24:]), c)
|
||||
b = b[32:]
|
||||
}
|
||||
for len(b) >= 8 {
|
||||
s, c = bits.Add64(s, binary.BigEndian.Uint64(b), c)
|
||||
b = b[8:]
|
||||
}
|
||||
if len(b) >= 4 {
|
||||
s, c = bits.Add64(s, uint64(binary.BigEndian.Uint32(b)), c)
|
||||
b = b[4:]
|
||||
}
|
||||
if len(b) >= 2 {
|
||||
s, c = bits.Add64(s, uint64(binary.BigEndian.Uint16(b)), c)
|
||||
b = b[2:]
|
||||
}
|
||||
if len(b) == 1 {
|
||||
s, c = bits.Add64(s, uint64(b[0])<<8, c)
|
||||
}
|
||||
s, c = bits.Add64(s, 0, c)
|
||||
return s + c
|
||||
}
|
||||
|
||||
// checksum folds s into the 16 bits that go into a header
|
||||
func checksum(s uint64) uint16 {
|
||||
s = s>>32 + s&0xffffffff
|
||||
s = s>>16 + s&0xffff
|
||||
s = s>>16 + s&0xffff
|
||||
s = s>>16 + s&0xffff
|
||||
return ^uint16(s)
|
||||
}
|
||||
@@ -1,7 +1,16 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"net/netip"
|
||||
"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"
|
||||
)
|
||||
|
||||
// Stack interface implement ip protocol stack, bridging raw network packets and data streams
|
||||
@@ -13,5 +22,259 @@ type Stack interface {
|
||||
// StackOptions for the stack implementation
|
||||
type StackOptions struct {
|
||||
Tun Tun
|
||||
MTU uint32
|
||||
IdleTimeout time.Duration
|
||||
}
|
||||
|
||||
// flow is what the packets of one connection have in common, src is the side of the system
|
||||
type flow struct {
|
||||
src, dst netip.AddrPort
|
||||
}
|
||||
|
||||
// stack turns the packets that the system sends to the tun into connections and back.
|
||||
// It has only what the two need to talk through a tun, and a local link when the system passes on
|
||||
// what others send, see tcpConn
|
||||
type stack struct {
|
||||
ctx context.Context
|
||||
tun Tun
|
||||
mtu int
|
||||
// segmenter is the tun if it takes segments that are larger than its MTU
|
||||
segmenter segmenter
|
||||
// window is the window of every connection
|
||||
window int32
|
||||
// handle is given every new connection
|
||||
handle func(conn net.Conn, destination net.Destination)
|
||||
udp *udpConnectionHandler
|
||||
|
||||
mu sync.Mutex
|
||||
conns map[flow]*tcpConn
|
||||
closed bool
|
||||
// opening is how many of conns wait for the answer to their SYN-ACK
|
||||
opening atomic.Int32
|
||||
}
|
||||
|
||||
// NewStack builds new ip stack
|
||||
func NewStack(ctx context.Context, options StackOptions, handler *Handler) (Stack, error) {
|
||||
s := &stack{
|
||||
ctx: ctx,
|
||||
tun: options.Tun,
|
||||
mtu: int(options.MTU),
|
||||
window: tcpWindow,
|
||||
handle: handler.HandleConnection,
|
||||
conns: make(map[flow]*tcpConn),
|
||||
}
|
||||
if t, ok := options.Tun.(segmenter); ok && t.Segments() {
|
||||
s.segmenter = t
|
||||
s.window = tcpLargeWindow
|
||||
}
|
||||
s.udp = newUdpConnectionHandler(s.handle, s.writeUDP)
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Start is called by Handler to bring stack to life
|
||||
func (s *stack) Start() error {
|
||||
go s.read()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close is called by Handler to shut down the stack
|
||||
func (s *stack) Close() error {
|
||||
s.mu.Lock()
|
||||
s.closed = true
|
||||
conns := make([]*tcpConn, 0, len(s.conns))
|
||||
for _, c := range s.conns {
|
||||
conns = append(conns, c)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
for _, c := range conns {
|
||||
c.mu.Lock()
|
||||
if c.err == nil {
|
||||
c.reset()
|
||||
}
|
||||
c.mu.Unlock()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// read takes the packets of the tun until it is closed
|
||||
func (s *stack) read() {
|
||||
// a tun that does not split segments gives them as large as a packet can be
|
||||
b := make([]byte, packetRoom+1<<16)
|
||||
for {
|
||||
b, err := s.tun.ReadPacket(b)
|
||||
if err != nil {
|
||||
s.mu.Lock()
|
||||
closed := s.closed
|
||||
s.mu.Unlock()
|
||||
if !closed {
|
||||
errors.LogErrorInner(s.ctx, err, "[tun] failed to read a packet, no more are read")
|
||||
}
|
||||
return
|
||||
}
|
||||
p, ok := parsePacket(b)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
switch p.proto {
|
||||
case protoTCP:
|
||||
s.handleTCP(p)
|
||||
case protoUDP:
|
||||
s.handleUDP(p)
|
||||
case protoICMPv4, protoICMPv6:
|
||||
s.handleICMP(p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stack) handleTCP(p packet) {
|
||||
t := p.payload
|
||||
if len(t) < tcpHeaderSize {
|
||||
return
|
||||
}
|
||||
size := int(t[12]>>4) * 4
|
||||
if size < tcpHeaderSize || size > len(t) {
|
||||
return
|
||||
}
|
||||
f := flow{
|
||||
src: netip.AddrPortFrom(p.src, binary.BigEndian.Uint16(t)),
|
||||
dst: netip.AddrPortFrom(p.dst, binary.BigEndian.Uint16(t[2:])),
|
||||
}
|
||||
seg := segment{
|
||||
seq: binary.BigEndian.Uint32(t[4:]),
|
||||
ack: binary.BigEndian.Uint32(t[8:]),
|
||||
flags: t[13],
|
||||
window: binary.BigEndian.Uint16(t[14:]),
|
||||
options: t[tcpHeaderSize:size],
|
||||
payload: t[size:],
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
c := s.conns[f]
|
||||
s.mu.Unlock()
|
||||
if c != nil && c.input(seg) {
|
||||
return
|
||||
}
|
||||
if seg.flags&(tcpSyn|tcpAck|tcpRst) != tcpSyn {
|
||||
if seg.flags&tcpRst == 0 {
|
||||
s.refuse(f, seg)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if s.opening.Load() >= tcpOpening {
|
||||
return
|
||||
}
|
||||
c = newTCPConn(s, f, seg)
|
||||
s.mu.Lock()
|
||||
if s.closed {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.conns[f] = c
|
||||
s.mu.Unlock()
|
||||
s.opening.Add(1)
|
||||
c.mu.Lock()
|
||||
c.sendSynAck()
|
||||
c.arm(tcpTick)
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
// refuse answers a segment of a connection that is not known with a reset
|
||||
func (s *stack) refuse(f flow, seg segment) {
|
||||
var b [ipv6HeaderSize + tcpHeaderSize]byte
|
||||
n := putIPHeader(b[:], protoTCP, f.dst.Addr(), f.src.Addr())
|
||||
t := b[n : n+tcpHeaderSize]
|
||||
binary.BigEndian.PutUint16(t, f.dst.Port())
|
||||
binary.BigEndian.PutUint16(t[2:], f.src.Port())
|
||||
t[12] = tcpHeaderSize / 4 << 4
|
||||
if seg.flags&tcpAck != 0 {
|
||||
binary.BigEndian.PutUint32(t[4:], seg.ack)
|
||||
t[13] = tcpRst
|
||||
} else {
|
||||
ack := seg.seq + uint32(len(seg.payload))
|
||||
if seg.flags&(tcpSyn|tcpFin) != 0 {
|
||||
ack++
|
||||
}
|
||||
binary.BigEndian.PutUint32(t[8:], ack)
|
||||
t[13] = tcpRst | tcpAck
|
||||
}
|
||||
setIPLength(b[:n], n+tcpHeaderSize)
|
||||
binary.BigEndian.PutUint16(t[16:], transportChecksum(b[:n], protoTCP, t, nil))
|
||||
_ = s.tun.WritePacket(b[:n+tcpHeaderSize], nil)
|
||||
}
|
||||
|
||||
// remove forgets a connection. c.mu is held
|
||||
func (s *stack) remove(c *tcpConn) {
|
||||
if !c.established {
|
||||
s.opening.Add(-1)
|
||||
}
|
||||
s.mu.Lock()
|
||||
if s.conns[c.flow] == c {
|
||||
delete(s.conns, c.flow)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *stack) handleUDP(p packet) {
|
||||
u := p.payload
|
||||
if len(u) < udpHeaderSize {
|
||||
return
|
||||
}
|
||||
size := int(binary.BigEndian.Uint16(u[4:]))
|
||||
if size < udpHeaderSize || size > len(u) {
|
||||
return
|
||||
}
|
||||
// the packet waits for its reader, longer than read keeps it
|
||||
b := buf.NewWithSize(int32(size - udpHeaderSize))
|
||||
b.Write(u[udpHeaderSize:size])
|
||||
src := net.UDPDestination(net.IPAddress(p.src.AsSlice()), net.Port(binary.BigEndian.Uint16(u)))
|
||||
dst := net.UDPDestination(net.IPAddress(p.dst.AsSlice()), net.Port(binary.BigEndian.Uint16(u[2:])))
|
||||
s.udp.HandlePacket(src, dst, b)
|
||||
}
|
||||
|
||||
// writeUDP writes a packet with the payload from src to dst to the tun
|
||||
func (s *stack) writeUDP(payload []byte, src net.Destination, dst net.Destination) error {
|
||||
srcIP, _ := netip.AddrFromSlice(src.Address.IP())
|
||||
dstIP, _ := netip.AddrFromSlice(dst.Address.IP())
|
||||
srcIP, dstIP = srcIP.Unmap(), dstIP.Unmap()
|
||||
if !srcIP.IsValid() || srcIP.Is4() != dstIP.Is4() {
|
||||
return errors.New("failed to write udp packet from ", src, " to ", dst)
|
||||
}
|
||||
var b [ipv6HeaderSize + udpHeaderSize]byte
|
||||
n := putIPHeader(b[:], protoUDP, srcIP, dstIP)
|
||||
u := b[n : n+udpHeaderSize]
|
||||
binary.BigEndian.PutUint16(u, uint16(src.Port))
|
||||
binary.BigEndian.PutUint16(u[2:], uint16(dst.Port))
|
||||
binary.BigEndian.PutUint16(u[4:], uint16(udpHeaderSize+len(payload)))
|
||||
setIPLength(b[:n], n+udpHeaderSize+len(payload))
|
||||
check := transportChecksum(b[:n], protoUDP, u, payload)
|
||||
if check == 0 {
|
||||
// zero stands for no checksum
|
||||
check = 0xffff
|
||||
}
|
||||
binary.BigEndian.PutUint16(u[6:], check)
|
||||
return s.tun.WritePacket(b[:n+udpHeaderSize], payload)
|
||||
}
|
||||
|
||||
// handleICMP answers an echo request as its destination would
|
||||
func (s *stack) handleICMP(p packet) {
|
||||
m := p.payload
|
||||
request, reply := byte(8), byte(0)
|
||||
if p.proto == protoICMPv6 {
|
||||
request, reply = 128, 129
|
||||
}
|
||||
if len(m) < 8 || m[0] != request || m[1] != 0 {
|
||||
return
|
||||
}
|
||||
var b [ipv6HeaderSize]byte
|
||||
n := putIPHeader(b[:], p.proto, p.dst, p.src)
|
||||
setIPLength(b[:n], n+len(m))
|
||||
// the reply is the request with another type
|
||||
m[0], m[2], m[3] = reply, 0, 0
|
||||
if p.proto == protoICMPv6 {
|
||||
binary.BigEndian.PutUint16(m[2:], transportChecksum(b[:n], protoICMPv6, m, nil))
|
||||
} else {
|
||||
binary.BigEndian.PutUint16(m[2:], checksum(sum(m, 0)))
|
||||
}
|
||||
_ = s.tun.WritePacket(b[:n], m)
|
||||
}
|
||||
|
||||
@@ -1,267 +0,0 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"gvisor.dev/gvisor/pkg/buffer"
|
||||
"gvisor.dev/gvisor/pkg/tcpip"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/checksum"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/header"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/stack"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/transport/icmp"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/transport/udp"
|
||||
"gvisor.dev/gvisor/pkg/waiter"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultNIC tcpip.NICID = 1
|
||||
|
||||
tcpRXBufMinSize = tcp.MinBufferSize
|
||||
tcpRXBufDefSize = tcp.DefaultSendBufferSize
|
||||
tcpRXBufMaxSize = 8 << 20 // 8MiB
|
||||
|
||||
tcpTXBufMinSize = tcp.MinBufferSize
|
||||
tcpTXBufDefSize = tcp.DefaultReceiveBufferSize
|
||||
tcpTXBufMaxSize = 6 << 20 // 6MiB
|
||||
)
|
||||
|
||||
// stackGVisor is ip stack implemented by gVisor package
|
||||
type stackGVisor struct {
|
||||
ctx context.Context
|
||||
tun Tun
|
||||
idleTimeout time.Duration
|
||||
handler *Handler
|
||||
stack *stack.Stack
|
||||
endpoint stack.LinkEndpoint
|
||||
}
|
||||
|
||||
// NewStack builds new ip stack (using gVisor)
|
||||
func NewStack(ctx context.Context, options StackOptions, handler *Handler) (Stack, error) {
|
||||
gStack := &stackGVisor{
|
||||
ctx: ctx,
|
||||
tun: options.Tun,
|
||||
idleTimeout: options.IdleTimeout,
|
||||
handler: handler,
|
||||
}
|
||||
|
||||
return gStack, nil
|
||||
}
|
||||
|
||||
// Start is called by Handler to bring stack to life
|
||||
func (t *stackGVisor) Start() error {
|
||||
linkEndpoint, err := t.tun.newEndpoint()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ipStack, err := createStack(linkEndpoint)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tcpForwarder := tcp.NewForwarder(ipStack, 0, 65535, func(r *tcp.ForwarderRequest) {
|
||||
go func(r *tcp.ForwarderRequest) {
|
||||
var wq waiter.Queue
|
||||
id := r.ID()
|
||||
|
||||
// Perform a TCP three-way handshake.
|
||||
ep, err := r.CreateEndpoint(&wq)
|
||||
if err != nil {
|
||||
errors.LogError(t.ctx, err.String())
|
||||
r.Complete(true)
|
||||
return
|
||||
}
|
||||
|
||||
options := ep.SocketOptions()
|
||||
options.SetKeepAlive(false)
|
||||
options.SetReuseAddress(true)
|
||||
options.SetReusePort(true)
|
||||
|
||||
t.handler.HandleConnection(
|
||||
gonet.NewTCPConn(&wq, ep),
|
||||
// local address on the gVisor side is connection destination
|
||||
net.TCPDestination(net.IPAddress(id.LocalAddress.AsSlice()), net.Port(id.LocalPort)),
|
||||
)
|
||||
|
||||
// close the socket
|
||||
ep.Close()
|
||||
// send connection complete upstream
|
||||
r.Complete(false)
|
||||
}(r)
|
||||
})
|
||||
ipStack.SetTransportProtocolHandler(tcp.ProtocolNumber, tcpForwarder.HandlePacket)
|
||||
|
||||
// Use custom UDP packet handler, instead of strict gVisor forwarder, for FullCone NAT support
|
||||
udpForwarder := newUdpConnectionHandler(t.handler.HandleConnection, t.writeRawUDPPacket)
|
||||
ipStack.SetTransportProtocolHandler(udp.ProtocolNumber, func(id stack.TransportEndpointID, pkt *stack.PacketBuffer) bool {
|
||||
data := pkt.Data().AsRange().ToSlice()
|
||||
// if len(data) == 0 {
|
||||
// return false
|
||||
// }
|
||||
// source/destination of the packet we process as incoming, on gVisor side are Remote/Local
|
||||
// in other terms, src is the side behind tun, dst is the side behind gVisor
|
||||
// this function handle packets passing from the tun to the gVisor, therefore the src/dst assignement
|
||||
srcIP := net.IPAddress(id.RemoteAddress.AsSlice())
|
||||
dstIP := net.IPAddress(id.LocalAddress.AsSlice())
|
||||
if srcIP == nil || dstIP == nil {
|
||||
panic(id)
|
||||
}
|
||||
src := net.UDPDestination(srcIP, net.Port(id.RemotePort))
|
||||
dst := net.UDPDestination(dstIP, net.Port(id.LocalPort))
|
||||
udpForwarder.HandlePacket(src, dst, data)
|
||||
return true
|
||||
})
|
||||
ipStack.SetTransportProtocolHandler(icmp.ProtocolNumber4, t.handleICMPv4Packet)
|
||||
ipStack.SetTransportProtocolHandler(icmp.ProtocolNumber6, t.handleICMPv6Packet)
|
||||
|
||||
t.stack = ipStack
|
||||
t.endpoint = linkEndpoint
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *stackGVisor) writeRawUDPPacket(payload []byte, src net.Destination, dst net.Destination) error {
|
||||
udpLen := header.UDPMinimumSize + len(payload)
|
||||
srcIP := tcpip.AddrFromSlice(src.Address.IP())
|
||||
dstIP := tcpip.AddrFromSlice(dst.Address.IP())
|
||||
|
||||
// build packet with appropriate IP header size
|
||||
isIPv4 := dst.Address.Family().IsIPv4()
|
||||
ipHdrSize := header.IPv6MinimumSize
|
||||
ipProtocol := header.IPv6ProtocolNumber
|
||||
if isIPv4 {
|
||||
ipHdrSize = header.IPv4MinimumSize
|
||||
ipProtocol = header.IPv4ProtocolNumber
|
||||
}
|
||||
|
||||
pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
|
||||
ReserveHeaderBytes: ipHdrSize + header.UDPMinimumSize,
|
||||
Payload: buffer.MakeWithData(payload),
|
||||
})
|
||||
defer pkt.DecRef()
|
||||
|
||||
// Build UDP header
|
||||
udpHdr := header.UDP(pkt.TransportHeader().Push(header.UDPMinimumSize))
|
||||
udpHdr.Encode(&header.UDPFields{
|
||||
SrcPort: uint16(src.Port),
|
||||
DstPort: uint16(dst.Port),
|
||||
Length: uint16(udpLen),
|
||||
})
|
||||
|
||||
// Calculate and set UDP checksum
|
||||
xsum := header.PseudoHeaderChecksum(header.UDPProtocolNumber, srcIP, dstIP, uint16(udpLen))
|
||||
udpHdr.SetChecksum(^udpHdr.CalculateChecksum(checksum.Checksum(payload, xsum)))
|
||||
|
||||
// Build IP header
|
||||
if isIPv4 {
|
||||
ipHdr := header.IPv4(pkt.NetworkHeader().Push(header.IPv4MinimumSize))
|
||||
ipHdr.Encode(&header.IPv4Fields{
|
||||
TotalLength: uint16(header.IPv4MinimumSize + udpLen),
|
||||
TTL: 64,
|
||||
Protocol: uint8(header.UDPProtocolNumber),
|
||||
SrcAddr: srcIP,
|
||||
DstAddr: dstIP,
|
||||
})
|
||||
ipHdr.SetChecksum(^ipHdr.CalculateChecksum())
|
||||
} else {
|
||||
ipHdr := header.IPv6(pkt.NetworkHeader().Push(header.IPv6MinimumSize))
|
||||
ipHdr.Encode(&header.IPv6Fields{
|
||||
PayloadLength: uint16(udpLen),
|
||||
TransportProtocol: header.UDPProtocolNumber,
|
||||
HopLimit: 64,
|
||||
SrcAddr: srcIP,
|
||||
DstAddr: dstIP,
|
||||
})
|
||||
}
|
||||
|
||||
// dispatch the packet
|
||||
err := t.stack.WriteRawPacket(defaultNIC, ipProtocol, buffer.MakeWithView(pkt.ToView()))
|
||||
if err != nil {
|
||||
return errors.New("failed to write raw udp packet back to stack", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close is called by Handler to shut down the stack
|
||||
func (t *stackGVisor) Close() error {
|
||||
if t.stack == nil {
|
||||
return nil
|
||||
}
|
||||
t.endpoint.Attach(nil)
|
||||
t.stack.Close()
|
||||
for _, endpoint := range t.stack.CleanupEndpoints() {
|
||||
endpoint.Abort()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// createStack configure gVisor ip stack
|
||||
func createStack(ep stack.LinkEndpoint) (*stack.Stack, error) {
|
||||
opts := stack.Options{
|
||||
NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
|
||||
TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol, icmp.NewProtocol4, icmp.NewProtocol6},
|
||||
HandleLocal: false,
|
||||
}
|
||||
gStack := stack.New(opts)
|
||||
|
||||
err := gStack.CreateNIC(defaultNIC, ep)
|
||||
if err != nil {
|
||||
return nil, errors.New(err.String())
|
||||
}
|
||||
|
||||
gStack.SetRouteTable([]tcpip.Route{
|
||||
{Destination: header.IPv4EmptySubnet, NIC: defaultNIC},
|
||||
{Destination: header.IPv6EmptySubnet, NIC: defaultNIC},
|
||||
})
|
||||
|
||||
err = gStack.SetSpoofing(defaultNIC, true)
|
||||
if err != nil {
|
||||
return nil, errors.New(err.String())
|
||||
}
|
||||
err = gStack.SetPromiscuousMode(defaultNIC, true)
|
||||
if err != nil {
|
||||
return nil, errors.New(err.String())
|
||||
}
|
||||
|
||||
cOpt := tcpip.CongestionControlOption("cubic")
|
||||
gStack.SetTransportProtocolOption(tcp.ProtocolNumber, &cOpt)
|
||||
sOpt := tcpip.TCPSACKEnabled(true)
|
||||
gStack.SetTransportProtocolOption(tcp.ProtocolNumber, &sOpt)
|
||||
mOpt := tcpip.TCPModerateReceiveBufferOption(true)
|
||||
gStack.SetTransportProtocolOption(tcp.ProtocolNumber, &mOpt)
|
||||
|
||||
// Disable RACK/TLP loss recovery to fix connection stalls under high load
|
||||
rOpt := tcpip.TCPRecovery(0)
|
||||
gStack.SetTransportProtocolOption(tcp.ProtocolNumber, &rOpt)
|
||||
|
||||
tcpRXBufOpt := tcpip.TCPReceiveBufferSizeRangeOption{
|
||||
Min: tcpRXBufMinSize,
|
||||
Default: tcpRXBufDefSize,
|
||||
Max: tcpRXBufMaxSize,
|
||||
}
|
||||
err = gStack.SetTransportProtocolOption(tcp.ProtocolNumber, &tcpRXBufOpt)
|
||||
if err != nil {
|
||||
return nil, errors.New(err.String())
|
||||
}
|
||||
|
||||
tcpTXBufOpt := tcpip.TCPSendBufferSizeRangeOption{
|
||||
Min: tcpTXBufMinSize,
|
||||
Default: tcpTXBufDefSize,
|
||||
Max: tcpTXBufMaxSize,
|
||||
}
|
||||
err = gStack.SetTransportProtocolOption(tcp.ProtocolNumber, &tcpTXBufOpt)
|
||||
if err != nil {
|
||||
return nil, errors.New(err.String())
|
||||
}
|
||||
|
||||
return gStack, nil
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"gvisor.dev/gvisor/pkg/tcpip"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/header"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/stack"
|
||||
)
|
||||
|
||||
var ErrQueueEmpty = errors.New("queue is empty")
|
||||
|
||||
type GVisorDevice interface {
|
||||
WritePacket(packet *stack.PacketBuffer) tcpip.Error
|
||||
ReadPacket() (byte, *stack.PacketBuffer, error)
|
||||
Wait()
|
||||
}
|
||||
|
||||
// LinkEndpoint implements GVisor stack.LinkEndpoint
|
||||
var _ stack.LinkEndpoint = (*LinkEndpoint)(nil)
|
||||
|
||||
type LinkEndpoint struct {
|
||||
deviceMTU uint32
|
||||
device GVisorDevice
|
||||
dispatcherCancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (e *LinkEndpoint) MTU() uint32 {
|
||||
return e.deviceMTU
|
||||
}
|
||||
|
||||
func (e *LinkEndpoint) SetMTU(_ uint32) {
|
||||
// not Implemented, as it is not expected GVisor will be asking tun device to be modified
|
||||
}
|
||||
|
||||
func (e *LinkEndpoint) MaxHeaderLength() uint16 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (e *LinkEndpoint) LinkAddress() tcpip.LinkAddress {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (e *LinkEndpoint) SetLinkAddress(_ tcpip.LinkAddress) {
|
||||
// not Implemented, as it is not expected GVisor will be asking tun device to be modified
|
||||
}
|
||||
|
||||
func (e *LinkEndpoint) Capabilities() stack.LinkEndpointCapabilities {
|
||||
return stack.CapabilityRXChecksumOffload
|
||||
}
|
||||
|
||||
func (e *LinkEndpoint) Attach(dispatcher stack.NetworkDispatcher) {
|
||||
if e.dispatcherCancel != nil {
|
||||
e.dispatcherCancel()
|
||||
e.dispatcherCancel = nil
|
||||
}
|
||||
|
||||
if dispatcher != nil {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
go e.dispatchLoop(ctx, dispatcher)
|
||||
e.dispatcherCancel = cancel
|
||||
}
|
||||
}
|
||||
|
||||
func (e *LinkEndpoint) IsAttached() bool {
|
||||
return e.dispatcherCancel != nil
|
||||
}
|
||||
|
||||
func (e *LinkEndpoint) Wait() {
|
||||
}
|
||||
|
||||
func (e *LinkEndpoint) ARPHardwareType() header.ARPHardwareType {
|
||||
return header.ARPHardwareNone
|
||||
}
|
||||
|
||||
func (e *LinkEndpoint) AddHeader(buffer *stack.PacketBuffer) {
|
||||
// tun interface doesn't have link layer header, it will be added by the OS
|
||||
}
|
||||
|
||||
func (e *LinkEndpoint) ParseHeader(ptr *stack.PacketBuffer) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (e *LinkEndpoint) Close() {
|
||||
if e.dispatcherCancel != nil {
|
||||
e.dispatcherCancel()
|
||||
e.dispatcherCancel = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (e *LinkEndpoint) SetOnCloseAction(_ func()) {
|
||||
}
|
||||
|
||||
func (e *LinkEndpoint) WritePackets(packetBufferList stack.PacketBufferList) (int, tcpip.Error) {
|
||||
var n int
|
||||
var err tcpip.Error
|
||||
|
||||
for _, packetBuffer := range packetBufferList.AsSlice() {
|
||||
err = e.device.WritePacket(packetBuffer)
|
||||
if err != nil {
|
||||
return n, &tcpip.ErrAborted{}
|
||||
}
|
||||
n++
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (e *LinkEndpoint) dispatchLoop(ctx context.Context, dispatcher stack.NetworkDispatcher) {
|
||||
var networkProtocolNumber tcpip.NetworkProtocolNumber
|
||||
var version byte
|
||||
var packet *stack.PacketBuffer
|
||||
var err error
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
version, packet, err = e.device.ReadPacket()
|
||||
// on "queue empty", ask device to yield slightly and continue
|
||||
if errors.Is(err, ErrQueueEmpty) {
|
||||
e.device.Wait()
|
||||
continue
|
||||
}
|
||||
// stop dispatcher loop on any other interface failure
|
||||
if err != nil {
|
||||
e.Attach(nil)
|
||||
return
|
||||
}
|
||||
|
||||
// extract network protocol number from the packet first byte
|
||||
// (which is returned separately, since it is so incredibly hard to extract one byte from
|
||||
// stack.PacketBuffer without additional memory allocation and full copying it back and forth)
|
||||
switch version {
|
||||
case 4:
|
||||
networkProtocolNumber = header.IPv4ProtocolNumber
|
||||
case 6:
|
||||
networkProtocolNumber = header.IPv6ProtocolNumber
|
||||
default:
|
||||
// discard unknown network protocol packet
|
||||
packet.DecRef()
|
||||
continue
|
||||
}
|
||||
|
||||
// dispatch the buffer to the stack
|
||||
dispatcher.DeliverNetworkPacket(networkProtocolNumber, packet)
|
||||
// signal the buffer that it can be released
|
||||
packet.DecRef()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
tunicmp "github.com/xtls/xray-core/proxy/tun/icmp"
|
||||
"gvisor.dev/gvisor/pkg/buffer"
|
||||
"gvisor.dev/gvisor/pkg/tcpip"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/header"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/stack"
|
||||
)
|
||||
|
||||
func (t *stackGVisor) handleICMPv4Packet(id stack.TransportEndpointID, pkt *stack.PacketBuffer) bool {
|
||||
return t.handleICMPEchoPacket(header.IPv4ProtocolNumber, id, pkt)
|
||||
}
|
||||
|
||||
func (t *stackGVisor) handleICMPv6Packet(id stack.TransportEndpointID, pkt *stack.PacketBuffer) bool {
|
||||
return t.handleICMPEchoPacket(header.IPv6ProtocolNumber, id, pkt)
|
||||
}
|
||||
|
||||
func (t *stackGVisor) handleICMPEchoPacket(netProto tcpip.NetworkProtocolNumber, id stack.TransportEndpointID, pkt *stack.PacketBuffer) bool {
|
||||
srcIP := id.RemoteAddress
|
||||
dstIP := id.LocalAddress
|
||||
if srcIP.Len() == 0 || dstIP.Len() == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
message := transportPacketBytes(pkt)
|
||||
ident, sequence, ok := tunicmp.ParseEchoRequest(netProto, message)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
|
||||
reply, err := tunicmp.BuildLocalEchoReply(netProto, message, dstIP, srcIP)
|
||||
if err != nil {
|
||||
errors.LogInfoInner(t.ctx, err, "[tun] failed to build local icmp echo reply")
|
||||
return true
|
||||
}
|
||||
|
||||
errors.LogDebug(t.ctx, "[tun][icmp] ", tunicmp.ProtocolLabel(netProto), " local echo reply ", dstIP, " -> ", srcIP, " id=", ident, " seq=", sequence)
|
||||
if err := t.writeRawICMPPacket(netProto, reply, dstIP, srcIP); err != nil {
|
||||
errors.LogInfoInner(t.ctx, err, "[tun] failed to write local icmp echo reply")
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (t *stackGVisor) writeRawICMPPacket(netProto tcpip.NetworkProtocolNumber, message []byte, srcIP, dstIP tcpip.Address) error {
|
||||
ipHeaderSize := header.IPv6MinimumSize
|
||||
ipProtocol := header.IPv6ProtocolNumber
|
||||
transportProtocol := header.ICMPv6ProtocolNumber
|
||||
if netProto == header.IPv4ProtocolNumber {
|
||||
ipHeaderSize = header.IPv4MinimumSize
|
||||
ipProtocol = header.IPv4ProtocolNumber
|
||||
transportProtocol = header.ICMPv4ProtocolNumber
|
||||
}
|
||||
|
||||
pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
|
||||
ReserveHeaderBytes: ipHeaderSize,
|
||||
Payload: buffer.MakeWithData(message),
|
||||
})
|
||||
defer pkt.DecRef()
|
||||
|
||||
if netProto == header.IPv4ProtocolNumber {
|
||||
ipHdr := header.IPv4(pkt.NetworkHeader().Push(header.IPv4MinimumSize))
|
||||
ipHdr.Encode(&header.IPv4Fields{
|
||||
TotalLength: uint16(header.IPv4MinimumSize + len(message)),
|
||||
TTL: 64,
|
||||
Protocol: uint8(transportProtocol),
|
||||
SrcAddr: srcIP,
|
||||
DstAddr: dstIP,
|
||||
})
|
||||
ipHdr.SetChecksum(^ipHdr.CalculateChecksum())
|
||||
} else {
|
||||
ipHdr := header.IPv6(pkt.NetworkHeader().Push(header.IPv6MinimumSize))
|
||||
ipHdr.Encode(&header.IPv6Fields{
|
||||
PayloadLength: uint16(len(message)),
|
||||
TransportProtocol: transportProtocol,
|
||||
HopLimit: 64,
|
||||
SrcAddr: srcIP,
|
||||
DstAddr: dstIP,
|
||||
})
|
||||
}
|
||||
|
||||
if err := t.stack.WriteRawPacket(defaultNIC, ipProtocol, buffer.MakeWithView(pkt.ToView())); err != nil {
|
||||
return errors.New("failed to write raw icmp packet back to stack", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func transportPacketBytes(pkt *stack.PacketBuffer) []byte {
|
||||
headerBytes := pkt.TransportHeader().Slice()
|
||||
payloadBytes := pkt.Data().AsRange().ToSlice()
|
||||
message := make([]byte, len(headerBytes)+len(payloadBytes))
|
||||
copy(message, headerBytes)
|
||||
copy(message[len(headerBytes):], payloadBytes)
|
||||
return message
|
||||
}
|
||||
@@ -0,0 +1,929 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
mrand "math/rand/v2"
|
||||
"net/netip"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"gvisor.dev/gvisor/pkg/buffer"
|
||||
"gvisor.dev/gvisor/pkg/tcpip"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/header"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/link/channel"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
|
||||
gstack "gvisor.dev/gvisor/pkg/tcpip/stack"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
|
||||
)
|
||||
|
||||
const testMTU = 1500
|
||||
|
||||
// link is a tun with the test on its other side
|
||||
type link struct {
|
||||
// in is what the stack reads
|
||||
in chan []byte
|
||||
// out takes what the stack writes
|
||||
out func(packet []byte)
|
||||
// segments is set if the link takes segments that are larger than the MTU, wrong tells what was wrong with one
|
||||
segments bool
|
||||
wrong func(args ...any)
|
||||
done chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func newLink() *link {
|
||||
return &link{in: make(chan []byte, 512), done: make(chan struct{})}
|
||||
}
|
||||
|
||||
func (l *link) Start() error { return nil }
|
||||
func (l *link) Name() (string, error) { return "test", nil }
|
||||
func (l *link) Index() (int, error) { return 1, nil }
|
||||
|
||||
func (l *link) Close() error {
|
||||
l.once.Do(func() { close(l.done) })
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *link) ReadPacket(b []byte) ([]byte, error) {
|
||||
select {
|
||||
case packet := <-l.in:
|
||||
return b[packetRoom : packetRoom+copy(b[packetRoom:], packet)], nil
|
||||
case <-l.done:
|
||||
return nil, io.EOF
|
||||
}
|
||||
}
|
||||
|
||||
func (l *link) WritePacket(header, payload []byte) error {
|
||||
l.out(append(append(make([]byte, 0, len(header)+len(payload)), header...), payload...))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Segments implements segmenter
|
||||
func (l *link) Segments() bool {
|
||||
return l.segments
|
||||
}
|
||||
|
||||
// WriteSegment implements segmenter as the system does when it sends a segment on: a packet for every mss bytes
|
||||
func (l *link) WriteSegment(header []byte, payload [][]byte, mss int) error {
|
||||
data := bytes.Join(payload, nil)
|
||||
size := ipv4HeaderSize
|
||||
if header[0]>>4 == 6 {
|
||||
size = ipv6HeaderSize
|
||||
}
|
||||
if expected := ^checksum(pseudoSum(header[:size], protoTCP, len(header)-size+len(data))); binary.BigEndian.Uint16(header[size+16:]) != expected {
|
||||
l.wrong("checksum of a segment for the link to split: ", header[size+16:size+18], ", expected ", expected)
|
||||
}
|
||||
for sent := 0; sent < len(data); {
|
||||
n := min(mss, len(data)-sent)
|
||||
h := bytes.Clone(header)
|
||||
t := h[size:]
|
||||
binary.BigEndian.PutUint32(t[4:], binary.BigEndian.Uint32(t[4:])+uint32(sent))
|
||||
if sent+n < len(data) {
|
||||
t[13] &^= tcpFin | tcpPsh
|
||||
}
|
||||
t[16], t[17] = 0, 0
|
||||
setIPLength(h[:size], len(h)+n)
|
||||
binary.BigEndian.PutUint16(t[16:], transportChecksum(h[:size], protoTCP, t, data[sent:sent+n]))
|
||||
l.out(append(h, data[sent:sent+n]...))
|
||||
sent += n
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func newTestStack(t *testing.T, l *link, handle func(net.Conn, net.Destination)) *stack {
|
||||
s := &stack{ctx: context.Background(), tun: l, mtu: testMTU, window: tcpWindow, handle: handle, conns: make(map[flow]*tcpConn)}
|
||||
if l.segments {
|
||||
s.segmenter, s.window, l.wrong = l, tcpLargeWindow, t.Error
|
||||
}
|
||||
s.udp = newUdpConnectionHandler(handle, s.writeUDP)
|
||||
s.Start()
|
||||
t.Cleanup(func() {
|
||||
s.Close()
|
||||
l.Close()
|
||||
})
|
||||
return s
|
||||
}
|
||||
|
||||
// forgotten waits until the stack has no connection left
|
||||
func forgotten(t *testing.T, s *stack) {
|
||||
for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(10 * time.Millisecond) {
|
||||
s.mu.Lock()
|
||||
n := len(s.conns)
|
||||
s.mu.Unlock()
|
||||
if n == 0 {
|
||||
if opening := s.opening.Load(); opening != 0 {
|
||||
t.Fatal("connections that are still counted as being opened: ", opening)
|
||||
}
|
||||
return
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("connections left in the stack: ", n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// echo sends back what it reads, and closes when the other side has
|
||||
func echo(conn net.Conn, _ net.Destination) {
|
||||
defer conn.Close()
|
||||
for {
|
||||
mb, err := conn.(buf.Reader).ReadMultiBuffer()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if conn.(buf.Writer).WriteMultiBuffer(mb) != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A real TCP on the other side of a tun that loses packets both ways gets back what it sent.
|
||||
func TestTCPEcho(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
// one packet of lose is lost
|
||||
lose int
|
||||
size int
|
||||
// the tun takes segments that are larger than its MTU
|
||||
segments bool
|
||||
}{
|
||||
{"lossless", 0, 16 << 20, false},
|
||||
{"lossy", 100, 4 << 20, false},
|
||||
{"very lossy", 20, 512 << 10, false},
|
||||
{"lossless, large segments", 0, 16 << 20, true},
|
||||
{"lossy, large segments", 100, 4 << 20, true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
l := newLink()
|
||||
l.segments = test.segments
|
||||
random := mrand.New(mrand.NewPCG(1, uint64(test.lose)))
|
||||
var mu sync.Mutex
|
||||
lost := func() bool {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return test.lose != 0 && random.IntN(test.lose) == 0
|
||||
}
|
||||
|
||||
// the system on the other side of the tun
|
||||
system := gstack.New(gstack.Options{
|
||||
NetworkProtocols: []gstack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
|
||||
TransportProtocols: []gstack.TransportProtocolFactory{tcp.NewProtocol},
|
||||
})
|
||||
defer system.Destroy()
|
||||
endpoint := channel.New(512, testMTU, "")
|
||||
if err := system.CreateNIC(1, endpoint); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, address := range []tcpip.ProtocolAddress{
|
||||
{Protocol: ipv4.ProtocolNumber, AddressWithPrefix: tcpip.AddrFrom4([4]byte{10, 0, 0, 1}).WithPrefix()},
|
||||
{Protocol: ipv6.ProtocolNumber, AddressWithPrefix: tcpip.AddrFrom16([16]byte{0xfd, 15: 1}).WithPrefix()},
|
||||
} {
|
||||
if err := system.AddProtocolAddress(1, address, gstack.AddressProperties{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
system.SetRouteTable([]tcpip.Route{{Destination: header.IPv4EmptySubnet, NIC: 1}, {Destination: header.IPv6EmptySubnet, NIC: 1}})
|
||||
sack := tcpip.TCPSACKEnabled(true)
|
||||
system.SetTransportProtocolOption(tcp.ProtocolNumber, &sack)
|
||||
// without RACK: after a tail loss probe of it that is lost too, it has no timer left to send what was lost again
|
||||
recovery := tcpip.TCPRecovery(0)
|
||||
system.SetTransportProtocolOption(tcp.ProtocolNumber, &recovery)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go func() {
|
||||
for {
|
||||
packet := endpoint.ReadContext(ctx)
|
||||
if packet == nil {
|
||||
return
|
||||
}
|
||||
var b []byte
|
||||
for _, part := range packet.AsSlices() {
|
||||
b = append(b, part...)
|
||||
}
|
||||
packet.DecRef()
|
||||
if !lost() {
|
||||
select {
|
||||
case l.in <- b:
|
||||
default:
|
||||
// as a tun does when its queue is full
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
l.out = func(b []byte) {
|
||||
if lost() {
|
||||
return
|
||||
}
|
||||
protocol := ipv4.ProtocolNumber
|
||||
if b[0]>>4 == 6 {
|
||||
protocol = ipv6.ProtocolNumber
|
||||
}
|
||||
packet := gstack.NewPacketBuffer(gstack.PacketBufferOptions{Payload: buffer.MakeWithData(b)})
|
||||
endpoint.InjectInbound(protocol, packet)
|
||||
packet.DecRef()
|
||||
}
|
||||
s := newTestStack(t, l, echo)
|
||||
|
||||
for _, to := range []struct {
|
||||
address tcpip.Address
|
||||
protocol tcpip.NetworkProtocolNumber
|
||||
}{
|
||||
{tcpip.AddrFrom4([4]byte{10, 0, 0, 2}), ipv4.ProtocolNumber},
|
||||
{tcpip.AddrFrom16([16]byte{0xfd, 15: 2}), ipv6.ProtocolNumber},
|
||||
} {
|
||||
conn, err := gonet.DialTCP(system, tcpip.FullAddress{NIC: 1, Addr: to.address, Port: 80}, to.protocol)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sent := make([]byte, test.size)
|
||||
rand.Read(sent)
|
||||
go func() {
|
||||
conn.Write(sent)
|
||||
conn.CloseWrite()
|
||||
}()
|
||||
conn.SetReadDeadline(time.Now().Add(2 * time.Minute))
|
||||
received, err := io.ReadAll(conn)
|
||||
if err != nil || !bytes.Equal(received, sent) {
|
||||
t.Fatal("received ", len(received), " of ", len(sent), " bytes, equal: ", bytes.Equal(received, sent), ", error: ", err)
|
||||
}
|
||||
conn.Close()
|
||||
forgotten(t, s)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// peer is the system's end of one connection, with every segment made by the test
|
||||
type peer struct {
|
||||
t *testing.T
|
||||
l *link
|
||||
sent chan []byte
|
||||
src, dst netip.AddrPort
|
||||
// seq is the next that the peer sends, ack the next that it expects
|
||||
seq, ack uint32
|
||||
window uint16
|
||||
}
|
||||
|
||||
func newPeer(t *testing.T, src, dst string) (*peer, *link) {
|
||||
l := newLink()
|
||||
p := &peer{t: t, l: l, sent: make(chan []byte, 1024), src: netip.MustParseAddrPort(src), dst: netip.MustParseAddrPort(dst), seq: 1000, window: 0xffff}
|
||||
l.out = func(b []byte) { p.sent <- b }
|
||||
return p, l
|
||||
}
|
||||
|
||||
// send gives the stack a segment of the peer
|
||||
func (p *peer) send(seq uint32, flags byte, options, payload []byte) {
|
||||
var b [ipv6HeaderSize + tcpHeaderSize + 40]byte
|
||||
n := putIPHeader(b[:], protoTCP, p.src.Addr(), p.dst.Addr())
|
||||
t := b[n : n+tcpHeaderSize+len(options)]
|
||||
binary.BigEndian.PutUint16(t, p.src.Port())
|
||||
binary.BigEndian.PutUint16(t[2:], p.dst.Port())
|
||||
binary.BigEndian.PutUint32(t[4:], seq)
|
||||
binary.BigEndian.PutUint32(t[8:], p.ack)
|
||||
t[12] = byte(len(t)/4) << 4
|
||||
t[13] = flags
|
||||
binary.BigEndian.PutUint16(t[14:], p.window)
|
||||
copy(t[tcpHeaderSize:], options)
|
||||
setIPLength(b[:n], n+len(t)+len(payload))
|
||||
binary.BigEndian.PutUint16(t[16:], transportChecksum(b[:n], protoTCP, t, payload))
|
||||
p.l.in <- append(b[:n+len(t):n+len(t)], payload...)
|
||||
}
|
||||
|
||||
// packet takes the next packet that the stack wrote
|
||||
func (p *peer) packet() []byte {
|
||||
p.t.Helper()
|
||||
select {
|
||||
case b := <-p.sent:
|
||||
return b
|
||||
case <-time.After(5 * time.Second):
|
||||
p.t.Fatal("no packet from the stack")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// receive takes the next segment that the stack wrote and checks its addresses and checksums
|
||||
func (p *peer) receive() segment {
|
||||
p.t.Helper()
|
||||
b := p.packet()
|
||||
size := ipv4HeaderSize
|
||||
if b[0]>>4 == 6 {
|
||||
size = ipv6HeaderSize
|
||||
} else if checksum(sum(b[:size], 0)) != 0 {
|
||||
p.t.Fatal("wrong checksum of the ip header")
|
||||
}
|
||||
packet, ok := parsePacket(b)
|
||||
if !ok || packet.proto != protoTCP || packet.src != p.dst.Addr() || packet.dst != p.src.Addr() {
|
||||
p.t.Fatal("not a segment of the connection: ", b)
|
||||
}
|
||||
t := packet.payload
|
||||
if transportChecksum(b[:size], protoTCP, t, nil) != 0 {
|
||||
p.t.Fatal("wrong checksum of the segment")
|
||||
}
|
||||
if binary.BigEndian.Uint16(t) != p.dst.Port() || binary.BigEndian.Uint16(t[2:]) != p.src.Port() {
|
||||
p.t.Fatal("wrong ports: ", t[:4])
|
||||
}
|
||||
offset := int(t[12]>>4) * 4
|
||||
return segment{
|
||||
seq: binary.BigEndian.Uint32(t[4:]),
|
||||
ack: binary.BigEndian.Uint32(t[8:]),
|
||||
flags: t[13],
|
||||
window: binary.BigEndian.Uint16(t[14:]),
|
||||
options: t[tcpHeaderSize:offset],
|
||||
payload: t[offset:],
|
||||
}
|
||||
}
|
||||
|
||||
// silent fails if the stack writes something within d
|
||||
func (p *peer) silent(d time.Duration) {
|
||||
p.t.Helper()
|
||||
select {
|
||||
case b := <-p.sent:
|
||||
p.t.Fatal("unexpected packet from the stack: ", b)
|
||||
case <-time.After(d):
|
||||
}
|
||||
}
|
||||
|
||||
// connect opens the connection with the given options in the SYN and returns the options of the answer
|
||||
func (p *peer) connect(options []byte) []byte {
|
||||
p.t.Helper()
|
||||
p.send(p.seq, tcpSyn, options, nil)
|
||||
p.seq++
|
||||
s := p.receive()
|
||||
if s.flags != tcpSyn|tcpAck || s.ack != p.seq {
|
||||
p.t.Fatal("not an answer to the SYN: flags ", s.flags, ", ack ", s.ack)
|
||||
}
|
||||
p.ack = s.seq + 1
|
||||
p.send(p.seq, tcpAck, nil, nil)
|
||||
return s.options
|
||||
}
|
||||
|
||||
// accepted is what a test gets of the connections that the stack hands over
|
||||
type accepted struct {
|
||||
conn net.Conn
|
||||
dest net.Destination
|
||||
}
|
||||
|
||||
func accept(conns chan accepted) func(net.Conn, net.Destination) {
|
||||
return func(conn net.Conn, dest net.Destination) { conns <- accepted{conn, dest} }
|
||||
}
|
||||
|
||||
func take(t *testing.T, conns chan accepted) accepted {
|
||||
t.Helper()
|
||||
select {
|
||||
case a := <-conns:
|
||||
return a
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("no connection from the stack")
|
||||
return accepted{}
|
||||
}
|
||||
}
|
||||
|
||||
func write(t *testing.T, conn net.Conn, payload []byte) {
|
||||
t.Helper()
|
||||
if err := conn.(buf.Writer).WriteMultiBuffer(buf.MergeBytes(nil, payload)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func read(t *testing.T, conn net.Conn, expected string) {
|
||||
t.Helper()
|
||||
mb, err := conn.(buf.Reader).ReadMultiBuffer()
|
||||
if err != nil || mb.String() != expected {
|
||||
t.Fatal("read ", mb.String(), ", expected ", expected, ", error: ", err)
|
||||
}
|
||||
buf.ReleaseMulti(mb)
|
||||
}
|
||||
|
||||
// The options of the SYN decide what the answer has, and both ends close the connection in turn.
|
||||
func TestTCPHandshakeAndClose(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
src, dst string
|
||||
options, expected []byte
|
||||
}{
|
||||
{"10.0.0.1:1234", "10.0.0.2:80", nil, []byte{2, 4, 5, 0xb4}},
|
||||
{"10.0.0.1:1234", "10.0.0.2:80", []byte{2, 4, 2, 0, 4, 2, 1, 3, 3, 7, 0, 0}, []byte{2, 4, 5, 0xb4, 1, 1, 4, 2, 1, 3, 3, tcpWindowShift}},
|
||||
{"[fd00::1]:1234", "[fd00::2]:80", []byte{2, 4, 5, 0xa0, 1, 3, 3, 7}, []byte{2, 4, 5, 0xa0, 1, 3, 3, tcpWindowShift}},
|
||||
} {
|
||||
conns := make(chan accepted, 1)
|
||||
p, l := newPeer(t, test.src, test.dst)
|
||||
s := newTestStack(t, l, accept(conns))
|
||||
if options := p.connect(test.options); !bytes.Equal(options, test.expected) {
|
||||
t.Fatal("options ", options, ", expected ", test.expected)
|
||||
}
|
||||
a := take(t, conns)
|
||||
if a.dest != net.TCPDestination(net.ParseAddress(p.dst.Addr().String()), net.Port(80)) || a.conn.RemoteAddr().String() != test.src {
|
||||
t.Fatal("connection from ", a.conn.RemoteAddr(), " to ", a.dest)
|
||||
}
|
||||
|
||||
// the system closes its side, what it sent is read first
|
||||
p.send(p.seq, tcpAck|tcpPsh|tcpFin, nil, []byte("abc"))
|
||||
p.seq += 4
|
||||
if s := p.receive(); s.flags != tcpAck || s.ack != p.seq {
|
||||
t.Fatal("the FIN is not acknowledged: flags ", s.flags, ", ack ", s.ack)
|
||||
}
|
||||
read(t, a.conn, "abc")
|
||||
if _, err := a.conn.(buf.Reader).ReadMultiBuffer(); err != io.EOF {
|
||||
t.Fatal("no end of the stream: ", err)
|
||||
}
|
||||
// the other side is still open
|
||||
write(t, a.conn, []byte("def"))
|
||||
if s := p.receive(); string(s.payload) != "def" || s.seq != p.ack || s.flags != tcpAck|tcpPsh {
|
||||
t.Fatal("wrong segment: seq ", s.seq, ", flags ", s.flags, ", payload ", s.payload)
|
||||
}
|
||||
p.ack += 3
|
||||
a.conn.Close()
|
||||
if s := p.receive(); s.flags != tcpFin|tcpAck || s.seq != p.ack {
|
||||
t.Fatal("not a FIN: flags ", s.flags, ", seq ", s.seq)
|
||||
}
|
||||
p.ack++
|
||||
// what the system sends again is not something that nobody reads anymore
|
||||
p.send(p.seq-4, tcpAck|tcpPsh|tcpFin, nil, []byte("abc"))
|
||||
if s := p.receive(); s.flags != tcpAck || s.ack != p.seq {
|
||||
t.Fatal("what was sent again is not acknowledged: flags ", s.flags, ", ack ", s.ack)
|
||||
}
|
||||
p.send(p.seq, tcpAck, nil, nil)
|
||||
forgotten(t, s)
|
||||
// what comes for it now is refused
|
||||
p.send(p.seq, tcpAck, nil, nil)
|
||||
if s := p.receive(); s.flags != tcpRst || s.seq != p.ack {
|
||||
t.Fatal("not a reset: flags ", s.flags, ", seq ", s.seq)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// What comes after a lost segment is kept and told to the system, and is read once the lost one comes.
|
||||
func TestTCPOutOfOrder(t *testing.T) {
|
||||
conns := make(chan accepted, 1)
|
||||
p, l := newPeer(t, "10.0.0.1:1234", "10.0.0.2:80")
|
||||
newTestStack(t, l, accept(conns))
|
||||
p.connect([]byte{2, 4, 5, 0xb4, 4, 2, 0, 0})
|
||||
a := take(t, conns)
|
||||
|
||||
sack := func(s segment, blocks ...uint32) {
|
||||
t.Helper()
|
||||
expected := []byte{1, 1, 5, byte(2 + 4*len(blocks))}
|
||||
for _, edge := range blocks {
|
||||
expected = binary.BigEndian.AppendUint32(expected, edge)
|
||||
}
|
||||
if s.flags != tcpAck || s.ack != p.seq || !bytes.Equal(s.options, expected) {
|
||||
t.Fatal("ack ", s.ack, " with options ", s.options, ", expected ", p.seq, " with ", expected)
|
||||
}
|
||||
}
|
||||
// "abc" is lost, then "ghi" and "def" come, each told with the block that it is in first
|
||||
p.send(p.seq+6, tcpAck, nil, []byte("ghi"))
|
||||
sack(p.receive(), p.seq+6, p.seq+9)
|
||||
p.send(p.seq+12, tcpAck, nil, []byte("mno"))
|
||||
sack(p.receive(), p.seq+12, p.seq+15, p.seq+6, p.seq+9)
|
||||
p.send(p.seq+3, tcpAck, nil, []byte("def"))
|
||||
sack(p.receive(), p.seq+3, p.seq+9, p.seq+12, p.seq+15)
|
||||
// the same again changes nothing
|
||||
p.send(p.seq+3, tcpAck, nil, []byte("defg"))
|
||||
sack(p.receive(), p.seq+3, p.seq+9, p.seq+12, p.seq+15)
|
||||
|
||||
p.send(p.seq, tcpAck, nil, []byte("abc"))
|
||||
p.seq += 9
|
||||
sack(p.receive(), p.seq+3, p.seq+6)
|
||||
read(t, a.conn, "abcdefghi")
|
||||
p.send(p.seq, tcpAck, nil, []byte("jklm"))
|
||||
p.seq += 6
|
||||
if s := p.receive(); s.ack != p.seq || len(s.options) != 0 {
|
||||
t.Fatal("ack ", s.ack, " with options ", s.options)
|
||||
}
|
||||
read(t, a.conn, "jklmno")
|
||||
}
|
||||
|
||||
// A segment is as large as the system makes it when the tun does not split what it reads.
|
||||
func TestTCPLargeSegment(t *testing.T) {
|
||||
conns := make(chan accepted, 1)
|
||||
p, l := newPeer(t, "10.0.0.1:1234", "10.0.0.2:80")
|
||||
newTestStack(t, l, accept(conns))
|
||||
p.connect(nil)
|
||||
a := take(t, conns)
|
||||
|
||||
sent := make([]byte, 60000)
|
||||
rand.Read(sent)
|
||||
p.send(p.seq, tcpAck|tcpPsh, nil, sent)
|
||||
var received []byte
|
||||
for len(received) < len(sent) {
|
||||
mb, err := a.conn.(buf.Reader).ReadMultiBuffer()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, b := range mb {
|
||||
received = append(received, b.Bytes()...)
|
||||
}
|
||||
buf.ReleaseMulti(mb)
|
||||
}
|
||||
if !bytes.Equal(received, sent) {
|
||||
t.Fatal("read something else than what was sent")
|
||||
}
|
||||
}
|
||||
|
||||
// What the system does not acknowledge is sent again: at once when it says what it has past it, or after a while.
|
||||
func TestTCPRetransmit(t *testing.T) {
|
||||
conns := make(chan accepted, 1)
|
||||
p, l := newPeer(t, "10.0.0.1:1234", "10.0.0.2:80")
|
||||
newTestStack(t, l, accept(conns))
|
||||
p.connect([]byte{2, 4, 0, 100, 4, 2, 0, 0})
|
||||
a := take(t, conns)
|
||||
|
||||
sent := make([]byte, 450)
|
||||
rand.Read(sent)
|
||||
go func() {
|
||||
if err := a.conn.(buf.Writer).WriteMultiBuffer(buf.MergeBytes(nil, sent)); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
for i := 0; i < 5; i++ {
|
||||
limit := 100
|
||||
if i == 4 {
|
||||
limit = 50
|
||||
}
|
||||
if s := p.receive(); s.seq != p.ack+uint32(100*i) || !bytes.Equal(s.payload, sent[100*i:100*i+limit]) {
|
||||
t.Fatal("segment ", i, ": seq ", s.seq-p.ack, " with ", len(s.payload), " bytes")
|
||||
}
|
||||
}
|
||||
// the second and the third segment are lost
|
||||
p.ack += 100
|
||||
p.send(p.seq, tcpAck, nil, nil)
|
||||
block := func(from, to uint32) []byte {
|
||||
b := []byte{1, 1, 5, 10}
|
||||
return binary.BigEndian.AppendUint32(binary.BigEndian.AppendUint32(b, from), to)
|
||||
}
|
||||
p.send(p.seq, tcpAck, block(p.ack+200, p.ack+350), nil)
|
||||
for i := 1; i < 3; i++ {
|
||||
if s := p.receive(); s.seq != p.ack+uint32(100*(i-1)) || !bytes.Equal(s.payload, sent[100*i:100*i+100]) {
|
||||
t.Fatal("segment ", i, " sent again: seq ", s.seq-p.ack, " with ", len(s.payload), " bytes")
|
||||
}
|
||||
}
|
||||
// said again, it is not sent again
|
||||
p.send(p.seq, tcpAck, block(p.ack+200, p.ack+350), nil)
|
||||
p.silent(tcpTick)
|
||||
// the one that was sent again came, the other one did not: it is sent after a while, without what the system has
|
||||
p.ack += 100
|
||||
p.send(p.seq, tcpAck, block(p.ack+100, p.ack+250), nil)
|
||||
p.silent(tcpTick)
|
||||
if s := p.receive(); s.seq != p.ack || !bytes.Equal(s.payload, sent[200:300]) {
|
||||
t.Fatal("segment 2 sent again later: seq ", s.seq-p.ack, " with ", len(s.payload), " bytes")
|
||||
}
|
||||
p.ack += 250
|
||||
p.send(p.seq, tcpAck, nil, nil)
|
||||
p.silent(2 * tcpRetransmitTicks * tcpTick)
|
||||
}
|
||||
|
||||
// No more is sent at once than has arrived before: twice as much when all of it arrives, half of it after a loss.
|
||||
func TestTCPCongestion(t *testing.T) {
|
||||
conns := make(chan accepted, 1)
|
||||
p, l := newPeer(t, "10.0.0.1:1234", "10.0.0.2:80")
|
||||
newTestStack(t, l, accept(conns))
|
||||
p.connect([]byte{2, 4, 0, 100, 4, 2, 0, 0})
|
||||
a := take(t, conns)
|
||||
|
||||
go a.conn.(buf.Writer).WriteMultiBuffer(buf.MergeBytes(nil, make([]byte, 8000)))
|
||||
// next is where what is new starts
|
||||
next := p.ack
|
||||
segments := func(seqs ...uint32) {
|
||||
t.Helper()
|
||||
for _, seq := range seqs {
|
||||
if s := p.receive(); s.seq != seq || len(s.payload) != 100 {
|
||||
t.Fatal("seq ", s.seq-p.ack, " with ", len(s.payload), " bytes, expected ", seq-p.ack, " with 100")
|
||||
}
|
||||
}
|
||||
p.silent(tcpTick / 2)
|
||||
}
|
||||
fresh := func(n int) (seqs []uint32) {
|
||||
for ; n > 0; n-- {
|
||||
seqs = append(seqs, next)
|
||||
next += 100
|
||||
}
|
||||
return
|
||||
}
|
||||
segments(fresh(tcpStart)...)
|
||||
p.ack = next
|
||||
p.send(p.seq, tcpAck, nil, nil)
|
||||
segments(fresh(2 * tcpStart)...)
|
||||
// the first of them is lost: it is sent again, and with what is new there is half as much on its way as before
|
||||
p.send(p.seq, tcpAck, binary.BigEndian.AppendUint32(binary.BigEndian.AppendUint32([]byte{1, 1, 5, 10}, p.ack+100), next), nil)
|
||||
segments(append([]uint32{p.ack}, fresh(tcpStart-1)...)...)
|
||||
// from then on a segment more for as much as there was on its way, and never a part of one
|
||||
p.ack = next
|
||||
p.send(p.seq, tcpAck, nil, nil)
|
||||
segments(fresh(tcpStart + 2)...)
|
||||
}
|
||||
|
||||
// No more is sent than the system takes, and the writer goes on when it takes more.
|
||||
// The FIN that comes with a segment before the one in front of it is taken when that one has come.
|
||||
func TestTCPEndOutOfOrder(t *testing.T) {
|
||||
conns := make(chan accepted, 1)
|
||||
p, l := newPeer(t, "10.0.0.1:1234", "10.0.0.2:80")
|
||||
newTestStack(t, l, accept(conns))
|
||||
p.connect(nil)
|
||||
a := take(t, conns)
|
||||
p.send(p.seq+3, tcpAck|tcpFin, nil, []byte("def"))
|
||||
if s := p.receive(); s.ack != p.seq {
|
||||
t.Fatal("ack ", s.ack, ", expected ", p.seq)
|
||||
}
|
||||
p.send(p.seq, tcpAck, nil, []byte("abc"))
|
||||
p.seq += 7
|
||||
if s := p.receive(); s.ack != p.seq {
|
||||
t.Fatal("ack ", s.ack, ", expected ", p.seq, " with the end")
|
||||
}
|
||||
read(t, a.conn, "abcdef")
|
||||
if _, err := a.conn.(buf.Reader).ReadMultiBuffer(); err != io.EOF {
|
||||
t.Fatal("no end after what was read: ", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The answer to the SYN-ACK tells how far the system is, and a segment is not sent again before
|
||||
// its acknowledgment had the time to come from there.
|
||||
func TestTCPRoundTrip(t *testing.T) {
|
||||
conns := make(chan accepted, 1)
|
||||
p, l := newPeer(t, "10.0.0.1:1234", "10.0.0.2:80")
|
||||
newTestStack(t, l, accept(conns))
|
||||
p.send(p.seq, tcpSyn, nil, nil)
|
||||
p.seq++
|
||||
p.ack = p.receive().seq + 1
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
p.send(p.seq, tcpAck, nil, nil)
|
||||
a := take(t, conns)
|
||||
write(t, a.conn, []byte("abc"))
|
||||
for range 2 {
|
||||
if s := p.receive(); s.seq != p.ack || string(s.payload) != "abc" {
|
||||
t.Fatal("seq ", s.seq, " with ", s.payload)
|
||||
}
|
||||
p.silent(350 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// A peer that says its segments are tiny is not believed all the way.
|
||||
func TestTCPSmallestSegment(t *testing.T) {
|
||||
conns := make(chan accepted, 1)
|
||||
p, l := newPeer(t, "10.0.0.1:1234", "10.0.0.2:80")
|
||||
newTestStack(t, l, accept(conns))
|
||||
p.connect([]byte{2, 4, 0, 1})
|
||||
a := take(t, conns)
|
||||
write(t, a.conn, make([]byte, 100))
|
||||
if s := p.receive(); len(s.payload) != tcpSmallest {
|
||||
t.Fatal("a segment of ", len(s.payload), " bytes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTCPWindow(t *testing.T) {
|
||||
conns := make(chan accepted, 1)
|
||||
p, l := newPeer(t, "10.0.0.1:1234", "10.0.0.2:80")
|
||||
newTestStack(t, l, accept(conns))
|
||||
p.window = 250
|
||||
p.connect(nil)
|
||||
a := take(t, conns)
|
||||
|
||||
sent := make([]byte, 1000)
|
||||
rand.Read(sent)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
if err := a.conn.(buf.Writer).WriteMultiBuffer(buf.MergeBytes(nil, sent)); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
close(done)
|
||||
}()
|
||||
var received []byte
|
||||
for len(received) < len(sent) {
|
||||
for space := 250; space > 0; {
|
||||
s := p.receive()
|
||||
if s.seq != p.ack || len(s.payload) > space {
|
||||
t.Fatal("seq ", s.seq, " with ", len(s.payload), " bytes, expected ", p.ack, " with ", space, " at most")
|
||||
}
|
||||
received = append(received, s.payload...)
|
||||
p.ack += uint32(len(s.payload))
|
||||
space -= len(s.payload)
|
||||
}
|
||||
// nothing more before the window opens
|
||||
p.silent(tcpTick / 2)
|
||||
p.send(p.seq, tcpAck, nil, nil)
|
||||
}
|
||||
<-done
|
||||
if !bytes.Equal(received, sent) {
|
||||
t.Fatal("received something else than what was written")
|
||||
}
|
||||
|
||||
// the time that the window was closed is not time without an acknowledgment of what is sent after it.
|
||||
// It is closed with a keepalive: that is answered, so the stack has seen it before something is written
|
||||
p.window = 0
|
||||
p.send(p.seq-1, tcpAck, nil, nil)
|
||||
p.receive()
|
||||
done = make(chan struct{})
|
||||
go func() {
|
||||
if err := a.conn.(buf.Writer).WriteMultiBuffer(buf.MergeBytes(nil, []byte("abc"))); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
close(done)
|
||||
}()
|
||||
p.silent(4 * tcpTick)
|
||||
p.window = 250
|
||||
p.send(p.seq, tcpAck, nil, nil)
|
||||
if s := p.receive(); s.seq != p.ack || string(s.payload) != "abc" {
|
||||
t.Fatal("seq ", s.seq, " with ", s.payload)
|
||||
}
|
||||
<-done
|
||||
p.silent(tcpTick + tcpTick/2)
|
||||
}
|
||||
|
||||
// A keepalive is answered, and not before a segment that was made before it is written.
|
||||
func TestTCPKeepalive(t *testing.T) {
|
||||
conns := make(chan accepted, 1)
|
||||
p, l := newPeer(t, "10.0.0.1:1234", "10.0.0.2:80")
|
||||
// the write of the segment with what is written below takes until it is let go
|
||||
out, writing, written := l.out, make(chan struct{}), make(chan struct{})
|
||||
l.out = func(b []byte) {
|
||||
if b[ipv4HeaderSize+13]&tcpPsh != 0 {
|
||||
close(writing)
|
||||
<-written
|
||||
}
|
||||
out(b)
|
||||
}
|
||||
newTestStack(t, l, accept(conns))
|
||||
p.connect(nil)
|
||||
a := take(t, conns)
|
||||
|
||||
p.send(p.seq-1, tcpAck, nil, nil)
|
||||
if s := p.receive(); s.flags != tcpAck || s.seq != p.ack || s.ack != p.seq {
|
||||
t.Fatal("not an answer to the keepalive: flags ", s.flags, ", seq ", s.seq, ", ack ", s.ack)
|
||||
}
|
||||
|
||||
go func() {
|
||||
if err := a.conn.(buf.Writer).WriteMultiBuffer(buf.MergeBytes(nil, []byte("abc"))); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
<-writing
|
||||
p.send(p.seq-1, tcpAck, nil, nil)
|
||||
p.silent(tcpTick / 2)
|
||||
close(written)
|
||||
if s := p.receive(); string(s.payload) != "abc" || s.seq != p.ack {
|
||||
t.Fatal("wrong segment: seq ", s.seq, ", flags ", s.flags, ", payload ", s.payload)
|
||||
}
|
||||
p.ack += 3
|
||||
if s := p.receive(); s.flags != tcpAck || s.seq != p.ack || s.ack != p.seq || len(s.payload) != 0 {
|
||||
t.Fatal("not an answer to the keepalive: flags ", s.flags, ", seq ", s.seq, ", ack ", s.ack)
|
||||
}
|
||||
p.send(p.seq, tcpAck, nil, nil)
|
||||
}
|
||||
|
||||
// A reset ends the connection for its reader, and a connection that is closed with something unread is reset.
|
||||
func TestTCPReset(t *testing.T) {
|
||||
conns := make(chan accepted, 1)
|
||||
p, l := newPeer(t, "10.0.0.1:1234", "10.0.0.2:80")
|
||||
s := newTestStack(t, l, accept(conns))
|
||||
p.connect(nil)
|
||||
a := take(t, conns)
|
||||
// a reset from somewhere else than where the connection is changes nothing
|
||||
p.send(p.seq+tcpWindow+1, tcpRst, nil, nil)
|
||||
p.send(p.seq-1, tcpRst, nil, nil)
|
||||
p.send(p.seq, tcpAck|tcpPsh, nil, []byte("abc"))
|
||||
p.seq += 3
|
||||
read(t, a.conn, "abc")
|
||||
if s := p.receive(); s.flags != tcpAck || s.ack != p.seq {
|
||||
t.Fatal("not acknowledged: flags ", s.flags, ", ack ", s.ack)
|
||||
}
|
||||
p.send(p.seq, tcpRst, nil, nil)
|
||||
if _, err := a.conn.(buf.Reader).ReadMultiBuffer(); err == nil || err == io.EOF {
|
||||
t.Fatal("no error after the reset: ", err)
|
||||
}
|
||||
a.conn.Close()
|
||||
forgotten(t, s)
|
||||
|
||||
// what came before the reset is read, to its end
|
||||
p.src = netip.MustParseAddrPort("10.0.0.1:1236")
|
||||
p.connect(nil)
|
||||
a = take(t, conns)
|
||||
p.send(p.seq, tcpAck|tcpPsh|tcpFin, nil, []byte("abc"))
|
||||
p.seq += 4
|
||||
if s := p.receive(); s.flags != tcpAck || s.ack != p.seq {
|
||||
t.Fatal("not acknowledged: flags ", s.flags, ", ack ", s.ack)
|
||||
}
|
||||
// with the number of the FIN, as the answer to a segment that was made before the FIN came
|
||||
p.send(p.seq-1, tcpRst, nil, nil)
|
||||
forgotten(t, s)
|
||||
read(t, a.conn, "abc")
|
||||
if _, err := a.conn.(buf.Reader).ReadMultiBuffer(); err != io.EOF {
|
||||
t.Fatal("no end after what was read: ", err)
|
||||
}
|
||||
a.conn.Close()
|
||||
|
||||
p.src = netip.MustParseAddrPort("10.0.0.1:1235")
|
||||
p.connect(nil)
|
||||
a = take(t, conns)
|
||||
p.send(p.seq, tcpAck|tcpPsh, nil, []byte("abc"))
|
||||
p.seq += 3
|
||||
// the timer acknowledges what nobody reads
|
||||
if s := p.receive(); s.flags != tcpAck || s.ack != p.seq {
|
||||
t.Fatal("not acknowledged: flags ", s.flags, ", ack ", s.ack)
|
||||
}
|
||||
a.conn.Close()
|
||||
if s := p.receive(); s.flags != tcpRst|tcpAck || s.seq != p.ack {
|
||||
t.Fatal("not a reset: flags ", s.flags, ", seq ", s.seq)
|
||||
}
|
||||
forgotten(t, s)
|
||||
|
||||
// one that the system gives up before it is open is not one that is being opened anymore
|
||||
p.src = netip.MustParseAddrPort("10.0.0.1:1237")
|
||||
p.send(p.seq, tcpSyn, nil, nil)
|
||||
p.seq++
|
||||
p.receive()
|
||||
p.send(p.seq, tcpRst, nil, nil)
|
||||
forgotten(t, s)
|
||||
}
|
||||
|
||||
// A UDP packet starts a connection, which answers from any address, and an echo request is answered.
|
||||
func TestUDPAndICMP(t *testing.T) {
|
||||
for _, test := range []struct{ src, dst, other string }{
|
||||
{"10.0.0.1:1234", "10.0.0.2:53", "10.0.0.3:5353"},
|
||||
{"[fd00::1]:1234", "[fd00::2]:53", "[fd00::3]:5353"},
|
||||
} {
|
||||
conns := make(chan accepted, 1)
|
||||
p, l := newPeer(t, test.src, test.dst)
|
||||
newTestStack(t, l, accept(conns))
|
||||
|
||||
var b [ipv6HeaderSize + udpHeaderSize]byte
|
||||
n := putIPHeader(b[:], protoUDP, p.src.Addr(), p.dst.Addr())
|
||||
u := b[n : n+udpHeaderSize]
|
||||
binary.BigEndian.PutUint16(u, p.src.Port())
|
||||
binary.BigEndian.PutUint16(u[2:], p.dst.Port())
|
||||
binary.BigEndian.PutUint16(u[4:], udpHeaderSize+3)
|
||||
setIPLength(b[:n], n+udpHeaderSize+3)
|
||||
l.in <- append(b[:n+udpHeaderSize:n+udpHeaderSize], "abc"...)
|
||||
a := take(t, conns)
|
||||
mb, err := a.conn.(buf.Reader).ReadMultiBuffer()
|
||||
if err != nil || mb.String() != "abc" || *mb[0].UDP != a.dest || a.dest.NetAddr() != test.dst || a.conn.RemoteAddr().String() != test.src {
|
||||
t.Fatal("read ", mb.String(), " from ", a.conn.RemoteAddr(), " to ", a.dest, ", error: ", err)
|
||||
}
|
||||
buf.ReleaseMulti(mb)
|
||||
|
||||
for _, from := range []string{test.dst, test.other} {
|
||||
answer := buf.FromBytes([]byte("defg"))
|
||||
source := net.UDPDestination(net.ParseAddress(netip.MustParseAddrPort(from).Addr().String()), net.Port(netip.MustParseAddrPort(from).Port()))
|
||||
answer.UDP = &source
|
||||
if err := a.conn.(buf.Writer).WriteMultiBuffer(buf.MultiBuffer{answer}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw := p.packet()
|
||||
packet, ok := parsePacket(raw)
|
||||
u := packet.payload
|
||||
// the system may have to split it on the way to where it goes
|
||||
if !ok || raw[0]>>4 == 4 && raw[6] != 0 || packet.proto != protoUDP || netip.AddrPortFrom(packet.src, binary.BigEndian.Uint16(u)).String() != from ||
|
||||
netip.AddrPortFrom(packet.dst, binary.BigEndian.Uint16(u[2:])) != p.src || string(u[udpHeaderSize:]) != "defg" {
|
||||
t.Fatal("wrong packet from ", from, ": ", packet)
|
||||
}
|
||||
var ip [ipv6HeaderSize]byte
|
||||
if size := putIPHeader(ip[:], protoUDP, packet.src, packet.dst); transportChecksum(ip[:size], protoUDP, u, nil) != 0 {
|
||||
t.Fatal("wrong checksum of the packet from ", from)
|
||||
}
|
||||
}
|
||||
a.conn.Close()
|
||||
|
||||
proto, request, reply := byte(protoICMPv4), byte(8), byte(0)
|
||||
if p.src.Addr().Is6() {
|
||||
proto, request, reply = protoICMPv6, 128, 129
|
||||
}
|
||||
n = putIPHeader(b[:], proto, p.src.Addr(), p.dst.Addr())
|
||||
setIPLength(b[:n], n+12)
|
||||
l.in <- append(b[:n:n], request, 0, 0, 0, 1, 2, 3, 4, 'a', 'b', 'c', 'd')
|
||||
packet, ok := parsePacket(p.packet())
|
||||
m := packet.payload
|
||||
if !ok || packet.proto != proto || packet.src != p.dst.Addr() || packet.dst != p.src.Addr() || m[0] != reply || string(m[4:]) != "\x01\x02\x03\x04abcd" {
|
||||
t.Fatal("wrong echo reply: ", packet)
|
||||
}
|
||||
var ip [ipv6HeaderSize]byte
|
||||
size := putIPHeader(ip[:], proto, packet.src, packet.dst)
|
||||
if proto == protoICMPv4 && checksum(sum(m, 0)) != 0 || proto == protoICMPv6 && transportChecksum(ip[:size], proto, m, nil) != 0 {
|
||||
t.Fatal("wrong checksum of the echo reply")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The checksum is that of the 16-bit words added one by one.
|
||||
func TestChecksum(t *testing.T) {
|
||||
b := make([]byte, 5000)
|
||||
rand.Read(b)
|
||||
for size := 0; size < len(b); size += 1 + size/64 {
|
||||
expected := uint32(size)
|
||||
for i := 0; i < size; i += 2 {
|
||||
expected += uint32(b[i]) << 8
|
||||
if i+1 < size {
|
||||
expected += uint32(b[i+1])
|
||||
}
|
||||
expected = expected>>16 + expected&0xffff
|
||||
}
|
||||
if got := checksum(sum(b[:size], uint64(size))); got != ^uint16(expected) {
|
||||
t.Fatal("checksum of ", size, " bytes: ", got, ", expected ", ^uint16(expected))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,999 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"math"
|
||||
"math/rand/v2"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
)
|
||||
|
||||
const (
|
||||
tcpFin = 1 << iota
|
||||
tcpSyn
|
||||
tcpRst
|
||||
tcpPsh
|
||||
tcpAck
|
||||
)
|
||||
|
||||
const (
|
||||
// tcpWindow is what a connection takes from the system before its reader has to take it,
|
||||
// and the most that it sends to the system before that is acknowledged. More than that, for several
|
||||
// connections at once, is more packets than the queue of a tun holds (500 on Linux)
|
||||
tcpWindow = 256 << 10
|
||||
// tcpLargeWindow is the same for a tun that takes and gives segments that are larger than its MTU: those are
|
||||
// few, and a way with a longer round trip, as a router has to what is behind it, is not held back by it
|
||||
tcpLargeWindow = 1 << 20
|
||||
// tcpWindowShift makes them fit the 16 bits of a window
|
||||
tcpWindowShift = 5
|
||||
// tcpHeld is how many segments wait for one that was lost before them,
|
||||
// and of how many parts what the system says it has is known
|
||||
tcpHeld = 1024
|
||||
// tcpSmallest is the smallest mss that the system is believed, the one of Linux
|
||||
tcpSmallest = 48
|
||||
// tcpOpening is how many connections can be waiting for the answer to their SYN-ACK
|
||||
tcpOpening = 65535
|
||||
// tcpStart is how many segments are sent before any of them is acknowledged
|
||||
tcpStart = 10
|
||||
// tcpSegment is the largest payload of a segment that the tun splits by itself,
|
||||
// tcpParts of how many parts of what was written it is made at most
|
||||
tcpSegment = math.MaxUint16 - ipv6HeaderSize - tcpHeaderSize
|
||||
tcpParts = 7
|
||||
|
||||
// tcpTick is how often a connection that waits for something looks at what it waits for
|
||||
tcpTick = 100 * time.Millisecond
|
||||
// ticks without anything acknowledged before it is sent again, twice as many every next time, a minute at most
|
||||
tcpRetransmitTicks = 3
|
||||
tcpRetransmitTicksMost = 600
|
||||
// how many times it is sent again before the connection is given up: that is after four minutes, as what is
|
||||
// behind a wireless link may be away for a while, and after twenty seconds for one that never answered
|
||||
tcpRetransmits = 10
|
||||
tcpSynRetransmits = 5
|
||||
// ticks between the probes of a window that stays closed
|
||||
tcpProbeTicks = 10
|
||||
// tcpLinger is how long a closed connection waits for the system to close its side
|
||||
tcpLinger = 30 * time.Second
|
||||
)
|
||||
|
||||
var (
|
||||
errTCPReset = errors.New("connection reset")
|
||||
errTCPTimeout = errors.New("connection timed out")
|
||||
)
|
||||
|
||||
// segment is a TCP segment that came from the tun
|
||||
type segment struct {
|
||||
seq, ack uint32
|
||||
flags byte
|
||||
window uint16
|
||||
options []byte
|
||||
payload []byte
|
||||
}
|
||||
|
||||
// nextOption returns the first option of o and what follows it, kind is zero when there is none
|
||||
func nextOption(o []byte) (kind byte, value, rest []byte) {
|
||||
for len(o) > 0 && o[0] == 1 {
|
||||
o = o[1:]
|
||||
}
|
||||
if len(o) < 2 || int(o[1]) < 2 || int(o[1]) > len(o) {
|
||||
return 0, nil, nil
|
||||
}
|
||||
return o[0], o[2:o[1]], o[o[1]:]
|
||||
}
|
||||
|
||||
// held is a segment that came before the one in front of it
|
||||
type held struct {
|
||||
seq uint32
|
||||
data *buf.Buffer
|
||||
}
|
||||
|
||||
// tcpConn is a TCP connection that the system opened through the tun.
|
||||
// Mostly the two are on the same machine, with nothing but the queue of the tun in between, which drops what
|
||||
// does not fit. But the system may also pass on what others send, as a router does, and then the link to them
|
||||
// is in between. So a connection has windows that are small enough, keeps what came after a lost segment,
|
||||
// tells the system what it has (SACK), sends again what the system misses, and sends no more at once
|
||||
// than what has arrived before (slow start and congestion avoidance as in RFC 5681)
|
||||
type tcpConn struct {
|
||||
stack *stack
|
||||
flow flow
|
||||
src, dst net.Destination
|
||||
// ip is the IP header of what is sent, without the length
|
||||
ip [ipv6HeaderSize]byte
|
||||
// ipSize is the size of that header
|
||||
ipSize int
|
||||
// mss is the largest payload of a segment that is sent
|
||||
mss int
|
||||
// window is tcpWindow or tcpLargeWindow
|
||||
window int32
|
||||
// sndShift and rcvShift are the window scale of what the system and we advertise
|
||||
sndShift, rcvShift uint8
|
||||
// sack is set if the system takes selective acknowledgments
|
||||
sack bool
|
||||
|
||||
mu sync.Mutex
|
||||
readable sync.Cond
|
||||
writable sync.Cond
|
||||
|
||||
established bool
|
||||
// closed is set when Close is called
|
||||
closed bool
|
||||
// err is why the connection is gone
|
||||
err error
|
||||
|
||||
rcvNxt uint32
|
||||
// rcvAcked is the last acknowledgment number sent
|
||||
rcvAcked uint32
|
||||
// rcvAdvertised is the last window sent, in bytes
|
||||
rcvAdvertised int32
|
||||
rcvQueue buf.MultiBuffer
|
||||
rcvLen int32
|
||||
rcvFin bool
|
||||
// rcvEnd is where what the system sends ends, if rcvEnds: its FIN came with a segment that waits in rcvHeld
|
||||
rcvEnd uint32
|
||||
rcvEnds bool
|
||||
// rcvHeld is what came after something that did not, in the order of seq and without overlaps
|
||||
rcvHeld []held
|
||||
// rcvLast is the seq of the last one that was put into rcvHeld
|
||||
rcvLast uint32
|
||||
|
||||
sndUna, sndNxt uint32
|
||||
sndWnd uint32
|
||||
// sndQueue is what was sent and is not acknowledged
|
||||
sndQueue buf.MultiBuffer
|
||||
// sndBase is the sequence number of the first byte of sndQueue
|
||||
sndBase uint32
|
||||
sndFin bool
|
||||
// writing is how many of the last of sndQueue WriteMultiBuffer is sending, it is the only one to release them
|
||||
writing int
|
||||
// blocked is set while WriteMultiBuffer waits for the window
|
||||
blocked bool
|
||||
// sending is set while WriteMultiBuffer writes a segment without mu, ackWanted if sendAck was called meanwhile
|
||||
sending, ackWanted bool
|
||||
dupAcks int
|
||||
// cwnd is how much the way to the system takes at once, as far as that is known: it grows while what is sent
|
||||
// arrives, by as much as arrives below ssthresh, and is cut when something is lost
|
||||
cwnd, ssthresh uint32
|
||||
// sacked is what the system says it has past sndUna, in order and apart from each other
|
||||
sacked [][2]uint32
|
||||
// recovering is set from a sign of loss until what was sent by then, up to recover, is acknowledged
|
||||
recovering bool
|
||||
recover uint32
|
||||
// lost is the end of what is lost past the last of sacked, resent the end of what was sent again since then
|
||||
lost, resent uint32
|
||||
// timed is the end of a segment that was sent at timedAt and not again, to see how long its acknowledgment takes.
|
||||
// The first one is the SYN-ACK
|
||||
timed uint32
|
||||
timedAt time.Time
|
||||
// srtt is how long an acknowledgment takes, rttvar how much that varies (RFC 6298)
|
||||
srtt, rttvar time.Duration
|
||||
|
||||
timer *time.Timer
|
||||
armed bool
|
||||
// stalled counts ticks without an acknowledgment of what waits for one
|
||||
stalled, retransmitTicks, retransmits int
|
||||
lingered bool
|
||||
}
|
||||
|
||||
func newTCPConn(s *stack, f flow, syn segment) *tcpConn {
|
||||
c := &tcpConn{
|
||||
stack: s,
|
||||
flow: f,
|
||||
src: net.TCPDestination(net.IPAddress(f.src.Addr().AsSlice()), net.Port(f.src.Port())),
|
||||
dst: net.TCPDestination(net.IPAddress(f.dst.Addr().AsSlice()), net.Port(f.dst.Port())),
|
||||
rcvNxt: syn.seq + 1,
|
||||
sndWnd: uint32(syn.window),
|
||||
window: s.window,
|
||||
ssthresh: uint32(s.window),
|
||||
timedAt: time.Now(),
|
||||
retransmitTicks: tcpRetransmitTicks,
|
||||
}
|
||||
c.readable.L = &c.mu
|
||||
c.writable.L = &c.mu
|
||||
c.ipSize = putIPHeader(c.ip[:], protoTCP, f.dst.Addr(), f.src.Addr())
|
||||
c.mss = s.mtu - c.ipSize - tcpHeaderSize
|
||||
for kind, value, o := nextOption(syn.options); kind != 0; kind, value, o = nextOption(o) {
|
||||
switch {
|
||||
case kind == 2 && len(value) == 2:
|
||||
c.mss = min(c.mss, int(binary.BigEndian.Uint16(value)))
|
||||
case kind == 3 && len(value) == 1:
|
||||
c.sndShift = min(value[0], 14)
|
||||
c.rcvShift = tcpWindowShift
|
||||
case kind == 4:
|
||||
c.sack = true
|
||||
}
|
||||
}
|
||||
c.mss = max(c.mss, tcpSmallest)
|
||||
c.cwnd = tcpStart * uint32(c.mss)
|
||||
c.sndUna = rand.Uint32()
|
||||
c.sndNxt = c.sndUna + 1
|
||||
return c
|
||||
}
|
||||
|
||||
// header writes the headers of a segment with size bytes of payload into b and returns their size.
|
||||
// The checksum of the segment is left to write. c.mu is held
|
||||
func (c *tcpConn) header(b []byte, seq uint32, flags byte, options []byte, size int) int {
|
||||
n := copy(b, c.ip[:c.ipSize])
|
||||
t := b[n : n+tcpHeaderSize+len(options)]
|
||||
binary.BigEndian.PutUint16(t, c.flow.dst.Port())
|
||||
binary.BigEndian.PutUint16(t[2:], c.flow.src.Port())
|
||||
binary.BigEndian.PutUint32(t[4:], seq)
|
||||
binary.BigEndian.PutUint32(t[8:], c.rcvNxt)
|
||||
t[12] = byte(len(t)/4) << 4
|
||||
t[13] = flags
|
||||
window := max(c.window-c.rcvLen, 0)
|
||||
if flags&tcpSyn != 0 {
|
||||
// the window of a SYN is not scaled
|
||||
binary.BigEndian.PutUint16(t[14:], uint16(min(window, math.MaxUint16)))
|
||||
} else {
|
||||
binary.BigEndian.PutUint16(t[14:], uint16(min(window>>c.rcvShift, math.MaxUint16)))
|
||||
}
|
||||
t[16], t[17], t[18], t[19] = 0, 0, 0, 0
|
||||
copy(t[tcpHeaderSize:], options)
|
||||
setIPLength(b[:n], n+len(t)+size)
|
||||
c.rcvAcked = c.rcvNxt
|
||||
c.rcvAdvertised = window
|
||||
return n + len(t)
|
||||
}
|
||||
|
||||
// write completes the headers h with the checksum of the segment and writes it to the tun.
|
||||
// A segment that is not written is one that is lost: it is sent again when it is not acknowledged
|
||||
func (c *tcpConn) write(h, payload []byte) {
|
||||
t := h[c.ipSize:]
|
||||
binary.BigEndian.PutUint16(t[16:], transportChecksum(h[:c.ipSize], protoTCP, t, payload))
|
||||
_ = c.stack.tun.WritePacket(h, payload)
|
||||
}
|
||||
|
||||
// send writes a segment to the tun. c.mu is held
|
||||
func (c *tcpConn) send(seq uint32, flags byte, options, payload []byte) {
|
||||
var b [ipv6HeaderSize + tcpHeaderSize + 40]byte
|
||||
c.write(b[:c.header(b[:], seq, flags, options, len(payload))], payload)
|
||||
}
|
||||
|
||||
func (c *tcpConn) sendSynAck() {
|
||||
options := [12]byte{2, 4}
|
||||
binary.BigEndian.PutUint16(options[2:], uint16(c.stack.mtu-c.ipSize-tcpHeaderSize))
|
||||
n := 4
|
||||
if c.sack {
|
||||
n += copy(options[n:], []byte{1, 1, 4, 2})
|
||||
}
|
||||
if c.rcvShift != 0 {
|
||||
n += copy(options[n:], []byte{1, 3, 3, c.rcvShift})
|
||||
}
|
||||
c.send(c.sndUna, tcpSyn|tcpAck, options[:n], nil)
|
||||
}
|
||||
|
||||
// sendAck acknowledges what was received, and tells what of rcvHeld waits for a lost segment
|
||||
func (c *tcpConn) sendAck() {
|
||||
if c.sending {
|
||||
// after the segment that is being written: it was made before, and what the system is told goes in that order
|
||||
c.ackWanted = true
|
||||
return
|
||||
}
|
||||
if !c.sack || len(c.rcvHeld) == 0 {
|
||||
c.send(c.sndNxt, tcpAck, nil, nil)
|
||||
return
|
||||
}
|
||||
// the block with the segment that came last goes first
|
||||
var blocks [4][2]uint32
|
||||
n, last := 1, false
|
||||
for i := 0; i < len(c.rcvHeld); {
|
||||
start, end, recent := c.rcvHeld[i].seq, c.rcvHeld[i].seq, false
|
||||
for ; i < len(c.rcvHeld) && c.rcvHeld[i].seq == end; i++ {
|
||||
recent = recent || end == c.rcvLast
|
||||
end += uint32(c.rcvHeld[i].data.Len())
|
||||
}
|
||||
if recent {
|
||||
blocks[0], last = [2]uint32{start, end}, true
|
||||
} else if n < len(blocks) {
|
||||
blocks[n] = [2]uint32{start, end}
|
||||
n++
|
||||
}
|
||||
}
|
||||
list := blocks[:n]
|
||||
if !last {
|
||||
list = list[1:]
|
||||
}
|
||||
options := [36]byte{1, 1, 5, byte(2 + 8*len(list))}
|
||||
for i, block := range list {
|
||||
binary.BigEndian.PutUint32(options[4+8*i:], block[0])
|
||||
binary.BigEndian.PutUint32(options[8+8*i:], block[1])
|
||||
}
|
||||
c.send(c.sndNxt, tcpAck, options[:4+8*len(list)], nil)
|
||||
}
|
||||
|
||||
// input takes a segment of the connection. It returns false if the connection is gone
|
||||
// and the segment is the start of another one
|
||||
func (c *tcpConn) input(s segment) bool {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.err != nil {
|
||||
return s.flags&(tcpSyn|tcpAck|tcpRst) != tcpSyn
|
||||
}
|
||||
if s.flags&tcpRst != 0 {
|
||||
// from where the system is, or was before its FIN, not from someone who knows no more than the addresses
|
||||
if s.seq-c.rcvNxt <= uint32(c.window) || c.rcvFin && s.seq+1 == c.rcvNxt {
|
||||
c.abort(errTCPReset)
|
||||
}
|
||||
return true
|
||||
}
|
||||
if s.flags&tcpSyn != 0 {
|
||||
switch {
|
||||
case !c.established && s.seq+1 == c.rcvNxt:
|
||||
c.sendSynAck()
|
||||
c.timedAt = time.Time{}
|
||||
case c.closed && s.flags&tcpAck == 0:
|
||||
c.abort(errTCPReset)
|
||||
return false
|
||||
default:
|
||||
c.sendAck()
|
||||
}
|
||||
return true
|
||||
}
|
||||
if s.flags&tcpAck == 0 {
|
||||
return true
|
||||
}
|
||||
if !c.established {
|
||||
if s.ack != c.sndNxt {
|
||||
return true
|
||||
}
|
||||
c.established = true
|
||||
c.sndUna = s.ack
|
||||
c.sndBase = s.ack
|
||||
c.sndWnd = uint32(s.window) << c.sndShift
|
||||
c.stalled, c.retransmits = 0, 0
|
||||
if !c.timedAt.IsZero() {
|
||||
c.clocked()
|
||||
}
|
||||
c.stack.opening.Add(-1)
|
||||
go c.stack.handle(c, c.dst)
|
||||
} else {
|
||||
c.acknowledge(s)
|
||||
}
|
||||
c.receive(s)
|
||||
if c.sndFin && c.rcvFin && c.sndUna == c.sndNxt {
|
||||
// both sides have closed it and nothing waits to be acknowledged
|
||||
c.abort(io.ErrClosedPipe)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// acknowledge takes what a segment says about what was sent. c.mu is held
|
||||
func (c *tcpConn) acknowledge(s segment) {
|
||||
acked, sent := s.ack-c.sndUna, c.sndNxt-c.sndUna
|
||||
if acked > sent {
|
||||
// older than the last one, or of what was not sent
|
||||
return
|
||||
}
|
||||
window := uint32(s.window) << c.sndShift
|
||||
if acked != 0 {
|
||||
c.sndUna = s.ack
|
||||
c.dupAcks, c.stalled, c.retransmits = 0, 0, 0
|
||||
c.release()
|
||||
n := 0
|
||||
for n < len(c.sacked) && int32(c.sacked[n][0]-c.sndUna) <= 0 {
|
||||
n++
|
||||
}
|
||||
c.sacked = slices.Delete(c.sacked, 0, n)
|
||||
if int32(c.resent-c.sndUna) < 0 {
|
||||
c.resent = c.sndUna
|
||||
}
|
||||
if !c.timedAt.IsZero() && int32(c.sndUna-c.timed) >= 0 {
|
||||
c.clocked()
|
||||
}
|
||||
switch {
|
||||
case c.recovering && int32(c.sndUna-c.recover) >= 0:
|
||||
c.recovering = false
|
||||
case c.recovering:
|
||||
// what was sent again has arrived, and what was sent before it has not: the next segment is lost as well
|
||||
if end := c.sndUna + min(uint32(c.mss), c.recover-c.sndUna); int32(end-c.lost) > 0 {
|
||||
c.lost = end
|
||||
}
|
||||
}
|
||||
// the way takes more if what it was given has arrived, as long as it was given about as much as it takes
|
||||
if sent >= c.cwnd/2 {
|
||||
if c.cwnd < c.ssthresh {
|
||||
c.cwnd = min(c.cwnd+acked, c.ssthresh)
|
||||
} else if !c.recovering {
|
||||
// a segment more for every cwnd that arrives
|
||||
c.cwnd = min(c.cwnd+max(uint32(uint64(c.mss)*uint64(acked)/uint64(c.cwnd)), 1), uint32(c.window))
|
||||
}
|
||||
}
|
||||
} else if sent != 0 && window == c.sndWnd && len(s.payload) == 0 && s.flags&tcpFin == 0 {
|
||||
c.dupAcks++
|
||||
}
|
||||
if c.sack {
|
||||
for kind, value, o := nextOption(s.options); kind != 0; kind, value, o = nextOption(o) {
|
||||
for ; kind == 5 && len(value) >= 8; value = value[8:] {
|
||||
// of what was sent and is not acknowledged
|
||||
start, end := binary.BigEndian.Uint32(value)-c.sndUna, binary.BigEndian.Uint32(value[4:])-c.sndUna
|
||||
if start != 0 && start < end && end <= c.sndNxt-c.sndUna {
|
||||
c.sackAdd(c.sndUna+start, c.sndUna+end)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !c.recovering && c.sndUna != c.sndNxt && (len(c.sacked) > 0 || c.dupAcks >= 3) {
|
||||
// the system has something past sndUna, or says the same for the third time: the segment at sndUna is lost
|
||||
c.congested()
|
||||
c.lost = c.sndUna + min(uint32(c.mss), c.sndNxt-c.sndUna)
|
||||
}
|
||||
if c.recovering {
|
||||
c.resend()
|
||||
}
|
||||
c.sndWnd = window
|
||||
// the writer goes on when it can write a good part of the window, not for every segment that is acknowledged.
|
||||
// Unless the way to the system is what holds it back: that takes what the acknowledgments say has left it,
|
||||
// and what is sent as they come does not come to it all at once
|
||||
limit := min(c.sndWnd, uint32(c.window))
|
||||
enough := limit / 2
|
||||
if c.cwnd < limit {
|
||||
enough = uint32(c.mss)
|
||||
}
|
||||
if c.blocked && (c.sndUna == c.sndNxt || c.space() >= enough) {
|
||||
c.writable.Broadcast()
|
||||
}
|
||||
}
|
||||
|
||||
// clocked takes the time since timedAt as how long an acknowledgment takes. The next ones are waited for as long
|
||||
// as that says and no less than a few ticks. Until there is such a time again, after something was sent again,
|
||||
// they are waited for as long as the last time. c.mu is held
|
||||
func (c *tcpConn) clocked() {
|
||||
d := time.Since(c.timedAt)
|
||||
c.timedAt = time.Time{}
|
||||
if c.srtt == 0 {
|
||||
c.srtt, c.rttvar = d, d/2
|
||||
} else {
|
||||
c.rttvar += ((c.srtt - d).Abs() - c.rttvar) / 4
|
||||
c.srtt += (d - c.srtt) / 8
|
||||
}
|
||||
c.retransmitTicks = max(tcpRetransmitTicks, int((c.srtt+4*c.rttvar)/tcpTick)+2)
|
||||
}
|
||||
|
||||
// sackAdd puts what the system says it has into sacked. c.mu is held
|
||||
func (c *tcpConn) sackAdd(start, end uint32) {
|
||||
i := 0
|
||||
for i < len(c.sacked) && int32(c.sacked[i][1]-start) < 0 {
|
||||
i++
|
||||
}
|
||||
j := i
|
||||
for ; j < len(c.sacked) && int32(c.sacked[j][0]-end) <= 0; j++ {
|
||||
if int32(c.sacked[j][0]-start) < 0 {
|
||||
start = c.sacked[j][0]
|
||||
}
|
||||
if int32(c.sacked[j][1]-end) > 0 {
|
||||
end = c.sacked[j][1]
|
||||
}
|
||||
}
|
||||
if i == j && len(c.sacked) == tcpHeld {
|
||||
return
|
||||
}
|
||||
c.sacked = slices.Replace(c.sacked, i, j, [2]uint32{start, end})
|
||||
}
|
||||
|
||||
// congested is called when something is lost: the way to the system takes half of what it was given,
|
||||
// and what is lost is sent again from sndUna. c.mu is held
|
||||
func (c *tcpConn) congested() {
|
||||
c.ssthresh = max(min(c.cwnd, c.sndNxt-c.sndUna)/2, 2*uint32(c.mss))
|
||||
c.cwnd = c.ssthresh
|
||||
c.recovering, c.recover, c.resent = true, c.sndNxt, c.sndUna
|
||||
c.timedAt = time.Time{}
|
||||
}
|
||||
|
||||
// hole returns the first part at or after seq of what is lost: what the system does not have
|
||||
// before something that it says it has, or before lost. There is none if it ends where it starts. c.mu is held
|
||||
func (c *tcpConn) hole(seq uint32) (uint32, uint32) {
|
||||
end := c.lost
|
||||
for _, b := range c.sacked {
|
||||
if int32(b[0]-seq) > 0 {
|
||||
end = b[0]
|
||||
break
|
||||
}
|
||||
if int32(b[1]-seq) > 0 {
|
||||
seq = b[1]
|
||||
}
|
||||
}
|
||||
if int32(end-seq) < 0 {
|
||||
end = seq
|
||||
}
|
||||
return seq, end
|
||||
}
|
||||
|
||||
// flight is how much of what was sent is on its way: not what the system says it has,
|
||||
// and not what is lost and was not sent again. c.mu is held
|
||||
func (c *tcpConn) flight() uint32 {
|
||||
n := c.sndNxt - c.sndUna
|
||||
if !c.recovering {
|
||||
return n
|
||||
}
|
||||
seq := c.resent
|
||||
for _, b := range c.sacked {
|
||||
n -= b[1] - b[0]
|
||||
if int32(b[0]-seq) > 0 {
|
||||
n -= b[0] - seq
|
||||
}
|
||||
if int32(b[1]-seq) > 0 {
|
||||
seq = b[1]
|
||||
}
|
||||
}
|
||||
if int32(c.lost-seq) > 0 {
|
||||
n -= c.lost - seq
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// resend sends again what is lost and was not yet: the segment that the system waits for at once,
|
||||
// the rest as the way to it takes it. c.mu is held
|
||||
func (c *tcpConn) resend() {
|
||||
for {
|
||||
start, end := c.hole(c.resent)
|
||||
if start == end {
|
||||
return
|
||||
}
|
||||
room := uint32(c.mss)
|
||||
if start != c.sndUna {
|
||||
flight := c.flight()
|
||||
if flight+room > c.cwnd {
|
||||
return
|
||||
}
|
||||
room = c.cwnd - flight
|
||||
}
|
||||
end = start + min(end-start, room)
|
||||
c.retransmit(start, end)
|
||||
c.resent = end
|
||||
}
|
||||
}
|
||||
|
||||
// space is how much can be sent now: what the system takes, and what the way to it takes. c.mu is held
|
||||
func (c *tcpConn) space() uint32 {
|
||||
window, sent, flight := min(c.sndWnd, uint32(c.window)), c.sndNxt-c.sndUna, c.flight()
|
||||
if sent >= window || flight >= c.cwnd {
|
||||
return 0
|
||||
}
|
||||
return min(window-sent, c.cwnd-flight)
|
||||
}
|
||||
|
||||
// receive takes the payload of a segment. c.mu is held
|
||||
func (c *tcpConn) receive(s segment) {
|
||||
seq, payload, fin := s.seq, s.payload, s.flags&tcpFin != 0
|
||||
if len(payload) == 0 && !fin {
|
||||
if int32(c.rcvNxt-seq) > 0 {
|
||||
// a keepalive, or a probe of a window that the system has as closed: answered with what is expected
|
||||
c.sendAck()
|
||||
}
|
||||
return
|
||||
}
|
||||
if before := int32(c.rcvNxt - seq); before > 0 {
|
||||
if int(before) > len(payload) || int(before) == len(payload) && !fin {
|
||||
// sent again, or a keepalive: answered with what is expected
|
||||
c.sendAck()
|
||||
return
|
||||
}
|
||||
seq, payload = c.rcvNxt, payload[before:]
|
||||
}
|
||||
if c.rcvFin {
|
||||
c.sendAck()
|
||||
return
|
||||
}
|
||||
if c.closed && len(payload) > 0 {
|
||||
// nobody reads it anymore
|
||||
c.reset()
|
||||
return
|
||||
}
|
||||
// the system is told at once when something is wrong, or it sends more of the same
|
||||
now := len(c.rcvHeld) > 0
|
||||
if room := int(c.window - c.rcvLen - int32(seq-c.rcvNxt)); len(payload) > room {
|
||||
payload, fin, now = payload[:max(room, 0)], false, true
|
||||
}
|
||||
if seq != c.rcvNxt {
|
||||
// something before it was lost, it waits for that, and so does the end if this is it
|
||||
c.hold(seq, payload)
|
||||
if fin {
|
||||
c.rcvEnd, c.rcvEnds = seq+uint32(len(payload)), true
|
||||
}
|
||||
c.sendAck()
|
||||
return
|
||||
}
|
||||
|
||||
c.rcvQueue = buf.MergeBytes(c.rcvQueue, payload)
|
||||
c.rcvLen += int32(len(payload))
|
||||
c.rcvNxt += uint32(len(payload))
|
||||
for !fin && len(c.rcvHeld) > 0 && int32(c.rcvNxt-c.rcvHeld[0].seq) >= 0 {
|
||||
h := c.rcvHeld[0]
|
||||
if before := int32(c.rcvNxt - h.seq); before < h.data.Len() {
|
||||
c.rcvQueue = buf.MergeBytes(c.rcvQueue, h.data.BytesFrom(before))
|
||||
c.rcvLen += h.data.Len() - before
|
||||
c.rcvNxt += uint32(h.data.Len() - before)
|
||||
}
|
||||
h.data.Release()
|
||||
c.rcvHeld = c.rcvHeld[1:]
|
||||
}
|
||||
if fin = fin || c.rcvEnds && c.rcvNxt == c.rcvEnd; fin {
|
||||
c.rcvFin = true
|
||||
c.rcvNxt++
|
||||
}
|
||||
c.readable.Signal()
|
||||
// the reader acknowledges what it takes, with one segment for all that came by then.
|
||||
// It is not waited for when it does not read for long
|
||||
if fin || now || c.rcvNxt-c.rcvAcked >= tcpWindow/4 {
|
||||
c.sendAck()
|
||||
} else {
|
||||
c.arm(tcpTick)
|
||||
}
|
||||
}
|
||||
|
||||
// release releases what of sndQueue is acknowledged. c.mu is held
|
||||
func (c *tcpConn) release() {
|
||||
for len(c.sndQueue) > c.writing {
|
||||
end := c.sndBase + uint32(c.sndQueue[0].Len())
|
||||
if int32(c.sndUna-end) < 0 {
|
||||
break
|
||||
}
|
||||
c.sndQueue[0].Release()
|
||||
c.sndQueue[0] = nil
|
||||
c.sndQueue = c.sndQueue[1:]
|
||||
c.sndBase = end
|
||||
}
|
||||
}
|
||||
|
||||
// hold keeps a segment that is not the next one. c.mu is held
|
||||
func (c *tcpConn) hold(seq uint32, payload []byte) {
|
||||
i := 0
|
||||
for i < len(c.rcvHeld) && int32(c.rcvHeld[i].seq-seq) < 0 {
|
||||
i++
|
||||
}
|
||||
// without what the one before and the one after have
|
||||
if i > 0 {
|
||||
if over := int32(c.rcvHeld[i-1].seq + uint32(c.rcvHeld[i-1].data.Len()) - seq); over > 0 {
|
||||
if int(over) >= len(payload) {
|
||||
return
|
||||
}
|
||||
seq, payload = seq+uint32(over), payload[over:]
|
||||
}
|
||||
}
|
||||
if i < len(c.rcvHeld) {
|
||||
if over := int32(seq + uint32(len(payload)) - c.rcvHeld[i].seq); over > 0 {
|
||||
if int(over) >= len(payload) {
|
||||
return
|
||||
}
|
||||
payload = payload[:len(payload)-int(over)]
|
||||
}
|
||||
}
|
||||
if len(payload) == 0 || len(c.rcvHeld) == tcpHeld {
|
||||
return
|
||||
}
|
||||
b := buf.NewWithSize(int32(len(payload)))
|
||||
b.Write(payload)
|
||||
c.rcvHeld = slices.Insert(c.rcvHeld, i, held{seq, b})
|
||||
c.rcvLast = seq
|
||||
}
|
||||
|
||||
// retransmit sends again what was sent from seq to end. c.mu is held
|
||||
func (c *tcpConn) retransmit(seq, end uint32) {
|
||||
fin := false
|
||||
if int32(end-c.sndNxt) >= 0 {
|
||||
end, fin = c.sndNxt, c.sndFin
|
||||
if fin {
|
||||
end--
|
||||
}
|
||||
}
|
||||
for int32(end-seq) > 0 {
|
||||
var part [1][]byte
|
||||
_, n := c.queued(part[:0], seq, min(c.mss, int(end-seq)))
|
||||
if n == 0 {
|
||||
break
|
||||
}
|
||||
c.send(seq, tcpAck, nil, part[0])
|
||||
seq += uint32(n)
|
||||
}
|
||||
if fin && seq == end {
|
||||
c.send(end, tcpFin|tcpAck, nil, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// queued adds to parts what of sndQueue starts at seq, size bytes at most and as many parts as it has room for,
|
||||
// and returns them with their size. c.mu is held
|
||||
func (c *tcpConn) queued(parts [][]byte, seq uint32, size int) ([][]byte, int) {
|
||||
skip, n := int32(seq-c.sndBase), 0
|
||||
for _, b := range c.sndQueue {
|
||||
if skip >= b.Len() {
|
||||
skip -= b.Len()
|
||||
continue
|
||||
}
|
||||
if n == size || len(parts) == cap(parts) {
|
||||
break
|
||||
}
|
||||
p := b.BytesFrom(skip)
|
||||
skip = 0
|
||||
p = p[:min(len(p), size-n)]
|
||||
parts = append(parts, p)
|
||||
n += len(p)
|
||||
}
|
||||
return parts, n
|
||||
}
|
||||
|
||||
// arm makes tick run after d, unless it is going to run already. c.mu is held
|
||||
func (c *tcpConn) arm(d time.Duration) {
|
||||
if c.armed {
|
||||
return
|
||||
}
|
||||
c.armed = true
|
||||
if c.timer == nil {
|
||||
c.timer = time.AfterFunc(d, c.tick)
|
||||
} else {
|
||||
c.timer.Reset(d)
|
||||
}
|
||||
}
|
||||
|
||||
// tick does what was put off and what has to be done again
|
||||
func (c *tcpConn) tick() {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.armed = false
|
||||
if c.err != nil {
|
||||
return
|
||||
}
|
||||
if c.rcvAcked != c.rcvNxt {
|
||||
c.sendAck()
|
||||
}
|
||||
switch {
|
||||
case c.sndUna != c.sndNxt:
|
||||
if c.stalled++; c.stalled >= c.retransmitTicks {
|
||||
if c.retransmits++; c.retransmits > tcpRetransmits || !c.established && c.retransmits > tcpSynRetransmits {
|
||||
c.abort(errTCPTimeout)
|
||||
return
|
||||
}
|
||||
c.stalled = 0
|
||||
c.retransmitTicks = min(c.retransmitTicks*2, tcpRetransmitTicksMost)
|
||||
if !c.established {
|
||||
c.sendSynAck()
|
||||
c.timedAt = time.Time{}
|
||||
} else {
|
||||
// what the system does not say it has is lost, and the way to it is tried with a segment again
|
||||
c.congested()
|
||||
c.cwnd, c.lost = uint32(c.mss), c.sndNxt
|
||||
c.resend()
|
||||
}
|
||||
}
|
||||
c.arm(tcpTick)
|
||||
case c.blocked:
|
||||
// the segment that opens the window may have been lost, this one is answered with the window
|
||||
if c.stalled++; c.stalled%tcpProbeTicks == 0 {
|
||||
c.send(c.sndUna-1, tcpAck, nil, nil)
|
||||
}
|
||||
c.arm(tcpTick)
|
||||
case c.closed:
|
||||
if c.lingered {
|
||||
c.reset()
|
||||
return
|
||||
}
|
||||
c.lingered = true
|
||||
c.arm(tcpLinger)
|
||||
}
|
||||
}
|
||||
|
||||
// reset tells the system that the connection is gone. c.mu is held
|
||||
func (c *tcpConn) reset() {
|
||||
c.send(c.sndNxt, tcpRst|tcpAck, nil, nil)
|
||||
c.abort(io.ErrClosedPipe)
|
||||
}
|
||||
|
||||
// abort ends the connection without another word to the system. What it has sent is still there to read.
|
||||
// c.mu is held
|
||||
func (c *tcpConn) abort(err error) {
|
||||
if c.err != nil {
|
||||
return
|
||||
}
|
||||
c.err = err
|
||||
if c.timer != nil {
|
||||
c.timer.Stop()
|
||||
}
|
||||
for _, h := range c.rcvHeld {
|
||||
h.data.Release()
|
||||
}
|
||||
c.rcvHeld = nil
|
||||
for _, b := range c.sndQueue[:len(c.sndQueue)-c.writing] {
|
||||
b.Release()
|
||||
}
|
||||
c.sndQueue = nil
|
||||
c.readable.Broadcast()
|
||||
c.writable.Broadcast()
|
||||
c.stack.remove(c)
|
||||
}
|
||||
|
||||
// wait waits for something to read. c.mu is held
|
||||
func (c *tcpConn) wait() error {
|
||||
for c.rcvLen == 0 && !c.rcvFin && !c.closed && c.err == nil {
|
||||
c.readable.Wait()
|
||||
}
|
||||
switch {
|
||||
case c.rcvLen > 0:
|
||||
return nil
|
||||
case c.err != nil && !c.rcvFin:
|
||||
return c.err
|
||||
}
|
||||
return io.EOF
|
||||
}
|
||||
|
||||
// taken is called when size bytes have been read. c.mu is held
|
||||
func (c *tcpConn) taken(size int32) {
|
||||
c.rcvLen -= size
|
||||
// the system may also have stopped at the window that it was told
|
||||
if c.err == nil && (c.rcvAcked != c.rcvNxt || c.rcvAdvertised < c.window/2) {
|
||||
c.sendAck()
|
||||
}
|
||||
}
|
||||
|
||||
// ReadMultiBuffer implements buf.Reader
|
||||
func (c *tcpConn) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if err := c.wait(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mb := c.rcvQueue
|
||||
c.rcvQueue = nil
|
||||
c.taken(c.rcvLen)
|
||||
return mb, nil
|
||||
}
|
||||
|
||||
// Read implements net.Conn
|
||||
func (c *tcpConn) Read(p []byte) (int, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if err := c.wait(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var n int
|
||||
c.rcvQueue, n = buf.SplitBytes(c.rcvQueue, p)
|
||||
c.taken(int32(n))
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// WriteMultiBuffer implements buf.Writer. It is not called again before it returns
|
||||
func (c *tcpConn) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
// without the empty ones
|
||||
n, size := 0, uint32(0)
|
||||
for _, b := range mb {
|
||||
if b.IsEmpty() {
|
||||
b.Release()
|
||||
continue
|
||||
}
|
||||
mb[n] = b
|
||||
n++
|
||||
size += uint32(b.Len())
|
||||
}
|
||||
mb = mb[:n]
|
||||
if c.err != nil || c.closed {
|
||||
buf.ReleaseMulti(mb)
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
// what is written is in sndQueue until it is acknowledged, and is not released before all of it is sent
|
||||
c.sndQueue = append(c.sndQueue, mb...)
|
||||
c.writing = len(mb)
|
||||
// a segment is one part of a Buffer, or as much as there is to send if the tun splits it by itself
|
||||
var room [tcpParts][]byte
|
||||
limit, parts := c.mss, room[:0:1]
|
||||
if c.stack.segmenter != nil {
|
||||
limit, parts = tcpSegment, room[:0]
|
||||
}
|
||||
for end := c.sndNxt + size; c.sndNxt != end; {
|
||||
// not a part of a segment when all of it can go later, with what is acknowledged by then
|
||||
for c.err == nil {
|
||||
if space := c.space(); space >= min(end-c.sndNxt, uint32(c.mss)) || space != 0 && c.sndUna == c.sndNxt {
|
||||
break
|
||||
}
|
||||
c.blocked = true
|
||||
c.arm(tcpTick)
|
||||
c.writable.Wait()
|
||||
c.blocked = false
|
||||
}
|
||||
if c.err != nil {
|
||||
break
|
||||
}
|
||||
most := min(limit, int(c.space()))
|
||||
if most > c.mss {
|
||||
// the same for what the tun splits
|
||||
most -= most % c.mss
|
||||
}
|
||||
p, n := c.queued(parts, c.sndNxt, most)
|
||||
flags := byte(tcpAck)
|
||||
if c.sndNxt+uint32(n) == end {
|
||||
flags |= tcpPsh
|
||||
}
|
||||
var b [ipv6HeaderSize + tcpHeaderSize]byte
|
||||
h := b[:c.header(b[:], c.sndNxt, flags, nil, n)]
|
||||
if c.sndUna == c.sndNxt {
|
||||
// the ticks without an acknowledgment are counted from the first segment that waits for one
|
||||
c.stalled = 0
|
||||
}
|
||||
c.sndNxt += uint32(n)
|
||||
if c.timedAt.IsZero() {
|
||||
c.timed, c.timedAt = c.sndNxt, time.Now()
|
||||
}
|
||||
c.arm(tcpTick)
|
||||
// segments that come in the meantime are taken while this one is written, and acknowledged after it
|
||||
c.sending = true
|
||||
c.mu.Unlock()
|
||||
if s := c.stack.segmenter; s != nil {
|
||||
t := h[c.ipSize:]
|
||||
binary.BigEndian.PutUint16(t[16:], ^checksum(pseudoSum(h[:c.ipSize], protoTCP, len(t)+n)))
|
||||
_ = s.WriteSegment(h, p, c.mss)
|
||||
} else {
|
||||
c.write(h, p[0])
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.sending = false
|
||||
if c.ackWanted && c.err == nil {
|
||||
c.sendAck()
|
||||
}
|
||||
c.ackWanted = false
|
||||
}
|
||||
c.writing = 0
|
||||
if c.err != nil {
|
||||
buf.ReleaseMulti(mb)
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
c.release()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Write implements net.Conn
|
||||
func (c *tcpConn) Write(p []byte) (int, error) {
|
||||
if err := c.WriteMultiBuffer(buf.MergeBytes(nil, p)); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
// Close implements net.Conn
|
||||
func (c *tcpConn) Close() error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.closed {
|
||||
return nil
|
||||
}
|
||||
c.closed = true
|
||||
unread := c.rcvLen > 0
|
||||
c.rcvQueue, c.rcvLen = buf.ReleaseMulti(c.rcvQueue), 0
|
||||
if c.err != nil {
|
||||
return nil
|
||||
}
|
||||
if unread || c.writing != 0 {
|
||||
// something was not read or not written, the system has to know
|
||||
c.reset()
|
||||
return nil
|
||||
}
|
||||
c.readable.Broadcast()
|
||||
c.send(c.sndNxt, tcpFin|tcpAck, nil, nil)
|
||||
c.sndFin = true
|
||||
c.sndNxt++
|
||||
c.arm(tcpTick)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *tcpConn) LocalAddr() net.Addr {
|
||||
return c.dst.RawNetAddr()
|
||||
}
|
||||
|
||||
func (c *tcpConn) RemoteAddr() net.Addr {
|
||||
return c.src.RawNetAddr()
|
||||
}
|
||||
|
||||
func (c *tcpConn) SetDeadline(time.Time) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *tcpConn) SetReadDeadline(time.Time) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *tcpConn) SetWriteDeadline(time.Time) error {
|
||||
return nil
|
||||
}
|
||||
+16
-2
@@ -1,6 +1,7 @@
|
||||
package tun
|
||||
|
||||
import "gvisor.dev/gvisor/pkg/tcpip/stack"
|
||||
// packetRoom is what a tun may need in front of a packet in the buffer that it is read into
|
||||
const packetRoom = 16
|
||||
|
||||
// Tun interface implements tun interface interaction
|
||||
type Tun interface {
|
||||
@@ -8,5 +9,18 @@ type Tun interface {
|
||||
Close() error
|
||||
Name() (string, error)
|
||||
Index() (int, error)
|
||||
newEndpoint() (stack.LinkEndpoint, error)
|
||||
// ReadPacket waits for a packet, reads it into b and returns it
|
||||
ReadPacket(b []byte) ([]byte, error)
|
||||
// WritePacket writes a packet that is in two parts, the second of which may be empty
|
||||
WritePacket(header, payload []byte) error
|
||||
}
|
||||
|
||||
// segmenter is a tun whose other side takes TCP segments that are larger than the MTU,
|
||||
// splits them only if it has to send them on, and completes their checksum then
|
||||
type segmenter interface {
|
||||
// Segments reports whether WriteSegment can be used
|
||||
Segments() bool
|
||||
// WriteSegment writes a packet with a TCP segment whose payload is in parts, to be sent on with mss bytes
|
||||
// of it at most in one. Its checksum is that of the pseudo-header only, not inverted
|
||||
WriteSegment(header []byte, payload [][]byte, mss int) error
|
||||
}
|
||||
|
||||
+10
-14
@@ -10,12 +10,10 @@ import (
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/platform"
|
||||
"golang.org/x/sys/unix"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/link/fdbased"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/stack"
|
||||
)
|
||||
|
||||
type AndroidTun struct {
|
||||
tunFd int
|
||||
*fdTun
|
||||
options *Config
|
||||
}
|
||||
|
||||
@@ -33,8 +31,14 @@ func NewTun(options *Config) (Tun, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// the descriptor stays with the application, Close ends the reading of a duplicate
|
||||
fd, err = unix.FcntlInt(uintptr(fd), unix.F_DUPFD_CLOEXEC, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &AndroidTun{
|
||||
tunFd: fd,
|
||||
fdTun: newFdTun(fd, 0),
|
||||
options: options,
|
||||
}, nil
|
||||
}
|
||||
@@ -44,7 +48,7 @@ func (t *AndroidTun) Start() error {
|
||||
}
|
||||
|
||||
func (t *AndroidTun) Close() error {
|
||||
return nil
|
||||
return t.closeFile()
|
||||
}
|
||||
|
||||
func (t *AndroidTun) Name() (string, error) {
|
||||
@@ -52,7 +56,7 @@ func (t *AndroidTun) Name() (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = unix.IoctlIfreq(t.tunFd, unix.TUNGETIFF, ifr); err != nil {
|
||||
if err = unix.IoctlIfreq(t.fd, unix.TUNGETIFF, ifr); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return ifr.Name(), nil
|
||||
@@ -70,14 +74,6 @@ func (t *AndroidTun) Index() (int, error) {
|
||||
return iface.Index, nil
|
||||
}
|
||||
|
||||
func (t *AndroidTun) newEndpoint() (stack.LinkEndpoint, error) {
|
||||
return fdbased.New(&fdbased.Options{
|
||||
FDs: []int{t.tunFd},
|
||||
MTU: t.options.MTU,
|
||||
RXChecksumOffload: true,
|
||||
})
|
||||
}
|
||||
|
||||
func setinterface(network, address string, fd uintptr, iface *net.Interface) error {
|
||||
return unix.BindToDevice(int(fd), iface.Name)
|
||||
}
|
||||
|
||||
+36
-76
@@ -20,9 +20,6 @@ import (
|
||||
"github.com/xtls/xray-core/common/platform"
|
||||
"golang.org/x/net/route"
|
||||
"golang.org/x/sys/unix"
|
||||
"gvisor.dev/gvisor/pkg/buffer"
|
||||
"gvisor.dev/gvisor/pkg/tcpip"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/stack"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -47,8 +44,8 @@ type DarwinTun struct {
|
||||
ownsFd bool // true for macOS (we created the fd), false for iOS (fd from system)
|
||||
|
||||
// Genuinely blocks Wait() until tunFd is readable, instead of the
|
||||
// previous procyield-only busy-spin (dispatchLoop in
|
||||
// stack_gvisor_endpoint.go calls ReadPacket() then Wait() in a tight
|
||||
// previous procyield-only busy-spin (ReadPacket() reads and then calls
|
||||
// Wait() in a tight
|
||||
// loop with no other throttling whenever the queue is empty -- with
|
||||
// only procyield(1), that pins a full CPU core for as long as the
|
||||
// tunnel is up, observed causing severe device heating/thermal
|
||||
@@ -66,7 +63,7 @@ type DarwinTun struct {
|
||||
// waitKqueue owns a kqueue fd used by DarwinTun.Wait() to block on
|
||||
// read-readiness. Closing and waiting can race from different goroutines
|
||||
// (Close() from the caller that tears down the tunnel, Wait() from
|
||||
// dispatchLoop's own goroutine) -- reviewer feedback on XTLS/Xray-core#6580
|
||||
// the goroutine that reads packets) -- reviewer feedback on XTLS/Xray-core#6580
|
||||
// found that a bare `int` fd field let Close() race Wait()'s use of the
|
||||
// same fd number, and on Darwin a closed fd number can be reused by an
|
||||
// unrelated concurrent open() before Wait() gets to call Kevent on it,
|
||||
@@ -110,9 +107,9 @@ func newWaitKqueue(fd int) *waitKqueue {
|
||||
// wait blocks until the registered fd is readable, timeout elapses, or a
|
||||
// benign interrupt occurs -- all three are "this kqueue is still healthy,
|
||||
// the caller should just try again" and return true; the caller
|
||||
// (DarwinTun.Wait) doesn't need to distinguish them since it always calls
|
||||
// ReadPacket() right after anyway, and that already handles "nothing was
|
||||
// actually there" via ErrQueueEmpty. Returns false only when the kqueue
|
||||
// (DarwinTun.Wait) doesn't need to distinguish them since ReadPacket()
|
||||
// reads right after anyway, and that already handles "nothing was
|
||||
// actually there" by waiting again. Returns false only when the kqueue
|
||||
// itself is no longer usable -- already closed, or the kevent syscall
|
||||
// failed for a reason other than EINTR -- see its own call site in
|
||||
// DarwinTun.Wait for why a persistent failure must not be silently
|
||||
@@ -145,10 +142,7 @@ func (w *waitKqueue) close() {
|
||||
})
|
||||
}
|
||||
|
||||
var (
|
||||
_ Tun = (*DarwinTun)(nil)
|
||||
_ GVisorDevice = (*DarwinTun)(nil)
|
||||
)
|
||||
var _ Tun = (*DarwinTun)(nil)
|
||||
|
||||
func NewTun(options *Config) (Tun, error) {
|
||||
// Check if fd is provided via environment (iOS mode)
|
||||
@@ -274,73 +268,43 @@ func (t *DarwinTun) Index() (int, error) {
|
||||
return iface.Index, nil
|
||||
}
|
||||
|
||||
// WritePacket implements GVisorDevice method to write one packet to the tun device
|
||||
func (t *DarwinTun) WritePacket(packet *stack.PacketBuffer) tcpip.Error {
|
||||
// request memory to write from reusable buffer pool
|
||||
b := buf.NewWithSize(int32(t.options.MTU) + utunHeaderSize)
|
||||
defer b.Release()
|
||||
|
||||
// prepare Darwin specific packet header
|
||||
_, _ = b.Write([]byte{0x0, 0x0, 0x0, 0x0})
|
||||
// copy the bytes of slices that compose the packet into the allocated buffer
|
||||
for _, packetElement := range packet.AsSlices() {
|
||||
_, _ = b.Write(packetElement)
|
||||
}
|
||||
// fill Darwin specific header from the first raw packet byte, that we can access now
|
||||
// WritePacket implements Tun: the two parts are copied behind the header that the system wants in front of a packet
|
||||
func (t *DarwinTun) WritePacket(header, payload []byte) error {
|
||||
var family byte
|
||||
switch b.Byte(4) >> 4 {
|
||||
switch header[0] >> 4 {
|
||||
case 4:
|
||||
family = unix.AF_INET
|
||||
case 6:
|
||||
family = unix.AF_INET6
|
||||
default:
|
||||
return &tcpip.ErrAborted{}
|
||||
return xerrors.New("not an ip packet")
|
||||
}
|
||||
b.SetByte(3, family)
|
||||
|
||||
if _, err := t.tunFile.Write(b.Bytes()); err != nil {
|
||||
if errors.Is(err, unix.EAGAIN) {
|
||||
return &tcpip.ErrWouldBlock{}
|
||||
}
|
||||
return &tcpip.ErrAborted{}
|
||||
}
|
||||
return nil
|
||||
// request memory to write from reusable buffer pool
|
||||
b := buf.NewWithSize(int32(utunHeaderSize + len(header) + len(payload)))
|
||||
defer b.Release()
|
||||
b.Extend(utunHeaderSize)[3] = family
|
||||
_, _ = b.Write(header)
|
||||
_, _ = b.Write(payload)
|
||||
|
||||
_, err := t.tunFile.Write(b.Bytes())
|
||||
return err
|
||||
}
|
||||
|
||||
// ReadPacket implements GVisorDevice method to read one packet from the tun device
|
||||
// It is expected that the method will not block, rather return ErrQueueEmpty when there is nothing on the line,
|
||||
// which will make the stack call Wait which should implement desired push-back
|
||||
func (t *DarwinTun) ReadPacket() (byte, *stack.PacketBuffer, error) {
|
||||
// request memory to write from reusable buffer pool
|
||||
b := buf.NewWithSize(int32(t.options.MTU) + utunHeaderSize)
|
||||
|
||||
// read the bytes to the interface file
|
||||
n, err := b.ReadFrom(t.tunFile)
|
||||
if errors.Is(err, unix.EAGAIN) || errors.Is(err, unix.EINTR) {
|
||||
b.Release()
|
||||
return 0, nil, ErrQueueEmpty
|
||||
// ReadPacket implements Tun: it reads into b, the packet follows the header that the system puts in front of it
|
||||
func (t *DarwinTun) ReadPacket(b []byte) ([]byte, error) {
|
||||
for {
|
||||
n, err := t.tunFile.Read(b)
|
||||
if errors.Is(err, unix.EAGAIN) || errors.Is(err, unix.EINTR) || err == nil && n <= utunHeaderSize {
|
||||
// nothing on the line, or an empty packet
|
||||
t.Wait()
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b[utunHeaderSize:n], nil
|
||||
}
|
||||
if err != nil {
|
||||
b.Release()
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
// discard empty or sub-empty packets
|
||||
if n <= utunHeaderSize {
|
||||
b.Release()
|
||||
return 0, nil, ErrQueueEmpty
|
||||
}
|
||||
|
||||
// network protocol version from first byte of the raw packet, the one that follows Darwin specific header
|
||||
version := b.Byte(utunHeaderSize) >> 4
|
||||
packetBuffer := buffer.MakeWithData(b.BytesFrom(utunHeaderSize))
|
||||
return version, stack.NewPacketBuffer(stack.PacketBufferOptions{
|
||||
Payload: packetBuffer,
|
||||
IsForwardedPacket: true,
|
||||
OnRelease: func() {
|
||||
b.Release()
|
||||
},
|
||||
}), nil
|
||||
}
|
||||
|
||||
// Wait blocks until tunFd is readable (or a short timeout elapses), rather
|
||||
@@ -349,8 +313,8 @@ func (t *DarwinTun) ReadPacket() (byte, *stack.PacketBuffer, error) {
|
||||
// happens to race a call already parked here.
|
||||
//
|
||||
// Reviewer feedback (XTLS/Xray-core#6580, P2): the original version
|
||||
// discarded every error from the underlying kevent syscall. dispatchLoop
|
||||
// (stack_gvisor_endpoint.go) calls ReadPacket() then Wait() in an
|
||||
// discarded every error from the underlying kevent syscall. ReadPacket()
|
||||
// reads and then calls Wait() in an
|
||||
// unconditional tight loop -- if kevent started failing at runtime for a
|
||||
// persistent reason (not just a benign EINTR), Wait() returning
|
||||
// immediately every time reintroduces exactly the busy-spin this whole
|
||||
@@ -378,14 +342,10 @@ func (t *DarwinTun) Wait() {
|
||||
// real Darwin systems, or having just failed permanently above)
|
||||
// instead of always -- a genuine bounded sleep actually yields the CPU
|
||||
// instead of being a near-instant scheduler hint that lets the tight
|
||||
// dispatchLoop caller spin just as hot as before.
|
||||
// loop of ReadPacket() spin just as hot as before.
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
|
||||
func (t *DarwinTun) newEndpoint() (stack.LinkEndpoint, error) {
|
||||
return &LinkEndpoint{deviceMTU: t.options.MTU, device: t}, nil
|
||||
}
|
||||
|
||||
// open the interface, by creating new utunN if in the system and returning its file descriptor
|
||||
func open(name string) (*os.File, error) {
|
||||
ifIndex := -1
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"net"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/stack"
|
||||
)
|
||||
|
||||
type DefaultTun struct{}
|
||||
@@ -35,10 +34,14 @@ func (t *DefaultTun) Index() (int, error) {
|
||||
return 0, errors.New("Tun is not supported on your platform")
|
||||
}
|
||||
|
||||
func (t *DefaultTun) newEndpoint() (stack.LinkEndpoint, error) {
|
||||
func (t *DefaultTun) ReadPacket([]byte) ([]byte, error) {
|
||||
return nil, errors.New("Tun is not supported on your platform")
|
||||
}
|
||||
|
||||
func (t *DefaultTun) WritePacket(header, payload []byte) error {
|
||||
return errors.New("Tun is not supported on your platform")
|
||||
}
|
||||
|
||||
func setinterface(string, string, uintptr, *net.Interface) error {
|
||||
return errors.New("Tun is not supported on your platform")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//go:build linux
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// vnetSize is the size of the virtio_net_hdr that a tun with IFF_VNET_HDR has in front of every packet,
|
||||
// unless it was told another one
|
||||
const vnetSize = 10
|
||||
|
||||
// fdTun reads and writes the packets of a tun that is a file descriptor
|
||||
type fdTun struct {
|
||||
fd int
|
||||
// file is what packets are read from: a read waits in the poller of the runtime and ends when file is closed
|
||||
file *os.File
|
||||
// vnet is the size of the virtio_net_hdr in front of every packet, zero if the tun has none.
|
||||
// With it the system does not split what it sends to the tun and takes what is not split from it
|
||||
vnet int
|
||||
|
||||
writeLock sync.RWMutex
|
||||
closed bool
|
||||
}
|
||||
|
||||
// newFdTun takes a file descriptor that does not block
|
||||
func newFdTun(fd, vnet int) *fdTun {
|
||||
return &fdTun{fd: fd, file: os.NewFile(uintptr(fd), "/dev/net/tun"), vnet: vnet}
|
||||
}
|
||||
|
||||
func (t *fdTun) ReadPacket(b []byte) ([]byte, error) {
|
||||
n, err := t.file.Read(b)
|
||||
// what the virtio_net_hdr says is of no use here: no checksum is looked at, and a segment may have any size
|
||||
return b[min(t.vnet, n):n], err
|
||||
}
|
||||
|
||||
func (t *fdTun) WritePacket(header, payload []byte) error {
|
||||
// a virtio_net_hdr of zeros leaves nothing to the system
|
||||
var vnet [packetRoom]byte
|
||||
return t.writev(vnet[:t.vnet], header, payload)
|
||||
}
|
||||
|
||||
// Segments implements segmenter
|
||||
func (t *fdTun) Segments() bool {
|
||||
return t.vnet != 0
|
||||
}
|
||||
|
||||
// WriteSegment implements segmenter
|
||||
func (t *fdTun) WriteSegment(header []byte, payload [][]byte, mss int) error {
|
||||
// the virtio_net_hdr and the headers go as one part
|
||||
var b [packetRoom + ipv6HeaderSize + 60]byte
|
||||
ip, gso := ipv4HeaderSize, byte(unix.VIRTIO_NET_HDR_GSO_TCPV4)
|
||||
if header[0]>>4 == 6 {
|
||||
ip, gso = ipv6HeaderSize, unix.VIRTIO_NET_HDR_GSO_TCPV6
|
||||
}
|
||||
size := 0
|
||||
for _, p := range payload {
|
||||
size += len(p)
|
||||
}
|
||||
b[0] = unix.VIRTIO_NET_HDR_F_NEEDS_CSUM
|
||||
if size > mss {
|
||||
b[1] = gso
|
||||
binary.NativeEndian.PutUint16(b[4:], uint16(mss))
|
||||
}
|
||||
binary.NativeEndian.PutUint16(b[2:], uint16(len(header)))
|
||||
// where the checksum starts, and where it is put from there
|
||||
binary.NativeEndian.PutUint16(b[6:], uint16(ip))
|
||||
binary.NativeEndian.PutUint16(b[8:], 16)
|
||||
var parts [8][]byte
|
||||
return t.writev(append(append(parts[:0], b[:t.vnet+copy(b[t.vnet:], header)]), payload...)...)
|
||||
}
|
||||
|
||||
func (t *fdTun) writev(parts ...[]byte) error {
|
||||
t.writeLock.RLock()
|
||||
defer t.writeLock.RUnlock()
|
||||
if t.closed {
|
||||
return os.ErrClosed
|
||||
}
|
||||
for {
|
||||
_, err := unix.Writev(t.fd, parts)
|
||||
if err != unix.EINTR {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *fdTun) closeFile() error {
|
||||
t.writeLock.Lock()
|
||||
defer t.writeLock.Unlock()
|
||||
t.closed = true
|
||||
return t.file.Close()
|
||||
}
|
||||
+249
-80
@@ -5,17 +5,17 @@ package tun
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"os/exec"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"golang.zx2c4.com/wireguard/tun"
|
||||
"gvisor.dev/gvisor/pkg/buffer"
|
||||
"gvisor.dev/gvisor/pkg/tcpip"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/stack"
|
||||
|
||||
"golang.org/x/net/route"
|
||||
"golang.org/x/sys/unix"
|
||||
@@ -41,8 +41,17 @@ func procyield(cycles uint32)
|
||||
type FreeBSDTun struct {
|
||||
device tun.Device
|
||||
options *Config
|
||||
name string
|
||||
tunIndex int
|
||||
autoInterface bool
|
||||
// local is the address the system itself has on the TUN; gateway is the
|
||||
// address before it, which nothing owns, so a packet to it is routed into
|
||||
// the TUN (see selectFreeBSDGateway).
|
||||
gateway netip.Prefix
|
||||
local netip.Addr
|
||||
|
||||
systemDNSSet bool
|
||||
systemDNSDirty bool
|
||||
|
||||
systemRoutes []netip.Prefix
|
||||
escapeMu sync.Mutex
|
||||
@@ -59,10 +68,7 @@ type escapeRoute struct {
|
||||
gateway netip.Addr
|
||||
}
|
||||
|
||||
var (
|
||||
_ Tun = (*FreeBSDTun)(nil)
|
||||
_ GVisorDevice = (*FreeBSDTun)(nil)
|
||||
)
|
||||
var _ Tun = (*FreeBSDTun)(nil)
|
||||
|
||||
// NewTun builds new tun interface handler
|
||||
func NewTun(options *Config) (Tun, error) {
|
||||
@@ -108,15 +114,19 @@ func NewTun(options *Config) (Tun, error) {
|
||||
return &FreeBSDTun{
|
||||
device: tunDev,
|
||||
options: options,
|
||||
name: name,
|
||||
tunIndex: iface.Index,
|
||||
autoInterface: options.AutoOutboundsInterface != "",
|
||||
gateway: gateway,
|
||||
local: local,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// selectFreeBSDGateway picks the first IPv4 prefix from the configured gateway
|
||||
// list and the local address derived from it (the darwin semantics: the
|
||||
// gateway is the remote side of the point-to-point pair, the local address is
|
||||
// the next one after it), falling back to the same link-local default.
|
||||
// interface gets the address right after the gateway, and the gateway, which
|
||||
// nothing owns, is routed into the TUN), falling back to the same link-local
|
||||
// default.
|
||||
func selectFreeBSDGateway(configured []string) (netip.Prefix, netip.Addr, error) {
|
||||
gateway := netip.MustParsePrefix(defaultFreeBSDGateway)
|
||||
if len(configured) > 0 {
|
||||
@@ -205,6 +215,7 @@ func (t *FreeBSDTun) Close() error {
|
||||
_ = t.routeMonitor.Close()
|
||||
}
|
||||
})
|
||||
t.unsetSystemDNS()
|
||||
t.unsetEscapeFib()
|
||||
routeErr := t.unsetSystemRoutes()
|
||||
name, nameErr := t.Name()
|
||||
@@ -218,6 +229,195 @@ func (t *FreeBSDTun) Close() error {
|
||||
return xerrors.Combine(routeErr, closeErr)
|
||||
}
|
||||
|
||||
// resolvconfRunner runs resolvconf(8) with the given stdin. Overridable for
|
||||
// tests.
|
||||
var resolvconfRunner = func(stdin string, args ...string) ([]byte, error) {
|
||||
cmd := exec.Command("resolvconf", args...)
|
||||
if stdin != "" {
|
||||
cmd.Stdin = strings.NewReader(stdin)
|
||||
}
|
||||
return cmd.CombinedOutput()
|
||||
}
|
||||
|
||||
// readResolverFile reads one of the files the applied check looks at.
|
||||
// Overridable for tests.
|
||||
var readResolverFile = os.ReadFile
|
||||
|
||||
// resolvconfApplied reports whether the nameserver resolvconf was handed
|
||||
// reached a resolver. resolvconf exits 0 with resolvconf=NO in
|
||||
// resolvconf.conf, and still records the entry for the interface, but runs no
|
||||
// subscriber, so the exit status and `resolvconf -l` prove nothing; what the
|
||||
// subscribers wrote does. The libc subscriber writes /etc/resolv.conf, where
|
||||
// the nameserver also has to be the exclusive one. With
|
||||
// local_unbound, local-unbound-setup turns that subscriber off and names
|
||||
// unbound's forwarders file as unbound_conf instead, with resolv.conf left
|
||||
// pointed at loopback, so that file is checked next.
|
||||
func resolvconfApplied(addr netip.Addr) (bool, error) {
|
||||
resolvConf, err := readResolverFile("/etc/resolv.conf")
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if exclusiveNameserver(resolvConf, addr) {
|
||||
return true, nil
|
||||
}
|
||||
resolvconfConf, err := readResolverFile("/etc/resolvconf.conf")
|
||||
if err != nil {
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
if path := shellAssignment(resolvconfConf, "unbound_conf"); path != "" {
|
||||
forwarders, err := readResolverFile(path)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if hasDirective(forwarders, "forward-addr:", addr) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// exclusiveNameserver reports whether resolv.conf lists addr as a nameserver
|
||||
// and no other one except on loopback. With inclusive_interfaces in
|
||||
// resolvconf.conf the exclusive marking of -x is ignored and the nameservers
|
||||
// DHCP supplied stay listed, and the system falls back to them: that is the
|
||||
// leak the takeover exists to close, so it does not count as applied. A
|
||||
// loopback nameserver alongside is a local resolver that resolvconf feeds.
|
||||
func exclusiveNameserver(resolvConf []byte, addr netip.Addr) bool {
|
||||
found := false
|
||||
for _, line := range strings.Split(string(resolvConf), "\n") {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) != 2 || fields[0] != "nameserver" {
|
||||
continue
|
||||
}
|
||||
if fields[1] == addr.String() {
|
||||
found = true
|
||||
continue
|
||||
}
|
||||
if other, err := netip.ParseAddr(fields[1]); err != nil || !other.IsLoopback() {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
// hasDirective reports whether a line of content is the keyword followed by
|
||||
// the address, as in `forward-addr: 10.0.0.1`.
|
||||
func hasDirective(content []byte, keyword string, addr netip.Addr) bool {
|
||||
for _, line := range strings.Split(string(content), "\n") {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) == 2 && fields[0] == keyword && fields[1] == addr.String() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// shellAssignment returns the value of `name=value` in a sh-style config such
|
||||
// as resolvconf.conf, without surrounding quotes, or empty when it is not set.
|
||||
func shellAssignment(content []byte, name string) string {
|
||||
for _, line := range strings.Split(string(content), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
value, ok := strings.CutPrefix(line, name+"=")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
return strings.Trim(value, `"'`)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ConfigureSystemDNS hands the TUN's gateway address to resolvconf(8) as the
|
||||
// exclusive nameserver, so name lookups resolve through Xray instead of
|
||||
// leaking to the physical link.
|
||||
//
|
||||
// It acts only when the config opts in, and it verifies the data path first:
|
||||
// unless a query to the gateway would actually be handled, host-wide
|
||||
// resolution is left to the OS and an error returned. The caller does not
|
||||
// start the TUN on an error, as the system DNS would bypass it.
|
||||
func (t *FreeBSDTun) ConfigureSystemDNS(ctx context.Context, inboundTag string) error {
|
||||
if !t.options.AutoSystemDnsToGateway {
|
||||
return nil
|
||||
}
|
||||
if t.systemDNSSet {
|
||||
return nil
|
||||
}
|
||||
|
||||
// A previous removal may have failed. Retry before applying anything, so a
|
||||
// stale entry does not silently outlive the attempt to clean it up.
|
||||
if t.systemDNSDirty {
|
||||
if err := t.revertSystemDNS(); err != nil {
|
||||
return xerrors.New("previous system DNS removal still failing").Base(err)
|
||||
}
|
||||
}
|
||||
|
||||
// The resolver is pointed at the gateway: on FreeBSD the system has no
|
||||
// address there, so a query to it is routed into the TUN and answered
|
||||
// inside Xray. A query from this host carries the local address.
|
||||
address := t.gateway.Addr()
|
||||
if err := verifyDNSRouting(ctx, inboundTag, t.local.String(), address.String()); err != nil {
|
||||
return xerrors.New("no DNS path at ", address.String(), ":53").Base(err)
|
||||
}
|
||||
|
||||
// -x makes this interface's nameserver the only one in use, the
|
||||
// equivalent of resolvectl's `domain ~.` plus `default-route true`:
|
||||
// without it openresolv keeps the nameservers dhclient supplied listed
|
||||
// alongside the gateway, and the system falls back to them.
|
||||
if _, err := resolvconfRunner("nameserver "+address.String()+"\n", "-a", t.name, "-x"); err != nil {
|
||||
return xerrors.New("resolvconf -a failed").Base(err)
|
||||
}
|
||||
applied, err := resolvconfApplied(address)
|
||||
if err != nil {
|
||||
return t.rollbackSystemDNS(xerrors.New("cannot confirm the system DNS").Base(err))
|
||||
}
|
||||
if !applied {
|
||||
return t.rollbackSystemDNS(xerrors.New("resolvconf did not apply ", address.String(), " to any resolver (resolvconf=NO or inclusive_interfaces in resolvconf.conf?)"))
|
||||
}
|
||||
|
||||
t.systemDNSSet = true
|
||||
xerrors.LogInfo(ctx, "[tun] system DNS set to ", address.String(), " on ", t.name)
|
||||
return nil
|
||||
}
|
||||
|
||||
// rollbackSystemDNS undoes a takeover that did not take. A failed removal is
|
||||
// recorded so the next attempt retries it, and is reported rather than
|
||||
// swallowed.
|
||||
func (t *FreeBSDTun) rollbackSystemDNS(cause error) error {
|
||||
if _, err := resolvconfRunner("", "-d", t.name); err != nil {
|
||||
t.systemDNSDirty = true
|
||||
// Combine, because Base overwrites: reporting only the cause would hide
|
||||
// the removal failure, and reporting only the removal failure would
|
||||
// hide why the removal was attempted.
|
||||
return xerrors.New("resolvconf -d failed, the entry may remain").Base(xerrors.Combine(err, cause))
|
||||
}
|
||||
return cause
|
||||
}
|
||||
|
||||
// revertSystemDNS issues the removal and keeps the dirty flag in step with the
|
||||
// outcome.
|
||||
func (t *FreeBSDTun) revertSystemDNS() error {
|
||||
_, err := resolvconfRunner("", "-d", t.name)
|
||||
t.systemDNSDirty = err != nil
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t.systemDNSSet = false
|
||||
return nil
|
||||
}
|
||||
|
||||
// unsetSystemDNS hands DNS back to the OS. Only meaningful when
|
||||
// ConfigureSystemDNS applied something, or a previous removal failed.
|
||||
func (t *FreeBSDTun) unsetSystemDNS() {
|
||||
if !t.systemDNSSet && !t.systemDNSDirty {
|
||||
return
|
||||
}
|
||||
if err := t.revertSystemDNS(); err != nil {
|
||||
xerrors.LogInfoInner(context.Background(), err, "[tun] failed to remove the system DNS entry; run `resolvconf -d ", t.name, "` to clean up")
|
||||
}
|
||||
}
|
||||
|
||||
func destroyInterface(name string) {
|
||||
fd, err := unix.Socket(unix.AF_INET, unix.SOCK_DGRAM, 0)
|
||||
if err != nil {
|
||||
@@ -242,73 +442,43 @@ func (t *FreeBSDTun) Index() (int, error) {
|
||||
return t.tunIndex, nil
|
||||
}
|
||||
|
||||
// WritePacket implements GVisorDevice method to write one packet to the tun device
|
||||
func (t *FreeBSDTun) WritePacket(packet *stack.PacketBuffer) tcpip.Error {
|
||||
// request memory to write from reusable buffer pool
|
||||
b := buf.NewWithSize(int32(t.options.MTU) + tunHeaderSize)
|
||||
defer b.Release()
|
||||
|
||||
// prepare Unix specific packet header
|
||||
_, _ = b.Write([]byte{0x0, 0x0, 0x0, 0x0})
|
||||
// copy the bytes of slices that compose the packet into the allocated buffer
|
||||
for _, packetElement := range packet.AsSlices() {
|
||||
_, _ = b.Write(packetElement)
|
||||
}
|
||||
// fill Unix specific header from the first raw packet byte, that we can access now
|
||||
// WritePacket implements Tun: the two parts are copied behind the header that the system wants in front of a packet
|
||||
func (t *FreeBSDTun) WritePacket(header, payload []byte) error {
|
||||
var family byte
|
||||
switch b.Byte(4) >> 4 {
|
||||
switch header[0] >> 4 {
|
||||
case 4:
|
||||
family = unix.AF_INET
|
||||
case 6:
|
||||
family = unix.AF_INET6
|
||||
default:
|
||||
return &tcpip.ErrAborted{}
|
||||
return xerrors.New("not an ip packet")
|
||||
}
|
||||
b.SetByte(3, family)
|
||||
|
||||
if _, err := t.device.File().Write(b.Bytes()); err != nil {
|
||||
if errors.Is(err, unix.EAGAIN) {
|
||||
return &tcpip.ErrWouldBlock{}
|
||||
}
|
||||
return &tcpip.ErrAborted{}
|
||||
}
|
||||
return nil
|
||||
// request memory to write from reusable buffer pool
|
||||
b := buf.NewWithSize(int32(tunHeaderSize + len(header) + len(payload)))
|
||||
defer b.Release()
|
||||
b.Extend(tunHeaderSize)[3] = family
|
||||
_, _ = b.Write(header)
|
||||
_, _ = b.Write(payload)
|
||||
|
||||
_, err := t.device.File().Write(b.Bytes())
|
||||
return err
|
||||
}
|
||||
|
||||
// ReadPacket implements GVisorDevice method to read one packet from the tun device
|
||||
// It is expected that the method will not block, rather return ErrQueueEmpty when there is nothing on the line,
|
||||
// which will make the stack call Wait which should implement desired push-back
|
||||
func (t *FreeBSDTun) ReadPacket() (byte, *stack.PacketBuffer, error) {
|
||||
// request memory to write from reusable buffer pool
|
||||
b := buf.NewWithSize(int32(t.options.MTU) + tunHeaderSize)
|
||||
|
||||
// read the bytes to the interface file
|
||||
n, err := b.ReadFrom(t.device.File())
|
||||
if errors.Is(err, unix.EAGAIN) || errors.Is(err, unix.EINTR) {
|
||||
b.Release()
|
||||
return 0, nil, ErrQueueEmpty
|
||||
// ReadPacket implements Tun: it reads into b, the packet follows the header that the system puts in front of it
|
||||
func (t *FreeBSDTun) ReadPacket(b []byte) ([]byte, error) {
|
||||
for {
|
||||
n, err := t.device.File().Read(b)
|
||||
if errors.Is(err, unix.EAGAIN) || errors.Is(err, unix.EINTR) || err == nil && n <= tunHeaderSize {
|
||||
// nothing on the line, or an empty packet
|
||||
t.Wait()
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b[tunHeaderSize:n], nil
|
||||
}
|
||||
if err != nil {
|
||||
b.Release()
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
// discard empty or sub-empty packets
|
||||
if n <= tunHeaderSize {
|
||||
b.Release()
|
||||
return 0, nil, ErrQueueEmpty
|
||||
}
|
||||
|
||||
// network protocol version from first byte of the raw packet, the one that follows Unix specific header
|
||||
version := b.Byte(tunHeaderSize) >> 4
|
||||
packetBuffer := buffer.MakeWithData(b.BytesFrom(tunHeaderSize))
|
||||
return version, stack.NewPacketBuffer(stack.PacketBufferOptions{
|
||||
Payload: packetBuffer,
|
||||
IsForwardedPacket: true,
|
||||
OnRelease: func() {
|
||||
b.Release()
|
||||
},
|
||||
}), nil
|
||||
}
|
||||
|
||||
// Wait some cpu cycles
|
||||
@@ -316,17 +486,14 @@ func (t *FreeBSDTun) Wait() {
|
||||
procyield(1)
|
||||
}
|
||||
|
||||
func (t *FreeBSDTun) newEndpoint() (stack.LinkEndpoint, error) {
|
||||
return &LinkEndpoint{deviceMTU: t.options.MTU, device: t}, nil
|
||||
}
|
||||
|
||||
const (
|
||||
IN6_IFF_NODAD = 0x0020 // netinet6/in6_var.h
|
||||
ND6_INFINITE_LIFETIME = 0xFFFFFFFF // netinet6/nd6.h
|
||||
)
|
||||
|
||||
// ifAliasReq4 is struct in_aliasreq from netinet/in_var.h in the 64-byte
|
||||
// layout unix.SIOCAIFADDR encodes (name + addr/dstaddr/mask sockaddrs).
|
||||
// layout unix.SIOCAIFADDR encodes (name + addr/dstaddr/mask sockaddrs; the
|
||||
// dstaddr slot is the broadcast address on a broadcast interface).
|
||||
type ifAliasReq4 struct {
|
||||
Name [unix.IFNAMSIZ]byte
|
||||
Addr unix.RawSockaddrInet4
|
||||
@@ -361,7 +528,7 @@ type addrLifetime6 struct {
|
||||
// header macro does.
|
||||
const siocaifaddrIn6 = 0x80000000 | (uintptr(unsafe.Sizeof(ifAliasReq6{})) << 16) | ('i' << 8) | 27
|
||||
|
||||
// setIPAddress assigns the local/remote point-to-point IPv4 pair and a
|
||||
// setIPAddress assigns the local IPv4 address with the gateway's mask and a
|
||||
// link-local IPv6 address to the interface, required for the routing to work
|
||||
// (same scheme as the darwin implementation: local address is the one right
|
||||
// after the gateway address).
|
||||
@@ -374,17 +541,20 @@ func setIPAddress(name string, gateway netip.Prefix, local netip.Addr, ifIndex i
|
||||
|
||||
local4 := local.As4()
|
||||
|
||||
// The interface runs in broadcast mode (the wireguard tun library puts it
|
||||
// there), so the second address slot of the request is the broadcast
|
||||
// address, not a point-to-point peer. It stays empty and the kernel
|
||||
// derives the broadcast address from the mask; the gateway is then an
|
||||
// ordinary on-link address, reachable through the interface route, which
|
||||
// is what the system routes and the system DNS takeover need. Filling it
|
||||
// with the gateway made the gateway the broadcast address, and a plain
|
||||
// socket cannot send to that.
|
||||
ifReq4 := ifAliasReq4{
|
||||
Addr: unix.RawSockaddrInet4{
|
||||
Len: unix.SizeofSockaddrInet4,
|
||||
Family: unix.AF_INET,
|
||||
Addr: local4,
|
||||
},
|
||||
Dstaddr: unix.RawSockaddrInet4{
|
||||
Len: unix.SizeofSockaddrInet4,
|
||||
Family: unix.AF_INET,
|
||||
Addr: gateway.Addr().As4(),
|
||||
},
|
||||
Mask: unix.RawSockaddrInet4{
|
||||
Len: unix.SizeofSockaddrInet4,
|
||||
Family: unix.AF_INET,
|
||||
@@ -471,10 +641,9 @@ func (t *FreeBSDTun) setSystemRoutes() error {
|
||||
return err
|
||||
}
|
||||
// Route through the interface, not a gateway: the tun(4) device is a
|
||||
// broadcast interface here, so its point-to-point peer address doubles as
|
||||
// the subnet broadcast and the kernel refuses to route to it (EACCES).
|
||||
// Interface routes sidestep the gateway entirely (what wg-quick does on
|
||||
// FreeBSD).
|
||||
// broadcast interface here with no address resolution, so a next hop adds
|
||||
// nothing. Interface routes sidestep the gateway entirely (what wg-quick
|
||||
// does on FreeBSD).
|
||||
for _, destination := range routes {
|
||||
if err := execRoute(-1, unix.RTM_ADD, t.tunIndex, destination, netip.Addr{}); err != nil {
|
||||
_ = t.unsetSystemRoutes()
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
//go:build freebsd
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type probeCall struct {
|
||||
inboundTag string
|
||||
source string
|
||||
address string
|
||||
}
|
||||
|
||||
// stubDNSRouting replaces the routing probe for the duration of a test and
|
||||
// records how it was called, so tests can assert the probe is representative.
|
||||
func stubDNSRouting(t *testing.T, err error) *[]probeCall {
|
||||
t.Helper()
|
||||
original := verifyDNSRouting
|
||||
calls := []probeCall{}
|
||||
verifyDNSRouting = func(_ context.Context, inboundTag, source, address string) error {
|
||||
calls = append(calls, probeCall{inboundTag, source, address})
|
||||
return err
|
||||
}
|
||||
t.Cleanup(func() { verifyDNSRouting = original })
|
||||
return &calls
|
||||
}
|
||||
|
||||
// recorder installs a resolvconf stub for the duration of a test and returns
|
||||
// the captured invocations, each as the arguments followed by the stdin in
|
||||
// angle brackets when there was one. An empty failOn succeeds every call;
|
||||
// otherwise the named subcommand fails.
|
||||
func recorder(t *testing.T, failOn string) *[]string {
|
||||
t.Helper()
|
||||
original := resolvconfRunner
|
||||
calls := []string{}
|
||||
resolvconfRunner = func(stdin string, args ...string) ([]byte, error) {
|
||||
call := strings.Join(args, " ")
|
||||
if stdin != "" {
|
||||
call += " <" + stdin + ">"
|
||||
}
|
||||
calls = append(calls, call)
|
||||
if failOn != "" && len(args) > 0 && args[0] == failOn {
|
||||
return nil, errors.New("boom")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
t.Cleanup(func() { resolvconfRunner = original })
|
||||
return &calls
|
||||
}
|
||||
|
||||
// files replaces the resolver files read by the applied check for the
|
||||
// duration of a test. A path not in the map does not exist.
|
||||
func files(t *testing.T, contents map[string]string) {
|
||||
t.Helper()
|
||||
original := readResolverFile
|
||||
readResolverFile = func(path string) ([]byte, error) {
|
||||
if data, ok := contents[path]; ok {
|
||||
return []byte(data), nil
|
||||
}
|
||||
return nil, fs.ErrNotExist
|
||||
}
|
||||
t.Cleanup(func() { readResolverFile = original })
|
||||
}
|
||||
|
||||
// takenOver is what the libc subscriber writes once the TUN's nameserver is
|
||||
// the exclusive one.
|
||||
const takenOver = "# Generated by resolvconf\nnameserver 192.168.100.1\n"
|
||||
|
||||
// untouched is the DHCP-supplied resolv.conf that resolvconf=NO leaves in
|
||||
// place.
|
||||
const untouched = "# Generated by resolvconf\nnameserver 10.0.0.1\n"
|
||||
|
||||
func optedInTun() *FreeBSDTun {
|
||||
return &FreeBSDTun{
|
||||
options: &Config{
|
||||
Name: "tun7",
|
||||
Gateway: []string{"192.168.100.1/30"},
|
||||
AutoSystemDnsToGateway: true,
|
||||
},
|
||||
name: "tun7",
|
||||
gateway: netip.MustParsePrefix("192.168.100.1/30"),
|
||||
local: netip.MustParseAddr("192.168.100.2"),
|
||||
}
|
||||
}
|
||||
|
||||
func joined(calls []string) string {
|
||||
return strings.Join(calls, " | ")
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSDisabledByDefault(t *testing.T) {
|
||||
probes := stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.options.AutoSystemDnsToGateway = false
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*calls) != 0 || len(*probes) != 0 {
|
||||
t.Errorf("nothing may run when the option is off, got %q and %d probes", joined(*calls), len(*probes))
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the option is off")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSLeavesOSDNSWhenNoRoute(t *testing.T) {
|
||||
stubDNSRouting(t, errors.New("no route"))
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the probe fails")
|
||||
}
|
||||
if len(*calls) != 0 {
|
||||
t.Errorf("resolvconf must not run when the probe fails, got %q", joined(*calls))
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the probe fails")
|
||||
}
|
||||
}
|
||||
|
||||
// On FreeBSD the addresses are the other way round from Linux: the local
|
||||
// address is the one after the gateway, and the gateway itself has no owner,
|
||||
// so a packet to it is routed into the TUN. The probe has to carry that pair,
|
||||
// and the resolver has to be pointed at the gateway.
|
||||
func TestConfigureSystemDNSProbeCarriesFreeBSDPair(t *testing.T) {
|
||||
probes := stubDNSRouting(t, nil)
|
||||
recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*probes) != 1 {
|
||||
t.Fatalf("expected one probe, got %d", len(*probes))
|
||||
}
|
||||
want := probeCall{"tun", "192.168.100.2", "192.168.100.1"}
|
||||
if (*probes)[0] != want {
|
||||
t.Errorf("probe = %+v, want %+v", (*probes)[0], want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSAppliesResolvconf(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !t1.systemDNSSet {
|
||||
t.Fatal("systemDNSSet should be true after a successful takeover")
|
||||
}
|
||||
|
||||
want := "-a tun7 -x <nameserver 192.168.100.1\n>"
|
||||
if got := joined(*calls); got != want {
|
||||
t.Errorf("resolvconf calls = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// resolvconf exits 0 with resolvconf=NO in resolvconf.conf, and still records
|
||||
// the entry for the interface, but runs no subscriber, so success has to be
|
||||
// confirmed in what the subscribers wrote.
|
||||
func TestConfigureSystemDNSRefusesWhenResolvconfDidNotApply(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the nameserver did not reach a resolver")
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the takeover did not take")
|
||||
}
|
||||
if !strings.HasSuffix(joined(*calls), "-d tun7") {
|
||||
t.Errorf("expected a removal after the failed check, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSIdempotent(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
before := len(*calls)
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*calls) != before {
|
||||
t.Errorf("second call must be a no-op, calls went %d -> %d", before, len(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSAddFailureIsNotDirty(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "-a")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when resolvconf -a fails")
|
||||
}
|
||||
if t1.systemDNSSet || t1.systemDNSDirty {
|
||||
t.Error("a failed add leaves nothing to clean up")
|
||||
}
|
||||
if len(*calls) != 1 {
|
||||
t.Errorf("nothing else may run after a failed add, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
// If the removal after a failed check fails too, the entry may still be
|
||||
// installed, so the state has to be remembered rather than silently dropped.
|
||||
func TestConfigureSystemDNSRollbackFailureKeepsDirty(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
recorder(t, "-d")
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the check fails")
|
||||
}
|
||||
if !t1.systemDNSDirty {
|
||||
t.Error("a failed removal must leave the resolver marked dirty")
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the takeover did not complete")
|
||||
}
|
||||
}
|
||||
|
||||
// A dirty resolver is retried before anything new is applied.
|
||||
func TestConfigureSystemDNSRetriesDirtyBeforeApplying(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.systemDNSDirty = true
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
got := joined(*calls)
|
||||
if !strings.HasPrefix(got, "-d tun7 | -a tun7") {
|
||||
t.Errorf("expected the stale removal first, got %q", got)
|
||||
}
|
||||
if t1.systemDNSDirty {
|
||||
t.Error("a successful retry should clear the dirty flag")
|
||||
}
|
||||
if !t1.systemDNSSet {
|
||||
t.Error("the takeover should proceed once the retry succeeds")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsetSystemDNSRemoves(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("setup failed: %v", err)
|
||||
}
|
||||
*calls = nil
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet should be false after unset")
|
||||
}
|
||||
if got := joined(*calls); got != "-d tun7" {
|
||||
t.Errorf("unset calls = %q, want %q", got, "-d tun7")
|
||||
}
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if len(*calls) != 1 {
|
||||
t.Errorf("unsetSystemDNS must be idempotent, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsetSystemDNSKeepsDirtyWhenRemoveFails(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "-d")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.systemDNSSet = true
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if !t1.systemDNSDirty {
|
||||
t.Error("a failed removal during unset must be remembered")
|
||||
}
|
||||
if got := joined(*calls); got != "-d tun7" {
|
||||
t.Errorf("expected a removal attempt, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedLibc(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("resolv.conf listing the nameserver must count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedNotWhenUntouched(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || ok {
|
||||
t.Errorf("an unchanged resolv.conf and no resolvconf.conf must not count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
// With inclusive_interfaces in resolvconf.conf the exclusive marking is
|
||||
// ignored and the DHCP nameservers stay listed, so the system falls back to
|
||||
// them; that is the leak the option exists to close, and it must not pass.
|
||||
func TestResolvconfAppliedNotWhenOthersRemain(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.1\nnameserver 10.0.0.1\n"})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("another nameserver alongside the TUN's must not count as applied")
|
||||
}
|
||||
}
|
||||
|
||||
// A loopback nameserver alongside is a local resolver that resolvconf feeds
|
||||
// (local_unbound with the libc subscriber left on), not a leak.
|
||||
func TestResolvconfAppliedWithLoopbackAlongside(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 127.0.0.1\nnameserver 192.168.100.1\n"})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("a loopback nameserver alongside must still count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedIgnoresPrefixMatches(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.10\n"})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("192.168.100.10 must not match 192.168.100.1")
|
||||
}
|
||||
}
|
||||
|
||||
// local-unbound-setup turns the libc subscriber off and has resolvconf write
|
||||
// unbound's forwarders instead; resolv.conf then stays pointed at loopback.
|
||||
func TestResolvconfAppliedUnbound(t *testing.T) {
|
||||
files(t, map[string]string{
|
||||
"/etc/resolv.conf": "# Generated by resolvconf\nnameserver 127.0.0.1\noptions edns0\n",
|
||||
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
|
||||
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 192.168.100.1\n",
|
||||
})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("the nameserver in unbound's forwarders must count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedNotWhenUnboundUntouched(t *testing.T) {
|
||||
files(t, map[string]string{
|
||||
"/etc/resolv.conf": "nameserver 127.0.0.1\n",
|
||||
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
|
||||
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 10.0.0.1\n",
|
||||
})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("unbound still forwarding to the old server must not count as applied")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedReportsUnreadableResolvConf(t *testing.T) {
|
||||
files(t, map[string]string{})
|
||||
if _, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err == nil {
|
||||
t.Error("a missing resolv.conf is an error, not a verdict")
|
||||
}
|
||||
}
|
||||
+39
-118
@@ -11,29 +11,16 @@ import (
|
||||
"sync"
|
||||
|
||||
"github.com/vishvananda/netlink"
|
||||
appdns "github.com/xtls/xray-core/app/dns"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
xnet "github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/platform"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/core"
|
||||
feature_dns "github.com/xtls/xray-core/features/dns"
|
||||
"github.com/xtls/xray-core/features/dns/localdns"
|
||||
"github.com/xtls/xray-core/features/outbound"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
routingsession "github.com/xtls/xray-core/features/routing/session"
|
||||
"github.com/xtls/xray-core/proxy/dns"
|
||||
"golang.org/x/sys/unix"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/link/fdbased"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/stack"
|
||||
)
|
||||
|
||||
// LinuxTun is an object that handles tun network interface on linux
|
||||
// current version is heavily stripped to do nothing more,
|
||||
// then create a network interface, to be provided as file descriptor to gVisor ip stack
|
||||
// then create a network interface, whose packets are read and written through its file descriptor
|
||||
type LinuxTun struct {
|
||||
tunFd int
|
||||
*fdTun
|
||||
tunLink netlink.Link
|
||||
options *Config
|
||||
ownsTun bool
|
||||
@@ -108,81 +95,6 @@ func (t *LinuxTun) ifaceName() string {
|
||||
return attrs.Name
|
||||
}
|
||||
|
||||
// probeSourcePort is a representative client port for the routing probe. A real
|
||||
// query arrives from an ephemeral port that cannot be known in advance, so this
|
||||
// only matters for a rule that matches on a source port.
|
||||
const probeSourcePort = 49152
|
||||
|
||||
// verifyDNSRouting reports whether a DNS query to address would actually be
|
||||
// handled. Redirecting the system resolver at an address nothing answers would
|
||||
// break name resolution outright, so the takeover only proceeds when routing
|
||||
// hands such a query to a DNS-capable outbound.
|
||||
//
|
||||
// Overridable for tests.
|
||||
var verifyDNSRouting = func(ctx context.Context, inboundTag, source, address string) error {
|
||||
ip, err := netip.ParseAddr(address)
|
||||
if err != nil {
|
||||
return errors.New("invalid DNS address ", address).Base(err)
|
||||
}
|
||||
src, err := netip.ParseAddr(source)
|
||||
if err != nil || src.Is4() != ip.Is4() {
|
||||
return errors.New("invalid source address ", source).Base(err)
|
||||
}
|
||||
|
||||
instance := core.MustFromContext(ctx)
|
||||
|
||||
// Any resolution path that could still reach the system resolver has to be
|
||||
// refused, because pointing the system resolver at the TUN would close a
|
||||
// loop through the DNS outbound. With no `dns` section Core installs such a
|
||||
// client; with a `dns` section that has no name servers app/dns falls back
|
||||
// to one; and a name server pointed at "localhost" is one even when
|
||||
// independent upstreams are configured alongside it, because name servers
|
||||
// are selected per domain.
|
||||
switch dnsFeature := instance.GetFeature(feature_dns.ClientType()).(type) {
|
||||
case *localdns.Client:
|
||||
return errors.New("DNS feature is the system resolver, takeover would loop")
|
||||
case *appdns.DNS:
|
||||
if dnsFeature.MayUseSystemResolver() {
|
||||
return errors.New("DNS configuration may resolve through the system resolver, takeover would loop")
|
||||
}
|
||||
}
|
||||
|
||||
router, ok := instance.GetFeature(routing.RouterType()).(routing.Router)
|
||||
if !ok {
|
||||
return errors.New("router feature unavailable")
|
||||
}
|
||||
|
||||
// A real query from this interface carries a source address, and rules may
|
||||
// match on it, so the probe has to carry one too.
|
||||
queryCtx := session.ContextWithInbound(ctx, &session.Inbound{
|
||||
Name: "tun",
|
||||
Tag: inboundTag,
|
||||
Source: xnet.UDPDestination(xnet.IPAddress(src.AsSlice()), probeSourcePort),
|
||||
})
|
||||
queryCtx = session.ContextWithOutbounds(queryCtx, []*session.Outbound{{
|
||||
Target: xnet.UDPDestination(xnet.IPAddress(ip.AsSlice()), 53),
|
||||
}})
|
||||
|
||||
route, err := router.PickRoute(routingsession.AsRoutingContext(queryCtx))
|
||||
if err != nil {
|
||||
return errors.New("no route for ", address, ":53").Base(err)
|
||||
}
|
||||
|
||||
manager, ok := instance.GetFeature(outbound.ManagerType()).(outbound.Manager)
|
||||
if !ok {
|
||||
return errors.New("outbound manager unavailable")
|
||||
}
|
||||
|
||||
handler := manager.GetHandler(route.GetOutboundTag())
|
||||
if handler == nil {
|
||||
return errors.New("outbound ", route.GetOutboundTag(), " does not exist")
|
||||
}
|
||||
if settings := handler.ProxySettings(); settings == nil || settings.Type != serial.GetMessageType(&dns.Config{}) {
|
||||
return errors.New("outbound ", route.GetOutboundTag(), " does not handle DNS")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ConfigureSystemDNS points systemd-resolved at this interface so name lookups
|
||||
// resolve through Xray instead of leaking to the physical link.
|
||||
//
|
||||
@@ -287,19 +199,30 @@ var _ Tun = (*LinuxTun)(nil)
|
||||
|
||||
// NewTun builds new tun interface handler (linux specific)
|
||||
func NewTun(options *Config) (Tun, error) {
|
||||
tunFd, tunLink, fdProvided, err := openFromEnv(options.Name)
|
||||
tunFd, vnet, tunLink, fdProvided, err := openFromEnv(options.Name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if fdProvided {
|
||||
return &LinuxTun{
|
||||
tunFd: tunFd,
|
||||
fdTun: newFdTun(tunFd, vnet),
|
||||
tunLink: tunLink,
|
||||
options: options,
|
||||
}, nil
|
||||
}
|
||||
|
||||
tunFd, err = open(options.Name)
|
||||
// with a virtio_net_hdr on every packet the system leaves its TCP segments as large as they are,
|
||||
// with their checksums not completed, and takes such segments. Without it where that is refused
|
||||
vnet = vnetSize
|
||||
tunFd, err = open(options.Name, unix.IFF_VNET_HDR)
|
||||
if err == nil && unix.IoctlSetInt(tunFd, unix.TUNSETOFFLOAD, unix.TUN_F_CSUM|unix.TUN_F_TSO4|unix.TUN_F_TSO6) != nil {
|
||||
_ = unix.Close(tunFd)
|
||||
err = unix.EINVAL
|
||||
}
|
||||
if err != nil {
|
||||
vnet = 0
|
||||
tunFd, err = open(options.Name, 0)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -311,7 +234,7 @@ func NewTun(options *Config) (Tun, error) {
|
||||
}
|
||||
|
||||
linuxTun := &LinuxTun{
|
||||
tunFd: tunFd,
|
||||
fdTun: newFdTun(tunFd, vnet),
|
||||
tunLink: tunLink,
|
||||
options: options,
|
||||
ownsTun: true,
|
||||
@@ -320,55 +243,62 @@ func NewTun(options *Config) (Tun, error) {
|
||||
return linuxTun, nil
|
||||
}
|
||||
|
||||
func openFromEnv(expectedName string) (int, netlink.Link, bool, error) {
|
||||
// openFromEnv takes the tun that was given to the process, with the size of the virtio_net_hdr of its packets
|
||||
func openFromEnv(expectedName string) (int, int, netlink.Link, bool, error) {
|
||||
fdStr := platform.NewEnvFlag(platform.TunFdKey).GetValue(func() string { return "" })
|
||||
if fdStr == "" {
|
||||
return -1, nil, false, nil
|
||||
return -1, 0, nil, false, nil
|
||||
}
|
||||
|
||||
fd, err := strconv.Atoi(fdStr)
|
||||
if err != nil {
|
||||
return -1, nil, true, errors.New("invalid ", platform.TunFdKey).Base(err)
|
||||
return -1, 0, nil, true, errors.New("invalid ", platform.TunFdKey).Base(err)
|
||||
}
|
||||
if fd < 3 {
|
||||
return -1, nil, true, errors.New("invalid ", platform.TunFdKey, ": file descriptor must be >= 3")
|
||||
return -1, 0, nil, true, errors.New("invalid ", platform.TunFdKey, ": file descriptor must be >= 3")
|
||||
}
|
||||
|
||||
ifr, err := unix.NewIfreq("")
|
||||
if err != nil {
|
||||
return -1, nil, true, err
|
||||
return -1, 0, nil, true, err
|
||||
}
|
||||
if err = unix.IoctlIfreq(fd, unix.TUNGETIFF, ifr); err != nil {
|
||||
return -1, nil, true, err
|
||||
return -1, 0, nil, true, err
|
||||
}
|
||||
|
||||
flags := ifr.Uint16()
|
||||
if flags&unix.IFF_TUN == 0 {
|
||||
return -1, nil, true, errors.New("invalid ", platform.TunFdKey, ": file descriptor is not a TUN device")
|
||||
return -1, 0, nil, true, errors.New("invalid ", platform.TunFdKey, ": file descriptor is not a TUN device")
|
||||
}
|
||||
if flags&unix.IFF_NO_PI == 0 {
|
||||
return -1, nil, true, errors.New("invalid ", platform.TunFdKey, ": TUN device must use IFF_NO_PI")
|
||||
return -1, 0, nil, true, errors.New("invalid ", platform.TunFdKey, ": TUN device must use IFF_NO_PI")
|
||||
}
|
||||
vnet := 0
|
||||
if flags&unix.IFF_VNET_HDR != 0 {
|
||||
if vnet, err = unix.IoctlGetInt(fd, unix.TUNGETVNETHDRSZ); err != nil || vnet < vnetSize || vnet > packetRoom {
|
||||
return -1, 0, nil, true, errors.New("invalid ", platform.TunFdKey, ": virtio_net_hdr of ", vnet, " bytes").Base(err)
|
||||
}
|
||||
}
|
||||
|
||||
actualName := ifr.Name()
|
||||
if expectedName != "" && actualName != expectedName {
|
||||
return -1, nil, true, errors.New("invalid ", platform.TunFdKey, ": TUN device name ", actualName, " does not match configured name ", expectedName)
|
||||
return -1, 0, nil, true, errors.New("invalid ", platform.TunFdKey, ": TUN device name ", actualName, " does not match configured name ", expectedName)
|
||||
}
|
||||
|
||||
tunLink, err := netlink.LinkByName(actualName)
|
||||
if err != nil {
|
||||
return -1, nil, true, err
|
||||
return -1, 0, nil, true, err
|
||||
}
|
||||
|
||||
if err = unix.SetNonblock(fd, true); err != nil {
|
||||
return -1, nil, true, err
|
||||
return -1, 0, nil, true, err
|
||||
}
|
||||
|
||||
return fd, tunLink, true, nil
|
||||
return fd, vnet, tunLink, true, nil
|
||||
}
|
||||
|
||||
// open the file that implements tun interface in the OS
|
||||
func open(name string) (int, error) {
|
||||
func open(name string, features int) (int, error) {
|
||||
fd, err := unix.Open("/dev/net/tun", unix.O_RDWR, 0)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
@@ -380,7 +310,7 @@ func open(name string) (int, error) {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
flags := unix.IFF_TUN | unix.IFF_NO_PI
|
||||
flags := unix.IFF_TUN | unix.IFF_NO_PI | features
|
||||
ifr.SetUint16(uint16(flags))
|
||||
err = unix.IoctlIfreq(fd, unix.TUNSETIFF, ifr)
|
||||
if err != nil {
|
||||
@@ -457,7 +387,7 @@ func (t *LinuxTun) Close() error {
|
||||
if t.ownsTun {
|
||||
_ = netlink.LinkSetDown(t.tunLink)
|
||||
}
|
||||
_ = unix.Close(t.tunFd)
|
||||
_ = t.closeFile()
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -470,15 +400,6 @@ func (t *LinuxTun) Index() (int, error) {
|
||||
return t.tunLink.Attrs().Index, nil
|
||||
}
|
||||
|
||||
// newEndpoint builds new gVisor stack.LinkEndpoint from the tun interface file descriptor
|
||||
func (t *LinuxTun) newEndpoint() (stack.LinkEndpoint, error) {
|
||||
return fdbased.New(&fdbased.Options{
|
||||
FDs: []int{t.tunFd},
|
||||
MTU: t.options.MTU,
|
||||
RXChecksumOffload: true,
|
||||
})
|
||||
}
|
||||
|
||||
func setinterface(network, address string, fd uintptr, iface *net.Interface) error {
|
||||
return unix.BindToDevice(int(fd), iface.Name)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//go:build (linux && !android) || freebsd
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/netip"
|
||||
|
||||
appdns "github.com/xtls/xray-core/app/dns"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
xnet "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"
|
||||
feature_dns "github.com/xtls/xray-core/features/dns"
|
||||
"github.com/xtls/xray-core/features/dns/localdns"
|
||||
"github.com/xtls/xray-core/features/outbound"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
routingsession "github.com/xtls/xray-core/features/routing/session"
|
||||
"github.com/xtls/xray-core/proxy/dns"
|
||||
)
|
||||
|
||||
// probeSourcePort is a representative client port for the routing probe. A real
|
||||
// query arrives from an ephemeral port that cannot be known in advance, so this
|
||||
// only matters for a rule that matches on a source port.
|
||||
const probeSourcePort = 49152
|
||||
|
||||
// verifyDNSRouting reports whether a DNS query to address would actually be
|
||||
// handled. Redirecting the system resolver at an address nothing answers would
|
||||
// break name resolution outright, so the takeover only proceeds when routing
|
||||
// hands such a query to a DNS-capable outbound.
|
||||
//
|
||||
// Overridable for tests.
|
||||
var verifyDNSRouting = func(ctx context.Context, inboundTag, source, address string) error {
|
||||
ip, err := netip.ParseAddr(address)
|
||||
if err != nil {
|
||||
return errors.New("invalid DNS address ", address).Base(err)
|
||||
}
|
||||
src, err := netip.ParseAddr(source)
|
||||
if err != nil || src.Is4() != ip.Is4() {
|
||||
return errors.New("invalid source address ", source).Base(err)
|
||||
}
|
||||
|
||||
instance := core.MustFromContext(ctx)
|
||||
|
||||
// Any resolution path that could still reach the system resolver has to be
|
||||
// refused, because pointing the system resolver at the TUN would close a
|
||||
// loop through the DNS outbound. With no `dns` section Core installs such a
|
||||
// client; with a `dns` section that has no name servers app/dns falls back
|
||||
// to one; and a name server pointed at "localhost" is one even when
|
||||
// independent upstreams are configured alongside it, because name servers
|
||||
// are selected per domain.
|
||||
switch dnsFeature := instance.GetFeature(feature_dns.ClientType()).(type) {
|
||||
case *localdns.Client:
|
||||
return errors.New("DNS feature is the system resolver, takeover would loop")
|
||||
case *appdns.DNS:
|
||||
if dnsFeature.MayUseSystemResolver() {
|
||||
return errors.New("DNS configuration may resolve through the system resolver, takeover would loop")
|
||||
}
|
||||
}
|
||||
|
||||
router, ok := instance.GetFeature(routing.RouterType()).(routing.Router)
|
||||
if !ok {
|
||||
return errors.New("router feature unavailable")
|
||||
}
|
||||
|
||||
// A real query from this interface carries a source address, and rules may
|
||||
// match on it, so the probe has to carry one too.
|
||||
queryCtx := session.ContextWithInbound(ctx, &session.Inbound{
|
||||
Name: "tun",
|
||||
Tag: inboundTag,
|
||||
Source: xnet.UDPDestination(xnet.IPAddress(src.AsSlice()), probeSourcePort),
|
||||
})
|
||||
queryCtx = session.ContextWithOutbounds(queryCtx, []*session.Outbound{{
|
||||
Target: xnet.UDPDestination(xnet.IPAddress(ip.AsSlice()), 53),
|
||||
}})
|
||||
|
||||
route, err := router.PickRoute(routingsession.AsRoutingContext(queryCtx))
|
||||
if err != nil {
|
||||
return errors.New("no route for ", address, ":53").Base(err)
|
||||
}
|
||||
|
||||
manager, ok := instance.GetFeature(outbound.ManagerType()).(outbound.Manager)
|
||||
if !ok {
|
||||
return errors.New("outbound manager unavailable")
|
||||
}
|
||||
|
||||
handler := manager.GetHandler(route.GetOutboundTag())
|
||||
if handler == nil {
|
||||
return errors.New("outbound ", route.GetOutboundTag(), " does not exist")
|
||||
}
|
||||
if settings := handler.ProxySettings(); settings == nil || settings.Type != serial.GetMessageType(&dns.Config{}) {
|
||||
return errors.New("outbound ", route.GetOutboundTag(), " does not handle DNS")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+30
-50
@@ -25,9 +25,6 @@ import (
|
||||
"golang.org/x/sys/windows"
|
||||
"golang.zx2c4.com/wintun"
|
||||
"golang.zx2c4.com/wireguard/windows/tunnel/winipcfg"
|
||||
"gvisor.dev/gvisor/pkg/buffer"
|
||||
"gvisor.dev/gvisor/pkg/tcpip"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/stack"
|
||||
)
|
||||
|
||||
//go:linkname procyield runtime.procyield
|
||||
@@ -35,7 +32,7 @@ func procyield(cycles uint32)
|
||||
|
||||
// WindowsTun is an object that handles tun network interface on Windows
|
||||
// current version is heavily stripped to do nothing more,
|
||||
// then create a network interface, to be provided as endpoint to gVisor ip stack
|
||||
// then create a network interface, whose packets are read and written through a Wintun session
|
||||
type WindowsTun struct {
|
||||
sync.RWMutex
|
||||
|
||||
@@ -57,9 +54,6 @@ type WindowsTun struct {
|
||||
// WindowsTun implements Tun
|
||||
var _ Tun = (*WindowsTun)(nil)
|
||||
|
||||
// WindowsTun implements GVisorDevice
|
||||
var _ GVisorDevice = (*WindowsTun)(nil)
|
||||
|
||||
// NewTun creates a Wintun interface with the given name. Should a Wintun
|
||||
// interface with the same name exist, it tried to be reused.
|
||||
func NewTun(options *Config) (Tun, error) {
|
||||
@@ -368,6 +362,8 @@ func (t *WindowsTun) Close() error {
|
||||
flushDNSCache()
|
||||
}
|
||||
if t.session != (wintun.Session{}) {
|
||||
// ReadPacket may be waiting for a packet
|
||||
_ = windows.SetEvent(t.readWait)
|
||||
t.session.End()
|
||||
}
|
||||
if t.adapter != nil {
|
||||
@@ -507,62 +503,46 @@ func (t *WindowsTun) Index() (int, error) {
|
||||
return int(row.InterfaceIndex), nil
|
||||
}
|
||||
|
||||
// WritePacket implements GVisorDevice method to write one packet to the tun device
|
||||
func (t *WindowsTun) WritePacket(packetBuffer *stack.PacketBuffer) tcpip.Error {
|
||||
// WritePacket implements Tun: the two parts are copied into the ring of Wintun
|
||||
func (t *WindowsTun) WritePacket(header, payload []byte) error {
|
||||
t.RLock()
|
||||
defer t.RUnlock()
|
||||
if t.closed {
|
||||
return &tcpip.ErrClosedForSend{}
|
||||
return windows.ERROR_HANDLE_EOF
|
||||
}
|
||||
|
||||
// request buffer from Wintun
|
||||
packet, err := t.session.AllocateSendPacket(packetBuffer.Size())
|
||||
packet, err := t.session.AllocateSendPacket(len(header) + len(payload))
|
||||
if err != nil {
|
||||
return &tcpip.ErrAborted{}
|
||||
return err
|
||||
}
|
||||
|
||||
// copy the bytes of slices that compose the packet into the allocated buffer
|
||||
var index int
|
||||
for _, packetElement := range packetBuffer.AsSlices() {
|
||||
index += copy(packet[index:], packetElement)
|
||||
}
|
||||
|
||||
// signal Wintun to send that buffer as the packet
|
||||
copy(packet[copy(packet, header):], payload)
|
||||
t.session.SendPacket(packet)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReadPacket implements GVisorDevice method to read one packet from the tun device
|
||||
// It is expected that the method will not block, rather return ErrQueueEmpty when there is nothing on the line,
|
||||
// which will make the stack call Wait which should implement desired push-back
|
||||
func (t *WindowsTun) ReadPacket() (byte, *stack.PacketBuffer, error) {
|
||||
packet, err := t.session.ReceivePacket()
|
||||
if go_errors.Is(err, windows.ERROR_NO_MORE_ITEMS) {
|
||||
return 0, nil, ErrQueueEmpty
|
||||
}
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
version := packet[0] >> 4
|
||||
packetBuffer := buffer.MakeWithView(buffer.NewViewWithData(packet))
|
||||
return version, stack.NewPacketBuffer(stack.PacketBufferOptions{
|
||||
Payload: packetBuffer,
|
||||
IsForwardedPacket: true,
|
||||
OnRelease: func() {
|
||||
// ReadPacket implements Tun: it waits until Wintun has a packet and copies it out of the ring
|
||||
func (t *WindowsTun) ReadPacket(b []byte) ([]byte, error) {
|
||||
for {
|
||||
t.RLock()
|
||||
if t.closed {
|
||||
t.RUnlock()
|
||||
return nil, windows.ERROR_HANDLE_EOF
|
||||
}
|
||||
packet, err := t.session.ReceivePacket()
|
||||
if err == nil {
|
||||
n := copy(b, packet)
|
||||
t.session.ReleaseReceivePacket(packet)
|
||||
},
|
||||
}), nil
|
||||
}
|
||||
|
||||
func (t *WindowsTun) Wait() {
|
||||
procyield(1)
|
||||
_, _ = windows.WaitForSingleObject(t.readWait, windows.INFINITE)
|
||||
}
|
||||
|
||||
func (t *WindowsTun) newEndpoint() (stack.LinkEndpoint, error) {
|
||||
return &LinkEndpoint{deviceMTU: t.options.MTU, device: t}, nil
|
||||
t.RUnlock()
|
||||
return b[:n], nil
|
||||
}
|
||||
t.RUnlock()
|
||||
if !go_errors.Is(err, windows.ERROR_NO_MORE_ITEMS) {
|
||||
return nil, err
|
||||
}
|
||||
procyield(1)
|
||||
_, _ = windows.WaitForSingleObject(t.readWait, windows.INFINITE)
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
|
||||
+19
-36
@@ -11,11 +11,6 @@ import (
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
)
|
||||
|
||||
type packet struct {
|
||||
data []byte
|
||||
dest *net.Destination
|
||||
}
|
||||
|
||||
// sub-handler specifically for udp connections under main handler
|
||||
type udpConnectionHandler struct {
|
||||
sync.RWMutex
|
||||
@@ -38,17 +33,17 @@ func newUdpConnectionHandler(handleConnection func(conn net.Conn, dest net.Desti
|
||||
|
||||
// HandlePacket handles UDP packets coming from tun, to forward to the dispatcher
|
||||
// this custom handler support FullCone NAT of returning packets, binding connection only by the source addr:port
|
||||
func (u *udpConnectionHandler) HandlePacket(src net.Destination, dst net.Destination, data []byte) {
|
||||
func (u *udpConnectionHandler) HandlePacket(src net.Destination, dst net.Destination, data *buf.Buffer) {
|
||||
data.UDP = &dst
|
||||
|
||||
u.RLock()
|
||||
conn, found := u.udpConns[src]
|
||||
if found {
|
||||
select {
|
||||
case conn.egress <- &packet{
|
||||
data: data,
|
||||
dest: &dst,
|
||||
}:
|
||||
case conn.egress <- data:
|
||||
default:
|
||||
errors.LogDebug(context.Background(), "drop udp with size ", len(data), " to ", dst.NetAddr(), " original ", conn.dst.NetAddr(), " > queue full")
|
||||
errors.LogDebug(context.Background(), "drop udp with size ", data.Len(), " to ", dst.NetAddr(), " original ", conn.dst.NetAddr(), " > queue full")
|
||||
data.Release()
|
||||
}
|
||||
u.RUnlock()
|
||||
return
|
||||
@@ -60,7 +55,7 @@ func (u *udpConnectionHandler) HandlePacket(src net.Destination, dst net.Destina
|
||||
|
||||
conn, found = u.udpConns[src]
|
||||
if !found {
|
||||
egress := make(chan *packet, 1024)
|
||||
egress := make(chan *buf.Buffer, 1024)
|
||||
conn = &udpConn{handler: u, egress: egress, src: src, dst: dst}
|
||||
u.udpConns[src] = conn
|
||||
|
||||
@@ -69,12 +64,10 @@ func (u *udpConnectionHandler) HandlePacket(src net.Destination, dst net.Destina
|
||||
|
||||
// send packet data to the egress channel, if it has buffer, or discard
|
||||
select {
|
||||
case conn.egress <- &packet{
|
||||
data: data,
|
||||
dest: &dst,
|
||||
}:
|
||||
case conn.egress <- data:
|
||||
default:
|
||||
errors.LogDebug(context.Background(), "drop udp with size ", len(data), " to ", dst.NetAddr(), " original ", conn.dst.NetAddr(), " > queue full 2")
|
||||
errors.LogDebug(context.Background(), "drop udp with size ", data.Len(), " to ", dst.NetAddr(), " original ", conn.dst.NetAddr(), " > queue full 2")
|
||||
data.Release()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,38 +85,28 @@ func (u *udpConnectionHandler) connectionFinished(conn *udpConn) {
|
||||
type udpConn struct {
|
||||
handler *udpConnectionHandler
|
||||
|
||||
egress chan *packet
|
||||
egress chan *buf.Buffer
|
||||
src net.Destination
|
||||
dst net.Destination
|
||||
}
|
||||
|
||||
func (c *udpConn) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
for {
|
||||
e, ok := <-c.egress
|
||||
if !ok {
|
||||
return nil, io.EOF
|
||||
}
|
||||
|
||||
b := buf.New()
|
||||
if _, err := b.Write(e.data); err != nil {
|
||||
errors.LogErrorInner(context.Background(), err, "drop packet to ", e.dest, " with size ", len(e.data))
|
||||
b.Release()
|
||||
continue
|
||||
}
|
||||
b.UDP = e.dest
|
||||
|
||||
return buf.MultiBuffer{b}, nil
|
||||
b, ok := <-c.egress
|
||||
if !ok {
|
||||
return nil, io.EOF
|
||||
}
|
||||
return buf.MultiBuffer{b}, nil
|
||||
}
|
||||
|
||||
// Read packets from the connection
|
||||
func (c *udpConn) Read(p []byte) (int, error) {
|
||||
e, ok := <-c.egress
|
||||
b, ok := <-c.egress
|
||||
if !ok {
|
||||
return 0, io.EOF
|
||||
}
|
||||
n := copy(p, e.data)
|
||||
if n != len(e.data) {
|
||||
defer b.Release()
|
||||
n := copy(p, b.Bytes())
|
||||
if n != int(b.Len()) {
|
||||
return 0, io.ErrShortBuffer
|
||||
}
|
||||
return n, nil
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/net/cnc"
|
||||
"github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask"
|
||||
"github.com/xtls/xray-core/transport/internet/hysteria/congestion"
|
||||
@@ -26,8 +27,9 @@ import (
|
||||
)
|
||||
|
||||
type client struct {
|
||||
sync.Mutex
|
||||
|
||||
lock chan struct{}
|
||||
instance *core.Instance
|
||||
forced bool
|
||||
dest net.Destination
|
||||
config *Config
|
||||
tlsConfig *gotls.Config
|
||||
@@ -64,11 +66,14 @@ func (c *client) close() {
|
||||
}
|
||||
|
||||
func (c *client) dial(ctx context.Context) error {
|
||||
status := c.status()
|
||||
if status == StatusActive {
|
||||
return nil
|
||||
if c.forced {
|
||||
return errors.New("client is closed")
|
||||
}
|
||||
if status == StatusInactive {
|
||||
|
||||
switch c.status() {
|
||||
case StatusActive:
|
||||
return nil
|
||||
case StatusInactive:
|
||||
c.close()
|
||||
}
|
||||
|
||||
@@ -90,7 +95,7 @@ func (c *client) dial(ctx context.Context) error {
|
||||
ChromeParrot: !quicParams.DisableChromeParrot,
|
||||
EnableDatagrams: true,
|
||||
MaxDatagramFrameSize: MaxDatagramFrameSize,
|
||||
OmitMaxDatagramFrameSize: time.Now().After(time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC)),
|
||||
OmitMaxDatagramFrameSize: true,
|
||||
DisablePathManager: true,
|
||||
}
|
||||
if quicParams.InitStreamReceiveWindow == 0 {
|
||||
@@ -171,8 +176,9 @@ func (c *client) dial(ctx context.Context) error {
|
||||
CommonHeaderPadding: []string{AuthRequestPadding.String()},
|
||||
},
|
||||
}
|
||||
resp, err := rt.RoundTrip(req)
|
||||
resp, err := rt.RoundTrip(req.WithContext(ctx))
|
||||
if err != nil {
|
||||
_ = rt.Close()
|
||||
if conn != nil {
|
||||
_ = conn.CloseWithError(closeErrCodeProtocolError, "")
|
||||
}
|
||||
@@ -180,13 +186,15 @@ func (c *client) dial(ctx context.Context) error {
|
||||
_ = pktConn.Close()
|
||||
return err
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != StatusAuthOK {
|
||||
_ = rt.Close()
|
||||
_ = conn.CloseWithError(closeErrCodeProtocolError, "")
|
||||
_ = tr.Close()
|
||||
_ = pktConn.Close()
|
||||
return errors.New("auth failed code ", resp.StatusCode)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
|
||||
// udp, _ := strconv.ParseBool(resp.Header.Get(ResponseHeaderUDPEnabled))
|
||||
down, _ := strconv.ParseUint(resp.Header.Get(CommonHeaderCCRX), 10, 64)
|
||||
@@ -221,9 +229,17 @@ func (c *client) dial(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *client) unlock() {
|
||||
<-c.lock
|
||||
}
|
||||
|
||||
func (c *client) tcp(ctx context.Context) (stat.Connection, error) {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case c.lock <- struct{}{}:
|
||||
defer c.unlock()
|
||||
}
|
||||
|
||||
err := c.dial(ctx)
|
||||
if err != nil {
|
||||
@@ -245,8 +261,12 @@ func (c *client) tcp(ctx context.Context) (stat.Connection, error) {
|
||||
}
|
||||
|
||||
func (c *client) udp(ctx context.Context) (stat.Connection, error) {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case c.lock <- struct{}{}:
|
||||
defer c.unlock()
|
||||
}
|
||||
|
||||
err := c.dial(ctx)
|
||||
if err != nil {
|
||||
@@ -256,12 +276,15 @@ func (c *client) udp(ctx context.Context) (stat.Connection, error) {
|
||||
return c.udpSM.udp()
|
||||
}
|
||||
|
||||
func (c *client) clean() {
|
||||
c.Lock()
|
||||
if c.status() == StatusInactive {
|
||||
func (c *client) clean(force bool) {
|
||||
c.lock <- struct{}{}
|
||||
if force {
|
||||
c.forced = true
|
||||
}
|
||||
if status := c.status(); force && status != StatusNull || status == StatusInactive {
|
||||
c.close()
|
||||
}
|
||||
c.Unlock()
|
||||
c.unlock()
|
||||
}
|
||||
|
||||
type dialerConf struct {
|
||||
@@ -278,10 +301,20 @@ func (m *clientManager) clean() {
|
||||
ticker := time.NewTicker(idleCleanupInterval)
|
||||
for range ticker.C {
|
||||
m.RLock()
|
||||
for _, c := range m.m {
|
||||
c.clean()
|
||||
entries := make(map[dialerConf]*client, len(m.m))
|
||||
for k, c := range m.m {
|
||||
entries[k] = c
|
||||
}
|
||||
m.RUnlock()
|
||||
for k, c := range entries {
|
||||
force := c.instance != nil && !c.instance.IsRunning()
|
||||
c.clean(force)
|
||||
if force {
|
||||
m.Lock()
|
||||
delete(m.m, k)
|
||||
m.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -306,15 +339,19 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me
|
||||
go manager.clean()
|
||||
})
|
||||
|
||||
dialerConfKey := dialerConf{dest, streamSettings}
|
||||
|
||||
manager.RLock()
|
||||
c := manager.m[dialerConf{dest, streamSettings}]
|
||||
c := manager.m[dialerConfKey]
|
||||
manager.RUnlock()
|
||||
|
||||
if c == nil {
|
||||
manager.Lock()
|
||||
c = manager.m[dialerConf{dest, streamSettings}]
|
||||
c = manager.m[dialerConfKey]
|
||||
if c == nil {
|
||||
c = &client{
|
||||
lock: make(chan struct{}, 1),
|
||||
instance: core.FromContext(ctx),
|
||||
dest: dest,
|
||||
config: streamSettings.ProtocolSettings.(*Config),
|
||||
tlsConfig: tlsConfig.GetTLSConfig(tls.WithDestination(dest)),
|
||||
@@ -322,7 +359,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me
|
||||
finalMask: streamSettings.FinalMask,
|
||||
quicParams: streamSettings.QuicParams,
|
||||
}
|
||||
manager.m[dialerConf{dest, streamSettings}] = c
|
||||
manager.m[dialerConfKey] = c
|
||||
}
|
||||
manager.Unlock()
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package masque
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
)
|
||||
@@ -9,6 +11,13 @@ const protocolName = "masque"
|
||||
|
||||
const DefaultPath = "/.well-known/masque/ip/*/*/"
|
||||
|
||||
func (c *Config) keepAlivePeriod() time.Duration {
|
||||
if c.Xmux == nil {
|
||||
return 0
|
||||
}
|
||||
return time.Duration(c.Xmux.HKeepAlivePeriod) * time.Second
|
||||
}
|
||||
|
||||
func init() {
|
||||
common.Must(internet.RegisterProtocolConfigCreator(protocolName, func() interface{} {
|
||||
return &Config{
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
package masque
|
||||
|
||||
import (
|
||||
splithttp "github.com/xtls/xray-core/transport/internet/splithttp"
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
@@ -27,6 +28,7 @@ type Config struct {
|
||||
Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
|
||||
Headers map[string]string `protobuf:"bytes,3,rep,name=headers,proto3" json:"headers,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
|
||||
Warp *Warp `protobuf:"bytes,4,opt,name=warp,proto3" json:"warp,omitempty"`
|
||||
Xmux *splithttp.XmuxConfig `protobuf:"bytes,5,opt,name=xmux,proto3" json:"xmux,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -89,6 +91,13 @@ func (x *Config) GetWarp() *Warp {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Config) GetXmux() *splithttp.XmuxConfig {
|
||||
if x != nil {
|
||||
return x.Xmux
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Warp struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
PrivateKey []byte `protobuf:"bytes,1,opt,name=private_key,json=privateKey,proto3" json:"private_key,omitempty"`
|
||||
@@ -153,12 +162,13 @@ var File_transport_internet_masque_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_transport_internet_masque_config_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"&transport/internet/masque/config.proto\x12\x1exray.transport.internet.masque\"\xf5\x01\n" +
|
||||
"&transport/internet/masque/config.proto\x12\x1exray.transport.internet.masque\x1a)transport/internet/splithttp/config.proto\"\xb8\x02\n" +
|
||||
"\x06Config\x12\x12\n" +
|
||||
"\x04host\x18\x01 \x01(\tR\x04host\x12\x12\n" +
|
||||
"\x04path\x18\x02 \x01(\tR\x04path\x12M\n" +
|
||||
"\aheaders\x18\x03 \x03(\v23.xray.transport.internet.masque.Config.HeadersEntryR\aheaders\x128\n" +
|
||||
"\x04warp\x18\x04 \x01(\v2$.xray.transport.internet.masque.WarpR\x04warp\x1a:\n" +
|
||||
"\x04warp\x18\x04 \x01(\v2$.xray.transport.internet.masque.WarpR\x04warp\x12A\n" +
|
||||
"\x04xmux\x18\x05 \x01(\v2-.xray.transport.internet.splithttp.XmuxConfigR\x04xmux\x1a:\n" +
|
||||
"\fHeadersEntry\x12\x10\n" +
|
||||
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
|
||||
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"`\n" +
|
||||
@@ -184,18 +194,20 @@ func file_transport_internet_masque_config_proto_rawDescGZIP() []byte {
|
||||
|
||||
var file_transport_internet_masque_config_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
|
||||
var file_transport_internet_masque_config_proto_goTypes = []any{
|
||||
(*Config)(nil), // 0: xray.transport.internet.masque.Config
|
||||
(*Warp)(nil), // 1: xray.transport.internet.masque.Warp
|
||||
nil, // 2: xray.transport.internet.masque.Config.HeadersEntry
|
||||
(*Config)(nil), // 0: xray.transport.internet.masque.Config
|
||||
(*Warp)(nil), // 1: xray.transport.internet.masque.Warp
|
||||
nil, // 2: xray.transport.internet.masque.Config.HeadersEntry
|
||||
(*splithttp.XmuxConfig)(nil), // 3: xray.transport.internet.splithttp.XmuxConfig
|
||||
}
|
||||
var file_transport_internet_masque_config_proto_depIdxs = []int32{
|
||||
2, // 0: xray.transport.internet.masque.Config.headers:type_name -> xray.transport.internet.masque.Config.HeadersEntry
|
||||
1, // 1: xray.transport.internet.masque.Config.warp:type_name -> xray.transport.internet.masque.Warp
|
||||
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
|
||||
3, // 2: xray.transport.internet.masque.Config.xmux:type_name -> xray.transport.internet.splithttp.XmuxConfig
|
||||
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_transport_internet_masque_config_proto_init() }
|
||||
|
||||
@@ -6,11 +6,14 @@ option go_package = "github.com/xtls/xray-core/transport/internet/masque";
|
||||
option java_package = "com.xray.transport.internet.masque";
|
||||
option java_multiple_files = true;
|
||||
|
||||
import "transport/internet/splithttp/config.proto";
|
||||
|
||||
message Config {
|
||||
string host = 1;
|
||||
string path = 2;
|
||||
map<string, string> headers = 3;
|
||||
Warp warp = 4;
|
||||
xray.transport.internet.splithttp.XmuxConfig xmux = 5;
|
||||
}
|
||||
|
||||
message Warp {
|
||||
|
||||
@@ -72,7 +72,11 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me
|
||||
quicConfig.MaxIdleTimeout = 30 * time.Second
|
||||
}
|
||||
if quicParams.KeepAlivePeriod == 0 {
|
||||
quicConfig.KeepAlivePeriod = net.QuicgoH3KeepAlivePeriod
|
||||
if keepAlivePeriod := config.keepAlivePeriod(); keepAlivePeriod == 0 {
|
||||
quicConfig.KeepAlivePeriod = net.QuicgoH3KeepAlivePeriod
|
||||
} else if keepAlivePeriod > 0 {
|
||||
quicConfig.KeepAlivePeriod = keepAlivePeriod
|
||||
}
|
||||
}
|
||||
|
||||
var pktConn net.PacketConn
|
||||
@@ -179,7 +183,11 @@ func dialHTTP2(ctx context.Context, dest net.Destination, streamSettings *intern
|
||||
return nil, errors.New("the server negotiated ", strconv.Quote(protocol), " instead of h2")
|
||||
}
|
||||
|
||||
cc, err := newHTTP2ClientConn(conn)
|
||||
keepAlivePeriod := config.keepAlivePeriod()
|
||||
if keepAlivePeriod == 0 {
|
||||
keepAlivePeriod = net.ChromeH2KeepAlivePeriod
|
||||
}
|
||||
cc, err := newHTTP2ClientConn(conn, keepAlivePeriod)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
@@ -212,22 +220,7 @@ func establish(ctx context.Context, client tunnelClient, hconn httpConn, abort f
|
||||
for k, v := range config.Headers {
|
||||
header.Set(k, v)
|
||||
}
|
||||
switch header.Get("User-Agent") {
|
||||
case "":
|
||||
header["User-Agent"] = nil
|
||||
case "chrome":
|
||||
header.Set("User-Agent", utils.ChromeUA)
|
||||
case "firefox":
|
||||
header.Set("User-Agent", utils.FirefoxUA)
|
||||
case "safari":
|
||||
header.Set("User-Agent", utils.SafariUA)
|
||||
case "edge":
|
||||
header.Set("User-Agent", utils.MSEdgeUA)
|
||||
case "curl":
|
||||
header.Set("User-Agent", utils.CurlUA)
|
||||
case "golang":
|
||||
header.Del("User-Agent")
|
||||
}
|
||||
setUserAgent(header)
|
||||
|
||||
ipConn, _, err := client.Dial(req)
|
||||
if err != nil {
|
||||
@@ -327,6 +320,28 @@ func authority(config *Config, serverName string, port net.Port) string {
|
||||
return net.JoinHostPort(host, port.String())
|
||||
}
|
||||
|
||||
func setUserAgent(header http.Header) {
|
||||
if _, ok := header["User-Agent"]; !ok {
|
||||
header.Set("User-Agent", "chrome")
|
||||
}
|
||||
switch header.Get("User-Agent") {
|
||||
case "":
|
||||
header["User-Agent"] = nil
|
||||
case "chrome":
|
||||
header.Set("User-Agent", utils.ChromeUA)
|
||||
case "firefox":
|
||||
header.Set("User-Agent", utils.FirefoxUA)
|
||||
case "safari":
|
||||
header.Set("User-Agent", utils.SafariUA)
|
||||
case "edge":
|
||||
header.Set("User-Agent", utils.MSEdgeUA)
|
||||
case "curl":
|
||||
header.Set("User-Agent", utils.CurlUA)
|
||||
case "golang":
|
||||
header.Del("User-Agent")
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
common.Must(internet.RegisterTransportDialer(protocolName, Dial))
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
package masque
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/utils"
|
||||
"github.com/xtls/xray-core/transport/internet/masque/connectip"
|
||||
"github.com/xtls/xray-core/transport/internet/tls"
|
||||
)
|
||||
@@ -77,3 +79,26 @@ func TestLocalAddrs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetUserAgent(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
header http.Header
|
||||
want []string
|
||||
}{
|
||||
{"default", http.Header{}, []string{utils.ChromeUA}},
|
||||
{"empty", http.Header{"User-Agent": {""}}, nil},
|
||||
{"preset", http.Header{"User-Agent": {"firefox"}}, []string{utils.FirefoxUA}},
|
||||
{"custom", http.Header{"User-Agent": {"custom/1.0"}}, []string{"custom/1.0"}},
|
||||
} {
|
||||
setUserAgent(tc.header)
|
||||
if got := tc.header["User-Agent"]; !slices.Equal(got, tc.want) {
|
||||
t.Errorf("%s: got %q, want %q", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
header := http.Header{"User-Agent": {"golang"}}
|
||||
setUserAgent(header)
|
||||
if _, ok := header["User-Agent"]; ok {
|
||||
t.Errorf("golang: the header should be removed, got %q", header["User-Agent"])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ const (
|
||||
http2WindowUpdateSize = 1 << 20
|
||||
http2KeepAlivePeriod = 10 * time.Second
|
||||
http2IdleTimeout = 30 * time.Second
|
||||
http2PingTimeout = 15 * time.Second
|
||||
http2DefaultUserAgent = "Go-http-client/2.0"
|
||||
)
|
||||
|
||||
@@ -79,7 +80,7 @@ type http2ClientConn struct {
|
||||
recvUnacked int64
|
||||
}
|
||||
|
||||
func newHTTP2ClientConn(conn net.Conn) (*http2ClientConn, error) {
|
||||
func newHTTP2ClientConn(conn net.Conn, keepAlivePeriod time.Duration) (*http2ClientConn, error) {
|
||||
c := &http2ClientConn{
|
||||
conn: conn,
|
||||
bw: bufio.NewWriter(conn),
|
||||
@@ -119,7 +120,9 @@ func newHTTP2ClientConn(conn net.Conn) (*http2ClientConn, error) {
|
||||
return nil, err
|
||||
}
|
||||
go c.readLoop()
|
||||
go c.keepAlive()
|
||||
if keepAlivePeriod > 0 {
|
||||
go c.keepAlive(keepAlivePeriod)
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
@@ -363,21 +366,29 @@ func (c *http2ClientConn) abortStream(err error, reset bool) {
|
||||
}
|
||||
}
|
||||
|
||||
func (c *http2ClientConn) keepAlive() {
|
||||
ticker := time.NewTicker(http2KeepAlivePeriod)
|
||||
func (c *http2ClientConn) keepAlive(period time.Duration) {
|
||||
ticker := time.NewTicker(max(min(period, http2PingTimeout)/3, time.Second))
|
||||
defer ticker.Stop()
|
||||
var pingAt time.Time
|
||||
for {
|
||||
select {
|
||||
case <-c.done:
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
idle := time.Since(time.Unix(0, c.lastFrame.Load()))
|
||||
if idle >= http2IdleTimeout {
|
||||
c.fail(errHTTP2IdleTimeout)
|
||||
return
|
||||
lastFrame := time.Unix(0, c.lastFrame.Load())
|
||||
if !pingAt.IsZero() {
|
||||
if lastFrame.Before(pingAt) {
|
||||
if time.Since(pingAt) >= http2PingTimeout {
|
||||
c.fail(errHTTP2IdleTimeout)
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
pingAt = time.Time{}
|
||||
}
|
||||
if idle >= http2KeepAlivePeriod {
|
||||
if time.Since(lastFrame) >= period {
|
||||
pingAt = time.Now()
|
||||
go c.write(func(fr *http2.Framer) error {
|
||||
return fr.WritePing(false, [8]byte{})
|
||||
})
|
||||
|
||||
@@ -127,7 +127,7 @@ func TestHTTP2ServerRoundTrip(t *testing.T) {
|
||||
_, err := io.Copy(w, r.Body)
|
||||
assert.NoError(t, err)
|
||||
})
|
||||
cc, err := newHTTP2ClientConn(serveHTTP2Pipe(t, handler))
|
||||
cc, err := newHTTP2ClientConn(serveHTTP2Pipe(t, handler), http2KeepAlivePeriod)
|
||||
require.NoError(t, err)
|
||||
defer cc.Close()
|
||||
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
package masque
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -52,7 +55,7 @@ func newHTTP2Peer(t *testing.T, settings ...http2.Setting) (*http2ClientConn, *h
|
||||
var cc *http2ClientConn
|
||||
go func() {
|
||||
var err error
|
||||
cc, err = newHTTP2ClientConn(client)
|
||||
cc, err = newHTTP2ClientConn(client, http2KeepAlivePeriod)
|
||||
ccErr <- err
|
||||
}()
|
||||
preface := make([]byte, len(http2.ClientPreface))
|
||||
@@ -423,3 +426,62 @@ func TestHTTP2ClientAnswersPings(t *testing.T) {
|
||||
require.True(t, f.(*http2.PingFrame).IsAck())
|
||||
require.Equal(t, data, f.(*http2.PingFrame).Data)
|
||||
}
|
||||
|
||||
func TestHTTP2ClientKeepAlive(t *testing.T) {
|
||||
for _, answer := range []bool{false, true} {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
client, server := net.Pipe()
|
||||
defer server.Close()
|
||||
var mu sync.Mutex
|
||||
var pings []time.Duration
|
||||
start := time.Now()
|
||||
go func() {
|
||||
br := bufio.NewReader(server)
|
||||
if _, err := io.ReadFull(br, make([]byte, len(http2.ClientPreface))); err != nil {
|
||||
return
|
||||
}
|
||||
fr := http2.NewFramer(server, br)
|
||||
time.Sleep(2 * time.Second)
|
||||
if fr.WriteSettings() != nil {
|
||||
return
|
||||
}
|
||||
for {
|
||||
f, err := fr.ReadFrame()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if p, ok := f.(*http2.PingFrame); ok && !p.IsAck() {
|
||||
mu.Lock()
|
||||
pings = append(pings, time.Since(start))
|
||||
mu.Unlock()
|
||||
if answer && fr.WritePing(true, p.Data) != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
cc, err := newHTTP2ClientConn(client, 60*time.Second)
|
||||
require.NoError(t, err)
|
||||
if answer {
|
||||
time.Sleep(200 * time.Second)
|
||||
select {
|
||||
case <-cc.done:
|
||||
t.Fatal("the connection closed although every PING was answered")
|
||||
default:
|
||||
}
|
||||
cc.conn.Close()
|
||||
<-cc.done
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
require.GreaterOrEqual(t, len(pings), 2)
|
||||
return
|
||||
}
|
||||
<-cc.done
|
||||
closed := time.Since(start)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
require.Len(t, pings, 1, "the connection must send a PING before closing")
|
||||
require.GreaterOrEqual(t, closed-pings[0], http2PingTimeout)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,25 +54,25 @@ func useWarp(config *Config, tlsConfig *gotls.Config) error {
|
||||
tlsConfig.GetClientCertificate = func(*gotls.CertificateRequestInfo) (*gotls.Certificate, error) {
|
||||
return cert, nil
|
||||
}
|
||||
if publicKey := config.Warp.PublicKey; len(publicKey) > 0 {
|
||||
verify := tlsConfig.VerifyPeerCertificate
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
tlsConfig.VerifyPeerCertificate = func(raw [][]byte, chains [][]*x509.Certificate) error {
|
||||
if len(raw) == 0 {
|
||||
return errors.New("the WARP endpoint sent no certificate")
|
||||
}
|
||||
leaf, err := x509.ParseCertificate(raw[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !bytes.Equal(leaf.RawSubjectPublicKeyInfo, publicKey) {
|
||||
return errors.New("the WARP endpoint's key doesn't match \"publicKey\"")
|
||||
}
|
||||
if verify != nil {
|
||||
return verify(raw, chains)
|
||||
}
|
||||
return nil
|
||||
if tlsConfig.InsecureSkipVerify == true {
|
||||
return nil // pcs or vcn or both
|
||||
}
|
||||
if _, err = x509.ParsePKIXPublicKey(config.Warp.PublicKey); err != nil {
|
||||
return err
|
||||
}
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
tlsConfig.VerifyPeerCertificate = func(raw [][]byte, chains [][]*x509.Certificate) error {
|
||||
if len(raw) == 0 {
|
||||
return errors.New("the WARP endpoint sent no certificate")
|
||||
}
|
||||
leaf, err := x509.ParseCertificate(raw[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !bytes.Equal(leaf.RawSubjectPublicKeyInfo, config.Warp.PublicKey) {
|
||||
return errors.New("the WARP endpoint's key doesn't match \"publicKey\"")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -79,6 +79,14 @@ func (m *XmuxManager) newXmuxClient() *XmuxClient {
|
||||
}
|
||||
|
||||
func (m *XmuxManager) GetXmuxClient(ctx context.Context) *XmuxClient { // when locking
|
||||
return m.getXmuxClient(ctx, true)
|
||||
}
|
||||
|
||||
func (m *XmuxManager) GetExistingXmuxClient(ctx context.Context) *XmuxClient {
|
||||
return m.getXmuxClient(ctx, false)
|
||||
}
|
||||
|
||||
func (m *XmuxManager) getXmuxClient(ctx context.Context, create bool) *XmuxClient {
|
||||
for i := 0; i < len(m.xmuxClients); {
|
||||
xmuxClient := m.xmuxClients[i]
|
||||
if xmuxClient.XmuxConn.IsClosed() ||
|
||||
@@ -99,11 +107,14 @@ func (m *XmuxManager) GetXmuxClient(ctx context.Context) *XmuxClient { // when l
|
||||
}
|
||||
|
||||
if len(m.xmuxClients) == 0 {
|
||||
if !create {
|
||||
return nil
|
||||
}
|
||||
errors.LogDebug(ctx, "XMUX: creating xmuxClient because xmuxClients is empty")
|
||||
return m.newXmuxClient()
|
||||
}
|
||||
|
||||
if m.connections > 0 && len(m.xmuxClients) < int(m.connections) {
|
||||
if create && m.connections > 0 && len(m.xmuxClients) < int(m.connections) {
|
||||
errors.LogDebug(ctx, "XMUX: creating xmuxClient because maxConnections was not hit, xmuxClients = ", len(m.xmuxClients))
|
||||
return m.newXmuxClient()
|
||||
}
|
||||
@@ -120,6 +131,9 @@ func (m *XmuxManager) GetXmuxClient(ctx context.Context) *XmuxClient { // when l
|
||||
}
|
||||
|
||||
if len(xmuxClients) == 0 {
|
||||
if !create {
|
||||
return nil
|
||||
}
|
||||
errors.LogDebug(ctx, "XMUX: creating xmuxClient because maxConcurrency was hit, xmuxClients = ", len(m.xmuxClients))
|
||||
return m.newXmuxClient()
|
||||
}
|
||||
|
||||
@@ -90,3 +90,23 @@ func TestDefault(t *testing.T) {
|
||||
t.Error("did not get 1 distinct clients, got ", len(xmuxClients))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetExistingXmuxClient(t *testing.T) {
|
||||
xmuxConfig := XmuxConfig{
|
||||
MaxConnections: &RangeConfig{From: 2, To: 2},
|
||||
}
|
||||
|
||||
xmuxManager := NewXmuxManager(xmuxConfig, func() XmuxConn {
|
||||
return &fakeRoundTripper{}
|
||||
})
|
||||
|
||||
if xmuxManager.GetExistingXmuxClient(context.Background()) != nil {
|
||||
t.Error("got a client without creating one")
|
||||
}
|
||||
xmuxClient := xmuxManager.GetXmuxClient(context.Background())
|
||||
for i := 0; i < 4; i++ {
|
||||
if xmuxManager.GetExistingXmuxClient(context.Background()) != xmuxClient {
|
||||
t.Error("did not reuse the existing client")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
|
||||
utls "github.com/refraction-networking/utls"
|
||||
"github.com/xtls/xray-core/common/crypto"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"golang.org/x/net/http2"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
@@ -198,23 +199,27 @@ func dnsQuery(server string, domain string, sockopt *internet.SocketConfig) ([]b
|
||||
IdleConnTimeout: net.ConnIdleTimeout,
|
||||
ReadIdleTimeout: net.ChromeH2KeepAlivePeriod,
|
||||
DialTLSContext: func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error) {
|
||||
host, _, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dest, err := net.ParseDestination(network + ":" + addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dnsCtx := ctx
|
||||
if h2c {
|
||||
dnsCtx = session.ContextWithMitmAlpn11(dnsCtx, false) // for insurance
|
||||
dnsCtx = session.ContextWithMitmServerName(dnsCtx, host)
|
||||
}
|
||||
var conn net.Conn
|
||||
|
||||
conn, err = internet.DialSystem(ctx, dest, sockopt)
|
||||
conn, err = internet.DialSystem(dnsCtx, dest, sockopt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !h2c {
|
||||
u, err := url.Parse(server)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn = utls.UClient(conn, &utls.Config{ServerName: u.Hostname()}, utls.HelloChrome_Auto)
|
||||
conn = utls.UClient(conn, &utls.Config{ServerName: host}, utls.HelloChrome_Auto)
|
||||
if err := conn.(*utls.UConn).HandshakeContext(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user