mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-10-21 16:54:29 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5622d2fe05 | ||
|
|
dda0fa2bde |
@@ -9,8 +9,8 @@ ARG TARGETARCH
|
||||
RUN GOOS=$TARGETOS GOARCH=$TARGETARCH CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags "-s -w -buildid=" ./main
|
||||
|
||||
# Download geodat into a staging directory
|
||||
ADD https://raw.githubusercontent.com/XTLS/Xray-rules-dat/release/geoip/geoip-full.dat /tmp/geodat/geoip.dat
|
||||
ADD https://raw.githubusercontent.com/XTLS/Xray-rules-dat/release/geosite/geosite-expand.dat /tmp/geodat/geosite.dat
|
||||
ADD https://raw.githubusercontent.com/Loyalsoldier/v2ray-rules-dat/release/geoip.dat /tmp/geodat/geoip.dat
|
||||
ADD https://raw.githubusercontent.com/Loyalsoldier/v2ray-rules-dat/release/geosite.dat /tmp/geodat/geosite.dat
|
||||
|
||||
RUN mkdir -p /tmp/empty
|
||||
|
||||
@@ -40,15 +40,21 @@ RUN echo '{}' >/tmp/usr/local/etc/xray/11_geodata.json
|
||||
RUN echo '{}' >/tmp/usr/local/etc/xray/12_env.json
|
||||
RUN echo '{}' >/tmp/usr/local/etc/xray/99_version.json
|
||||
|
||||
# Create log files
|
||||
RUN mkdir -p /tmp/var/log/xray && touch \
|
||||
/tmp/var/log/xray/access.log \
|
||||
/tmp/var/log/xray/error.log
|
||||
|
||||
# Build finally image
|
||||
FROM gcr.io/distroless/static:nonroot
|
||||
|
||||
COPY --from=build --chown=0:0 --chmod=755 /src/xray /usr/local/bin/xray
|
||||
COPY --from=build --chown=65532:65532 --chmod=755 /tmp/empty /usr/local/share/xray
|
||||
COPY --from=build --chown=65532:65532 --chmod=644 /tmp/geodat/*.dat /usr/local/share/xray/
|
||||
COPY --from=build --chown=0:65532 --chmod=750 /tmp/empty /usr/local/etc/xray
|
||||
COPY --from=build --chown=0:65532 --chmod=640 /tmp/usr/local/etc/xray/*.json /usr/local/etc/xray/
|
||||
COPY --from=build --chown=65532:65532 --chmod=700 /tmp/empty /var/log/xray
|
||||
COPY --from=build --chown=0:0 --chmod=755 /tmp/empty /usr/local/etc/xray
|
||||
COPY --from=build --chown=0:0 --chmod=644 /tmp/usr/local/etc/xray/*.json /usr/local/etc/xray/
|
||||
COPY --from=build --chown=0:0 --chmod=755 /tmp/empty /var/log/xray
|
||||
COPY --from=build --chown=65532:65532 --chmod=600 /tmp/var/log/xray/*.log /var/log/xray/
|
||||
|
||||
VOLUME /usr/local/etc/xray
|
||||
VOLUME /var/log/xray
|
||||
|
||||
@@ -9,8 +9,8 @@ ARG TARGETARCH
|
||||
RUN GOOS=$TARGETOS GOARCH=$TARGETARCH CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags "-s -w -buildid=" ./main
|
||||
|
||||
# Download geodat into a staging directory
|
||||
ADD https://raw.githubusercontent.com/XTLS/Xray-rules-dat/release/geoip/geoip-full.dat /tmp/geodat/geoip.dat
|
||||
ADD https://raw.githubusercontent.com/XTLS/Xray-rules-dat/release/geosite/geosite-expand.dat /tmp/geodat/geosite.dat
|
||||
ADD https://raw.githubusercontent.com/Loyalsoldier/v2ray-rules-dat/release/geoip.dat /tmp/geodat/geoip.dat
|
||||
ADD https://raw.githubusercontent.com/Loyalsoldier/v2ray-rules-dat/release/geosite.dat /tmp/geodat/geosite.dat
|
||||
|
||||
RUN mkdir -p /tmp/empty
|
||||
|
||||
@@ -40,6 +40,11 @@ RUN echo '{}' >/tmp/usr/local/etc/xray/11_geodata.json
|
||||
RUN echo '{}' >/tmp/usr/local/etc/xray/12_env.json
|
||||
RUN echo '{}' >/tmp/usr/local/etc/xray/99_version.json
|
||||
|
||||
# Create log files
|
||||
RUN mkdir -p /tmp/var/log/xray && touch \
|
||||
/tmp/var/log/xray/access.log \
|
||||
/tmp/var/log/xray/error.log
|
||||
|
||||
# Build finally image
|
||||
# Note on Distroless Base Image and Architecture Support:
|
||||
# - The official 'gcr.io/distroless/static' image provided by Google only supports a limited set of architectures for Linux:
|
||||
@@ -55,9 +60,10 @@ FROM --platform=linux/amd64 gcr.io/distroless/static:nonroot
|
||||
COPY --from=build --chown=0:0 --chmod=755 /src/xray /usr/local/bin/xray
|
||||
COPY --from=build --chown=65532:65532 --chmod=755 /tmp/empty /usr/local/share/xray
|
||||
COPY --from=build --chown=65532:65532 --chmod=644 /tmp/geodat/*.dat /usr/local/share/xray/
|
||||
COPY --from=build --chown=0:65532 --chmod=750 /tmp/empty /usr/local/etc/xray
|
||||
COPY --from=build --chown=0:65532 --chmod=640 /tmp/usr/local/etc/xray/*.json /usr/local/etc/xray/
|
||||
COPY --from=build --chown=65532:65532 --chmod=700 /tmp/empty /var/log/xray
|
||||
COPY --from=build --chown=0:0 --chmod=755 /tmp/empty /usr/local/etc/xray
|
||||
COPY --from=build --chown=0:0 --chmod=644 /tmp/usr/local/etc/xray/*.json /usr/local/etc/xray/
|
||||
COPY --from=build --chown=0:0 --chmod=755 /tmp/empty /var/log/xray
|
||||
COPY --from=build --chown=65532:65532 --chmod=600 /tmp/var/log/xray/*.log /var/log/xray/
|
||||
|
||||
VOLUME /usr/local/etc/xray
|
||||
VOLUME /var/log/xray
|
||||
|
||||
@@ -40,7 +40,7 @@ jobs:
|
||||
max_attempts: 60
|
||||
command: |
|
||||
[ -d 'resources' ] || mkdir resources
|
||||
LIST=('XTLS Xray-rules-dat geoip/geoip-lite geoip' 'XTLS Xray-rules-dat geosite/geosite geosite')
|
||||
LIST=('Loyalsoldier v2ray-rules-dat geoip geoip' 'Loyalsoldier v2ray-rules-dat geosite geosite')
|
||||
for i in "${LIST[@]}"
|
||||
do
|
||||
INFO=($(echo $i | awk 'BEGIN{FS=" ";OFS=" "} {print $1,$2,$3,$4}'))
|
||||
|
||||
@@ -266,9 +266,10 @@ 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
|
||||
// Absolute path to the Lua DNS query script.
|
||||
Script string `protobuf:"bytes,15,opt,name=script,proto3" json:"script,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Config) Reset() {
|
||||
|
||||
@@ -75,5 +75,6 @@ message Config {
|
||||
|
||||
bool enableParallelQuery = 14;
|
||||
|
||||
// Absolute path to the Lua DNS query script.
|
||||
string script = 15;
|
||||
}
|
||||
|
||||
+6
-10
@@ -32,6 +32,7 @@ type DNS struct {
|
||||
matcherInfos []*DomainMatcherInfo
|
||||
checkSystem bool
|
||||
script *scriptEngine
|
||||
scriptPath string
|
||||
}
|
||||
|
||||
// DomainMatcherInfo contains information attached to index returned by Server.domainMatcher.
|
||||
@@ -170,13 +171,6 @@ 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,
|
||||
@@ -188,7 +182,7 @@ func New(ctx context.Context, config *Config) (*DNS, error) {
|
||||
disableFallbackIfMatch: config.DisableFallbackIfMatch,
|
||||
enableParallelQuery: config.EnableParallelQuery,
|
||||
checkSystem: checkSystem,
|
||||
script: script,
|
||||
scriptPath: config.Script,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -199,10 +193,12 @@ 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 {
|
||||
if s.scriptPath != "" {
|
||||
engine, err := newScriptEngine(s.scriptPath, s)
|
||||
if err != nil {
|
||||
return errors.New("failed to initialize DNS script").Base(err)
|
||||
}
|
||||
s.script = engine
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ func luaServers(s *DNS) []luaDNSServer {
|
||||
|
||||
func registerLua(L *lua.LState, servers []luaDNSServer, client featureDNS.Client) {
|
||||
L.PreloadModule("xray.dns", func(L *lua.LState) int {
|
||||
pushIPs := xlua.NewReadOnlySlicePusher[net.IP](L)
|
||||
pushIPs := xlua.NewSlicePusher[net.IP](L)
|
||||
|
||||
serverList := L.CreateTable(len(servers), 0)
|
||||
for i, client := range servers {
|
||||
|
||||
@@ -72,13 +72,10 @@ end
|
||||
if err := os.WriteFile(path, []byte(script), 0o600); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
engine, err := newScriptEngine(path)
|
||||
engine, err := newScriptEngine(path, server)
|
||||
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
|
||||
|
||||
+8
-16
@@ -15,22 +15,17 @@ import (
|
||||
const scriptExecutionTimeout = 6 * time.Second
|
||||
|
||||
type scriptEngine struct {
|
||||
program *xlua.Program
|
||||
pool *xlua.Pool
|
||||
pool *xlua.Pool
|
||||
}
|
||||
|
||||
func newScriptEngine(script string) (*scriptEngine, error) {
|
||||
program, err := xlua.Compile(script)
|
||||
func newScriptEngine(path string, server *DNS) (*scriptEngine, error) {
|
||||
program, err := xlua.CompileFile(path)
|
||||
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(
|
||||
pool, err := xlua.NewPool(server.ctx, scriptExecutionTimeout, program.NewStateFactory(
|
||||
scriptExecutionTimeout*20,
|
||||
256,
|
||||
func(L *lua.LState) {
|
||||
geodata.RegisterLua(L)
|
||||
log.RegisterLua(L)
|
||||
@@ -43,18 +38,15 @@ func (e *scriptEngine) start(server *DNS) error {
|
||||
return nil
|
||||
}))
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
e.pool = pool
|
||||
errors.LogInfo(server.ctx, "DNS script initialized")
|
||||
return nil
|
||||
errors.LogInfo(server.ctx, "DNS script initialized from ", path)
|
||||
return &scriptEngine{pool: pool}, nil
|
||||
}
|
||||
|
||||
func (e *scriptEngine) close() {
|
||||
if e.pool != nil {
|
||||
e.pool.Close()
|
||||
}
|
||||
e.pool.Close()
|
||||
}
|
||||
|
||||
func (e *scriptEngine) query(domain string, option dns.IPOption) (ips []net.IP, ttl uint32, queryErr error) {
|
||||
|
||||
+22
-71
@@ -85,13 +85,10 @@ end
|
||||
ctx: context.Background(),
|
||||
clients: []*Client{{server: upstream, ipOption: &option, timeoutMs: time.Second}},
|
||||
}
|
||||
engine, err := newScriptEngine(path)
|
||||
engine, err := newScriptEngine(path, server)
|
||||
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)
|
||||
@@ -128,7 +125,7 @@ func TestDNSScriptGeoIPFallback(t *testing.T) {
|
||||
t.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
||||
script := `
|
||||
local servers = require("xray.dns").Servers
|
||||
local ru_ips = require("xray.geodata").BuildIPMatcher("geoip:ru")
|
||||
local us_ips = require("xray.geodata").BuildIPMatcher("geoip:us")
|
||||
|
||||
local by_id = {}
|
||||
for _, server in ipairs(servers) do
|
||||
@@ -138,7 +135,7 @@ assert(by_id.primary and by_id.fallback, "primary and fallback DNS servers are r
|
||||
|
||||
function HandleDNSQuery(domain, ipv4, ipv6, fake)
|
||||
local ips, ttl, err = by_id.primary:Query(domain, ipv4, ipv6, fake)
|
||||
if not err and ru_ips:AnyMatch(ips) then
|
||||
if not err and us_ips:AnyMatch(ips) then
|
||||
return ips, ttl, nil
|
||||
end
|
||||
return by_id.fallback:Query(domain, ipv4, ipv6, fake)
|
||||
@@ -152,7 +149,7 @@ end
|
||||
primary := &scriptNameServer{
|
||||
name: "primary",
|
||||
answers: map[string]net.IP{
|
||||
"ru.example": net.ParseIP("2a02:6b8::feed:0ff"),
|
||||
"us.example": net.ParseIP("2001:4860:4860::8888"),
|
||||
"other.example": net.ParseIP("127.0.0.1"),
|
||||
},
|
||||
ttl: 30,
|
||||
@@ -167,15 +164,11 @@ end
|
||||
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,
|
||||
ctx: context.Background(),
|
||||
hosts: hosts,
|
||||
ipOption: &option,
|
||||
scriptPath: scriptPath,
|
||||
clients: []*Client{
|
||||
{id: "primary", server: primary, ipOption: &option, timeoutMs: 2 * time.Second},
|
||||
{id: "fallback", server: fallback, ipOption: &option, timeoutMs: 2 * time.Second},
|
||||
@@ -191,7 +184,7 @@ end
|
||||
ip net.IP
|
||||
ttl uint32
|
||||
}{
|
||||
{"Ru.Example.", net.ParseIP("2a02:6b8::feed:0ff"), 30},
|
||||
{"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)
|
||||
@@ -209,67 +202,29 @@ end
|
||||
|
||||
func TestDNSScriptRejectsInvalidStartup(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, script string
|
||||
compileError bool
|
||||
name string
|
||||
script string
|
||||
}{
|
||||
{"syntax", "function HandleDNSQuery(", true},
|
||||
{"missing hook", "value = 1", false},
|
||||
{"invalid hook", "HandleDNSQuery = true", false},
|
||||
{"top-level error", `error("setup failed")`, false},
|
||||
{"syntax", "function HandleDNSQuery("},
|
||||
{"missing hook", "value = 1"},
|
||||
{"top-level error", `error("setup failed")`},
|
||||
} {
|
||||
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)
|
||||
}
|
||||
server := &DNS{ctx: context.Background(), scriptPath: path}
|
||||
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")
|
||||
if server.script != nil {
|
||||
t.Fatal("Start retained a script engine 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 := `
|
||||
@@ -296,16 +251,12 @@ end
|
||||
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}},
|
||||
ctx: context.Background(),
|
||||
hosts: hosts,
|
||||
ipOption: &option,
|
||||
scriptPath: path,
|
||||
clients: []*Client{{id: "fake", server: upstream, ipOption: &option, timeoutMs: time.Second}},
|
||||
}
|
||||
if err := server.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -23,9 +23,6 @@ import (
|
||||
|
||||
const idleTimeout = 30 * time.Second
|
||||
|
||||
// DO NOT EDIT. Ignored by geodata, rejected by Lua.
|
||||
const luaGuardHeader = "\x12\x01\x00"
|
||||
|
||||
type stage struct {
|
||||
target string
|
||||
temp string
|
||||
@@ -173,10 +170,6 @@ func (d *downloader) downloadOne(asset *Asset) (stage, error) {
|
||||
}
|
||||
}()
|
||||
|
||||
if _, err := temp.WriteString(luaGuardHeader); err != nil {
|
||||
temp.Close()
|
||||
return stage{}, err
|
||||
}
|
||||
if err := d.fetch(asset.Url, temp); err != nil {
|
||||
temp.Close()
|
||||
return stage{}, err
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
package geodata
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
commongeodata "github.com/xtls/xray-core/common/geodata"
|
||||
xlua "github.com/xtls/xray-core/common/lua"
|
||||
"github.com/yuin/gopher-lua/parse"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func TestDownloadOneLuaGuard(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
body string
|
||||
code string
|
||||
}{
|
||||
{"geodata", "\x0a\x03\x0a\x01A", "A"},
|
||||
{"prefixed geodata", luaGuardHeader + "\x0a\x03\x0a\x01A", "A"},
|
||||
{"Lua", "function HandleRoute() end", ""},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("xray.location.asset", dir)
|
||||
if err := os.WriteFile(filepath.Join(dir, "asset.lua"), nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(tc.body))
|
||||
}))
|
||||
defer server.Close()
|
||||
d := &downloader{ctx: context.Background(), httpClient: server.Client()}
|
||||
staged, err := d.downloadOne(&Asset{Url: server.URL, File: "asset.lua"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tx, err := swapAll([]stage{staged})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := os.ReadFile(staged.target)
|
||||
if err != nil || string(data) != luaGuardHeader+tc.body {
|
||||
t.Fatalf("downloaded data = % x, %v", data, err)
|
||||
}
|
||||
program, err := xlua.Compile(staged.target)
|
||||
var syntaxErr *parse.Error
|
||||
if program != nil || !errors.As(err, &syntaxErr) || syntaxErr.Pos.Line != 1 || syntaxErr.Pos.Column != 1 {
|
||||
t.Fatalf("want Lua rejection at the first byte, got %v, %v", program, err)
|
||||
}
|
||||
if tc.code != "" {
|
||||
var list commongeodata.GeoSiteList
|
||||
if err := proto.Unmarshal(data, &list); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(list.Entry) != 1 || list.Entry[0].Code != tc.code {
|
||||
t.Fatalf("header changed geodata: %v", &list)
|
||||
}
|
||||
if _, err := commongeodata.ParseDomainRules([]string{"ext:" + filepath.Base(staged.target) + ":" + tc.code}, commongeodata.Domain_Full); err != nil {
|
||||
t.Fatalf("geodata loader rejected the header: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -109,7 +109,7 @@ func (h *HealthPingRTTS) getStatistics() *HealthPingStats {
|
||||
stats.Min = 0
|
||||
return stats
|
||||
}
|
||||
stats.Average = sum / time.Duration(cnt)
|
||||
stats.Average = time.Duration(int(sum) / cnt)
|
||||
var std float64
|
||||
if cnt < 2 {
|
||||
// no enough data for standard deviation, we assume it's half of the average rtt
|
||||
|
||||
@@ -174,7 +174,7 @@ func NewHandler(ctx context.Context, config *core.InboundHandlerConfig) (inbound
|
||||
Mark: streamSettings.SocketSettings.Mark,
|
||||
})
|
||||
}
|
||||
if streamSettings != nil && (streamSettings.ProtocolName == "splithttp" || streamSettings.ProtocolName == "masque") {
|
||||
if streamSettings != nil && streamSettings.ProtocolName == "splithttp" {
|
||||
ctx = session.ContextWithAllowedNetwork(ctx, net.Network_UDP)
|
||||
}
|
||||
|
||||
|
||||
@@ -415,7 +415,7 @@ func BenchmarkMphDomainMatcher(b *testing.B) {
|
||||
|
||||
func BenchmarkMultiGeoIPMatcher(b *testing.B) {
|
||||
b.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
||||
rules, err := geodata.ParseIPRules([]string{"geoip:cn", "geoip:ir", "geoip:ru"})
|
||||
rules, err := geodata.ParseIPRules([]string{"geoip:cn", "geoip:jp", "geoip:ca", "geoip:us"})
|
||||
common.Must(err)
|
||||
|
||||
matcher, err := NewIPMatcher(rules, MatcherAsType_Target)
|
||||
|
||||
@@ -587,9 +587,10 @@ 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
|
||||
// Absolute path to the Lua routing script.
|
||||
Script string `protobuf:"bytes,4,opt,name=script,proto3" json:"script,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Config) Reset() {
|
||||
|
||||
@@ -110,5 +110,6 @@ message Config {
|
||||
DomainStrategy domain_strategy = 1;
|
||||
repeated RoutingRule rule = 2;
|
||||
repeated BalancingRule balancing_rule = 3;
|
||||
// Absolute path to the Lua routing script.
|
||||
string script = 4;
|
||||
}
|
||||
|
||||
+3
-3
@@ -30,9 +30,9 @@ func (r *Router) RegisterLua(L *lua.LState) {
|
||||
module.RawSetString("LocalOS", lua.LString(runtime.GOOS))
|
||||
|
||||
module.RawSetString("PickOutbound", L.NewFunction(func(L *lua.LState) int {
|
||||
tag, ok := L.Get(1).(lua.LString)
|
||||
tag, ok := L.Get(2).(lua.LString)
|
||||
if !ok {
|
||||
L.ArgError(1, "balancer tag must be a string")
|
||||
L.ArgError(2, "balancer tag must be a string")
|
||||
return 0
|
||||
}
|
||||
balancer, found := (*r.balancers.Load())[string(tag)]
|
||||
@@ -62,7 +62,7 @@ func (r *Router) RegisterLua(L *lua.LState) {
|
||||
}
|
||||
|
||||
func registerLuaContext(L *lua.LState) {
|
||||
pushIPs := xlua.NewReadOnlySlicePusher[net.IP](L)
|
||||
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)
|
||||
|
||||
+6
-10
@@ -20,6 +20,7 @@ import (
|
||||
type Router struct {
|
||||
domainStrategy Config_DomainStrategy
|
||||
rules atomic.Pointer[[]*Rule]
|
||||
scriptPath string
|
||||
script *scriptEngine
|
||||
balancers atomic.Pointer[map[string]*Balancer]
|
||||
dns dns.Client
|
||||
@@ -41,19 +42,12 @@ type Route struct {
|
||||
// Init initializes the Router.
|
||||
func (r *Router) Init(ctx context.Context, config *Config, d dns.Client, ohm outbound.Manager, dispatcher routing.Dispatcher) error {
|
||||
r.domainStrategy = config.DomainStrategy
|
||||
r.scriptPath = config.Script
|
||||
r.dns = d
|
||||
r.ctx = ctx
|
||||
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)
|
||||
@@ -234,10 +228,12 @@ 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 {
|
||||
if r.scriptPath != "" {
|
||||
engine, err := newScriptEngine(r.scriptPath, r)
|
||||
if err != nil {
|
||||
return errors.New("failed to initialize routing script").Base(err)
|
||||
}
|
||||
r.script = engine
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
+8
-16
@@ -16,22 +16,17 @@ import (
|
||||
const scriptExecutionTimeout = 6 * time.Second
|
||||
|
||||
type scriptEngine struct {
|
||||
program *xlua.Program
|
||||
pool *xlua.Pool
|
||||
pool *xlua.Pool
|
||||
}
|
||||
|
||||
func newScriptEngine(script string) (*scriptEngine, error) {
|
||||
program, err := xlua.Compile(script)
|
||||
func newScriptEngine(path string, router *Router) (*scriptEngine, error) {
|
||||
program, err := xlua.CompileFile(path)
|
||||
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(
|
||||
pool, err := xlua.NewPool(router.ctx, scriptExecutionTimeout, program.NewStateFactory(
|
||||
scriptExecutionTimeout*20,
|
||||
256,
|
||||
func(L *lua.LState) {
|
||||
geodata.RegisterLua(L)
|
||||
log.RegisterLua(L)
|
||||
@@ -45,18 +40,15 @@ func (e *scriptEngine) start(router *Router) error {
|
||||
return nil
|
||||
}))
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
e.pool = pool
|
||||
errors.LogInfo(router.ctx, "routing script initialized")
|
||||
return nil
|
||||
errors.LogInfo(router.ctx, "routing script initialized from ", path)
|
||||
return &scriptEngine{pool: pool}, nil
|
||||
}
|
||||
|
||||
func (e *scriptEngine) close() {
|
||||
if e.pool != nil {
|
||||
e.pool.Close()
|
||||
}
|
||||
e.pool.Close()
|
||||
}
|
||||
|
||||
func (e *scriptEngine) pickRoute(ctx routing.Context) (routing.Route, error) {
|
||||
|
||||
@@ -72,63 +72,24 @@ func startLuaRouter(t *testing.T, script string, d featureDNS.Client, config *Co
|
||||
}
|
||||
|
||||
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},
|
||||
for _, tc := range []struct{ name, script string }{
|
||||
{"syntax error", "function HandleRoute("},
|
||||
{"missing hook", "value = 1"},
|
||||
{"initialization error", `error("setup failed")`},
|
||||
} {
|
||||
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 {
|
||||
if err := r.Init(context.Background(), &Config{Script: writeRouteScript(t, tc.script)}, nil, nil, nil); 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
|
||||
@@ -140,7 +101,7 @@ func TestRouterScriptRouting(t *testing.T) {
|
||||
{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: "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"},
|
||||
@@ -241,7 +202,7 @@ func TestRouterScriptBalancerReload(t *testing.T) {
|
||||
r := startLuaRouter(t, `
|
||||
local router = require("xray.router")
|
||||
function HandleRoute()
|
||||
local tag, err = router.PickOutbound("balance")
|
||||
local tag, err = router:PickOutbound("balance")
|
||||
return tag, "balanced", err
|
||||
end`, nil, config("old"))
|
||||
pick := func(want string) {
|
||||
@@ -275,7 +236,7 @@ func TestRouterScriptConcurrentBalancerReload(t *testing.T) {
|
||||
r := startLuaRouter(t, `
|
||||
local router = require("xray.router")
|
||||
function HandleRoute()
|
||||
local tag, err = router.PickOutbound("balance")
|
||||
local tag, err = router:PickOutbound("balance")
|
||||
return tag, nil, err
|
||||
end`, nil, config("a"))
|
||||
|
||||
@@ -406,10 +367,10 @@ end`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer instance.Close()
|
||||
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" {
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
package base64
|
||||
|
||||
const (
|
||||
Prefix = "base64:"
|
||||
GzipPrefix = "base64+gzip:"
|
||||
)
|
||||
@@ -1,38 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
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")
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -17,12 +17,12 @@ import (
|
||||
)
|
||||
|
||||
func checkFile(file, code string) error {
|
||||
r, size, err := filesystem.OpenAsset(file)
|
||||
r, err := filesystem.OpenAsset(file)
|
||||
if err != nil {
|
||||
return errors.New("failed to open ", file).Base(err)
|
||||
}
|
||||
defer r.Close()
|
||||
if _, err := find(r, []byte(code), false, size); err != nil {
|
||||
if _, err := find(r, []byte(code), false); err != nil {
|
||||
return errors.New("failed to check code ", code, " from ", file).Base(err)
|
||||
}
|
||||
return nil
|
||||
@@ -30,12 +30,12 @@ func checkFile(file, code string) error {
|
||||
|
||||
func loadFile(file, code string) ([]byte, error) {
|
||||
runtime.GC() // peak mem
|
||||
r, size, err := filesystem.OpenAsset(file)
|
||||
r, err := filesystem.OpenAsset(file)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to open ", file).Base(err)
|
||||
}
|
||||
defer r.Close()
|
||||
bs, err := find(r, []byte(code), true, size)
|
||||
bs, err := find(r, []byte(code), true)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to load code ", code, " from ", file).Base(err)
|
||||
}
|
||||
@@ -60,13 +60,13 @@ func loadIP(file, code string) ([]*CIDR, error) {
|
||||
// unmarshalling it into a []*Domain, so value is only valid during fn.
|
||||
func loadSite(file, code, attrs string, fn func(Domain_Type, []byte)) error {
|
||||
runtime.GC() // peak mem
|
||||
r, size, err := filesystem.OpenAsset(file)
|
||||
r, err := filesystem.OpenAsset(file)
|
||||
if err != nil {
|
||||
return errors.New("failed to open ", file).Base(err)
|
||||
}
|
||||
defer r.Close()
|
||||
br := bufio.NewReaderSize(r, 64*1024)
|
||||
n, err := seek(br, []byte(code), size)
|
||||
n, err := seek(br, []byte(code))
|
||||
if err != nil {
|
||||
return errors.New("failed to load code ", code, " from ", file).Base(err)
|
||||
}
|
||||
@@ -114,9 +114,6 @@ func decodeVarint(br *bufio.Reader) (uint64, error) {
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if shift == 63 && b > 1 {
|
||||
break // Only one value bit fits in the tenth byte.
|
||||
}
|
||||
x |= (uint64(b) & 0x7F) << shift
|
||||
if (b & 0x80) == 0 {
|
||||
return x, nil
|
||||
@@ -126,9 +123,9 @@ func decodeVarint(br *bufio.Reader) (uint64, error) {
|
||||
return 0, errors.New("varint overflow")
|
||||
}
|
||||
|
||||
func find(r io.Reader, code []byte, readBody bool, size int64) ([]byte, error) {
|
||||
func find(r io.Reader, code []byte, readBody bool) ([]byte, error) {
|
||||
br := bufio.NewReaderSize(r, 64*1024)
|
||||
bodyL, err := seek(br, code, size)
|
||||
bodyL, err := seek(br, code)
|
||||
if err != nil || !readBody {
|
||||
return nil, err
|
||||
}
|
||||
@@ -140,7 +137,7 @@ func find(r io.Reader, code []byte, readBody bool, size int64) ([]byte, error) {
|
||||
}
|
||||
|
||||
// seek advances br to the body of the entry for code and returns the body length.
|
||||
func seek(br *bufio.Reader, code []byte, size int64) (int, error) {
|
||||
func seek(br *bufio.Reader, code []byte) (int, error) {
|
||||
codeL := len(code)
|
||||
if codeL == 0 {
|
||||
return 0, errors.New("empty code")
|
||||
@@ -148,8 +145,7 @@ func seek(br *bufio.Reader, code []byte, size int64) (int, error) {
|
||||
need := 2 + codeL // TODO: if code too long
|
||||
|
||||
for {
|
||||
tag, err := br.ReadByte()
|
||||
if err != nil {
|
||||
if _, err := br.ReadByte(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
@@ -157,10 +153,10 @@ func seek(br *bufio.Reader, code []byte, size int64) (int, error) {
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if x == 0 || x > uint64(size) || x > uint64(^uint(0)>>1) {
|
||||
return 0, errors.New("invalid body length: ", x)
|
||||
}
|
||||
bodyL := int(x)
|
||||
if bodyL <= 0 {
|
||||
return 0, errors.New("invalid body length: ", bodyL)
|
||||
}
|
||||
|
||||
// Peek no more than the buffer holds: a code longer than the buffer cannot match a single
|
||||
// length byte anyway, so a short peek only skips it, as base find (io.ReadFull) does.
|
||||
@@ -171,8 +167,7 @@ func seek(br *bufio.Reader, code []byte, size int64) (int, error) {
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
if tag == 0x0a && bodyL >= need && len(prefix) >= need &&
|
||||
prefix[0] == 0x0a && int(prefix[1]) == codeL && bytes.Equal(prefix[2:], code) {
|
||||
if bodyL >= need && len(prefix) >= need && int(prefix[1]) == codeL && bytes.Equal(prefix[2:], code) {
|
||||
return bodyL, nil
|
||||
}
|
||||
if _, err := br.Discard(bodyL); err != nil {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package geodata
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -13,58 +12,6 @@ import (
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func TestFindChecksEntryAndCodeTags(t *testing.T) {
|
||||
for _, payload := range [][]byte{
|
||||
{0x12, 6, 0x0a, 4, 'T', 'E', 'S', 'T'}, // Unknown field posing as entry.
|
||||
{0x08, 6, 0x0a, 4, 'T', 'E', 'S', 'T'}, // Wrong entry wire type.
|
||||
{0x0a, 6, 0x1a, 4, 'T', 'E', 'S', 'T'}, // Unknown field posing as code.
|
||||
{0x0a, 6, 0x08, 4, 'T', 'E', 'S', 'T'}, // Wrong code wire type.
|
||||
} {
|
||||
if _, err := find(bytes.NewReader(payload), []byte("TEST"), true, int64(len(payload))); err == nil {
|
||||
t.Fatalf("matched incorrect entry/code tags in %x", payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFileRejectsVarintOverflow(t *testing.T) {
|
||||
payload := []byte{
|
||||
0x0a,
|
||||
0x86, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x02, // 2^64 + 6
|
||||
0x0a, 0x04, 'T', 'E', 'S', 'T',
|
||||
}
|
||||
dir := t.TempDir()
|
||||
t.Setenv("xray.location.asset", dir)
|
||||
if err := os.WriteFile(filepath.Join(dir, "overflow.dat"), payload, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := loadFile("overflow.dat", "TEST"); err == nil || !strings.Contains(err.Error(), "varint overflow") {
|
||||
t.Fatalf("want varint overflow, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFileRejectsOversizedEntry(t *testing.T) {
|
||||
payload := []byte{
|
||||
0x0a, 0x03, 0x0a, 0x01, 'A', // A valid entry before the oversized one.
|
||||
0x0a, 0x80, 0x80, 0x80, 0x80, 0x04, // Entry length: 1 GiB.
|
||||
0x0a, 0x04, 'T', 'E', 'S', 'T',
|
||||
}
|
||||
dir := t.TempDir()
|
||||
t.Setenv("xray.location.asset", dir)
|
||||
if err := os.WriteFile(filepath.Join(dir, "oversized.dat"), payload, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Check without allocating the body first, so a regression fails safely.
|
||||
if err := checkFile("oversized.dat", "TEST"); err == nil {
|
||||
t.Fatal("accepted an entry length larger than the file")
|
||||
}
|
||||
if _, err := loadFile("oversized.dat", "TEST"); err == nil || !strings.Contains(err.Error(), "invalid body length") {
|
||||
t.Fatalf("want invalid body length, got %v", err)
|
||||
}
|
||||
if err := loadSite("oversized.dat", "TEST", "", func(Domain_Type, []byte) {}); err == nil || !strings.Contains(err.Error(), "invalid body length") {
|
||||
t.Fatalf("want invalid body length, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type siteEntry struct {
|
||||
Type Domain_Type
|
||||
Value string
|
||||
|
||||
@@ -400,13 +400,13 @@ func TestIPMatcher4CN(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIPMatcher6RU(t *testing.T) {
|
||||
func TestIPMatcher6US(t *testing.T) {
|
||||
t.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
||||
|
||||
matcher := buildIPMatcher("geoip:ru")
|
||||
matcher := buildIPMatcher("geoip:us")
|
||||
|
||||
if !matcher.Match(xnet.ParseAddress("2a02:6b8::feed:0ff").IP()) {
|
||||
t.Error("expect RU geoip contain 2a02:6b8::feed:0ff, but actually not")
|
||||
if !matcher.Match(xnet.ParseAddress("2001:4860:4860::8888").IP()) {
|
||||
t.Error("expect US geoip contain 2001:4860:4860::8888, but actually not")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -423,11 +423,11 @@ func BenchmarkIPMatcher4CN(b *testing.B) {
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkIPMatcher6RU(b *testing.B) {
|
||||
func BenchmarkIPMatcher6US(b *testing.B) {
|
||||
b.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
||||
|
||||
matcher := buildIPMatcher("geoip:ru")
|
||||
ip := xnet.ParseAddress("2a02:6b8::feed:0ff").IP()
|
||||
matcher := buildIPMatcher("geoip:us")
|
||||
ip := xnet.ParseAddress("2001:4860:4860::8888").IP()
|
||||
|
||||
b.ResetTimer()
|
||||
|
||||
|
||||
@@ -44,8 +44,8 @@ func RegisterLua(L *lua.LState) {
|
||||
"Match": luaIPMatch,
|
||||
"AnyMatch": luaIPAnyMatch,
|
||||
"Matches": luaIPMatches,
|
||||
"FilterIPs": newLuaIPFilterIPs(xlua.NewReadOnlySlicePusher[net.IP](L)),
|
||||
}, "SetReverse", "ToggleReverse")
|
||||
"FilterIPs": newLuaIPFilterIPs(xlua.NewSlicePusher[net.IP](L)),
|
||||
})
|
||||
return 1
|
||||
}))
|
||||
|
||||
|
||||
@@ -78,7 +78,6 @@ 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.Reload == nil and matcher.reload == nil)
|
||||
assert(matcher:match(ip))
|
||||
assert(matcher:anyMatch({ip}) and matcher:matches({ip}))
|
||||
assert(not matcher:AnyMatch(nil))
|
||||
@@ -98,11 +97,6 @@ assert(matcher.missing == nil)
|
||||
|
||||
local domain = geodata.BuildDomainMatcher("full:example.com")
|
||||
assert(domain.Match == domain.match and domain.MatchAny == domain.matchAny)
|
||||
assert(domain.Reload == nil and domain.reload == nil)
|
||||
for _, value in ipairs({matcher, domain}) do
|
||||
assert(not pcall(function() return -value end))
|
||||
assert(not pcall(function() return value ^ {} end))
|
||||
end
|
||||
assert(domain:matchAny("example.com"))
|
||||
assert(#domain:Match("example.com") == 1)
|
||||
assert(domain:match("example.com")[1] == 0)
|
||||
|
||||
@@ -11,7 +11,7 @@ func TestParseIPRules(t *testing.T) {
|
||||
t.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
||||
|
||||
rules := []string{
|
||||
"geoip:ru",
|
||||
"geoip:us",
|
||||
"geoip:cn",
|
||||
"!geoip:cn",
|
||||
"!!geoip:cn",
|
||||
@@ -20,9 +20,9 @@ func TestParseIPRules(t *testing.T) {
|
||||
"!geoip:!cn",
|
||||
"ext:geoip.dat:!cn",
|
||||
"ext:geoip.dat:!!cn",
|
||||
"ext:geoip.dat:ir",
|
||||
"ext:geoip.dat:ca",
|
||||
"ext-ip:geoip.dat:!cn",
|
||||
"ext-ip:geoip.dat:!ir",
|
||||
"ext-ip:geoip.dat:!ca",
|
||||
"192.168.0.0/24",
|
||||
"!192.168.0.0/24",
|
||||
"!!192.168.0.0/24",
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
// DO NOT EDIT. Regression test for app/geodata's luaGuardHeader.
|
||||
|
||||
package lua
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yuin/gopher-lua/parse"
|
||||
)
|
||||
|
||||
func TestGeodataLuaGuard(t *testing.T) {
|
||||
_, err := parse.Parse(strings.NewReader("\x12\x01\x00function HandleRoute() end"), "geodata")
|
||||
var syntaxErr *parse.Error
|
||||
if !errors.As(err, &syntaxErr) || syntaxErr.Pos.Line != 1 || syntaxErr.Pos.Column != 1 {
|
||||
t.Fatalf("want Lua rejection at the first byte, got %v", err)
|
||||
}
|
||||
}
|
||||
+4
-95
@@ -1,9 +1,6 @@
|
||||
package lua
|
||||
|
||||
import (
|
||||
"net"
|
||||
"reflect"
|
||||
|
||||
glua "github.com/yuin/gopher-lua"
|
||||
luar "layeh.com/gopher-luar"
|
||||
)
|
||||
@@ -12,7 +9,7 @@ import (
|
||||
// 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.MT(L, []T(nil)).LTable
|
||||
metatable := luar.New(L, []T{}).(*glua.LUserData).Metatable
|
||||
return func(L *glua.LState, values []T) {
|
||||
if values == nil {
|
||||
L.Push(glua.LNil)
|
||||
@@ -25,105 +22,21 @@ func NewSlicePusher[T any](L *glua.LState) func(*glua.LState, []T) {
|
||||
}
|
||||
}
|
||||
|
||||
// NewReadOnlySlicePusher borrows slices without copying and recursively makes
|
||||
// nested slice types read-only through their shared metatables. IP byte views
|
||||
// and masks are also read-only. Other referenced elements retain their mutability.
|
||||
// Element bindings are initialized on first indexing or iteration.
|
||||
func NewReadOnlySlicePusher[T any](L *glua.LState) func(*glua.LState, []T) {
|
||||
sliceMetatable := luar.MT(L, []T{})
|
||||
if sliceMetatable.RawGetString("__readonly") != glua.LTrue {
|
||||
readOnly := L.NewFunction(func(L *glua.LState) int {
|
||||
L.RaiseError("slice is read-only")
|
||||
return 0
|
||||
})
|
||||
setSliceReadOnly[[]T](L, readOnly)
|
||||
}
|
||||
return NewSlicePusher[T](L)
|
||||
}
|
||||
|
||||
func setSliceReadOnly[S ~[]E, E any](L *glua.LState, readOnly *glua.LFunction) {
|
||||
var visit func(reflect.Type)
|
||||
visit = func(typ reflect.Type) {
|
||||
if typ.Kind() != reflect.Slice {
|
||||
return
|
||||
}
|
||||
metatable := luar.MT(L, reflect.Zero(typ).Interface())
|
||||
if metatable.RawGetString("__readonly") == glua.LTrue {
|
||||
return
|
||||
}
|
||||
// Mark before descending because named slice types can be recursive.
|
||||
metatable.RawSetString("__readonly", glua.LTrue)
|
||||
metatable.RawSetString("__newindex", readOnly)
|
||||
// Reject explicitly so Lua cannot fall back to the other operand.
|
||||
metatable.RawSetString("__add", readOnly)
|
||||
if typ == reflect.TypeFor[net.IP]() {
|
||||
// A nil receiver lets AppendText return its argument as a writable []byte.
|
||||
methods := metatable.RawGetString("methods").(*glua.LTable)
|
||||
appendText := methods.RawGetString("AppendText")
|
||||
for key, method := methods.Next(glua.LNil); key != glua.LNil; key, method = methods.Next(key) {
|
||||
if method == appendText {
|
||||
methods.RawSet(key, glua.LNil)
|
||||
}
|
||||
}
|
||||
visit(reflect.TypeFor[net.IPMask]())
|
||||
}
|
||||
if element := typ.Elem(); element.Kind() == reflect.Slice {
|
||||
index := metatable.RawGetString("__index").(*glua.LFunction)
|
||||
call := metatable.RawGetString("__call").(*glua.LFunction)
|
||||
initialize := func() {
|
||||
visit(element)
|
||||
metatable.RawSetString("__index", index)
|
||||
metatable.RawSetString("__call", call)
|
||||
}
|
||||
metatable.RawSetString("__index", L.NewFunction(func(L *glua.LState) int {
|
||||
initialize()
|
||||
return index.GFunction(L)
|
||||
}))
|
||||
metatable.RawSetString("__call", L.NewFunction(func(L *glua.LState) int {
|
||||
initialize()
|
||||
return call.GFunction(L)
|
||||
}))
|
||||
}
|
||||
}
|
||||
visit(reflect.TypeFor[S]())
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
// PushMethods pushes a luar userdata exposing only the named Go methods and
|
||||
// their aliases through reflected calls. The method list is fixed by the first
|
||||
// binding of that Go type in each LState.
|
||||
func PushMethods(L *glua.LState, value any, methods ...string) {
|
||||
PushWithDirectMethods(L, value, nil, methods...)
|
||||
}
|
||||
|
||||
// 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.
|
||||
// Only directMethods and additionalMethods are exposed, including their aliases.
|
||||
// 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, additionalMethods ...string) {
|
||||
// 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 {
|
||||
// Keep all aliases for the explicitly exposed methods.
|
||||
exposed := make(map[glua.LValue]bool, len(directMethods)+len(additionalMethods))
|
||||
for name := range directMethods {
|
||||
exposed[methods.RawGetString(name)] = true
|
||||
}
|
||||
for _, name := range additionalMethods {
|
||||
exposed[methods.RawGetString(name)] = true
|
||||
}
|
||||
for key, method := methods.Next(glua.LNil); key != glua.LNil; key, method = methods.Next(key) {
|
||||
if !exposed[method] {
|
||||
methods.RawSet(key, glua.LNil)
|
||||
}
|
||||
}
|
||||
for name, direct := range directMethods {
|
||||
original := methods.RawGetString(name)
|
||||
fn := L.NewFunction(func(L *glua.LState) int {
|
||||
@@ -139,10 +52,6 @@ func PushWithDirectMethods(L *glua.LState, value any, directMethods map[string]D
|
||||
}
|
||||
}
|
||||
}
|
||||
// Pointer operations would bypass the method-only API.
|
||||
metatable.RawSetString("__newindex", glua.LNil)
|
||||
metatable.RawSetString("__pow", glua.LNil)
|
||||
metatable.RawSetString("__unm", glua.LNil)
|
||||
metatable.RawSetString("__index", methods)
|
||||
}
|
||||
L.Push(userdata)
|
||||
|
||||
@@ -2,7 +2,6 @@ package lua
|
||||
|
||||
import (
|
||||
"net"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
glua "github.com/yuin/gopher-lua"
|
||||
@@ -48,188 +47,6 @@ assert(ok and result == true)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadOnlySlicePusher(t *testing.T) {
|
||||
L := glua.NewState()
|
||||
defer L.Close()
|
||||
values := []int{3, 5}
|
||||
NewReadOnlySlicePusher[int](L)(L, values)
|
||||
L.SetGlobal("values", L.Get(-1))
|
||||
L.Pop(1)
|
||||
if err := L.DoString(`
|
||||
assert(#values == 2 and values[1] == 3 and values[2] == 5)
|
||||
assert(not pcall(function() values[1] = 7 end))
|
||||
assert(not pcall(function() return values + 7 end))
|
||||
local sum = 0
|
||||
for _, value in values() do sum = sum + value end
|
||||
assert(sum == 8)
|
||||
`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := L.GetGlobal("values").(*glua.LUserData).Value.([]int)
|
||||
if &got[0] != &values[0] || values[0] != 3 || values[1] != 5 {
|
||||
t.Fatal("read-only binding copied or modified the slice")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadOnlyIPSlicePusher(t *testing.T) {
|
||||
L := glua.NewState()
|
||||
defer L.Close()
|
||||
ips := []net.IP{{192, 0, 2, 1}, net.ParseIP("2001:db8::1")}
|
||||
NewReadOnlySlicePusher[net.IP](L)(L, ips)
|
||||
L.SetGlobal("ips", L.Get(-1))
|
||||
L.Pop(1)
|
||||
readOnly := luar.MT(L, ips).RawGetString("__newindex")
|
||||
NewReadOnlySlicePusher[net.IP](L)
|
||||
if luar.MT(L, ips).RawGetString("__newindex") != readOnly {
|
||||
t.Fatal("IP metatables were initialized more than once")
|
||||
}
|
||||
if err := L.DoString(`
|
||||
local function readOnly(value)
|
||||
assert(not pcall(function() value[1] = value[1] end))
|
||||
assert(not pcall(function() return value + value[1] end))
|
||||
end
|
||||
assert(#ips == 2 and ips[1]:String() == "192.0.2.1")
|
||||
readOnly(ips)
|
||||
for _, ip in ips() do
|
||||
readOnly(ip)
|
||||
readOnly(ip:To16())
|
||||
if ip:To4() then
|
||||
readOnly(ip:To4())
|
||||
readOnly(ip:DefaultMask())
|
||||
end
|
||||
assert(ip:Equal(ip:To16()) and type(ip:String()) == "string")
|
||||
assert(ip.AppendText == nil and ip.appendText == nil)
|
||||
local text, err = ip:MarshalText()
|
||||
assert(not err)
|
||||
text[1] = 88 -- Independently owned byte buffers remain writable.
|
||||
assert(not pcall(function() return ips + text end))
|
||||
end
|
||||
`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := L.GetGlobal("ips").(*glua.LUserData).Value.([]net.IP)
|
||||
if &got[0] != &ips[0] || &got[0][0] != &ips[0][0] || &got[1][0] != &ips[1][0] {
|
||||
t.Fatal("read-only binding copied the IP data")
|
||||
}
|
||||
for i, want := range []string{"192.0.2.1", "2001:db8::1"} {
|
||||
if got[i].String() != want {
|
||||
t.Fatalf("IP %d changed to %s; want %s", i, got[i], want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadOnlyIPSlicePusherLazy(t *testing.T) {
|
||||
for _, tc := range []struct{ name, access string }{
|
||||
{"index", `local ip = ips[1]`},
|
||||
{"iterate", `local _, ip = ips()()`},
|
||||
{"coroutine", `local co = coroutine.create(function() return ips[1] end); local ok, ip = coroutine.resume(co); assert(ok)`},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
L := glua.NewState()
|
||||
defer L.Close()
|
||||
methods := 0
|
||||
luar.GetConfig(L).MethodNames = func(_ reflect.Type, method reflect.Method) []string {
|
||||
methods++
|
||||
return []string{method.Name}
|
||||
}
|
||||
NewReadOnlySlicePusher[net.IP](L)(L, []net.IP{{192, 0, 2, 1}})
|
||||
L.SetGlobal("ips", L.Get(-1))
|
||||
L.Pop(1)
|
||||
if err := L.DoString(`assert(#ips == 1); assert(not pcall(function() ips[1] = nil end))`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if methods != 0 {
|
||||
t.Fatal("IP methods initialized without reading an element")
|
||||
}
|
||||
source := tc.access + `
|
||||
assert(ip:String() == "192.0.2.1" and ip.AppendText == nil)
|
||||
assert(not pcall(function() ip[1] = 0 end))
|
||||
assert(not pcall(function() ip:To4()[1] = 0 end))
|
||||
assert(not pcall(function() ip:To16()[1] = 0 end))
|
||||
assert(not pcall(function() ip:DefaultMask()[1] = 0 end))
|
||||
`
|
||||
if err := L.DoString(source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
initialized := methods
|
||||
if initialized == 0 {
|
||||
t.Fatal("IP access did not initialize its methods")
|
||||
}
|
||||
if err := L.DoString(source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if methods != initialized {
|
||||
t.Fatal("IP methods initialized more than once")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadOnlyNestedSlicePusher(t *testing.T) {
|
||||
L := glua.NewState()
|
||||
defer L.Close()
|
||||
values := [][][]byte{{{3, 5}}}
|
||||
NewReadOnlySlicePusher[[][]byte](L)(L, values)
|
||||
L.SetGlobal("values", L.Get(-1))
|
||||
L.Pop(1)
|
||||
ips := [][]net.IP{{{192, 0, 2, 1}}}
|
||||
NewReadOnlySlicePusher[[]net.IP](L)(L, ips)
|
||||
L.SetGlobal("ips", L.Get(-1))
|
||||
L.Pop(1)
|
||||
if err := L.DoString(`
|
||||
local function readOnly(value)
|
||||
assert(not pcall(function() value[1] = value[1] end))
|
||||
assert(not pcall(function() return value + value[1] end))
|
||||
end
|
||||
assert(values[1][1][1] == 3 and values[1][1][2] == 5)
|
||||
readOnly(values)
|
||||
for _, group in values() do
|
||||
readOnly(group)
|
||||
for _, bytes in group() do readOnly(bytes) end
|
||||
end
|
||||
readOnly(ips)
|
||||
readOnly(ips[1])
|
||||
local ip = ips[1][1]
|
||||
assert(ip:String() == "192.0.2.1")
|
||||
readOnly(ip)
|
||||
readOnly(ip:To4())
|
||||
readOnly(ip:To16())
|
||||
readOnly(ip:DefaultMask())
|
||||
assert(ip.AppendText == nil and ip.appendText == nil)
|
||||
`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
readOnly := luar.MT(L, ips[0]).RawGetString("__newindex")
|
||||
NewReadOnlySlicePusher[net.IP](L)
|
||||
if luar.MT(L, ips[0]).RawGetString("__newindex") != readOnly {
|
||||
t.Fatal("nested slice metatable was initialized again")
|
||||
}
|
||||
got := L.GetGlobal("values").(*glua.LUserData).Value.([][][]byte)
|
||||
if &got[0][0][0] != &values[0][0][0] || values[0][0][0] != 3 || values[0][0][1] != 5 {
|
||||
t.Fatal("read-only binding copied or modified the nested slice")
|
||||
}
|
||||
}
|
||||
|
||||
type recursiveReadOnlySlice []recursiveReadOnlySlice
|
||||
|
||||
func TestReadOnlyRecursiveSlicePusher(t *testing.T) {
|
||||
L := glua.NewState()
|
||||
defer L.Close()
|
||||
values := make(recursiveReadOnlySlice, 1)
|
||||
values[0] = values
|
||||
NewReadOnlySlicePusher[recursiveReadOnlySlice](L)(L, values)
|
||||
L.SetGlobal("values", L.Get(-1))
|
||||
L.Pop(1)
|
||||
if err := L.DoString(`
|
||||
local nested = values[1][1][1]
|
||||
assert(#nested == 1)
|
||||
assert(not pcall(function() nested[1] = nested end))
|
||||
assert(not pcall(function() return nested + nested end))
|
||||
`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlicePusherMetatablePerState(t *testing.T) {
|
||||
first := glua.NewState()
|
||||
defer first.Close()
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
package lua
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"sync"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
)
|
||||
|
||||
var privilegedKey struct {
|
||||
sync.Once
|
||||
publicKey ed25519.PublicKey
|
||||
}
|
||||
|
||||
// SetPrivilegedPublicKey configures the trusted Ed25519 public key once at
|
||||
// startup, before compiling scripts. An empty value disables authorization.
|
||||
// Nonempty values must be unpadded Base64URL encodings of exactly 32 bytes.
|
||||
func SetPrivilegedPublicKey(value string) error {
|
||||
var publicKey ed25519.PublicKey
|
||||
if value != "" {
|
||||
decoded, err := decodePrivilegedValue(value, ed25519.PublicKeySize)
|
||||
if err != nil {
|
||||
return errors.New("invalid Lua privileged public key").Base(err)
|
||||
}
|
||||
publicKey = ed25519.PublicKey(decoded)
|
||||
}
|
||||
privilegedKey.Do(func() {
|
||||
privilegedKey.publicKey = publicKey
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func decodePrivilegedValue(value string, size int) ([]byte, error) {
|
||||
encoding := base64.RawURLEncoding.Strict()
|
||||
if len(value) != encoding.EncodedLen(size) {
|
||||
return nil, errors.New("expected an unpadded Base64URL encoding of ", size, " bytes")
|
||||
}
|
||||
decoded, err := encoding.DecodeString(value)
|
||||
if err != nil || len(decoded) != size || encoding.EncodeToString(decoded) != value {
|
||||
return nil, errors.New("expected an unpadded Base64URL encoding of ", size, " bytes")
|
||||
}
|
||||
return decoded, nil
|
||||
}
|
||||
|
||||
func verifyPrivilegedSignature(code []byte) (bool, error) {
|
||||
_, end, value, found := privilegedSignatureLine(code)
|
||||
if !found {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
publicKey := privilegedKey.publicKey
|
||||
if len(publicKey) == 0 {
|
||||
return false, errors.New("Lua privileged signature requires --lua-privileged-pubkey")
|
||||
}
|
||||
signature, err := decodePrivilegedValue(string(bytes.TrimSpace(value)), ed25519.SignatureSize)
|
||||
if err != nil {
|
||||
return false, errors.New("invalid Lua privileged signature").Base(err)
|
||||
}
|
||||
digest := sha256.Sum256(bytes.TrimSpace(code[end:]))
|
||||
if !ed25519.Verify(publicKey, digest[:], signature) {
|
||||
return false, errors.New("Lua privileged signature verification failed")
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// SignPrivilegedScript signs the script body, then prepends or replaces the signature line.
|
||||
func SignPrivilegedScript(code []byte, seed string) ([]byte, error) {
|
||||
decoded, err := decodePrivilegedValue(seed, ed25519.SeedSize)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid Ed25519 private key seed").Base(err)
|
||||
}
|
||||
|
||||
start, end, _, found := privilegedSignatureLine(code)
|
||||
body := code
|
||||
if found {
|
||||
body = code[end:]
|
||||
}
|
||||
|
||||
digest := sha256.Sum256(bytes.TrimSpace(body))
|
||||
signature := ed25519.Sign(ed25519.NewKeyFromSeed(decoded), digest[:])
|
||||
header := []byte("-- @xray:privileged-signature=" + base64.RawURLEncoding.EncodeToString(signature))
|
||||
|
||||
if !found {
|
||||
if newline := bytes.IndexByte(code, '\n'); newline > 0 && code[newline-1] == '\r' {
|
||||
header = append(header, '\r')
|
||||
}
|
||||
header = append(header, '\n')
|
||||
return append(header, code...), nil
|
||||
}
|
||||
signed := make([]byte, 0, start+len(header)+len(code)-end)
|
||||
signed = append(signed, code[:start]...)
|
||||
signed = append(signed, header...)
|
||||
return append(signed, code[end:]...), nil
|
||||
}
|
||||
|
||||
func privilegedSignatureLine(code []byte) (start, end int, value []byte, found bool) {
|
||||
for rest := code; len(rest) != 0; {
|
||||
start = len(code) - len(rest)
|
||||
var line []byte
|
||||
line, rest, _ = bytes.Cut(rest, []byte{'\n'})
|
||||
line = bytes.TrimSuffix(line, []byte{'\r'})
|
||||
if len(bytes.TrimSpace(line)) == 0 {
|
||||
continue
|
||||
}
|
||||
end = start + len(line)
|
||||
line, found := bytes.CutPrefix(bytes.TrimLeft(line, " \t"), []byte("--"))
|
||||
if !found {
|
||||
return 0, 0, nil, false
|
||||
}
|
||||
value, found = bytes.CutPrefix(bytes.TrimLeft(line, " \t"), []byte("@xray:privileged-signature="))
|
||||
return start, end, value, found
|
||||
}
|
||||
return 0, 0, nil, false
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
package lua
|
||||
|
||||
// TODO: Re-enable these tests and their helper when Compile supports privileged signature authorization again.
|
||||
/*
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func privilegedSeed(t *testing.T) string {
|
||||
t.Helper()
|
||||
seed, err := hex.DecodeString(privilegedTestSeed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(seed)
|
||||
}
|
||||
|
||||
func TestSignPrivilegedScriptPreservesSource(t *testing.T) {
|
||||
setTestPrivilegedPublicKey(t, privilegedTestPublicKey)
|
||||
seed := privilegedSeed(t)
|
||||
for _, tc := range []struct {
|
||||
name, prefix, header, body, newline string
|
||||
}{
|
||||
{name: "unsigned", body: privilegedFixtureBody, newline: "\n"},
|
||||
{name: "unsigned boundary whitespace", body: " \t\n\n" + privilegedFixtureBody + " \t\n", newline: "\n"},
|
||||
{name: "unsigned CRLF", body: strings.ReplaceAll(privilegedFixtureBody, "\n", "\r\n"), newline: "\r\n"},
|
||||
{name: "replace invalid header", header: privilegedSignatureHeader + "%", body: "\n" + privilegedFixtureBody, newline: "\n"},
|
||||
{name: "replace indented header", prefix: " \t\r\n\n", header: " \t--\t @xray:privileged-signature=% \t", body: "\r\n \t\r\n" + privilegedFixtureBody + "\r\n", newline: "\r\n"},
|
||||
{name: "replace valid header", header: privilegedSignatureHeader + privilegedFixtureSignature, body: "\n" + privilegedFixtureBody, newline: "\n"},
|
||||
{name: "empty script", newline: "\n"},
|
||||
{name: "header without newline", header: privilegedSignatureHeader + "%"},
|
||||
{name: "ordinary comment before marker", body: "-- ordinary comment\n" + privilegedSignatureHeader + "%\nvalue = 1", newline: "\n"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
code := []byte(tc.prefix + tc.header + tc.body)
|
||||
original := bytes.Clone(code)
|
||||
signed, err := SignPrivilegedScript(code, seed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(code, original) {
|
||||
t.Fatal("signing modified the input buffer")
|
||||
}
|
||||
body := tc.body
|
||||
if tc.header != "" {
|
||||
body = strings.TrimPrefix(body, tc.newline)
|
||||
}
|
||||
header := privilegedSignatureHeader + testSignature(t, body)
|
||||
want := header + tc.newline + tc.body
|
||||
if tc.header != "" {
|
||||
want = tc.prefix + header + tc.body
|
||||
}
|
||||
if string(signed) != want {
|
||||
t.Fatalf("signed source = %q, want %q", signed, want)
|
||||
}
|
||||
program, err := Compile(writeTestScript(t, string(signed)))
|
||||
if err != nil || program == nil || !program.privileged {
|
||||
t.Fatalf("signed source Compile = %v, %v; want privileged program", program, err)
|
||||
}
|
||||
again, err := SignPrivilegedScript(signed, seed)
|
||||
if err != nil || !bytes.Equal(again, signed) {
|
||||
t.Fatalf("resigning changed the source: %q, %v", again, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignPrivilegedScriptRejectsInvalidSeed(t *testing.T) {
|
||||
seed := privilegedSeed(t)
|
||||
for _, value := range []string{
|
||||
"", "%", seed + "=",
|
||||
base64.RawURLEncoding.EncodeToString(make([]byte, ed25519.SeedSize-1)),
|
||||
base64.RawURLEncoding.EncodeToString(make([]byte, ed25519.PrivateKeySize)),
|
||||
} {
|
||||
if signed, err := SignPrivilegedScript([]byte(privilegedFixtureBody), value); signed != nil || err == nil {
|
||||
t.Fatalf("SignPrivilegedScript with invalid seed = %q, %v; want rejection", signed, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
+13
-196
@@ -1,80 +1,47 @@
|
||||
package lua
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/base64"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"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
|
||||
proto *glua.FunctionProto
|
||||
}
|
||||
|
||||
// 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) {
|
||||
// TODO: Restore inline script support and re-enable the related tests.
|
||||
return nil, errors.New("currently unavailable")
|
||||
code, err = base64.Decode(script)
|
||||
} else if name, err = platform.ResolveLuaFile(script); err == nil {
|
||||
code, err = os.ReadFile(name)
|
||||
// TODO: Restore privileged signature authorization and re-enable the related tests and CLI entries.
|
||||
// if err == nil {
|
||||
// privileged, err = verifyPrivilegedSignature(code)
|
||||
// }
|
||||
}
|
||||
// CompileFile reads and compiles a Lua file once.
|
||||
func CompileFile(path string) (*Program, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
chunk, err := parse.Parse(bytes.NewReader(code), name)
|
||||
defer f.Close()
|
||||
chunk, err := parse.Parse(bufio.NewReader(f), path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
proto, err := glua.Compile(chunk, name)
|
||||
proto, err := glua.Compile(chunk, path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Program{proto: proto, privileged: privileged}, nil
|
||||
return &Program{proto: proto}, nil
|
||||
}
|
||||
|
||||
// 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.
|
||||
// Choose registrySize for the script type's expected stack usage, balancing
|
||||
// per-state memory usage against the number of states retained in a pool.
|
||||
func (p *Program) NewState(ctx context.Context, registrySize int, register func(*glua.LState), validate func(*glua.LState) error) (*glua.LState, error) {
|
||||
options := glua.Options{
|
||||
RegistrySize: registrySize,
|
||||
RegistryMaxSize: glua.RegistrySize,
|
||||
RegistryGrowStep: registrySize,
|
||||
}
|
||||
var L *glua.LState
|
||||
if p.privileged {
|
||||
L = glua.NewState(options)
|
||||
} else {
|
||||
L = newSandboxedState(options)
|
||||
}
|
||||
func (p *Program) NewState(ctx context.Context, register func(*glua.LState), validate func(*glua.LState) error) (*glua.LState, error) {
|
||||
L := glua.NewState()
|
||||
valid := false
|
||||
defer func() {
|
||||
if !valid {
|
||||
@@ -86,10 +53,6 @@ func (p *Program) NewState(ctx context.Context, registrySize int, register func(
|
||||
if register != nil {
|
||||
register(L)
|
||||
}
|
||||
if !p.privileged {
|
||||
// Hide package internals to prevent data snooping and sandbox escape.
|
||||
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 {
|
||||
@@ -104,157 +67,11 @@ func (p *Program) NewState(ctx context.Context, registrySize int, register func(
|
||||
return L, nil
|
||||
}
|
||||
|
||||
func newSandboxedState(options glua.Options) *glua.LState {
|
||||
options.SkipOpenLibs = true
|
||||
L := glua.NewState(options)
|
||||
|
||||
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.OsLibName, glua.OpenOs},
|
||||
} {
|
||||
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",
|
||||
"getmetatable", "setmetatable", "rawget", "rawset",
|
||||
"collectgarbage", "module", "newproxy", "print", "_printregs",
|
||||
} {
|
||||
L.SetGlobal(name, glua.LNil)
|
||||
}
|
||||
|
||||
// Prevent printing memory addresses that reveal the memory layout.
|
||||
toString := func(value glua.LValue) glua.LString {
|
||||
result := "<opaque>"
|
||||
switch value.Type() {
|
||||
case glua.LTNil, glua.LTBool, glua.LTNumber, glua.LTString:
|
||||
result = value.String()
|
||||
case glua.LTUserData:
|
||||
switch native := value.(*glua.LUserData).Value.(type) {
|
||||
case error: // Errors can also implement fmt.Stringer; redact them first.
|
||||
result = redactMemoryAddresses(native.Error())
|
||||
case fmt.Stringer:
|
||||
result = native.String()
|
||||
}
|
||||
}
|
||||
return glua.LString(result)
|
||||
}
|
||||
L.SetGlobal("tostring", L.NewFunction(func(L *glua.LState) int {
|
||||
L.Push(toString(L.CheckAny(1)))
|
||||
return 1
|
||||
}))
|
||||
|
||||
// Prevent printing memory addresses that reveal the memory layout.
|
||||
stringLib := L.GetGlobal(glua.StringLibName).(*glua.LTable)
|
||||
stringLib.RawSetString("dump", glua.LNil)
|
||||
format := stringLib.RawGetString("format")
|
||||
stringLib.RawSetString("format", L.NewFunction(func(L *glua.LState) int {
|
||||
nargs := L.GetTop()
|
||||
for i := 2; i <= nargs; i++ {
|
||||
value := L.Get(i)
|
||||
switch value.Type() {
|
||||
case glua.LTBool, glua.LTNumber, glua.LTString:
|
||||
continue
|
||||
}
|
||||
L.Replace(i, toString(value))
|
||||
}
|
||||
L.Insert(format, 1)
|
||||
L.Call(nargs, 1)
|
||||
return 1
|
||||
}))
|
||||
|
||||
// Redact addresses before caught errors become readable by the script.
|
||||
redactError := func(value glua.LValue) glua.LValue {
|
||||
if message, ok := value.(glua.LString); ok {
|
||||
if redacted := redactMemoryAddresses(string(message)); redacted != string(message) {
|
||||
return glua.LString(redacted)
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
for _, name := range []string{"pcall", "xpcall"} {
|
||||
call := L.GetGlobal(name)
|
||||
L.SetGlobal(name, L.NewFunction(func(L *glua.LState) int {
|
||||
nargs := L.GetTop()
|
||||
if name == "xpcall" {
|
||||
L.CheckFunction(1)
|
||||
handler := L.CheckFunction(2)
|
||||
L.Replace(2, L.NewFunction(func(L *glua.LState) int {
|
||||
L.Replace(1, redactError(L.Get(1)))
|
||||
L.Insert(handler, 1)
|
||||
L.Call(1, 1)
|
||||
return 1
|
||||
}))
|
||||
}
|
||||
L.Insert(call, 1)
|
||||
L.Call(nargs, glua.MultRet)
|
||||
if L.Get(1) == glua.LFalse {
|
||||
L.Replace(2, redactError(L.Get(2)))
|
||||
}
|
||||
return L.GetTop()
|
||||
}))
|
||||
}
|
||||
|
||||
// Prevent seed output from compromising cryptographic security.
|
||||
L.GetGlobal(glua.MathLibName).(*glua.LTable).RawSetString("randomseed", glua.LNil)
|
||||
|
||||
// Keep only time functions, including when os is accessed through require.
|
||||
osLib := L.GetGlobal(glua.OsLibName).(*glua.LTable)
|
||||
for key, _ := osLib.Next(glua.LNil); key != glua.LNil; key, _ = osLib.Next(key) {
|
||||
switch key {
|
||||
case glua.LString("clock"), glua.LString("date"), glua.LString("difftime"), glua.LString("time"):
|
||||
default:
|
||||
osLib.RawSet(key, glua.LNil)
|
||||
}
|
||||
}
|
||||
|
||||
// Prevent module injection through the global package table.
|
||||
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
|
||||
}
|
||||
|
||||
var memoryAddressPattern = regexp.MustCompile(`0[xX][0-9a-fA-F]+`)
|
||||
|
||||
func redactMemoryAddresses(message string) string {
|
||||
if !strings.Contains(message, "0x") && !strings.Contains(message, "0X") {
|
||||
return message
|
||||
}
|
||||
return memoryAddressPattern.ReplaceAllString(message, "<address>")
|
||||
}
|
||||
|
||||
// NewStateFactory returns a factory that gives each state an initialization timeout.
|
||||
// Choose registrySize for the script type's expected stack usage, balancing
|
||||
// per-state memory usage against the number of states retained in a pool.
|
||||
func (p *Program) NewStateFactory(initTimeout time.Duration, registrySize int, register func(*glua.LState), validate func(*glua.LState) error) LStateFactory {
|
||||
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, registrySize, register, validate)
|
||||
return p.NewState(initCtx, register, validate)
|
||||
}
|
||||
}
|
||||
|
||||
+11
-1117
File diff suppressed because it is too large
Load Diff
@@ -26,20 +26,20 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
|
||||
panic("Unsupported network type for process lookup.")
|
||||
}
|
||||
|
||||
var procFiles []string
|
||||
var procFile string
|
||||
|
||||
switch network {
|
||||
case "tcp":
|
||||
if net.ParseIP(srcIP).To4() != nil {
|
||||
procFiles = []string{"/proc/net/tcp"}
|
||||
procFile = "/proc/net/tcp"
|
||||
} else {
|
||||
procFiles = []string{"/proc/net/tcp6"}
|
||||
procFile = "/proc/net/tcp6"
|
||||
}
|
||||
case "udp":
|
||||
if net.ParseIP(srcIP).To4() != nil {
|
||||
procFiles = []string{"/proc/net/udp", "/proc/net/udp6"}
|
||||
procFile = "/proc/net/udp"
|
||||
} else {
|
||||
procFiles = []string{"/proc/net/udp6", "/proc/net/udp"}
|
||||
procFile = "/proc/net/udp6"
|
||||
}
|
||||
default:
|
||||
panic("Unsupported network type for process lookup.")
|
||||
@@ -50,17 +50,12 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
|
||||
return 0, "", "", errors.New("failed to format address: ", err)
|
||||
}
|
||||
|
||||
portFallback := ""
|
||||
if network == "udp" {
|
||||
portFallback = fmt.Sprintf(":%04X", srcPort)
|
||||
}
|
||||
|
||||
inode, err := findInodeInFiles(procFiles, targetHexAddr, portFallback)
|
||||
inode, err := findInodeInFile(procFile, targetHexAddr)
|
||||
if err != nil {
|
||||
return 0, "", "", errors.New("could not search in ", strings.Join(procFiles, " and ")).Base(err)
|
||||
return 0, "", "", errors.New("could not search in ", procFile).Base(err)
|
||||
}
|
||||
if inode == "" {
|
||||
return 0, "", "", errors.New("connection for ", srcIP, ":", srcPort, " not found in ", strings.Join(procFiles, " or "))
|
||||
return 0, "", "", errors.New("connection for ", srcIP, ":", srcPort, " not found in ", procFile)
|
||||
}
|
||||
|
||||
pidStr, err := findPidByInode(inode)
|
||||
@@ -107,43 +102,31 @@ func formatLittleEndianString(addr net.IP, port Port) (string, error) {
|
||||
return fmt.Sprintf("%s:%s", ipHex, portHex), nil
|
||||
}
|
||||
|
||||
func findInodeInFiles(filePaths []string, targetHexAddr, portFallback string) (string, error) {
|
||||
onlyMatchedPort := ""
|
||||
func findInodeInFile(filePath, targetHexAddr string) (string, error) {
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
for i, filePath := range filePaths {
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
if i > 0 && os.IsNotExist(err) {
|
||||
continue
|
||||
}
|
||||
return "", err
|
||||
scanner := bufio.NewScanner(file)
|
||||
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
fields := strings.Fields(line)
|
||||
|
||||
if len(fields) < 10 {
|
||||
continue
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
for scanner.Scan() {
|
||||
fields := strings.Fields(scanner.Text())
|
||||
if len(fields) < 10 {
|
||||
continue
|
||||
}
|
||||
|
||||
localAddress := fields[1]
|
||||
if localAddress == targetHexAddr {
|
||||
return fields[9], nil
|
||||
}
|
||||
if portFallback != "" && strings.HasSuffix(localAddress, portFallback) {
|
||||
wildcardIP := strings.TrimSuffix(localAddress, portFallback)
|
||||
if (len(wildcardIP) == 8 || len(wildcardIP) == 32) && strings.Trim(wildcardIP, "0") == "" {
|
||||
onlyMatchedPort = fields[9]
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return "", err
|
||||
localAddress := fields[1]
|
||||
if localAddress == targetHexAddr {
|
||||
inode := fields[9]
|
||||
return inode, nil
|
||||
}
|
||||
}
|
||||
|
||||
return onlyMatchedPort, nil
|
||||
return "", scanner.Err()
|
||||
}
|
||||
|
||||
func findPidByInode(inode string) (string, error) {
|
||||
|
||||
@@ -34,13 +34,12 @@ func ReadAsset(file string) ([]byte, error) {
|
||||
return ReadFile(path)
|
||||
}
|
||||
|
||||
func OpenAsset(file string) (io.ReadCloser, int64, error) {
|
||||
path, info, err := getAssetFileLocation(file)
|
||||
func OpenAsset(file string) (io.ReadCloser, error) {
|
||||
path, _, err := getAssetFileLocation(file)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
return nil, err
|
||||
}
|
||||
r, err := NewFileReader(path)
|
||||
return r, info.Size(), err
|
||||
return NewFileReader(path)
|
||||
}
|
||||
|
||||
func StatAsset(file string) (os.FileInfo, error) {
|
||||
|
||||
@@ -93,7 +93,7 @@ func GetConfDirPath() string {
|
||||
return configPath
|
||||
}
|
||||
|
||||
// ResolveLuaFile finds a local .lua script and returns its resolved absolute path.
|
||||
// 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 == "" {
|
||||
@@ -113,22 +113,7 @@ func ResolveLuaFile(path string) (string, error) {
|
||||
}
|
||||
}
|
||||
}
|
||||
path, err := resolveFile(paths)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return resolveLuaTarget(path)
|
||||
}
|
||||
|
||||
func resolveLuaTarget(path string) (string, error) {
|
||||
path, err := filepath.EvalSymlinks(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to resolve Lua file symlinks: %w", err)
|
||||
}
|
||||
if filepath.Ext(path) != ".lua" {
|
||||
return "", errors.New("Lua file extension must be .lua")
|
||||
}
|
||||
return path, nil
|
||||
return resolveFile(paths)
|
||||
}
|
||||
|
||||
func resolveFile(paths []string) (string, error) {
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
@@ -89,10 +88,6 @@ func TestResolveLuaFile(t *testing.T) {
|
||||
for _, path := range paths[:3] {
|
||||
common.Must(os.WriteFile(path, nil, 0o600))
|
||||
}
|
||||
for i, path := range paths {
|
||||
paths[i], err = filepath.EvalSymlinks(path)
|
||||
common.Must(err)
|
||||
}
|
||||
if got, err := ResolveLuaFile(paths[2]); err != nil || got != paths[2] {
|
||||
t.Fatalf("absolute path = %q, %v; want %q", got, err, paths[2])
|
||||
}
|
||||
@@ -120,35 +115,3 @@ func TestResolveLuaFile(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveLuaFileSymlink(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
link, target string
|
||||
valid bool
|
||||
}{
|
||||
{"alias.lua", "data.dat", false},
|
||||
{"alias.dat", "script.lua", true},
|
||||
} {
|
||||
t.Run(tc.link, func(t *testing.T) {
|
||||
dir, err := filepath.EvalSymlinks(t.TempDir())
|
||||
common.Must(err)
|
||||
target := filepath.Join(dir, tc.target)
|
||||
common.Must(os.WriteFile(target, nil, 0o600))
|
||||
link := filepath.Join(dir, tc.link)
|
||||
if err := os.Symlink(tc.target, link); err != nil {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skipf("cannot create symlinks: %v", err)
|
||||
}
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := ResolveLuaFile(link)
|
||||
if tc.valid {
|
||||
if err != nil || got != target {
|
||||
t.Fatalf("ResolveLuaFile(%q) = %q, %v; want %q", link, got, err, target)
|
||||
}
|
||||
} else if err == nil || got != "" || !strings.Contains(err.Error(), "Lua file extension must be .lua") {
|
||||
t.Fatalf("ResolveLuaFile(%q) = %q, %v; want .lua extension error", link, got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+2
-6
@@ -175,13 +175,9 @@ func init() {
|
||||
switch v := input.(type) {
|
||||
case cmdarg.Arg:
|
||||
r, err := confloader.LoadConfig(v[0])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
common.Must(err)
|
||||
data, err := buf.ReadAllToBytes(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
common.Must(err)
|
||||
return loadProtobufConfig(data)
|
||||
case io.Reader:
|
||||
data, err := buf.ReadAllToBytes(v)
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ import (
|
||||
var (
|
||||
Version_x byte = 26
|
||||
Version_y byte = 10
|
||||
Version_z byte = 21
|
||||
Version_z byte = 10
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
@@ -4,12 +4,13 @@ go 1.27
|
||||
|
||||
require (
|
||||
github.com/apernet/quic-go v0.61.1-0.20260806010916-184d081eef3e
|
||||
github.com/cloudflare/circl v1.6.5
|
||||
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344
|
||||
github.com/golang/mock v1.7.0-rc.1
|
||||
github.com/google/go-cmp v0.7.0
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/klauspost/cpuid/v2 v2.4.1
|
||||
github.com/klauspost/cpuid/v2 v2.4.0
|
||||
github.com/libp2p/go-nat v1.0.1-0.20250821073202-01afc089f138
|
||||
github.com/miekg/dns v1.1.73
|
||||
github.com/pelletier/go-toml v1.9.5
|
||||
@@ -19,20 +20,20 @@ require (
|
||||
github.com/robfig/cron/v3 v3.0.1
|
||||
github.com/stretchr/testify v1.12.1
|
||||
github.com/vishvananda/netlink v1.3.1
|
||||
github.com/xtls/reality v0.0.0-20261014101318-83f621788ca8
|
||||
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.58.0
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a
|
||||
golang.org/x/crypto v0.57.0
|
||||
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842
|
||||
golang.org/x/net v0.61.0
|
||||
golang.org/x/sync v0.24.0
|
||||
golang.org/x/sys v0.49.0
|
||||
golang.org/x/net v0.59.0
|
||||
golang.org/x/sync v0.23.0
|
||||
golang.org/x/sys v0.48.0
|
||||
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2
|
||||
golang.zx2c4.com/wireguard v0.0.0-20250521234502-f333402bd9cb
|
||||
golang.zx2c4.com/wireguard/windows v1.1.1
|
||||
google.golang.org/grpc v1.84.0
|
||||
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
|
||||
@@ -40,12 +41,13 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/andybalholm/brotli v1.2.3 // indirect
|
||||
github.com/andybalholm/brotli v1.0.6 // indirect
|
||||
github.com/google/btree v1.1.2 // indirect
|
||||
github.com/google/gopacket v1.1.19 // indirect
|
||||
github.com/huin/goupnp v1.2.0 // indirect
|
||||
github.com/jackpal/go-nat-pmp v1.0.2 // indirect
|
||||
github.com/juju/ratelimit v1.0.2 // indirect
|
||||
github.com/klauspost/compress v1.20.0 // indirect
|
||||
github.com/klauspost/compress v1.17.4 // indirect
|
||||
github.com/koron/go-ssdp v0.0.4 // indirect
|
||||
github.com/libp2p/go-netroute v0.2.1 // indirect
|
||||
github.com/pion/dtls/v3 v3.1.5 // indirect
|
||||
@@ -55,9 +57,10 @@ 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/text v0.43.0 // indirect
|
||||
golang.org/x/tools v0.51.0 // 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
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gvisor.dev/gvisor v0.0.0-20260122175437-89a5d21be8f0 // indirect
|
||||
)
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
github.com/andybalholm/brotli v1.2.3 h1:8H1qwOkl2LPfjf3YezB90JnCliZb6SInJ/OJkEbA5NQ=
|
||||
github.com/andybalholm/brotli v1.2.3/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/andybalholm/brotli v1.0.6 h1:Yf9fFpf49Zrxb9NlQaluyE92/+X7UVHlhMNJN2sxfOI=
|
||||
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=
|
||||
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I=
|
||||
github.com/go-quicktest/qt v1.102.0 h1:HSQxCeh5YZH3EL3W39ixjtyaEhcWSXQHtHnMBzSs474=
|
||||
@@ -31,10 +33,10 @@ github.com/jackpal/go-nat-pmp v1.0.2 h1:KzKSgb7qkJvOUTqYl9/Hg/me3pWgBmERKrTGD7Bd
|
||||
github.com/jackpal/go-nat-pmp v1.0.2/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc=
|
||||
github.com/juju/ratelimit v1.0.2 h1:sRxmtRiajbvrcLQT7S+JbqU0ntsb9W2yhSdNN8tWfaI=
|
||||
github.com/juju/ratelimit v1.0.2/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk=
|
||||
github.com/klauspost/compress v1.20.0 h1:a3C1ke2ohxFymNlb2HWAHjDeKCI90scRskErZkR0ezA=
|
||||
github.com/klauspost/compress v1.20.0/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/klauspost/cpuid/v2 v2.4.1 h1:I9KxadAkvo+QjtcEE2f2tyfEvmIla/T0m+14PrZNl0U=
|
||||
github.com/klauspost/cpuid/v2 v2.4.1/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4=
|
||||
github.com/klauspost/compress v1.17.4/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
github.com/koron/go-ssdp v0.0.4 h1:1IDwrghSKYM7yLf7XCzbByg2sJ/JcNOZRXS2jczTwz0=
|
||||
github.com/koron/go-ssdp v0.0.4/go.mod h1:oDXq+E5IL5q0U8uSBcoAXzTzInwy5lEgC91HoKtbmZk=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
@@ -79,10 +81,8 @@ github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zd
|
||||
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
|
||||
github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=
|
||||
github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
|
||||
github.com/xtls/reality v0.0.0-20261014101318-83f621788ca8 h1:RjLnVvlzK4q6zWaSBPNRGsrgx2fbJDeUWffjw574uzs=
|
||||
github.com/xtls/reality v0.0.0-20261014101318-83f621788ca8/go.mod h1:ptlSkJ8k/7IDauNH0SA96JPOo+nYGLTv2Y3UMpwvAsY=
|
||||
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||
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=
|
||||
@@ -95,10 +95,10 @@ go4.org/netipx v0.0.0-20231129151722-fdeea329fbba h1:0b9z3AuHCjxk0x/opv64kcgZLBs
|
||||
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a h1:V5oicZXS0oqZx30gY/apgSVD7YvNBfrIOdcMnlelJY4=
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a/go.mod h1:HPze8vhfG6fO06AM+VSvxRm4E3+5Yk375mgrJ5M2z1E=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20261005185213-c3db4df58582 h1:wjDBrGbfLuifgrVLFEWUBJYAfh5Q1wkMc5t0FY0tCbs=
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20261005185213-c3db4df58582/go.mod h1:HPze8vhfG6fO06AM+VSvxRm4E3+5Yk375mgrJ5M2z1E=
|
||||
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 h1:vr/HnozRka3pE4EsMEg1lgkXJkTFJCVUX+S/ZT6wYzM=
|
||||
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc=
|
||||
golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
|
||||
@@ -107,12 +107,12 @@ 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.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw=
|
||||
golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
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/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.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
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=
|
||||
@@ -121,22 +121,22 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
|
||||
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
|
||||
golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
|
||||
golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
|
||||
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
|
||||
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
|
||||
+9
-12
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/platform"
|
||||
)
|
||||
|
||||
type NameServerConfig struct {
|
||||
@@ -272,17 +273,6 @@ 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,
|
||||
@@ -292,7 +282,14 @@ func (c *DNSConfig) Build() (*dns.Config, error) {
|
||||
DisableFallbackIfMatch: c.DisableFallbackIfMatch,
|
||||
EnableParallelQuery: c.EnableParallelQuery,
|
||||
QueryStrategy: resolveQueryStrategy(c.QueryStrategy),
|
||||
Script: c.Script,
|
||||
}
|
||||
|
||||
if c.Script != "" {
|
||||
path, err := platform.ResolveLuaFile(c.Script)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to resolve DNS script: ", c.Script).Base(err)
|
||||
}
|
||||
config.Script = path
|
||||
}
|
||||
|
||||
if c.ClientIP != nil {
|
||||
|
||||
+37
-42
@@ -2,7 +2,8 @@ package conf_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
@@ -124,7 +125,41 @@ func TestDNSConfigParsing(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSNameServerID(t *testing.T) {
|
||||
func TestDNSScriptConfig(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("xray.location.confdir", dir)
|
||||
path := filepath.Join(dir, "lookup.lua")
|
||||
if err := os.WriteFile(path, []byte("function HandleDNSQuery(domain, ipv4, ipv6, fake) end"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
script string
|
||||
wantError bool
|
||||
}{
|
||||
{"relative", "lookup.lua", false},
|
||||
{"absolute", path, false},
|
||||
{"missing", "missing.lua", true},
|
||||
{"directory", dir, true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
built, err := (&DNSConfig{Script: tc.script}).Build()
|
||||
if tc.wantError {
|
||||
if err == nil {
|
||||
t.Fatal("Build accepted an invalid script path")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if built.Script != path {
|
||||
t.Fatalf("script path = %q, want %q", built.Script, path)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
var parsed DNSConfig
|
||||
if err := json.Unmarshal([]byte(`{"servers":[{"id":"primary","address":"1.1.1.1"}]}`), &parsed); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -137,43 +172,3 @@ func TestDNSNameServerID(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+11
-68
@@ -16,61 +16,8 @@ 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)
|
||||
@@ -80,7 +27,7 @@ func TestMasqueConfig(t *testing.T) {
|
||||
{
|
||||
Input: `{}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &masque.Config{Path: "/.well-known/masque/ip/*/*/", Xmux: defaultMasqueXmux()},
|
||||
Output: &masque.Config{Path: "/.well-known/masque/ip/*/*/"},
|
||||
},
|
||||
{
|
||||
Input: `{
|
||||
@@ -93,13 +40,12 @@ 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=*", Xmux: defaultMasqueXmux()},
|
||||
Output: &masque.Config{Path: "/masque/ip?target=*&ipproto=*"},
|
||||
},
|
||||
{
|
||||
Input: `{"user": "u", "pass": "p:q", "headers": {"X-Token": "a"}}`,
|
||||
@@ -107,7 +53,6 @@ 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(),
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -177,7 +122,6 @@ func TestMasqueWarpConfig(t *testing.T) {
|
||||
Host: "cloudflareaccess.com",
|
||||
Path: "/",
|
||||
Warp: &masque.Warp{PrivateKey: pkcs8, PublicKey: publicKey, Address: address},
|
||||
Xmux: defaultMasqueXmux(),
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -190,7 +134,6 @@ func TestMasqueWarpConfig(t *testing.T) {
|
||||
Host: "example.com",
|
||||
Path: "/warp",
|
||||
Warp: &masque.Warp{PrivateKey: pkcs8, PublicKey: publicKey, Address: address},
|
||||
Xmux: defaultMasqueXmux(),
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -221,7 +164,6 @@ 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(),
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -257,17 +199,18 @@ func TestMasqueOutboundConfig(t *testing.T) {
|
||||
return 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)
|
||||
}
|
||||
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"}, "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 {
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"github.com/xtls/xray-core/app/router"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
"github.com/xtls/xray-core/common/platform"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
|
||||
"google.golang.org/protobuf/proto"
|
||||
@@ -94,10 +95,13 @@ 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")
|
||||
if c.Script != "" {
|
||||
path, err := platform.ResolveLuaFile(c.Script)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to resolve routing script").Base(err)
|
||||
}
|
||||
config.Script = path
|
||||
}
|
||||
config.Script = c.Script
|
||||
|
||||
config.DomainStrategy = c.getDomainStrategy()
|
||||
|
||||
|
||||
+22
-22
@@ -2,7 +2,8 @@ package conf_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
_ "unsafe"
|
||||
@@ -239,37 +240,36 @@ func TestRouterConfig(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRouterScriptConfig(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("xray.location.confdir", dir)
|
||||
path := filepath.Join(dir, "route.lua")
|
||||
if err := os.WriteFile(path, []byte("function HandleRoute() end"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
input string
|
||||
script 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"]}]}`},
|
||||
{"relative", "route.lua", false},
|
||||
{"absolute", path, false},
|
||||
{"missing", "missing.lua", true},
|
||||
{"directory", dir, true},
|
||||
} {
|
||||
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)
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
built, err := (&RouterConfig{Script: tc.script}).Build()
|
||||
if tc.wantError {
|
||||
if err == nil {
|
||||
t.Fatal("Build accepted invalid script path")
|
||||
}
|
||||
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)
|
||||
if built.Script != path {
|
||||
t.Fatalf("script path = %q, want %q", built.Script, path)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -9,17 +9,12 @@ import (
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
googleuuid "github.com/google/uuid"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
xlua "github.com/xtls/xray-core/common/lua"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask/filter"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask/fragment"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask/header/custom"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask/mkcp/aes128gcm"
|
||||
@@ -33,7 +28,6 @@ import (
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask/xdns"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask/xicmp"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask/xmc"
|
||||
"github.com/xtls/xray-core/transport/internet/hysteria/congestion/bbr"
|
||||
"github.com/xtls/xray-core/transport/internet/tls"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
@@ -76,7 +70,6 @@ var (
|
||||
customVarNamePattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
|
||||
|
||||
tcpmaskLoader = NewJSONConfigLoader(ConfigCreatorCache{
|
||||
"filter": func() interface{} { return new(Filter) },
|
||||
"header-custom": func() interface{} { return new(HeaderCustomTCP) },
|
||||
"fragment": func() interface{} { return new(FragmentMask) },
|
||||
"sudoku": func() interface{} { return new(Sudoku) },
|
||||
@@ -84,7 +77,6 @@ var (
|
||||
}, "type", "settings")
|
||||
|
||||
udpmaskLoader = NewJSONConfigLoader(ConfigCreatorCache{
|
||||
"filter": func() interface{} { return new(Filter) },
|
||||
"header-custom": func() interface{} { return new(HeaderCustomUDP) },
|
||||
"mkcp-legacy": func() interface{} { return new(MkcpLegacy) },
|
||||
"noise": func() interface{} { return new(NoiseMask) },
|
||||
@@ -97,23 +89,6 @@ var (
|
||||
}, "type", "settings")
|
||||
)
|
||||
|
||||
type Filter struct {
|
||||
BlockedSourceIPs []string `json:"blockedSourceIPs"`
|
||||
AllowedSourceIPs []string `json:"allowedSourceIPs"`
|
||||
}
|
||||
|
||||
func (c *Filter) Build() (proto.Message, error) {
|
||||
rules, err := geodata.ParseIPRules(c.BlockedSourceIPs)
|
||||
if err != nil {
|
||||
return nil, errors.New(`invalid "blockedSourceIPs"`).Base(err)
|
||||
}
|
||||
allowed, err := geodata.ParseIPRules(c.AllowedSourceIPs)
|
||||
if err != nil {
|
||||
return nil, errors.New(`invalid "allowedSourceIPs"`).Base(err)
|
||||
}
|
||||
return &filter.Config{BlockedSourceIps: rules, AllowedSourceIps: allowed}, nil
|
||||
}
|
||||
|
||||
type TCPItem struct {
|
||||
Delay Int32Range `json:"delay"`
|
||||
Rand int32 `json:"rand"`
|
||||
@@ -329,26 +304,11 @@ type NoiseItem struct {
|
||||
}
|
||||
|
||||
type NoiseMask struct {
|
||||
Reset Int32Range `json:"reset"`
|
||||
Noise []NoiseItem `json:"noise"`
|
||||
Script string `json:"script"`
|
||||
Reset Int32Range `json:"reset"`
|
||||
Noise []NoiseItem `json:"noise"`
|
||||
}
|
||||
|
||||
func (c *NoiseMask) Build() (proto.Message, error) {
|
||||
if c.Script != "" {
|
||||
if len(c.Noise) > 0 {
|
||||
return nil, errors.New(`"script" and "noise" can't be used together`)
|
||||
}
|
||||
if _, err := xlua.Compile(c.Script); err != nil {
|
||||
return nil, errors.New("failed to compile the noise script").Base(err)
|
||||
}
|
||||
return &noise.Config{
|
||||
ResetMin: int64(c.Reset.From),
|
||||
ResetMax: int64(c.Reset.To),
|
||||
Script: c.Script,
|
||||
}, nil
|
||||
}
|
||||
|
||||
noiseSlice := make([]*noise.Item, 0, len(c.Noise))
|
||||
for _, item := range c.Noise {
|
||||
if len(item.Packet) > 0 && item.Rand.To > 0 {
|
||||
@@ -839,10 +799,7 @@ type XDNSDomain struct {
|
||||
}
|
||||
|
||||
type XDNSResolver struct {
|
||||
Addrs []string `json:"addrs"`
|
||||
Worker int32 `json:"worker"`
|
||||
TlsConfig *TLSConfig `json:"tlsConfig"`
|
||||
QuicConfig *QuicParamsConfig `json:"quicConfig"`
|
||||
Addrs []string `json:"addrs"`
|
||||
}
|
||||
|
||||
type XDNS struct {
|
||||
@@ -877,26 +834,6 @@ func (c *XDNS) Build() (proto.Message, error) {
|
||||
}
|
||||
}
|
||||
for i := range c.Resolvers {
|
||||
worker := c.Resolvers[i].Worker
|
||||
if worker == 0 {
|
||||
worker = 32
|
||||
}
|
||||
var tlsConfig *tls.Config
|
||||
var quicConfig *internet.QuicParams
|
||||
if c.Resolvers[i].TlsConfig != nil {
|
||||
proto, err := c.Resolvers[i].TlsConfig.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tlsConfig = proto.(*tls.Config)
|
||||
}
|
||||
if c.Resolvers[i].QuicConfig != nil {
|
||||
proto, err := c.Resolvers[i].QuicConfig.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
quicConfig = proto.(*internet.QuicParams)
|
||||
}
|
||||
for j := range c.Resolvers[i].Addrs {
|
||||
var u *url.URL
|
||||
var e error
|
||||
@@ -908,21 +845,18 @@ func (c *XDNS) Build() (proto.Message, error) {
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
var addr string
|
||||
switch u.Scheme {
|
||||
case "tcp", "udp":
|
||||
host := u.Hostname()
|
||||
port := u.Port()
|
||||
if port == "" {
|
||||
port = "53"
|
||||
}
|
||||
addr = net.JoinHostPort(host, port)
|
||||
case "https":
|
||||
addr = u.String()
|
||||
default:
|
||||
return nil, errors.New("invalid protocol")
|
||||
}
|
||||
resolvers = append(resolvers, &xdns.ResolverProto{Type: u.Scheme, Addr: addr, Worker: worker, TlsConfig: tlsConfig, QuicConfig: quicConfig})
|
||||
var host, port string
|
||||
host = u.Hostname()
|
||||
port = u.Port()
|
||||
if port == "" {
|
||||
port = "53"
|
||||
}
|
||||
resolvers = append(resolvers, &xdns.ResolverProto{Type: u.Scheme, Addr: net.JoinHostPort(host, port)})
|
||||
}
|
||||
}
|
||||
if c.ExtraPoll < 0 || c.ExtraPoll > 3 {
|
||||
@@ -1215,91 +1149,6 @@ type QuicParamsConfig struct {
|
||||
DisableStatelessReset bool `json:"disableStatelessReset"`
|
||||
}
|
||||
|
||||
func (config *QuicParamsConfig) Build() (proto.Message, error) {
|
||||
profile := strings.ToLower(config.BbrProfile)
|
||||
switch profile {
|
||||
case "", string(bbr.ProfileConservative), string(bbr.ProfileStandard), string(bbr.ProfileAggressive):
|
||||
if profile == "" {
|
||||
profile = string(bbr.ProfileStandard)
|
||||
}
|
||||
default:
|
||||
return nil, errors.New("unknown bbr profile")
|
||||
}
|
||||
|
||||
up, err := config.BrutalUp.Bps()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
down, err := config.BrutalDown.Bps()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if up > 0 && up < 65536 {
|
||||
return nil, errors.New("BrutalUp must be at least 65536 bytes per second")
|
||||
}
|
||||
if down > 0 && down < 65536 {
|
||||
return nil, errors.New("BrutalDown must be at least 65536 bytes per second")
|
||||
}
|
||||
|
||||
config.Congestion = strings.ToLower(config.Congestion)
|
||||
switch config.Congestion {
|
||||
case "", "brutal", "reno", "bbr":
|
||||
case "force-brutal":
|
||||
if up == 0 {
|
||||
return nil, errors.New("force-brutal requires up")
|
||||
}
|
||||
default:
|
||||
return nil, errors.New("unknown congestion control: ", config.Congestion, ", valid values: reno, bbr, brutal, force-brutal")
|
||||
}
|
||||
|
||||
if config.InitStreamReceiveWindow > 0 && config.InitStreamReceiveWindow < 16384 {
|
||||
return nil, errors.New("InitStreamReceiveWindow must be at least 16384")
|
||||
}
|
||||
if config.MaxStreamReceiveWindow > 0 && config.MaxStreamReceiveWindow < 16384 {
|
||||
return nil, errors.New("MaxStreamReceiveWindow must be at least 16384")
|
||||
}
|
||||
if config.InitConnectionReceiveWindow > 0 && config.InitConnectionReceiveWindow < 16384 {
|
||||
return nil, errors.New("InitConnectionReceiveWindow must be at least 16384")
|
||||
}
|
||||
if config.MaxConnectionReceiveWindow > 0 && config.MaxConnectionReceiveWindow < 16384 {
|
||||
return nil, errors.New("MaxConnectionReceiveWindow must be at least 16384")
|
||||
}
|
||||
if config.MaxIdleTimeout != 0 && (config.MaxIdleTimeout < 4 || config.MaxIdleTimeout > 120) {
|
||||
return nil, errors.New("MaxIdleTimeout must be between 4 and 120")
|
||||
}
|
||||
if config.KeepAlivePeriod != 0 && (config.KeepAlivePeriod < 2 || config.KeepAlivePeriod > 60) {
|
||||
return nil, errors.New("KeepAlivePeriod must be between 2 and 60")
|
||||
}
|
||||
if config.MaxIncomingStreams != 0 && config.MaxIncomingStreams < 8 {
|
||||
return nil, errors.New("MaxIncomingStreams must be at least 8")
|
||||
}
|
||||
|
||||
if config.Debug {
|
||||
os.Setenv("HYSTERIA_BBR_DEBUG", "true")
|
||||
os.Setenv("HYSTERIA_BRUTAL_DEBUG", "true")
|
||||
}
|
||||
|
||||
return &internet.QuicParams{
|
||||
Congestion: config.Congestion,
|
||||
BbrProfile: profile,
|
||||
BrutalUp: up,
|
||||
BrutalDown: down,
|
||||
BrutalDisableLossCompensation: config.BrutalDisableLossCompensation,
|
||||
InitStreamReceiveWindow: config.InitStreamReceiveWindow,
|
||||
MaxStreamReceiveWindow: config.MaxStreamReceiveWindow,
|
||||
InitConnReceiveWindow: config.InitConnectionReceiveWindow,
|
||||
MaxConnReceiveWindow: config.MaxConnectionReceiveWindow,
|
||||
MaxIdleTimeout: config.MaxIdleTimeout,
|
||||
KeepAlivePeriod: config.KeepAlivePeriod,
|
||||
DisablePathMtuDiscovery: config.DisablePathMTUDiscovery,
|
||||
DisableChromeParrot: config.DisableChromeParrot,
|
||||
DisableGSO: config.DisableGSO,
|
||||
MaxIncomingStreams: config.MaxIncomingStreams,
|
||||
DisableStatelessReset: config.DisableStatelessReset,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type FinalMask struct {
|
||||
Tcp []Mask `json:"tcp"`
|
||||
Udp []Mask `json:"udp"`
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
package conf_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
. "github.com/xtls/xray-core/infra/conf"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask/filter"
|
||||
)
|
||||
|
||||
func TestFinalMaskFilter(t *testing.T) {
|
||||
for _, network := range []string{"tcp", "udp"} {
|
||||
for _, test := range []struct {
|
||||
name, settings string
|
||||
blocked, allowed int
|
||||
}{
|
||||
{"blacklist", `{"blockedSourceIPs":["192.0.2.0/24"]}`, 1, 0},
|
||||
{"whitelist", `{"allowedSourceIPs":["192.0.2.0/24"]}`, 0, 1},
|
||||
{"both", `{"blockedSourceIPs":["192.0.2.0/24"],"allowedSourceIPs":["192.0.2.0/24"]}`, 1, 1},
|
||||
{"empty_whitelist", `{"allowedSourceIPs":[]}`, 0, 0},
|
||||
{"empty_blacklist", `{"blockedSourceIPs":[]}`, 0, 0},
|
||||
} {
|
||||
t.Run(network+"/"+test.name, func(t *testing.T) {
|
||||
input := fmt.Sprintf(`{"finalmask":{"%s":[{"type":"filter","settings":%s}]}}`, network, test.settings)
|
||||
var config StreamConfig
|
||||
if err := json.Unmarshal([]byte(input), &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
built, err := config.Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
masks := built.Tcpmasks
|
||||
if network == "udp" {
|
||||
masks = built.Udpmasks
|
||||
}
|
||||
if len(masks) != 1 {
|
||||
t.Fatalf("expected one mask, got %d", len(masks))
|
||||
}
|
||||
instance, err := masks[0].GetInstance()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
filter, ok := instance.(*filter.Config)
|
||||
if !ok {
|
||||
t.Fatalf("unexpected mask type: %T", instance)
|
||||
}
|
||||
if len(filter.BlockedSourceIps) != test.blocked || len(filter.AllowedSourceIps) != test.allowed {
|
||||
t.Fatalf("unexpected filter policy: %v", filter)
|
||||
}
|
||||
for _, rules := range [][]*geodata.IPRule{filter.BlockedSourceIps, filter.AllowedSourceIps} {
|
||||
for _, rule := range rules {
|
||||
cidr := rule.GetCustom().GetCidr()
|
||||
if cidr.GetPrefix() != 24 || !net.IP(cidr.GetIp()).Equal(net.IPv4(192, 0, 2, 0)) {
|
||||
t.Fatalf("unexpected IP rule: %v", cidr)
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, err := internet.ToMemoryStreamConfig(built); err != nil {
|
||||
t.Fatalf("failed to initialize runtime finalmask: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
for _, field := range []string{"blockedSourceIPs", "allowedSourceIPs"} {
|
||||
var config Filter
|
||||
if err := json.Unmarshal([]byte(fmt.Sprintf(`{"%s":["192.0.2.0/33"]}`, field)), &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := config.Build(); err == nil || !strings.Contains(err.Error(), field) {
|
||||
t.Errorf("expected invalid %s, got %v", field, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,6 @@ package conf
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask/noise"
|
||||
@@ -137,68 +134,3 @@ func TestNoiseExpFromJSON(t *testing.T) {
|
||||
t.Errorf("item 3 = %+v", items[3])
|
||||
}
|
||||
}
|
||||
|
||||
const noiseScript = `function HandleNoise(plan, address) plan:Add("n") end
|
||||
`
|
||||
|
||||
func writeNoiseScript(t *testing.T, script string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "noise.lua")
|
||||
if err := os.WriteFile(path, []byte(script), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func buildNoiseMask(t *testing.T, mask *NoiseMask) *noise.Config {
|
||||
t.Helper()
|
||||
msg, err := mask.Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return msg.(*noise.Config)
|
||||
}
|
||||
|
||||
func TestNoiseScriptFromFile(t *testing.T) {
|
||||
path := writeNoiseScript(t, noiseScript)
|
||||
cfg := buildNoiseMask(t, &NoiseMask{Script: path, Reset: Int32Range{From: 30, To: 60}})
|
||||
|
||||
if cfg.Script != path {
|
||||
t.Errorf("got script %q, want the path", cfg.Script)
|
||||
}
|
||||
if len(cfg.Items) != 0 {
|
||||
t.Errorf("got %d items, want none", len(cfg.Items))
|
||||
}
|
||||
if cfg.ResetMin != 30 || cfg.ResetMax != 60 {
|
||||
t.Errorf("got reset %d-%d, want 30-60", cfg.ResetMin, cfg.ResetMax)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoiseScriptFromJSON(t *testing.T) {
|
||||
path := writeNoiseScript(t, noiseScript)
|
||||
input := `{"script": ` + strconv.Quote(path) + `, "reset": "30-60"}`
|
||||
var mask NoiseMask
|
||||
if err := json.Unmarshal([]byte(input), &mask); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg := buildNoiseMask(t, &mask); cfg.Script != path {
|
||||
t.Errorf("got script %q, want the path", cfg.Script)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoiseScriptRejected(t *testing.T) {
|
||||
path := writeNoiseScript(t, noiseScript)
|
||||
invalid := writeNoiseScript(t, "function HandleNoise(")
|
||||
|
||||
for name, mask := range map[string]*NoiseMask{
|
||||
"script with noise": {Script: path, Noise: []NoiseItem{{Rand: Int32Range{From: 10, To: 20}}}},
|
||||
"missing file": {Script: filepath.Join(t.TempDir(), "absent.lua")},
|
||||
"not lua": {Script: invalid},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if _, err := mask.Build(); err == nil {
|
||||
t.Error("expected an error")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
utls "github.com/refraction-networking/utls"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/internet/tls"
|
||||
"github.com/xtls/xray-core/transport/internet/hysteria/congestion/bbr"
|
||||
)
|
||||
|
||||
type TransportProtocol string
|
||||
@@ -90,7 +88,6 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
|
||||
config.ProtocolName = protocol
|
||||
}
|
||||
|
||||
var xdriveH3 bool
|
||||
switch strings.ToLower(c.Security) {
|
||||
case "", "none":
|
||||
case "tls":
|
||||
@@ -105,15 +102,6 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
|
||||
tm := serial.ToTypedMessage(ts)
|
||||
config.SecuritySettings = append(config.SecuritySettings, tm)
|
||||
config.SecurityType = tm.Type
|
||||
xdriveH3 = config.ProtocolName == "xdrive" && tlsSettings.ALPN != nil && slices.Equal(*tlsSettings.ALPN, StringList{"h3"})
|
||||
if config.ProtocolName == "xdrive" && tlsSettings.ALPN != nil && slices.Equal(*tlsSettings.ALPN, StringList{"http/1.1"}) && tlsSettings.ECHConfigList == "" {
|
||||
// a fingerprint puts its own ALPN into the hello, except Go TLS and the
|
||||
// randomized ones, which take it from the config or send none
|
||||
if fp := tls.GetFingerprint(strings.ToLower(tlsSettings.Fingerprint)); fp != nil && fp.Client != utls.HelloGolang.Client &&
|
||||
!strings.HasPrefix(fp.Client, utls.HelloRandomized.Client) {
|
||||
errors.LogWarning(context.Background(), `XDRIVE: "alpn" ["http/1.1"] reaches the wire only inside ECH, without "echConfigList" the hello carries the ALPN of the fingerprint and the server may pick h2`)
|
||||
}
|
||||
}
|
||||
case "reality":
|
||||
if config.ProtocolName != "tcp" && config.ProtocolName != "splithttp" && config.ProtocolName != "grpc" {
|
||||
return nil, errors.New("REALITY only supports RAW, XHTTP and gRPC for now.")
|
||||
@@ -221,7 +209,6 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
|
||||
})
|
||||
}
|
||||
if c.XDRIVESettings != nil {
|
||||
c.XDRIVESettings.h3 = xdriveH3
|
||||
xs, err := c.XDRIVESettings.Build()
|
||||
if err != nil {
|
||||
return nil, errors.New("Failed to build XDRIVE config.").Base(err)
|
||||
@@ -241,40 +228,102 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
|
||||
|
||||
if c.FinalMask != nil {
|
||||
for _, mask := range c.FinalMask.Tcp {
|
||||
proto, err := mask.Build(true)
|
||||
u, err := mask.Build(true)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to build mask with type ", mask.Type).Base(err)
|
||||
}
|
||||
config.Tcpmasks = append(config.Tcpmasks, serial.ToTypedMessage(proto))
|
||||
config.Tcpmasks = append(config.Tcpmasks, serial.ToTypedMessage(u))
|
||||
}
|
||||
for _, mask := range c.FinalMask.Udp {
|
||||
proto, err := mask.Build(false)
|
||||
u, err := mask.Build(false)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to build mask with type ", mask.Type).Base(err)
|
||||
}
|
||||
config.Udpmasks = append(config.Udpmasks, serial.ToTypedMessage(proto))
|
||||
config.Udpmasks = append(config.Udpmasks, serial.ToTypedMessage(u))
|
||||
}
|
||||
if c.FinalMask.QuicParams != nil {
|
||||
proto, err := c.FinalMask.QuicParams.Build()
|
||||
profile := strings.ToLower(c.FinalMask.QuicParams.BbrProfile)
|
||||
switch profile {
|
||||
case "", string(bbr.ProfileConservative), string(bbr.ProfileStandard), string(bbr.ProfileAggressive):
|
||||
if profile == "" {
|
||||
profile = string(bbr.ProfileStandard)
|
||||
}
|
||||
default:
|
||||
return nil, errors.New("unknown bbr profile")
|
||||
}
|
||||
|
||||
up, err := c.FinalMask.QuicParams.BrutalUp.Bps()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config.QuicParams = proto.(*internet.QuicParams)
|
||||
}
|
||||
}
|
||||
|
||||
if xdriveH3 && c.FinalMask != nil {
|
||||
if c.XDRIVESettings != nil && c.XDRIVESettings.Service == "google-drive" {
|
||||
// noise only sends datagrams of its own ahead of the QUIC ones, the
|
||||
// other masks change those or need a peer that undoes them
|
||||
for _, mask := range c.FinalMask.Udp {
|
||||
if strings.ToLower(mask.Type) != "noise" {
|
||||
return nil, errors.New(`XDRIVE: over h3 to Google Drive the only "udp" mask that works is "noise", not "`, mask.Type, `"`)
|
||||
}
|
||||
down, err := c.FinalMask.QuicParams.BrutalDown.Bps()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if up > 0 && up < 65536 {
|
||||
return nil, errors.New("BrutalUp must be at least 65536 bytes per second")
|
||||
}
|
||||
if down > 0 && down < 65536 {
|
||||
return nil, errors.New("BrutalDown must be at least 65536 bytes per second")
|
||||
}
|
||||
|
||||
c.FinalMask.QuicParams.Congestion = strings.ToLower(c.FinalMask.QuicParams.Congestion)
|
||||
switch c.FinalMask.QuicParams.Congestion {
|
||||
case "", "brutal", "reno", "bbr":
|
||||
case "force-brutal":
|
||||
if up == 0 {
|
||||
return nil, errors.New("force-brutal requires up")
|
||||
}
|
||||
default:
|
||||
return nil, errors.New("unknown congestion control: ", c.FinalMask.QuicParams.Congestion, ", valid values: reno, bbr, brutal, force-brutal")
|
||||
}
|
||||
|
||||
if c.FinalMask.QuicParams.InitStreamReceiveWindow > 0 && c.FinalMask.QuicParams.InitStreamReceiveWindow < 16384 {
|
||||
return nil, errors.New("InitStreamReceiveWindow must be at least 16384")
|
||||
}
|
||||
if c.FinalMask.QuicParams.MaxStreamReceiveWindow > 0 && c.FinalMask.QuicParams.MaxStreamReceiveWindow < 16384 {
|
||||
return nil, errors.New("MaxStreamReceiveWindow must be at least 16384")
|
||||
}
|
||||
if c.FinalMask.QuicParams.InitConnectionReceiveWindow > 0 && c.FinalMask.QuicParams.InitConnectionReceiveWindow < 16384 {
|
||||
return nil, errors.New("InitConnectionReceiveWindow must be at least 16384")
|
||||
}
|
||||
if c.FinalMask.QuicParams.MaxConnectionReceiveWindow > 0 && c.FinalMask.QuicParams.MaxConnectionReceiveWindow < 16384 {
|
||||
return nil, errors.New("MaxConnectionReceiveWindow must be at least 16384")
|
||||
}
|
||||
if c.FinalMask.QuicParams.MaxIdleTimeout != 0 && (c.FinalMask.QuicParams.MaxIdleTimeout < 4 || c.FinalMask.QuicParams.MaxIdleTimeout > 120) {
|
||||
return nil, errors.New("MaxIdleTimeout must be between 4 and 120")
|
||||
}
|
||||
if c.FinalMask.QuicParams.KeepAlivePeriod != 0 && (c.FinalMask.QuicParams.KeepAlivePeriod < 2 || c.FinalMask.QuicParams.KeepAlivePeriod > 60) {
|
||||
return nil, errors.New("KeepAlivePeriod must be between 2 and 60")
|
||||
}
|
||||
if c.FinalMask.QuicParams.MaxIncomingStreams != 0 && c.FinalMask.QuicParams.MaxIncomingStreams < 8 {
|
||||
return nil, errors.New("MaxIncomingStreams must be at least 8")
|
||||
}
|
||||
|
||||
if c.FinalMask.QuicParams.Debug {
|
||||
os.Setenv("HYSTERIA_BBR_DEBUG", "true")
|
||||
os.Setenv("HYSTERIA_BRUTAL_DEBUG", "true")
|
||||
}
|
||||
|
||||
config.QuicParams = &internet.QuicParams{
|
||||
Congestion: c.FinalMask.QuicParams.Congestion,
|
||||
BbrProfile: profile,
|
||||
BrutalUp: up,
|
||||
BrutalDown: down,
|
||||
BrutalDisableLossCompensation: c.FinalMask.QuicParams.BrutalDisableLossCompensation,
|
||||
InitStreamReceiveWindow: c.FinalMask.QuicParams.InitStreamReceiveWindow,
|
||||
MaxStreamReceiveWindow: c.FinalMask.QuicParams.MaxStreamReceiveWindow,
|
||||
InitConnReceiveWindow: c.FinalMask.QuicParams.InitConnectionReceiveWindow,
|
||||
MaxConnReceiveWindow: c.FinalMask.QuicParams.MaxConnectionReceiveWindow,
|
||||
MaxIdleTimeout: c.FinalMask.QuicParams.MaxIdleTimeout,
|
||||
KeepAlivePeriod: c.FinalMask.QuicParams.KeepAlivePeriod,
|
||||
DisablePathMtuDiscovery: c.FinalMask.QuicParams.DisablePathMTUDiscovery,
|
||||
DisableChromeParrot: c.FinalMask.QuicParams.DisableChromeParrot,
|
||||
DisableGSO: c.FinalMask.QuicParams.DisableGSO,
|
||||
MaxIncomingStreams: c.FinalMask.QuicParams.MaxIncomingStreams,
|
||||
DisableStatelessReset: c.FinalMask.QuicParams.DisableStatelessReset,
|
||||
}
|
||||
}
|
||||
if config.QuicParams != nil && (config.QuicParams.Congestion == "brutal" || config.QuicParams.Congestion == "force-brutal") {
|
||||
return nil, errors.New(`XDRIVE: brutal is for Hysteria servers, over h3 "congestion" is "bbr" or "reno", not "`, config.QuicParams.Congestion, `"`)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -808,7 +808,6 @@ 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) {
|
||||
@@ -879,28 +878,11 @@ 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
|
||||
}
|
||||
|
||||
@@ -997,10 +979,6 @@ type XDriveConfig struct {
|
||||
EagerWindowMs uint32 `json:"eagerWindowMs"`
|
||||
HoleTimeoutMs uint32 `json:"holeTimeoutMs"`
|
||||
Template json.RawMessage `json:"template"`
|
||||
Xmux XmuxConfig `json:"xmux"`
|
||||
|
||||
// set by StreamConfig when "alpn" is ["h3"]
|
||||
h3 bool
|
||||
}
|
||||
|
||||
// Build implements Buildable.
|
||||
@@ -1008,10 +986,6 @@ func (c *XDriveConfig) Build() (proto.Message, error) {
|
||||
switch c.Service {
|
||||
case "local":
|
||||
case "Google Drive":
|
||||
errors.PrintDeprecatedFeatureWarning(`"service": "Google Drive"`, `"service": "google-drive"`)
|
||||
c.Service = "google-drive"
|
||||
fallthrough
|
||||
case "google-drive":
|
||||
if len(c.Secrets) != 3 {
|
||||
return nil, errors.New("Google Drive needs 3 secrets in order of ClientID, ClientSecret, RefreshToken")
|
||||
}
|
||||
@@ -1020,22 +994,7 @@ func (c *XDriveConfig) Build() (proto.Message, error) {
|
||||
return nil, errors.New(`service "template" needs a "template" object`)
|
||||
}
|
||||
default:
|
||||
return nil, errors.New(`unknown "service": "`, c.Service, `", use "google-drive", "template" or "local"`)
|
||||
}
|
||||
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
|
||||
if c.Service == "google-drive" && !c.h3 {
|
||||
// Google gives an h2 connection 1 MiB of window, which a few sessions on
|
||||
// a long rtt would share, an h3 connection has no such limit
|
||||
c.Xmux.MaxConnections.From = 4
|
||||
c.Xmux.MaxConnections.To = 4
|
||||
}
|
||||
c.Xmux.HMaxReusableSecs.From = 1800
|
||||
c.Xmux.HMaxReusableSecs.To = 3000
|
||||
return nil, errors.New("unsupported service")
|
||||
}
|
||||
config := &xdrive.Config{
|
||||
RemoteFolder: c.RemoteFolder,
|
||||
@@ -1050,14 +1009,6 @@ func (c *XDriveConfig) Build() (proto.Message, error) {
|
||||
EagerWindowMs: c.EagerWindowMs,
|
||||
HoleTimeoutMs: c.HoleTimeoutMs,
|
||||
Template: string(c.Template),
|
||||
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,
|
||||
},
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
@@ -5,12 +5,9 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
. "github.com/xtls/xray-core/infra/conf"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
finalmaskcustom "github.com/xtls/xray-core/transport/internet/finalmask/header/custom"
|
||||
"github.com/xtls/xray-core/transport/internet/splithttp"
|
||||
"github.com/xtls/xray-core/transport/internet/xdrive"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
@@ -324,25 +321,8 @@ func TestXDriveRejectsUnknownService(t *testing.T) {
|
||||
if err := json.Unmarshal([]byte(`{"remoteFolder": "/tmp/xdrive", "service": "Dropbox"}`), config); err != nil {
|
||||
t.Fatalf("Unmarshal: %v", err)
|
||||
}
|
||||
if _, err := config.Build(); err == nil || !strings.Contains(err.Error(), `use "google-drive", "template" or "local"`) {
|
||||
t.Fatalf("expected an unknown service error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestXDriveGoogleDriveName(t *testing.T) {
|
||||
for _, service := range []string{"google-drive", "Google Drive"} {
|
||||
config := &XDriveConfig{RemoteFolder: "folder-id", Service: service, Secrets: []string{"a", "b", "c"}}
|
||||
built, err := config.Build()
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", service, err)
|
||||
}
|
||||
if got := built.(*xdrive.Config).Service; got != "google-drive" {
|
||||
t.Errorf("%s: service is %q, want google-drive", service, got)
|
||||
}
|
||||
config = &XDriveConfig{RemoteFolder: "folder-id", Service: service, Secrets: []string{"a", "b"}}
|
||||
if _, err := config.Build(); err == nil {
|
||||
t.Errorf("%s: accepted two secrets", service)
|
||||
}
|
||||
if _, err := config.Build(); err == nil {
|
||||
t.Fatal("Build accepted an unsupported service")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -375,131 +355,6 @@ func TestXDriveTemplateStreamConfig(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
type logLines []string
|
||||
|
||||
func (l *logLines) Handle(msg log.Message) {
|
||||
*l = append(*l, msg.String())
|
||||
}
|
||||
|
||||
// "alpn" ["http/1.1"] is warned about where the hello does not carry it, which
|
||||
// is outside ECH with a fingerprint that has an ALPN of its own
|
||||
func TestXDriveHTTP1ALPNWarning(t *testing.T) {
|
||||
var lines logLines
|
||||
log.RegisterHandler(&lines)
|
||||
|
||||
for _, c := range []struct {
|
||||
method, tlsSettings string
|
||||
warn bool
|
||||
}{
|
||||
{"xdrive", `{}`, false},
|
||||
{"xdrive", `{"alpn": ["http/1.1"]}`, true},
|
||||
{"xdrive", `{"alpn": ["http/1.1"], "fingerprint": "Firefox"}`, true},
|
||||
{"raw", `{"alpn": ["http/1.1"]}`, false},
|
||||
{"xdrive", `{"alpn": ["h2", "http/1.1"]}`, false},
|
||||
{"xdrive", `{"alpn": ["http/1.1"], "echConfigList": "udp://1.1.1.1"}`, false},
|
||||
{"xdrive", `{"alpn": ["http/1.1"], "fingerprint": "unsafe"}`, false},
|
||||
{"xdrive", `{"alpn": ["http/1.1"], "fingerprint": "hellogolang"}`, false},
|
||||
{"xdrive", `{"alpn": ["http/1.1"], "fingerprint": "randomized"}`, false},
|
||||
{"xdrive", `{"alpn": ["http/1.1"], "fingerprint": "hellorandomizednoalpn"}`, false},
|
||||
} {
|
||||
lines = nil
|
||||
config := new(StreamConfig)
|
||||
if err := json.Unmarshal([]byte(`{
|
||||
"method": "`+c.method+`",
|
||||
"security": "tls",
|
||||
"tlsSettings": `+c.tlsSettings+`,
|
||||
"xdriveSettings": {"remoteFolder": "/tmp/xdrive", "service": "local"}
|
||||
}`), config); err != nil {
|
||||
t.Fatalf("Unmarshal: %v", err)
|
||||
}
|
||||
if _, err := config.Build(); err != nil {
|
||||
t.Fatalf("%s %s: %v", c.method, c.tlsSettings, err)
|
||||
}
|
||||
warned := false
|
||||
for _, line := range lines {
|
||||
warned = warned || strings.HasPrefix(line, "[Warning]") && strings.Contains(line, `"alpn"`)
|
||||
}
|
||||
if warned != c.warn {
|
||||
t.Errorf("%s %s: warned %v, want %v", c.method, c.tlsSettings, warned, c.warn)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// over h3 Google Drive takes only the noise mask, and no service takes brutal
|
||||
func TestXDriveH3Checks(t *testing.T) {
|
||||
const (
|
||||
drive = `"method": "xdrive", "xdriveSettings": {"remoteFolder": "f", "service": "google-drive", "secrets": ["a", "b", "c"]}`
|
||||
local = `"method": "xdrive", "xdriveSettings": {"remoteFolder": "/tmp/xdrive", "service": "local"}`
|
||||
noise = `{"type": "Noise", "settings": {"noise": [{"rand": "50-100"}]}}`
|
||||
salamander = `{"type": "salamander", "settings": {"password": "p"}}`
|
||||
forceBrutal = `{"quicParams": {"congestion": "force-brutal", "brutalUp": "10 mbps"}}`
|
||||
)
|
||||
for _, c := range []struct {
|
||||
alpn, transport, finalmask string
|
||||
ok bool
|
||||
}{
|
||||
{`["h3"]`, drive, `{"udp": [` + noise + `]}`, true},
|
||||
{`["h3"]`, drive, `{"udp": [` + salamander + `]}`, false},
|
||||
{`["h3"]`, drive, `{"udp": [` + noise + `, ` + salamander + `]}`, false},
|
||||
{`["h3"]`, local, `{"udp": [` + salamander + `]}`, true},
|
||||
{`["h3"]`, `"method": "xdrive"`, `{"udp": [` + salamander + `]}`, true},
|
||||
{`["h2"]`, drive, `{"udp": [` + salamander + `]}`, true},
|
||||
{`null`, drive, `{"udp": [` + salamander + `]}`, true},
|
||||
{`["h3"]`, drive, `null`, true},
|
||||
{`["h3"]`, drive, `{"quicParams": {"congestion": "bbr"}}`, true},
|
||||
{`["h3"]`, drive, `{"quicParams": {"congestion": "brutal"}}`, false},
|
||||
{`["h3"]`, local, forceBrutal, false},
|
||||
{`["h3", "h2"]`, drive, `{"quicParams": {"congestion": "brutal"}}`, true},
|
||||
{`["h3"]`, `"method": "xhttp"`, forceBrutal, true},
|
||||
} {
|
||||
config := new(StreamConfig)
|
||||
if err := json.Unmarshal([]byte(`{
|
||||
`+c.transport+`,
|
||||
"security": "tls",
|
||||
"tlsSettings": {"alpn": `+c.alpn+`},
|
||||
"finalmask": `+c.finalmask+`
|
||||
}`), config); err != nil {
|
||||
t.Fatalf("Unmarshal: %v", err)
|
||||
}
|
||||
if _, err := config.Build(); (err == nil) != c.ok {
|
||||
t.Errorf("alpn %s, %s, finalmask %s: %v", c.alpn, c.transport, c.finalmask, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// one h3 connection is not held back by a window like h2, so h3 takes one by default
|
||||
func TestXDriveH3Connections(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
alpn string
|
||||
want int32
|
||||
}{
|
||||
{`["h3"]`, 1},
|
||||
{`["h2"]`, 4},
|
||||
{`null`, 4},
|
||||
} {
|
||||
config := new(StreamConfig)
|
||||
if err := json.Unmarshal([]byte(`{
|
||||
"method": "xdrive",
|
||||
"xdriveSettings": {"remoteFolder": "f", "service": "google-drive", "secrets": ["a", "b", "c"]},
|
||||
"security": "tls",
|
||||
"tlsSettings": {"alpn": `+c.alpn+`}
|
||||
}`), config); err != nil {
|
||||
t.Fatalf("Unmarshal: %v", err)
|
||||
}
|
||||
built, err := config.Build()
|
||||
if err != nil {
|
||||
t.Fatalf("alpn %s: %v", c.alpn, err)
|
||||
}
|
||||
xs, err := built.TransportSettings[0].Settings.GetInstance()
|
||||
if err != nil {
|
||||
t.Fatalf("alpn %s: %v", c.alpn, err)
|
||||
}
|
||||
if got := xs.(*xdrive.Config).Xmux.MaxConnections; got.From != c.want || got.To != c.want {
|
||||
t.Errorf("alpn %s: maxConnections is %d-%d, want %d", c.alpn, got.From, got.To, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestXDriveTemplateNeedsTemplate(t *testing.T) {
|
||||
config := new(XDriveConfig)
|
||||
if err := json.Unmarshal([]byte(`{"remoteFolder": "f", "service": "template"}`), config); err != nil {
|
||||
@@ -509,130 +364,3 @@ func TestXDriveTemplateNeedsTemplate(t *testing.T) {
|
||||
t.Fatal("Build accepted a template service without a template")
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
xdriveStream = `"streamSettings": {"network": "xdrive", "xdriveSettings": {"remoteFolder": "f", "service": "local"}}`
|
||||
xdriveID = `"id": "27848739-7e62-4138-9fd3-098a63964b6b"`
|
||||
xdriveServer = `"address": "127.0.0.1", "port": 443, ` + xdriveID
|
||||
xdriveEnc = `"encryption": "mlkem768x25519plus.native.0rtt.XKbaq1BuzJKKKPxZbwgRpn-gYQbnhrYketgezASCL1I"`
|
||||
xdriveDec = `"decryption": "mlkem768x25519plus.native.600s.UKfUEMDdjlEnycTMBP0a08acky8vRRKSrM1MRnaYk3s"`
|
||||
)
|
||||
|
||||
func TestXDriveOutboundConfig(t *testing.T) {
|
||||
build := func(s string) error {
|
||||
c := new(OutboundDetourConfig)
|
||||
if err := json.Unmarshal([]byte(s), c); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := c.Build()
|
||||
return err
|
||||
}
|
||||
|
||||
for _, input := range []string{
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`,
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": 0, "xudpConcurrency": 8, "xudpProxyUDP443": "allow"}}`,
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "reverse": {"tag": "r"}}, ` + xdriveStream + `}`,
|
||||
`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `}]}]}, ` + xdriveStream + `, "mux": {"enabled": true}}`,
|
||||
} {
|
||||
if err := build(input); err != nil {
|
||||
t.Errorf("%s: %v", input, err)
|
||||
}
|
||||
}
|
||||
for _, c := range []struct{ input, err string }{
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, "encryption": "none"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"encryption"`},
|
||||
{`{"protocol": "vless", "settings": {"address": "example.com", "port": 443, ` + xdriveID + `, "encryption": "none"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"encryption"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `}`, `"mux"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": false}}`, `"mux"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": -1}}`, `"mux"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "xudpConcurrency": -1}}`, `"mux"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "xudpProxyUDP443": "skip"}}`, `"mux"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision"}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": -1}}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision"}]}]}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": -1}}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "testpre": 1}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"testpre"`},
|
||||
{`{"protocol": "vmess", "settings": {` + xdriveServer + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"},
|
||||
{`{"protocol": "trojan", "settings": {"address": "example.com", "port": 443, "password": "p"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"},
|
||||
{`{"protocol": "freedom", ` + xdriveStream + `}`, "VLESS"},
|
||||
} {
|
||||
if err := build(c.input); err == nil || !strings.Contains(err.Error(), "xdrive transport") || !strings.Contains(err.Error(), c.err) {
|
||||
t.Errorf("expected an xdrive error about %s for %s, got %v", c.err, c.input, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestXDriveInboundConfig(t *testing.T) {
|
||||
build := func(s string) error {
|
||||
c := new(InboundDetourConfig)
|
||||
if err := json.Unmarshal([]byte(s), c); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := c.Build()
|
||||
return err
|
||||
}
|
||||
|
||||
for _, input := range []string{
|
||||
`{"protocol": "vless", "port": 443, "settings": {"clients": [{` + xdriveID + `}], ` + xdriveDec + `}, ` + xdriveStream + `}`,
|
||||
`{"protocol": "vless", "listen": "@xdrive", "settings": {"clients": [{` + xdriveID + `}], ` + xdriveDec + `}, ` + xdriveStream + `}`,
|
||||
} {
|
||||
if err := build(input); err != nil {
|
||||
t.Errorf("%s: %v", input, err)
|
||||
}
|
||||
}
|
||||
for _, c := range []struct{ input, err string }{
|
||||
{`{"protocol": "vless", "port": 443, "settings": {"clients": [{` + xdriveID + `}], "decryption": "none"}, ` + xdriveStream + `}`, `"decryption"`},
|
||||
{`{"protocol": "vless", "port": 443, "settings": {"clients": [{` + xdriveID + `}], ` + xdriveDec + `, "flow": "xtls-rprx-vision"}, ` + xdriveStream + `}`, `"flow"`},
|
||||
{`{"protocol": "vless", "port": 443, "settings": {"clients": [{` + xdriveID + `, "flow": "xtls-rprx-vision"}], ` + xdriveDec + `}, ` + xdriveStream + `}`, `"flow"`},
|
||||
{`{"protocol": "vmess", "port": 443, "settings": {"clients": [{` + xdriveID + `}]}, ` + xdriveStream + `}`, "VLESS"},
|
||||
{`{"protocol": "vless", "port": "10800-10803", "settings": {"clients": [{` + xdriveID + `}], ` + xdriveDec + `}, ` + xdriveStream + `}`, "one port"},
|
||||
} {
|
||||
if err := build(c.input); err == nil || !strings.Contains(err.Error(), "xdrive transport") || !strings.Contains(err.Error(), c.err) {
|
||||
t.Errorf("expected an xdrive error about %s for %s, got %v", c.err, c.input, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestXDriveXmux(t *testing.T) {
|
||||
defaults := func(connections int32) *splithttp.XmuxConfig {
|
||||
return &splithttp.XmuxConfig{
|
||||
MaxConcurrency: &splithttp.RangeConfig{},
|
||||
MaxConnections: &splithttp.RangeConfig{From: connections, To: connections},
|
||||
CMaxReuseTimes: &splithttp.RangeConfig{},
|
||||
HMaxRequestTimes: &splithttp.RangeConfig{},
|
||||
HMaxReusableSecs: &splithttp.RangeConfig{From: 1800, To: 3000},
|
||||
}
|
||||
}
|
||||
for _, c := range []struct {
|
||||
input string
|
||||
want *splithttp.XmuxConfig
|
||||
}{
|
||||
{`{"service": "google-drive", "secrets": ["a", "b", "c"]}`, defaults(4)},
|
||||
{`{"service": "template", "template": {}}`, defaults(1)},
|
||||
{`{"service": "google-drive", "secrets": ["a", "b", "c"], "xmux": {"maxConcurrency": "1-2", "hMaxRequestTimes": 100, "hKeepAlivePeriod": -1}}`, &splithttp.XmuxConfig{
|
||||
MaxConcurrency: &splithttp.RangeConfig{From: 1, To: 2},
|
||||
MaxConnections: &splithttp.RangeConfig{},
|
||||
CMaxReuseTimes: &splithttp.RangeConfig{},
|
||||
HMaxRequestTimes: &splithttp.RangeConfig{From: 100, To: 100},
|
||||
HMaxReusableSecs: &splithttp.RangeConfig{},
|
||||
HKeepAlivePeriod: -1,
|
||||
}},
|
||||
} {
|
||||
config := new(XDriveConfig)
|
||||
if err := json.Unmarshal([]byte(c.input), config); err != nil {
|
||||
t.Fatalf("%s: Unmarshal: %v", c.input, err)
|
||||
}
|
||||
built, err := config.Build()
|
||||
if err != nil {
|
||||
t.Fatalf("%s: Build: %v", c.input, err)
|
||||
}
|
||||
if got := built.(*xdrive.Config).Xmux; !proto.Equal(got, c.want) {
|
||||
t.Errorf("%s: xmux is %v, want %v", c.input, got, c.want)
|
||||
}
|
||||
}
|
||||
|
||||
config := new(XDriveConfig)
|
||||
if err := json.Unmarshal([]byte(`{"service": "template", "template": {}, "xmux": {"maxConnections": 2, "maxConcurrency": 8}}`), config); err != nil {
|
||||
t.Fatalf("Unmarshal: %v", err)
|
||||
}
|
||||
if _, err := config.Build(); err == nil {
|
||||
t.Error("Build accepted maxConnections with maxConcurrency")
|
||||
}
|
||||
}
|
||||
|
||||
+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", "freebsd":
|
||||
case "linux":
|
||||
if v.AutoSystemDnsToGateway && len(v.Gateway) == 0 {
|
||||
return nil, errors.New("autoSystemDnsToGateway needs gateway to be set")
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package conf_test
|
||||
import (
|
||||
"encoding/json"
|
||||
"runtime"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
. "github.com/xtls/xray-core/infra/conf"
|
||||
@@ -44,18 +43,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"]}`, []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"}},
|
||||
{`{"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"},
|
||||
} {
|
||||
config := new(TunConfig)
|
||||
if err := json.Unmarshal([]byte(c.input), config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := config.Build(); (err != nil) != slices.Contains(c.goos, runtime.GOOS) {
|
||||
if _, err := config.Build(); (err != nil) != (runtime.GOOS == c.goos) {
|
||||
t.Errorf("%s on %s: error = %v", c.input, runtime.GOOS, err)
|
||||
}
|
||||
}
|
||||
|
||||
+5
-59
@@ -17,11 +17,7 @@ import (
|
||||
core "github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
"github.com/xtls/xray-core/proxy/masque"
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/proxy/vless/inbound"
|
||||
"github.com/xtls/xray-core/proxy/vless/outbound"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -213,9 +209,6 @@ func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
|
||||
if _, ok := ts.(*masque.ServerConfig); !ok && receiverSettings.StreamSettings != nil && receiverSettings.StreamSettings.ProtocolName == "masque" {
|
||||
return nil, errors.New("the masque transport can only be used by the masque inbound")
|
||||
}
|
||||
if err := validateXDrive(ts, receiverSettings.StreamSettings, nil, receiverSettings.PortList); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &core.InboundHandlerConfig{
|
||||
Tag: c.Tag,
|
||||
@@ -269,54 +262,6 @@ func validateOutboundTransportSecurity(rawConfig interface{}, senderSettings *pr
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateXDrive allows only VLESS with encryption on xdrive, and on the client Mux.Cool for every connection
|
||||
func validateXDrive(ts proto.Message, ss *internet.StreamConfig, ms *proxyman.MultiplexingConfig, pl *net.PortList) error {
|
||||
if ss == nil || ss.ProtocolName != "xdrive" {
|
||||
return nil
|
||||
}
|
||||
switch c := ts.(type) {
|
||||
case *outbound.Config:
|
||||
a, err := c.Vnext.User.Account.GetInstance()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
account := a.(*vless.Account)
|
||||
if account.Flow != "" {
|
||||
return errors.New(`the xdrive transport doesn't support VLESS "flow"`)
|
||||
}
|
||||
if account.Encryption == "none" {
|
||||
return errors.New(`the xdrive transport needs VLESS "encryption", run "xray vlessenc" to get one`)
|
||||
}
|
||||
// reverse opens its own mux
|
||||
if account.Reverse == nil && (ms == nil || !ms.Enabled || ms.Concurrency < 0 || ms.XudpConcurrency < 0 || ms.XudpProxyUDP443 == "skip") {
|
||||
return errors.New(`the xdrive transport needs "mux" enabled, with no negative "concurrency" or "xudpConcurrency" and no "xudpProxyUDP443":"skip"`)
|
||||
}
|
||||
if account.Testpre != 0 {
|
||||
return errors.New(`the xdrive transport doesn't support VLESS "testpre"`)
|
||||
}
|
||||
case *inbound.Config:
|
||||
if c.Decryption == "none" {
|
||||
return errors.New(`the xdrive transport needs VLESS "decryption", run "xray vlessenc" to get one`)
|
||||
}
|
||||
for _, user := range c.Users {
|
||||
a, err := user.Account.GetInstance()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.(*vless.Account).Flow != "" {
|
||||
return errors.New(`the xdrive transport doesn't support VLESS "flow"`)
|
||||
}
|
||||
}
|
||||
// every port gets its own listener on the same folder, and each of them accepts the same session
|
||||
if pl != nil && len(pl.Ports()) != 1 {
|
||||
return errors.New("the xdrive transport can only listen on one port")
|
||||
}
|
||||
default:
|
||||
return errors.New("the xdrive transport can only be used by VLESS")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Build implements Buildable.
|
||||
func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
|
||||
if c.ProxySettings != nil {
|
||||
@@ -395,14 +340,15 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to build outbound handler for protocol ", c.Protocol).Base(err)
|
||||
}
|
||||
if err := validateXDrive(ts, senderSettings.StreamSettings, senderSettings.MultiplexSettings, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := validateOutboundTransportSecurity(rawConfig, senderSettings); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, ok := ts.(*masque.ClientConfig); !ok && senderSettings.StreamSettings != nil && senderSettings.StreamSettings.ProtocolName == "masque" {
|
||||
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" {
|
||||
return nil, errors.New("the masque transport can only be used by the masque outbound")
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
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,
|
||||
},
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
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,10 +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"
|
||||
// TODO: Restore this import and lua.CmdLua when Lua privileged signature authorization is re-enabled.
|
||||
// "github.com/xtls/xray-core/main/commands/all/lua"
|
||||
"github.com/xtls/xray-core/main/commands/all/tls"
|
||||
"github.com/xtls/xray-core/main/commands/base"
|
||||
)
|
||||
@@ -14,13 +11,10 @@ func init() {
|
||||
base.RootCommand.Commands = append(
|
||||
base.RootCommand.Commands,
|
||||
api.CmdAPI,
|
||||
base64.CmdBase64,
|
||||
convert.CmdConvert,
|
||||
// lua.CmdLua,
|
||||
tls.CmdTLS,
|
||||
cmdUUID,
|
||||
cmdX25519,
|
||||
// cmdEd25519,
|
||||
cmdWG,
|
||||
cmdMLDSA65,
|
||||
cmdMLKEM768,
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
package all
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
|
||||
"github.com/xtls/xray-core/main/commands/base"
|
||||
)
|
||||
|
||||
var cmdEd25519 = &base.Command{
|
||||
UsageLine: `{{.Exec}} ed25519 [-i "private key seed (Base64URL)"]`,
|
||||
Short: "Generate an Ed25519 key pair",
|
||||
Long: `
|
||||
Generate an Ed25519 key pair, or restore it from a 32-byte private key seed
|
||||
with -i. PrivateKey (seed) and PublicKey use unpadded Base64URL.
|
||||
`,
|
||||
}
|
||||
|
||||
var inputEd25519 = cmdEd25519.Flag.String("i", "", "Ed25519 private key seed in unpadded Base64URL.")
|
||||
|
||||
func init() {
|
||||
cmdEd25519.Run = executeEd25519
|
||||
}
|
||||
|
||||
func executeEd25519(cmd *base.Command, args []string) {
|
||||
if len(args) != 0 {
|
||||
cmd.Usage()
|
||||
}
|
||||
|
||||
var privateKey ed25519.PrivateKey
|
||||
if *inputEd25519 == "" {
|
||||
_, key, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
base.Fatalf("failed to generate Ed25519 key: %s", err)
|
||||
}
|
||||
privateKey = key
|
||||
} else {
|
||||
encoding := base64.RawURLEncoding.Strict()
|
||||
seed, err := encoding.DecodeString(*inputEd25519)
|
||||
if err != nil || len(seed) != ed25519.SeedSize || encoding.EncodeToString(seed) != *inputEd25519 {
|
||||
base.Fatalf("invalid Ed25519 private key seed: expected 32 bytes in unpadded Base64URL")
|
||||
}
|
||||
privateKey = ed25519.NewKeyFromSeed(seed)
|
||||
}
|
||||
|
||||
if _, err := fmt.Printf("PrivateKey: %s\nPublicKey: %s\n",
|
||||
base64.RawURLEncoding.EncodeToString(privateKey.Seed()),
|
||||
base64.RawURLEncoding.EncodeToString(privateKey.Public().(ed25519.PublicKey))); err != nil {
|
||||
base.Fatalf("failed to write Ed25519 keys: %s", err)
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package lua
|
||||
|
||||
import "github.com/xtls/xray-core/main/commands/base"
|
||||
|
||||
// CmdLua holds the Lua script commands.
|
||||
var CmdLua = &base.Command{
|
||||
UsageLine: "{{.Exec}} lua",
|
||||
Short: "Manage Lua scripts",
|
||||
Long: "{{.Exec}} {{.LongName}} provides tools for local Lua scripts.",
|
||||
Commands: []*base.Command{
|
||||
cmdSign,
|
||||
},
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
package lua
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
xlua "github.com/xtls/xray-core/common/lua"
|
||||
"github.com/xtls/xray-core/main/commands/base"
|
||||
)
|
||||
|
||||
var cmdSign = &base.Command{
|
||||
UsageLine: "{{.Exec}} lua sign [-key seed] [-o output-file] <input-file>",
|
||||
Short: "Sign a local Lua script for privileged execution",
|
||||
Long: `
|
||||
Sign a local Lua file using a 32-byte Ed25519 private key seed in unpadded
|
||||
Base64URL. Use {{.Exec}} ed25519 to generate a key pair.
|
||||
Write back to the input file, or use -o to write another file (- for stdout).
|
||||
`,
|
||||
}
|
||||
|
||||
var (
|
||||
signKey = cmdSign.Flag.String("key", "", "Ed25519 private key seed in unpadded Base64URL.")
|
||||
signOutput = cmdSign.Flag.String("o", "", "Output file, or - for stdout. Default: input file.")
|
||||
)
|
||||
|
||||
func init() {
|
||||
cmdSign.Run = executeSign
|
||||
}
|
||||
|
||||
func executeSign(cmd *base.Command, args []string) {
|
||||
if len(args) != 1 {
|
||||
cmd.Usage()
|
||||
}
|
||||
|
||||
info, err := os.Stat(args[0])
|
||||
if err != nil {
|
||||
base.Fatalf("failed to inspect Lua file: %s", err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
base.Fatalf("Lua input is not a regular file: %s", args[0])
|
||||
}
|
||||
|
||||
code, err := os.ReadFile(args[0])
|
||||
if err != nil {
|
||||
base.Fatalf("failed to read Lua file: %s", err)
|
||||
}
|
||||
|
||||
signed, err := xlua.SignPrivilegedScript(code, *signKey)
|
||||
if err != nil {
|
||||
base.Fatalf("failed to sign Lua file: %s", err)
|
||||
}
|
||||
|
||||
if *signOutput == "-" {
|
||||
if _, err := os.Stdout.Write(signed); err != nil {
|
||||
base.Fatalf("failed to write signed Lua file: %s", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
output := *signOutput
|
||||
if output == "" {
|
||||
output = args[0]
|
||||
}
|
||||
if err := writeSignedFile(output, signed, info.Mode().Perm()); err != nil {
|
||||
base.Fatalf("failed to write signed Lua file: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func writeSignedFile(path string, code []byte, mode os.FileMode) error {
|
||||
if info, err := os.Stat(path); err == nil {
|
||||
if !info.Mode().IsRegular() {
|
||||
return &os.PathError{Op: "write", Path: path, Err: os.ErrInvalid}
|
||||
}
|
||||
mode = info.Mode().Perm()
|
||||
path, err = filepath.EvalSymlinks(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
|
||||
file, err := os.CreateTemp(filepath.Dir(path), ".xray-lua-sign-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(file.Name())
|
||||
defer file.Close()
|
||||
if _, err := file.Write(code); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := file.Chmod(mode); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(file.Name(), path)
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
package all
|
||||
|
||||
import (
|
||||
"crypto/mldsa"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
|
||||
"github.com/cloudflare/circl/sign/mldsa/mldsa65"
|
||||
"github.com/xtls/xray-core/main/commands/base"
|
||||
)
|
||||
|
||||
@@ -39,8 +39,8 @@ func executeMLDSA65(cmd *base.Command, args []string) {
|
||||
} else {
|
||||
rand.Read(seed[:])
|
||||
}
|
||||
key, _ := mldsa.NewPrivateKey(mldsa.MLDSA65(), seed[:])
|
||||
pub, _ := mldsa65.NewKeyFromSeed(&seed)
|
||||
fmt.Printf("Seed: %v\nVerify: %v\n",
|
||||
base64.RawURLEncoding.EncodeToString(seed[:]),
|
||||
base64.RawURLEncoding.EncodeToString(key.PublicKey().Bytes()))
|
||||
base64.RawURLEncoding.EncodeToString(pub.Bytes()))
|
||||
}
|
||||
|
||||
@@ -4,8 +4,6 @@ package base
|
||||
type CommandEnvHolder struct {
|
||||
// Executable name of current binary
|
||||
Exec string
|
||||
// Full name of the command being executed
|
||||
CommandName string
|
||||
// commands column width of current command
|
||||
CommandsWidth int
|
||||
}
|
||||
|
||||
@@ -61,7 +61,6 @@ BigCmdLoop:
|
||||
}
|
||||
|
||||
buildCommandText(cmd)
|
||||
CommandEnv.CommandName = cmdName
|
||||
cmd.Run(cmd, args)
|
||||
Exit()
|
||||
return
|
||||
|
||||
Vendored
+1
-35
@@ -8,14 +8,12 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/utils"
|
||||
"github.com/xtls/xray-core/main/commands/base"
|
||||
"github.com/xtls/xray-core/main/confloader"
|
||||
)
|
||||
|
||||
@@ -33,12 +31,7 @@ func ConfigLoader(arg string) (out io.Reader, err error) {
|
||||
data, err = io.ReadAll(os.Stdin)
|
||||
|
||||
default:
|
||||
file, openErr := os.Open(arg)
|
||||
if openErr != nil {
|
||||
return nil, openErr
|
||||
}
|
||||
defer file.Close()
|
||||
data, err = readConfigFile(file)
|
||||
data, err = os.ReadFile(arg)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
@@ -48,33 +41,6 @@ func ConfigLoader(arg string) (out io.Reader, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func readConfigFile(file *os.File) ([]byte, error) {
|
||||
if base.CommandEnv.CommandName != "run" {
|
||||
return io.ReadAll(file)
|
||||
}
|
||||
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if info.Mode().IsRegular() {
|
||||
path, err := filepath.Abs(file.Name())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
path, err = filepath.EvalSymlinks(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch strings.ToLower(filepath.Ext(path)) {
|
||||
case ".jsonc", ".json", ".yml", ".yaml", ".toml", ".pb", ".protobuf":
|
||||
default:
|
||||
return nil, errors.New("unsupported config file extension: ", path)
|
||||
}
|
||||
}
|
||||
return io.ReadAll(file)
|
||||
}
|
||||
|
||||
// FetchHTTPContent issues an HTTP GET against either a regular HTTP(S) URL
|
||||
// or a Unix socket HTTP endpoint.
|
||||
//
|
||||
|
||||
+4
-10
@@ -36,6 +36,10 @@ The -confdir=dir flag sets a dir with multiple json config
|
||||
The -format=json flag sets the format of config files.
|
||||
Default "auto".
|
||||
|
||||
The config root env object sets process environment variables after all config
|
||||
files are parsed. Variables needed to locate or parse config files must be set
|
||||
in the process environment before Xray starts.
|
||||
|
||||
The -test flag tells Xray to test config files only,
|
||||
without launching the server.
|
||||
|
||||
@@ -43,9 +47,6 @@ The -dump flag tells Xray to print the merged config.
|
||||
`,
|
||||
}
|
||||
|
||||
// The --lua-privileged-pubkey=key flag sets the trusted Ed25519 public key
|
||||
// for privileged local Lua scripts, encoded as unpadded Base64URL.
|
||||
|
||||
func init() {
|
||||
cmdRun.Run = executeRun // break init loop
|
||||
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds)
|
||||
@@ -57,8 +58,6 @@ var (
|
||||
dump = cmdRun.Flag.Bool("dump", false, "Dump merged config only, without launching Xray server.")
|
||||
test = cmdRun.Flag.Bool("test", false, "Test config file only, without launching Xray server.")
|
||||
format = cmdRun.Flag.String("format", "auto", "Format of input file.")
|
||||
// TODO: Restore this flag and its help text when Lua privileged signature authorization is re-enabled.
|
||||
// luaPrivilegedPublicKey = cmdRun.Flag.String("lua-privileged-pubkey", "", "Unpadded Base64URL Ed25519 public key for privileged local Lua scripts.")
|
||||
|
||||
/* We have to do this here because Golang's Test will also need to parse flag, before
|
||||
* main func in this file is run.
|
||||
@@ -215,11 +214,6 @@ func getConfigFormat() string {
|
||||
}
|
||||
|
||||
func startXray() (core.Server, error) {
|
||||
// TODO: Restore public key initialization when Lua privileged signature authorization is re-enabled.
|
||||
// if err := lua.SetPrivilegedPublicKey(*luaPrivilegedPublicKey); err != nil {
|
||||
// return nil, errors.New("failed to configure Lua privileged authorization").Base(err)
|
||||
// }
|
||||
|
||||
configFiles := getConfigFilePath(true)
|
||||
|
||||
c, err := core.LoadConfig(getConfigFormat(), configFiles)
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRunConfigCommands(t *testing.T) {
|
||||
if os.Getenv("XRAY_TEST_CONFIG_COMMAND") == "1" {
|
||||
os.Args = append([]string{os.Args[0]}, flag.Args()...)
|
||||
main()
|
||||
return
|
||||
}
|
||||
dir := t.TempDir()
|
||||
config := filepath.Join(dir, "config.yaml")
|
||||
script := filepath.Join(dir, "config.lua")
|
||||
binary := filepath.Join(dir, "config.pb")
|
||||
message := filepath.Join(dir, "user.tmsg")
|
||||
for path, body := range map[string]string{
|
||||
config: "{}",
|
||||
script: "{}",
|
||||
binary: "",
|
||||
message: `{"type":"xray.app.dispatcher.Config","value":""}`,
|
||||
} {
|
||||
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
file, err := os.Open(script)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer file.Close()
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
args []string
|
||||
code int
|
||||
input io.Reader
|
||||
}{
|
||||
{"format override", []string{"run", "-test", "-format", "json", "-c", config}, 0, nil},
|
||||
{"invalid extension", []string{"run", "-test", "-format", "json", "-c", script}, 23, nil},
|
||||
{"default command", []string{"-test", "-format", "json", "-c", script}, 23, nil},
|
||||
{"protobuf config", []string{"run", "-test", "-c", binary}, 0, nil},
|
||||
{"protobuf error", []string{"run", "-test", "-format", "protobuf", "-c", script}, 23, nil},
|
||||
{"merged source", []string{"run", "-test", "-format", "json", "-c", config, "-c", script}, 23, nil},
|
||||
{"dump", []string{"run", "-dump", "-c", config}, 0, nil},
|
||||
{"stdin pipe", []string{"run", "-test", "-c", "stdin:"}, 0, nil},
|
||||
{"stdin file", []string{"run", "-test", "-c", "stdin:"}, 0, file},
|
||||
{"convert json", []string{"convert", "json", message}, 0, nil},
|
||||
{"convert pb", []string{"convert", "pb", "-debug", config}, 0, nil},
|
||||
{"convert pb stdin", []string{"convert", "pb", "-debug", "stdin:"}, 0, file},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
args := append([]string{"-test.run=^TestRunConfigCommands$", "--"}, tc.args...)
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], args...)
|
||||
cmd.Env = append(os.Environ(), "XRAY_TEST_CONFIG_COMMAND=1")
|
||||
cmd.Stdin = strings.NewReader("{}")
|
||||
if tc.input != nil {
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd.Stdin = tc.input
|
||||
}
|
||||
output, err := cmd.CombinedOutput()
|
||||
if cmd.ProcessState == nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code := cmd.ProcessState.ExitCode(); code != tc.code {
|
||||
t.Fatalf("exit code = %d, want %d: %v\n%s", code, tc.code, err, output)
|
||||
}
|
||||
if tc.code == 23 && !strings.Contains(string(output), "failed to load config files") {
|
||||
t.Fatalf("missing config error:\n%s", output)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+2
-30
@@ -10,7 +10,6 @@ import (
|
||||
"net/url"
|
||||
"sync"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
@@ -87,13 +86,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
|
||||
user := server.User
|
||||
var conn stat.Connection
|
||||
|
||||
var mbuf buf.MultiBuffer
|
||||
if reader, ok := link.Reader.(buf.TimeoutReader); ok {
|
||||
// Don't wait forever: server-first protocols (SMTP, FTP, MySQL...) send nothing until the server greets.
|
||||
mbuf, _ = reader.ReadMultiBufferTimeout(time.Millisecond * 500)
|
||||
} else {
|
||||
mbuf, _ = link.Reader.ReadMultiBuffer()
|
||||
}
|
||||
mbuf, _ := link.Reader.ReadMultiBuffer()
|
||||
len := mbuf.Len()
|
||||
firstPayload := bytespool.Alloc(len)
|
||||
mbuf, _ = buf.SplitBytes(mbuf, firstPayload)
|
||||
@@ -241,8 +234,7 @@ func setUpHTTPTunnel(ctx context.Context, dest net.Destination, target string, u
|
||||
return nil, err
|
||||
}
|
||||
|
||||
reader := bufio.NewReader(rawConn)
|
||||
resp, err := http.ReadResponse(reader, req)
|
||||
resp, err := http.ReadResponse(bufio.NewReader(rawConn), req)
|
||||
if err != nil {
|
||||
rawConn.Close()
|
||||
return nil, err
|
||||
@@ -253,11 +245,6 @@ func setUpHTTPTunnel(ctx context.Context, dest net.Destination, target string, u
|
||||
rawConn.Close()
|
||||
return nil, errors.New("Proxy responded with non 200 code: " + resp.Status)
|
||||
}
|
||||
// Tunneled bytes (e.g. a server-first greeting) may arrive in the same read as the 200 response.
|
||||
if n := reader.Buffered(); n > 0 {
|
||||
early, _ := reader.Peek(n)
|
||||
return &earlyDataConn{Conn: rawConn, early: early}, nil
|
||||
}
|
||||
return rawConn, nil
|
||||
}
|
||||
|
||||
@@ -388,21 +375,6 @@ func (h *http2Conn) Close() error {
|
||||
return h.out.Close()
|
||||
}
|
||||
|
||||
// earlyDataConn returns the bytes read ahead together with the CONNECT response before reading from Conn.
|
||||
type earlyDataConn struct {
|
||||
net.Conn
|
||||
early []byte
|
||||
}
|
||||
|
||||
func (c *earlyDataConn) Read(p []byte) (int, error) {
|
||||
if len(c.early) > 0 {
|
||||
n := copy(p, c.early)
|
||||
c.early = c.early[n:]
|
||||
return n, nil
|
||||
}
|
||||
return c.Conn.Read(p)
|
||||
}
|
||||
|
||||
func init() {
|
||||
common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
|
||||
return NewClient(ctx, config.(*ClientConfig))
|
||||
|
||||
+35
-104
@@ -7,6 +7,7 @@ import (
|
||||
"net/netip"
|
||||
"slices"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"golang.zx2c4.com/wireguard/tun"
|
||||
@@ -25,7 +26,6 @@ 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,15 +43,11 @@ 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) {
|
||||
@@ -59,8 +55,7 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
|
||||
p := v.GetFeature(policy.ManagerType()).(policy.Manager)
|
||||
|
||||
streamSettings := session.StreamSettingsFromContext(ctx).(*internet.MemoryStreamConfig)
|
||||
transportConfig, ok := streamSettings.ProtocolSettings.(*masque.Config)
|
||||
if !ok {
|
||||
if _, ok := streamSettings.ProtocolSettings.(*masque.Config); !ok {
|
||||
return nil, errors.New("not masque transport")
|
||||
}
|
||||
if tls.ConfigFromStreamSettings(streamSettings) == nil {
|
||||
@@ -91,13 +86,7 @@ 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
|
||||
}
|
||||
@@ -111,11 +100,10 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
|
||||
ob.Name = "masque"
|
||||
ob.CanSpliceCopy = 3
|
||||
|
||||
xmuxClient, t, err := c.getTunnel(ctx, dialer)
|
||||
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
|
||||
@@ -192,63 +180,40 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) getTunnel(ctx context.Context, dialer internet.Dialer) (*splithttp.XmuxClient, *tunnel, error) {
|
||||
func (c *Client) getTunnel(ctx context.Context, dialer internet.Dialer) (*tunnel, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.ctx.Err() != nil {
|
||||
return nil, nil, errors.New("closed")
|
||||
return nil, errors.New("closed")
|
||||
}
|
||||
if t := c.tunnel.Load(); t != nil {
|
||||
select {
|
||||
case <-t.done:
|
||||
default:
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
return nil, err
|
||||
}
|
||||
var xmuxClient *splithttp.XmuxClient
|
||||
if c.lastErr != nil && time.Since(c.lastErrAt) < retryInterval {
|
||||
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
|
||||
}
|
||||
}
|
||||
return nil, c.lastErr
|
||||
}
|
||||
t := xmuxClient.XmuxConn.(*tunnel)
|
||||
if c.ctx.Err() != nil {
|
||||
return nil, nil, errors.New("closed")
|
||||
}
|
||||
xmuxClient.AddRunning()
|
||||
return xmuxClient, t, nil
|
||||
}
|
||||
|
||||
func (c *Client) newXmuxConn() splithttp.XmuxConn {
|
||||
t, err := c.establish(c.dialCtx, c.dialer)
|
||||
t, err := c.establish(ctx, dialer)
|
||||
if err != nil {
|
||||
c.lastErr, c.lastErrAt = err, time.Now()
|
||||
return failedTunnel(err)
|
||||
return nil, err
|
||||
}
|
||||
c.lastErr = nil
|
||||
c.tunnelsMu.Lock()
|
||||
if c.tunnels == nil {
|
||||
c.tunnelsMu.Unlock()
|
||||
t.close()
|
||||
return failedTunnel(errors.New("closed"))
|
||||
c.tunnel.Store(t)
|
||||
if c.ctx.Err() != nil {
|
||||
if c.tunnel.CompareAndSwap(t, nil) {
|
||||
t.close()
|
||||
}
|
||||
return nil, errors.New("closed")
|
||||
}
|
||||
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()
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (c *Client) establish(ctx context.Context, dialer internet.Dialer) (*tunnel, error) {
|
||||
@@ -264,7 +229,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, c.removeTunnel)
|
||||
t, err := newTunnel(conn, mconn.LocalAddrs(), c.remoteDNS)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
@@ -275,11 +240,7 @@ func (c *Client) establish(ctx context.Context, dialer internet.Dialer) (*tunnel
|
||||
|
||||
func (c *Client) Close() error {
|
||||
c.cancel()
|
||||
c.tunnelsMu.Lock()
|
||||
tunnels := c.tunnels
|
||||
c.tunnels = nil
|
||||
c.tunnelsMu.Unlock()
|
||||
for t := range tunnels {
|
||||
if t := c.tunnel.Swap(nil); t != nil {
|
||||
t.close()
|
||||
}
|
||||
return nil
|
||||
@@ -291,31 +252,9 @@ type tunnel struct {
|
||||
tnet *wireguard.Net
|
||||
done chan struct{}
|
||||
closeOnce sync.Once
|
||||
onClose func(*tunnel)
|
||||
err 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) {
|
||||
func newTunnel(conn stat.Connection, local []netip.Addr, remoteDNS []netip.Addr) (*tunnel, error) {
|
||||
var dns []netip.Addr
|
||||
for _, addr := range remoteDNS {
|
||||
if slices.ContainsFunc(local, func(l netip.Addr) bool { return l.Is4() == addr.Is4() }) {
|
||||
@@ -327,16 +266,15 @@ func newTunnel(conn stat.Connection, local []netip.Addr, remoteDNS []netip.Addr,
|
||||
dns = remoteDNS
|
||||
}
|
||||
|
||||
dev, tnet, err := wireguard.CreateNetTUN(local, dns, masque.MinPacketSize, nil)
|
||||
dev, tnet, _, err := wireguard.CreateNetTUN(local, dns, masque.MinPacketSize, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t := &tunnel{
|
||||
conn: conn,
|
||||
dev: dev,
|
||||
tnet: tnet,
|
||||
done: make(chan struct{}),
|
||||
onClose: onClose,
|
||||
conn: conn,
|
||||
dev: dev,
|
||||
tnet: tnet,
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
go t.readFromTunnel()
|
||||
go t.writeToTunnel()
|
||||
@@ -378,15 +316,8 @@ func (t *tunnel) writeToTunnel() {
|
||||
func (t *tunnel) close() {
|
||||
t.closeOnce.Do(func() {
|
||||
close(t.done)
|
||||
if t.conn != nil {
|
||||
t.conn.Close()
|
||||
}
|
||||
if t.dev != nil {
|
||||
t.dev.Close()
|
||||
}
|
||||
if t.onClose != nil {
|
||||
t.onClose(t)
|
||||
}
|
||||
t.conn.Close()
|
||||
t.dev.Close()
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-13
@@ -22,7 +22,6 @@ import (
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
xtun "github.com/xtls/xray-core/proxy/tun"
|
||||
"github.com/xtls/xray-core/proxy/wireguard"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
@@ -167,11 +166,17 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
|
||||
if mtu == 0 {
|
||||
mtu = masque.MinPacketSize
|
||||
}
|
||||
dev, _, gstack, err := wireguard.CreateNetTUN(local, nil, mtu, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s := &Server{
|
||||
validator: users,
|
||||
dispatcher: v.GetFeature(routing.DispatcherType()).(routing.Dispatcher),
|
||||
ctx: core.ToBackgroundDetachedContext(ctx),
|
||||
mtu: mtu,
|
||||
dev: dev,
|
||||
pools: pools,
|
||||
local: local,
|
||||
tunnels: make(map[netip.Addr]*serverTunnel),
|
||||
@@ -182,11 +187,7 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
|
||||
if content := session.ContentFromContext(ctx); content != nil {
|
||||
s.sniffing = content.SniffingRequest
|
||||
}
|
||||
dev, _, err := wireguard.CreateNetTUN(local, nil, mtu, s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.dev = dev
|
||||
wireguard.CreateForwarder(gstack, s.handleConnection)
|
||||
return s, nil
|
||||
}
|
||||
|
||||
@@ -499,8 +500,7 @@ func packetDestination(packet []byte) (netip.Addr, bool) {
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
|
||||
// HandleConnection implements tun.ConnectionHandler
|
||||
func (s *Server) HandleConnection(conn net.Conn, dest net.Destination) {
|
||||
func (s *Server) handleConnection(conn net.Conn, dest net.Destination) {
|
||||
defer conn.Close()
|
||||
source := net.DestinationFromAddr(conn.RemoteAddr())
|
||||
addr, _ := netip.AddrFromSlice(source.Address.IP())
|
||||
@@ -534,13 +534,9 @@ func (s *Server) HandleConnection(conn net.Conn, dest net.Destination) {
|
||||
})
|
||||
errors.LogInfo(ctx, "processing from ", source, " to ", dest)
|
||||
|
||||
writer := buf.NewWriter(conn)
|
||||
if dest.Network == net.Network_TCP {
|
||||
writer = &xtun.TCPWriter{Writer: writer}
|
||||
}
|
||||
link := &transport.Link{
|
||||
Reader: &buf.TimeoutWrapperReader{Reader: buf.NewReader(conn)},
|
||||
Writer: writer,
|
||||
Writer: buf.NewWriter(conn),
|
||||
}
|
||||
if err := s.dispatcher.DispatchLink(ctx, dest, link); err != nil {
|
||||
errors.LogError(ctx, errors.New("connection closed").Base(err))
|
||||
|
||||
@@ -7,17 +7,13 @@ import (
|
||||
"net/netip"
|
||||
"os"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"golang.zx2c4.com/wireguard/tun"
|
||||
)
|
||||
|
||||
@@ -330,56 +326,3 @@ func TestPacketDestination(t *testing.T) {
|
||||
require.False(t, ok)
|
||||
}
|
||||
}
|
||||
|
||||
// stackConn is a TCP connection as the stack hands it over: it is its own buf.Writer.
|
||||
type stackConn struct {
|
||||
net.Conn
|
||||
closed atomic.Int32
|
||||
}
|
||||
|
||||
func (c *stackConn) Read([]byte) (int, error) { return 0, io.EOF }
|
||||
|
||||
func (c *stackConn) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
buf.ReleaseMulti(mb)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *stackConn) Close() error {
|
||||
c.closed.Add(1)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *stackConn) RemoteAddr() net.Addr {
|
||||
return &net.TCPAddr{IP: net.IP{10, 13, 0, 2}, Port: 1234}
|
||||
}
|
||||
|
||||
// closingDispatcher does what an outbound does when the other side has no more to send.
|
||||
type closingDispatcher struct {
|
||||
routing.Dispatcher
|
||||
conn *stackConn
|
||||
closed int32
|
||||
}
|
||||
|
||||
func (d *closingDispatcher) DispatchLink(_ context.Context, _ net.Destination, link *transport.Link) error {
|
||||
common.Close(link.Writer)
|
||||
d.closed = d.conn.closed.Load()
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestServerKeepsConnectionOpenWhenWriterCloses(t *testing.T) {
|
||||
conn := &stackConn{}
|
||||
dispatcher := &closingDispatcher{conn: conn}
|
||||
s := &Server{
|
||||
ctx: context.Background(),
|
||||
dispatcher: dispatcher,
|
||||
tunnels: map[netip.Addr]*serverTunnel{netip.MustParseAddr("10.13.0.2"): newServerTunnel(nil, &protocol.MemoryUser{})},
|
||||
}
|
||||
s.HandleConnection(conn, net.TCPDestination(net.ParseAddress("192.0.2.1"), 443))
|
||||
|
||||
if dispatcher.closed != 0 {
|
||||
t.Fatal("the connection was closed with its writer, while the client may still be sending")
|
||||
}
|
||||
if got := conn.closed.Load(); got != 1 {
|
||||
t.Fatalf("connection closed %d times, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
+6
-9
@@ -180,14 +180,14 @@ type VisionReader struct {
|
||||
isUplink bool
|
||||
conn net.Conn
|
||||
input *bytes.Reader
|
||||
rawInput **bytes.Buffer
|
||||
rawInput *bytes.Buffer
|
||||
ob *session.Outbound
|
||||
|
||||
// internal
|
||||
directReadCounter stats.Counter
|
||||
}
|
||||
|
||||
func NewVisionReader(reader buf.Reader, trafficState *TrafficState, isUplink bool, ctx context.Context, conn net.Conn, input *bytes.Reader, rawInput **bytes.Buffer, ob *session.Outbound) *VisionReader {
|
||||
func NewVisionReader(reader buf.Reader, trafficState *TrafficState, isUplink bool, ctx context.Context, conn net.Conn, input *bytes.Reader, rawInput *bytes.Buffer, ob *session.Outbound) *VisionReader {
|
||||
return &VisionReader{
|
||||
Reader: reader,
|
||||
trafficState: trafficState,
|
||||
@@ -261,15 +261,12 @@ func (w *VisionReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
if inputBuffer, err := buf.ReadFrom(w.input); err == nil && !inputBuffer.IsEmpty() {
|
||||
buffer, _ = buf.MergeMulti(buffer, inputBuffer)
|
||||
}
|
||||
if rawInputBuffer, err := buf.ReadFrom(w.rawInput); err == nil && !rawInputBuffer.IsEmpty() {
|
||||
buffer, _ = buf.MergeMulti(buffer, rawInputBuffer)
|
||||
}
|
||||
*w.input = bytes.Reader{} // release memory
|
||||
w.input = nil
|
||||
|
||||
if raw := *w.rawInput; raw != nil {
|
||||
if rawInputBuffer, err := buf.ReadFrom(raw); err == nil && !rawInputBuffer.IsEmpty() {
|
||||
buffer, _ = buf.MergeMulti(buffer, rawInputBuffer)
|
||||
}
|
||||
// *raw = bytes.Buffer{} // may not be suitable for Go 1.27.3+
|
||||
}
|
||||
*w.rawInput = bytes.Buffer{} // release memory
|
||||
w.rawInput = nil
|
||||
|
||||
if inbound := session.InboundFromContext(w.ctx); inbound != nil && inbound.Conn != nil {
|
||||
|
||||
@@ -169,17 +169,11 @@ func (i *Inbound) processUDP(ctx context.Context, conn stat.Connection, dispatch
|
||||
}
|
||||
sessionItem.Unlock()
|
||||
}
|
||||
link := sessionItem.link.Load()
|
||||
if link != nil {
|
||||
sessionItem.UpdateConn(conn)
|
||||
} else {
|
||||
var err error
|
||||
link, err = sessionItem.EnsureLink(ctx, conn, decoded.Destination, dispatcher, i.policyManager, func(dest net.Destination, payload []byte) ([]byte, error) {
|
||||
return i.udpCodec.EncodeServerPacket(decoded.SessionID, dest, payload)
|
||||
})
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
link, err := sessionItem.EnsureLink(ctx, conn, decoded.Destination, dispatcher, i.policyManager, func(dest net.Destination, payload []byte) ([]byte, error) {
|
||||
return i.udpCodec.EncodeServerPacket(decoded.SessionID, dest, payload)
|
||||
})
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
payloadBuf := buf.New()
|
||||
|
||||
@@ -336,17 +336,11 @@ func (i *MultiUserInbound) processUDP(ctx context.Context, conn stat.Connection,
|
||||
}
|
||||
sessionItem.Unlock()
|
||||
|
||||
link := sessionItem.link.Load()
|
||||
if link != nil {
|
||||
sessionItem.UpdateConn(conn)
|
||||
} else {
|
||||
var err error
|
||||
link, err = sessionItem.EnsureLink(ctx, conn, decoded.Destination, dispatcher, i.policyManager, func(replyDest net.Destination, payload []byte) ([]byte, error) {
|
||||
return i.encodeServerUDPPacket(sessionID, userPSK, replyDest, payload)
|
||||
})
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
link, err := sessionItem.EnsureLink(ctx, conn, decoded.Destination, dispatcher, i.policyManager, func(replyDest net.Destination, payload []byte) ([]byte, error) {
|
||||
return i.encodeServerUDPPacket(sessionID, userPSK, replyDest, payload)
|
||||
})
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
pBuf := buf.New()
|
||||
|
||||
@@ -253,16 +253,10 @@ func (i *RelayInbound) processUDP(ctx context.Context, conn stat.Connection, dis
|
||||
}
|
||||
sessionItem.Unlock()
|
||||
}
|
||||
link := sessionItem.link.Load()
|
||||
if link != nil {
|
||||
sessionItem.UpdateConn(conn)
|
||||
} else {
|
||||
var err error
|
||||
link, err = sessionItem.EnsureLink(ctx, conn, dest, dispatcher, i.policyManager, nil)
|
||||
if err != nil {
|
||||
b.Release()
|
||||
continue
|
||||
}
|
||||
link, err := sessionItem.EnsureLink(ctx, conn, dest, dispatcher, i.policyManager, nil)
|
||||
if err != nil {
|
||||
b.Release()
|
||||
continue
|
||||
}
|
||||
|
||||
_ = link.Writer.WriteMultiBuffer(buf.MultiBuffer{b})
|
||||
|
||||
@@ -169,8 +169,8 @@ func (o *Outbound) Process(ctx context.Context, link *transport.Link, dialer int
|
||||
return buf.Copy(responseReader, link.Writer, buf.UpdateActivity(timer))
|
||||
}
|
||||
|
||||
responseDonePost := task.OnSuccess(responseDone, task.Close(link.Writer))
|
||||
if err := task.Run(ctx, requestDone, responseDonePost); err != nil {
|
||||
responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
|
||||
if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
|
||||
return errors.New("connection ends").Base(err)
|
||||
}
|
||||
|
||||
@@ -212,8 +212,8 @@ func (o *Outbound) Process(ctx context.Context, link *transport.Link, dialer int
|
||||
return nil
|
||||
}
|
||||
|
||||
responseDonePost := task.OnSuccess(responseDone, task.Close(link.Writer))
|
||||
if err := task.Run(ctx, requestDone, responseDonePost); err != nil {
|
||||
responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
|
||||
if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
|
||||
return errors.New("connection ends").Base(err)
|
||||
}
|
||||
|
||||
|
||||
@@ -153,7 +153,7 @@ func parsePlainUDPPacket(sessionID, packetID uint64, bodyPlain []byte) (DecodedU
|
||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||
}
|
||||
epoch := binary.BigEndian.Uint64(bodyPlain[1:9])
|
||||
diff := math.Abs(float64(time.Now().Unix() - int64(epoch)))
|
||||
diff := int(math.Abs(float64(time.Now().Unix() - int64(epoch))))
|
||||
if diff > 30 {
|
||||
return DecodedUDPPacket{}, ErrBadTimestamp
|
||||
}
|
||||
|
||||
@@ -49,12 +49,12 @@ func (f *SlidingWindow) Add(counter uint64) {
|
||||
|
||||
if counter > f.last {
|
||||
lastBlockIndex := f.last >> swBlockBitLog
|
||||
diff := blockIndex - lastBlockIndex
|
||||
diff := int(blockIndex - lastBlockIndex)
|
||||
if diff > swRingBlocks {
|
||||
diff = swRingBlocks
|
||||
}
|
||||
|
||||
for i := 0; i < int(diff); i++ {
|
||||
for i := 0; i < diff; i++ {
|
||||
lastBlockIndex = (lastBlockIndex + 1) & swBlockMask
|
||||
f.ring[lastBlockIndex] = 0
|
||||
}
|
||||
|
||||
@@ -18,8 +18,12 @@ import (
|
||||
)
|
||||
|
||||
func (s *ServerUDPSession) UpdateConn(conn stat.Connection) {
|
||||
s.currentConn.Store(conn)
|
||||
s.timer.Update()
|
||||
if s.currentConn.Load() == nil {
|
||||
s.currentConn.Store(conn)
|
||||
}
|
||||
if s.timer != nil {
|
||||
s.timer.Update()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ServerUDPSession) WriteToClient(b []byte) error {
|
||||
@@ -53,16 +57,19 @@ func (s *ServerUDPSession) EnsureLink(
|
||||
policyManager policy.Manager,
|
||||
responseEncoder func(dest net.Destination, payload []byte) ([]byte, error),
|
||||
) (*transport.Link, error) {
|
||||
s.UpdateConn(conn)
|
||||
|
||||
if link := s.link.Load(); link != nil {
|
||||
return link, nil
|
||||
}
|
||||
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
if link := s.link.Load(); link != nil {
|
||||
s.UpdateConn(conn)
|
||||
return link, nil
|
||||
}
|
||||
|
||||
s.currentConn.Store(conn)
|
||||
|
||||
sessCtx, cancel := context.WithCancel(ctx)
|
||||
inbound := session.InboundFromContext(sessCtx)
|
||||
if inbound != nil && s.User != nil {
|
||||
@@ -87,6 +94,7 @@ func (s *ServerUDPSession) EnsureLink(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s.link.Store(link)
|
||||
sessionPolicy := policyManager.ForLevel(level)
|
||||
s.timer = signal.CancelAfterInactivity(sessCtx, func() {
|
||||
if s.manager != nil {
|
||||
@@ -95,7 +103,6 @@ func (s *ServerUDPSession) EnsureLink(
|
||||
s.Close()
|
||||
cancel()
|
||||
}, sessionPolicy.Timeouts.ConnectionIdle)
|
||||
s.link.Store(link)
|
||||
|
||||
go handleUDPResponse(s, link, dest, responseEncoder)
|
||||
return link, nil
|
||||
@@ -111,13 +118,19 @@ func ResetTCPConn(conn net.Conn) {
|
||||
}
|
||||
|
||||
func handleUDPResponse(s *ServerUDPSession, link *transport.Link, fallbackDest net.Destination, encode func(dest net.Destination, payload []byte) ([]byte, error)) {
|
||||
defer s.timer.SetTimeout(0)
|
||||
defer func() {
|
||||
if s.timer != nil {
|
||||
s.timer.SetTimeout(0)
|
||||
}
|
||||
}()
|
||||
for {
|
||||
resMb, err := link.Reader.ReadMultiBuffer()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.timer.Update()
|
||||
if s.timer != nil {
|
||||
s.timer.Update()
|
||||
}
|
||||
for i, rb := range resMb {
|
||||
b := rb.Bytes()
|
||||
if encode != nil {
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/antireplay"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
@@ -254,7 +253,7 @@ func ReadClientRequestHeaderWithFixed(reader *StreamReader, fixedChunk []byte) (
|
||||
}
|
||||
|
||||
epoch := binary.BigEndian.Uint64(plainFixed[1:9])
|
||||
diff := math.Abs(float64(time.Now().Unix() - int64(epoch)))
|
||||
diff := int(math.Abs(float64(time.Now().Unix() - int64(epoch))))
|
||||
if diff > 30 {
|
||||
return nil, ErrBadTimestamp
|
||||
}
|
||||
@@ -431,7 +430,7 @@ func ReadTCPResponse(r io.Reader, method *CipherMethod, psk []byte, clientSalt [
|
||||
}
|
||||
|
||||
serverEpoch := binary.BigEndian.Uint64(decryptedFixed[1:9])
|
||||
diff := math.Abs(float64(time.Now().Unix() - int64(serverEpoch)))
|
||||
diff := int(math.Abs(float64(time.Now().Unix() - int64(serverEpoch))))
|
||||
if diff > 30 {
|
||||
return nil, ErrBadTimestamp
|
||||
}
|
||||
@@ -630,7 +629,6 @@ func InitServerStream(conn net.Conn, method *CipherMethod, psk, saltSlice []byte
|
||||
func TransportTCP(ctx context.Context, sessionPolicy policy.Session, reader buf.Reader, writer buf.Writer, link *transport.Link) error {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
|
||||
defer timer.SetTimeout(0)
|
||||
ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
|
||||
|
||||
requestDone := func() error {
|
||||
@@ -646,12 +644,6 @@ func TransportTCP(ctx context.Context, sessionPolicy policy.Session, reader buf.
|
||||
return buf.Copy(link.Reader, writer, buf.UpdateActivity(timer))
|
||||
}
|
||||
|
||||
requestDoneAndCloseWriter := task.OnSuccess(requestDone, task.Close(link.Writer))
|
||||
if err := task.Run(ctx, requestDoneAndCloseWriter, responseDone); err != nil {
|
||||
common.Interrupt(link.Reader)
|
||||
common.Interrupt(link.Writer)
|
||||
return errors.New("connection ends").Base(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
|
||||
return task.Run(ctx, requestDone, responseDoneAndCloseWriter)
|
||||
}
|
||||
|
||||
@@ -2,10 +2,10 @@ package socks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/signal"
|
||||
)
|
||||
|
||||
@@ -14,9 +14,6 @@ func NewTempUDPConn(udpConn net.PacketConn, tcpConn net.Conn, expectedRemote *ne
|
||||
PacketConn: udpConn,
|
||||
AssociatedTCPConn: tcpConn,
|
||||
}
|
||||
t.Timer = signal.CancelAfterInactivity(context.Background(), func() {
|
||||
t.Close()
|
||||
}, net.ConnIdleTimeout)
|
||||
t.ExpectedRemote.Store(expectedRemote)
|
||||
return t
|
||||
}
|
||||
@@ -63,7 +60,9 @@ func (c *TempUDPConn) RemoteAddr() net.Addr {
|
||||
}
|
||||
|
||||
func (c *TempUDPConn) SetTimeout(d time.Duration) {
|
||||
c.Timer.SetTimeout(d)
|
||||
c.Timer = signal.CancelAfterInactivity(context.Background(), func() {
|
||||
c.Close()
|
||||
}, d)
|
||||
}
|
||||
|
||||
func (c *TempUDPConn) Close() error {
|
||||
|
||||
+9
-31
@@ -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 uses the first IPv4 prefix from `gateway` for the point-to-point address and FreeBSD for the interface address, the one after the gateway. \
|
||||
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. \
|
||||
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, 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. \
|
||||
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. \
|
||||
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 AND FREEBSD (`autoSystemDnsToGateway`)
|
||||
### SYSTEM DNS ON LINUX (`autoSystemDnsToGateway`)
|
||||
|
||||
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).
|
||||
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.
|
||||
|
||||
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,24 +66,6 @@ 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:
|
||||
```
|
||||
@@ -263,10 +245,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. \
|
||||
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.
|
||||
|
||||
It's necessary to set an IP address to the interface, ex.:
|
||||
```
|
||||
ifconfig tun0 inet 169.254.10.1/30
|
||||
```
|
||||
To attach routing to the interface, route command like following can be executed:
|
||||
```
|
||||
route add -net 1.1.1.0/24 -iface tun10
|
||||
@@ -275,10 +257,6 @@ 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
|
||||
|
||||
+22
-27
@@ -56,25 +56,6 @@ func (w *tunUDPStatsWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// TCPWriter is the writing side of a TCP connection of the stack 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 TCPWriter struct {
|
||||
Writer buf.Writer
|
||||
// Counter counts what is written, if there is one
|
||||
Counter stats.Counter
|
||||
}
|
||||
|
||||
func (w *TCPWriter) 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)
|
||||
@@ -167,7 +148,6 @@ 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)
|
||||
@@ -219,7 +199,22 @@ func (t *Handler) HandleConnection(conn net.Conn, destination net.Destination) {
|
||||
defer cancel()
|
||||
ctx = c.ContextWithID(ctx, session.NewID())
|
||||
|
||||
source := net.DestinationFromAddr(conn.RemoteAddr())
|
||||
// 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,
|
||||
}
|
||||
}
|
||||
|
||||
inbound := session.Inbound{
|
||||
Name: "tun",
|
||||
@@ -245,13 +240,13 @@ func (t *Handler) HandleConnection(conn net.Conn, destination net.Destination) {
|
||||
})
|
||||
errors.LogInfo(ctx, "processing from ", source, " to ", destination)
|
||||
|
||||
// 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}
|
||||
reader := &buf.TimeoutWrapperReader{Reader: buf.NewReader(conn)}
|
||||
writer := buf.NewWriter(conn)
|
||||
if destination.Network != net.Network_UDP {
|
||||
writer = &TCPWriter{Writer: writer, Counter: t.downlinkCounter}
|
||||
} else if t.downlinkCounter != nil {
|
||||
writer = &tunUDPStatsWriter{writer: writer, counter: t.downlinkCounter}
|
||||
if isUDP {
|
||||
reader.Counter = t.uplinkCounter
|
||||
if t.downlinkCounter != nil {
|
||||
writer = &tunUDPStatsWriter{writer: writer, counter: t.downlinkCounter}
|
||||
}
|
||||
}
|
||||
|
||||
link := &transport.Link{
|
||||
|
||||
@@ -8,7 +8,6 @@ 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"
|
||||
@@ -104,53 +103,6 @@ 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,106 @@
|
||||
package icmp
|
||||
|
||||
import (
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"gvisor.dev/gvisor/pkg/tcpip"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/checksum"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/header"
|
||||
)
|
||||
|
||||
func ProtocolLabel(netProto tcpip.NetworkProtocolNumber) string {
|
||||
switch netProto {
|
||||
case header.IPv4ProtocolNumber:
|
||||
return "ipv4"
|
||||
case header.IPv6ProtocolNumber:
|
||||
return "ipv6"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
func ParseEchoRequest(netProto tcpip.NetworkProtocolNumber, message []byte) (uint16, uint16, bool) {
|
||||
switch netProto {
|
||||
case header.IPv4ProtocolNumber:
|
||||
if len(message) < header.ICMPv4MinimumSize {
|
||||
return 0, 0, false
|
||||
}
|
||||
icmpHdr := header.ICMPv4(message)
|
||||
if icmpHdr.Type() != header.ICMPv4Echo || icmpHdr.Code() != header.ICMPv4UnusedCode {
|
||||
return 0, 0, false
|
||||
}
|
||||
return icmpHdr.Ident(), icmpHdr.Sequence(), true
|
||||
case header.IPv6ProtocolNumber:
|
||||
if len(message) < header.ICMPv6MinimumSize {
|
||||
return 0, 0, false
|
||||
}
|
||||
icmpHdr := header.ICMPv6(message)
|
||||
if icmpHdr.Type() != header.ICMPv6EchoRequest || icmpHdr.Code() != header.ICMPv6UnusedCode {
|
||||
return 0, 0, false
|
||||
}
|
||||
return icmpHdr.Ident(), icmpHdr.Sequence(), true
|
||||
default:
|
||||
return 0, 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func RewriteChecksum(netProto tcpip.NetworkProtocolNumber, message []byte, srcIP, dstIP tcpip.Address) error {
|
||||
switch netProto {
|
||||
case header.IPv4ProtocolNumber:
|
||||
if len(message) < header.ICMPv4MinimumSize {
|
||||
return errors.New("invalid icmpv4 packet")
|
||||
}
|
||||
icmpHdr := header.ICMPv4(message)
|
||||
icmpHdr.SetChecksum(0)
|
||||
icmpHdr.SetChecksum(header.ICMPv4Checksum(icmpHdr[:header.ICMPv4MinimumSize], checksum.Checksum(icmpHdr.Payload(), 0)))
|
||||
return nil
|
||||
case header.IPv6ProtocolNumber:
|
||||
if len(message) < header.ICMPv6MinimumSize {
|
||||
return errors.New("invalid icmpv6 packet")
|
||||
}
|
||||
icmpHdr := header.ICMPv6(message)
|
||||
icmpHdr.SetChecksum(0)
|
||||
icmpHdr.SetChecksum(header.ICMPv6Checksum(header.ICMPv6ChecksumParams{
|
||||
Header: icmpHdr[:header.ICMPv6MinimumSize],
|
||||
Src: srcIP,
|
||||
Dst: dstIP,
|
||||
PayloadCsum: checksum.Checksum(icmpHdr.Payload(), 0),
|
||||
PayloadLen: len(icmpHdr.Payload()),
|
||||
}))
|
||||
return nil
|
||||
default:
|
||||
return errors.New("unsupported icmp network protocol")
|
||||
}
|
||||
}
|
||||
|
||||
func BuildLocalEchoReply(netProto tcpip.NetworkProtocolNumber, request []byte, srcIP, dstIP tcpip.Address) ([]byte, error) {
|
||||
reply := append([]byte(nil), request...)
|
||||
|
||||
switch netProto {
|
||||
case header.IPv4ProtocolNumber:
|
||||
if len(reply) < header.ICMPv4MinimumSize {
|
||||
return nil, errors.New("invalid icmpv4 echo packet")
|
||||
}
|
||||
icmpHdr := header.ICMPv4(reply)
|
||||
if icmpHdr.Type() != header.ICMPv4Echo || icmpHdr.Code() != header.ICMPv4UnusedCode {
|
||||
return nil, errors.New("not an icmpv4 echo request")
|
||||
}
|
||||
reply[0] = byte(header.ICMPv4EchoReply)
|
||||
case header.IPv6ProtocolNumber:
|
||||
if len(reply) < header.ICMPv6MinimumSize {
|
||||
return nil, errors.New("invalid icmpv6 echo packet")
|
||||
}
|
||||
icmpHdr := header.ICMPv6(reply)
|
||||
if icmpHdr.Type() != header.ICMPv6EchoRequest || icmpHdr.Code() != header.ICMPv6UnusedCode {
|
||||
return nil, errors.New("not an icmpv6 echo request")
|
||||
}
|
||||
reply[0] = byte(header.ICMPv6EchoReply)
|
||||
default:
|
||||
return nil, errors.New("unsupported icmp network protocol")
|
||||
}
|
||||
|
||||
if err := RewriteChecksum(netProto, reply, srcIP, dstIP); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return reply, nil
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package icmp
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gvisor.dev/gvisor/pkg/tcpip"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/checksum"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/header"
|
||||
)
|
||||
|
||||
func TestParseEchoRequest(t *testing.T) {
|
||||
t.Run("ipv4 echo", func(t *testing.T) {
|
||||
var zero tcpip.Address
|
||||
packet := []byte{
|
||||
byte(header.ICMPv4Echo), 0,
|
||||
0, 0,
|
||||
0x12, 0x34,
|
||||
0x56, 0x78,
|
||||
0xaa, 0xbb,
|
||||
}
|
||||
if err := RewriteChecksum(header.IPv4ProtocolNumber, packet, zero, zero); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
ident, sequence, ok := ParseEchoRequest(header.IPv4ProtocolNumber, packet)
|
||||
if !ok {
|
||||
t.Fatal("expected ipv4 echo request to parse")
|
||||
}
|
||||
if ident != 0x1234 || sequence != 0x5678 {
|
||||
t.Fatalf("unexpected ident/sequence: %x/%x", ident, sequence)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ipv6 echo", func(t *testing.T) {
|
||||
packet := []byte{
|
||||
byte(header.ICMPv6EchoRequest), 0,
|
||||
0, 0,
|
||||
0xab, 0xcd,
|
||||
0xef, 0x01,
|
||||
0xaa, 0xbb,
|
||||
}
|
||||
src := tcpip.AddrFromSlice([]byte{0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1})
|
||||
dst := tcpip.AddrFromSlice([]byte{0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2})
|
||||
if err := RewriteChecksum(header.IPv6ProtocolNumber, packet, src, dst); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
ident, sequence, ok := ParseEchoRequest(header.IPv6ProtocolNumber, packet)
|
||||
if !ok {
|
||||
t.Fatal("expected ipv6 echo request to parse")
|
||||
}
|
||||
if ident != 0xabcd || sequence != 0xef01 {
|
||||
t.Fatalf("unexpected ident/sequence: %x/%x", ident, sequence)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRewriteChecksum(t *testing.T) {
|
||||
t.Run("ipv4", func(t *testing.T) {
|
||||
var zero tcpip.Address
|
||||
packet := []byte{
|
||||
byte(header.ICMPv4Echo), 0,
|
||||
0xff, 0xff,
|
||||
0x12, 0x34,
|
||||
0x56, 0x78,
|
||||
0xaa, 0xbb, 0xcc,
|
||||
}
|
||||
if err := RewriteChecksum(header.IPv4ProtocolNumber, packet, zero, zero); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
icmpHdr := header.ICMPv4(packet)
|
||||
if got, want := icmpHdr.Checksum(), header.ICMPv4Checksum(icmpHdr[:header.ICMPv4MinimumSize], checksumPayloadV4(icmpHdr.Payload())); got != want {
|
||||
t.Fatalf("unexpected ipv4 checksum: got %x want %x", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ipv6", func(t *testing.T) {
|
||||
packet := []byte{
|
||||
byte(header.ICMPv6EchoReply), 0,
|
||||
0xff, 0xff,
|
||||
0x12, 0x34,
|
||||
0x56, 0x78,
|
||||
0xaa, 0xbb, 0xcc,
|
||||
}
|
||||
src := tcpip.AddrFromSlice([]byte{0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1})
|
||||
dst := tcpip.AddrFromSlice([]byte{0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2})
|
||||
if err := RewriteChecksum(header.IPv6ProtocolNumber, packet, src, dst); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
icmpHdr := header.ICMPv6(packet)
|
||||
want := header.ICMPv6Checksum(header.ICMPv6ChecksumParams{
|
||||
Header: icmpHdr[:header.ICMPv6MinimumSize],
|
||||
Src: src,
|
||||
Dst: dst,
|
||||
PayloadLen: len(icmpHdr.Payload()),
|
||||
PayloadCsum: checksumPayloadV6(icmpHdr.Payload()),
|
||||
})
|
||||
if got := icmpHdr.Checksum(); got != want {
|
||||
t.Fatalf("unexpected ipv6 checksum: got %x want %x", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestBuildLocalEchoReply(t *testing.T) {
|
||||
t.Run("ipv4", func(t *testing.T) {
|
||||
request := []byte{
|
||||
byte(header.ICMPv4Echo), 0,
|
||||
0, 0,
|
||||
0x12, 0x34,
|
||||
0x56, 0x78,
|
||||
0xaa, 0xbb, 0xcc,
|
||||
}
|
||||
src := tcpip.Address{}
|
||||
dst := tcpip.Address{}
|
||||
if err := RewriteChecksum(header.IPv4ProtocolNumber, request, src, dst); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
reply, err := BuildLocalEchoReply(header.IPv4ProtocolNumber, request, dst, src)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if request[0] != byte(header.ICMPv4Echo) {
|
||||
t.Fatal("request mutated")
|
||||
}
|
||||
icmpHdr := header.ICMPv4(reply)
|
||||
if icmpHdr.Type() != header.ICMPv4EchoReply || icmpHdr.Code() != header.ICMPv4UnusedCode {
|
||||
t.Fatalf("unexpected ipv4 reply type/code: %d/%d", icmpHdr.Type(), icmpHdr.Code())
|
||||
}
|
||||
if icmpHdr.Ident() != 0x1234 || icmpHdr.Sequence() != 0x5678 {
|
||||
t.Fatalf("unexpected ipv4 ident/sequence: %x/%x", icmpHdr.Ident(), icmpHdr.Sequence())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ipv6", func(t *testing.T) {
|
||||
request := []byte{
|
||||
byte(header.ICMPv6EchoRequest), 0,
|
||||
0, 0,
|
||||
0xab, 0xcd,
|
||||
0xef, 0x01,
|
||||
0xaa, 0xbb, 0xcc,
|
||||
}
|
||||
src := tcpip.AddrFromSlice([]byte{0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1})
|
||||
dst := tcpip.AddrFromSlice([]byte{0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2})
|
||||
if err := RewriteChecksum(header.IPv6ProtocolNumber, request, src, dst); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
reply, err := BuildLocalEchoReply(header.IPv6ProtocolNumber, request, dst, src)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if request[0] != byte(header.ICMPv6EchoRequest) {
|
||||
t.Fatal("request mutated")
|
||||
}
|
||||
icmpHdr := header.ICMPv6(reply)
|
||||
if icmpHdr.Type() != header.ICMPv6EchoReply || icmpHdr.Code() != header.ICMPv6UnusedCode {
|
||||
t.Fatalf("unexpected ipv6 reply type/code: %d/%d", icmpHdr.Type(), icmpHdr.Code())
|
||||
}
|
||||
if icmpHdr.Ident() != 0xabcd || icmpHdr.Sequence() != 0xef01 {
|
||||
t.Fatalf("unexpected ipv6 ident/sequence: %x/%x", icmpHdr.Ident(), icmpHdr.Sequence())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func checksumPayloadV4(payload []byte) uint16 {
|
||||
return checksum.Checksum(payload, 0)
|
||||
}
|
||||
|
||||
func checksumPayloadV6(payload []byte) uint16 {
|
||||
return checksum.Checksum(payload, 0)
|
||||
}
|
||||
@@ -1,391 +0,0 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"math"
|
||||
"math/bits"
|
||||
"net/netip"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
ipv4HeaderSize = 20
|
||||
ipv6HeaderSize = 40
|
||||
tcpHeaderSize = 20
|
||||
udpHeaderSize = 8
|
||||
|
||||
protoICMPv4 = 1
|
||||
protoTCP = 6
|
||||
protoUDP = 17
|
||||
protoICMPv6 = 58
|
||||
|
||||
// the smallest that a link is believed to take whatever is said about it: what every IPv4 host takes,
|
||||
// and the smallest link that IPv6 runs on
|
||||
ipv4SmallestMTU = 576
|
||||
ipv6SmallestMTU = 1280
|
||||
|
||||
// the header that an IPv6 packet has in front of each of its fragments, and its number
|
||||
fragmentHeaderSize = 8
|
||||
protoFragment = 44
|
||||
// fragmentsMost is how many packets can be waiting for the rest of their fragments,
|
||||
// fragmentsTime how long they are waited for at most
|
||||
fragmentsMost = 64
|
||||
fragmentsTime = 30 * time.Second
|
||||
)
|
||||
|
||||
// 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, without the last rest bytes of it when they are in other buffers
|
||||
payload []byte
|
||||
rest int
|
||||
// fragment is set if payload is a part of what follows the IP header: the one at offset of the packet
|
||||
// with the number id, which has more after it or not
|
||||
fragment bool
|
||||
more bool
|
||||
offset int
|
||||
id uint32
|
||||
}
|
||||
|
||||
// parsePacket reads the IP header of a packet that is b and rest bytes after it
|
||||
func parsePacket(b []byte, rest int) (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)+rest {
|
||||
return p, false
|
||||
}
|
||||
if f := binary.BigEndian.Uint16(b[6:]); f&0x3fff != 0 {
|
||||
p.fragment, p.more, p.offset, p.id = true, f&0x2000 != 0, int(f&0x1fff)*8, uint32(binary.BigEndian.Uint16(b[4:]))
|
||||
}
|
||||
p.proto = b[9]
|
||||
p.src = netip.AddrFrom4([4]byte(b[12:16]))
|
||||
p.dst = netip.AddrFrom4([4]byte(b[16:20]))
|
||||
p.payload, p.rest = b[size:min(total, len(b))], max(total-len(b), 0)
|
||||
case 6:
|
||||
if len(b) < ipv6HeaderSize {
|
||||
return p, false
|
||||
}
|
||||
total := ipv6HeaderSize + int(binary.BigEndian.Uint16(b[4:]))
|
||||
if total > len(b)+rest {
|
||||
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, p.rest = b[ipv6HeaderSize:min(total, len(b))], max(total-len(b), 0)
|
||||
// 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:]
|
||||
}
|
||||
if p.proto == protoFragment {
|
||||
f := p.payload
|
||||
if len(f) < fragmentHeaderSize {
|
||||
return p, false
|
||||
}
|
||||
p.fragment, p.more, p.offset, p.id = true, f[3]&1 != 0, int(binary.BigEndian.Uint16(f[2:])&^7), binary.BigEndian.Uint32(f[4:])
|
||||
p.proto, p.payload = f[0], f[fragmentHeaderSize:]
|
||||
}
|
||||
default:
|
||||
return p, false
|
||||
}
|
||||
return p, true
|
||||
}
|
||||
|
||||
// verified reports whether the checksum of what the packet carries is right
|
||||
func (p packet) verified() bool {
|
||||
data := p.payload
|
||||
switch p.proto {
|
||||
case protoICMPv4:
|
||||
return checksum(sum(data, 0)) == 0
|
||||
case protoUDP:
|
||||
if len(data) < udpHeaderSize {
|
||||
return false
|
||||
}
|
||||
// the packet may be longer than what it carries
|
||||
size := int(binary.BigEndian.Uint16(data[4:]))
|
||||
if size < udpHeaderSize || size > len(data) {
|
||||
return false
|
||||
}
|
||||
if p.src.Is4() && data[6]|data[7] == 0 {
|
||||
// zero stands for no checksum
|
||||
return true
|
||||
}
|
||||
data = data[:size]
|
||||
case protoTCP, protoICMPv6:
|
||||
default:
|
||||
return true
|
||||
}
|
||||
pseudo := uint64(p.proto) + uint64(len(data))
|
||||
if p.src.Is4() {
|
||||
src, dst := p.src.As4(), p.dst.As4()
|
||||
pseudo = sum(dst[:], sum(src[:], pseudo))
|
||||
} else {
|
||||
src, dst := p.src.As16(), p.dst.As16()
|
||||
pseudo = sum(dst[:], sum(src[:], pseudo))
|
||||
}
|
||||
return checksum(sum(data, pseudo)) == 0
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
// writeFragments writes a packet that is larger than mtu to tun in fragments that are not. header is its IP header
|
||||
// with what follows that up to payload, which is no more than the header of a UDP packet. id is the number
|
||||
// of the packet if it is an IPv6 one
|
||||
func writeFragments(tun Tun, mtu int, id uint32, header, payload []byte) error {
|
||||
var b [ipv6HeaderSize + fragmentHeaderSize + udpHeaderSize]byte
|
||||
size := ipv4HeaderSize
|
||||
if header[0]>>4 == 6 {
|
||||
size = ipv6HeaderSize
|
||||
}
|
||||
n := copy(b[:], header[:size])
|
||||
if size == ipv6HeaderSize {
|
||||
// the number goes into a header of its own, behind the IP header. That of IPv4 has it
|
||||
b[6], b[n] = protoFragment, header[6]
|
||||
binary.BigEndian.PutUint32(b[n+4:], id)
|
||||
n += fragmentHeaderSize
|
||||
}
|
||||
// first goes in front of payload, in the first fragment
|
||||
first := header[size:]
|
||||
if n+len(first) > len(b) {
|
||||
return errors.New("no room for a header of ", len(first), " bytes in a fragment")
|
||||
}
|
||||
// every fragment but the last is a number of 8 bytes
|
||||
room, total := (mtu-n)&^7, len(first)+len(payload)
|
||||
if room < 8 {
|
||||
return errors.New("no room for a fragment in an MTU of ", mtu)
|
||||
}
|
||||
for offset := 0; offset < total; {
|
||||
h, part := b[:n], min(room, total-offset)
|
||||
last := offset+part == total
|
||||
if size == ipv6HeaderSize {
|
||||
f := uint16(offset)
|
||||
if !last {
|
||||
f |= 1
|
||||
}
|
||||
binary.BigEndian.PutUint16(b[size+2:], f)
|
||||
} else {
|
||||
f := uint16(offset / 8)
|
||||
if !last {
|
||||
f |= 0x2000
|
||||
}
|
||||
binary.BigEndian.PutUint16(b[6:], f)
|
||||
}
|
||||
setIPLength(b[:size], n+part)
|
||||
data := payload[max(offset-len(first), 0):min(offset+part-len(first), len(payload))]
|
||||
if offset == 0 {
|
||||
h = b[:n+copy(b[n:], first)]
|
||||
}
|
||||
if err := tun.WritePacket(h, data); err != nil {
|
||||
return err
|
||||
}
|
||||
offset += part
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// fragmented is a packet of which not every fragment has come yet
|
||||
type fragmented struct {
|
||||
// data is what follows its IP header, as far as its last fragment that has come goes
|
||||
data []byte
|
||||
// parts are what of data has come, in order and apart from each other
|
||||
parts [][2]int
|
||||
// size is that of data when all of it has come, known from the last fragment
|
||||
size int
|
||||
known bool
|
||||
since time.Time
|
||||
}
|
||||
|
||||
// reassembly puts the packets that come in fragments together
|
||||
type reassembly struct {
|
||||
mu sync.Mutex
|
||||
packets map[fragments]*fragmented
|
||||
}
|
||||
|
||||
// fragments is what the fragments of a packet have in common
|
||||
type fragments struct {
|
||||
src, dst netip.Addr
|
||||
proto byte
|
||||
id uint32
|
||||
}
|
||||
|
||||
// add takes the fragment p of a packet. With the last one that was missing, it returns the packet.
|
||||
// A packet whose fragments do not fit each other is given up
|
||||
func (r *reassembly) add(p packet) (packet, bool) {
|
||||
fragment, offset, end := p.payload, p.offset, p.offset+len(p.payload)
|
||||
// what an IP packet can carry
|
||||
most := math.MaxUint16
|
||||
if p.src.Is4() {
|
||||
most -= ipv4HeaderSize
|
||||
}
|
||||
if len(fragment) == 0 || end > most || p.more && len(fragment)%8 != 0 {
|
||||
return p, false
|
||||
}
|
||||
key, now := fragments{p.src, p.dst, p.proto, p.id}, time.Now()
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
f := r.packets[key]
|
||||
if f != nil && now.Sub(f.since) > fragmentsTime {
|
||||
// what is left of a packet whose other fragments were lost: this is one of another packet with its number
|
||||
f = nil
|
||||
}
|
||||
if f == nil {
|
||||
if _, stale := r.packets[key]; !stale && len(r.packets) >= fragmentsMost {
|
||||
// the one that is waited for the longest makes room, not the one that comes now
|
||||
var longest fragments
|
||||
var since time.Time
|
||||
for other, old := range r.packets {
|
||||
if since.IsZero() || old.since.Before(since) {
|
||||
longest, since = other, old.since
|
||||
}
|
||||
}
|
||||
delete(r.packets, longest)
|
||||
}
|
||||
if r.packets == nil {
|
||||
r.packets = make(map[fragments]*fragmented)
|
||||
}
|
||||
f = &fragmented{since: now}
|
||||
r.packets[key] = f
|
||||
}
|
||||
for _, part := range f.parts {
|
||||
if offset >= part[0] && end <= part[1] {
|
||||
// came already
|
||||
return p, false
|
||||
}
|
||||
if offset < part[1] && part[0] < end {
|
||||
// fragments of one packet do not overlap: these are of two, or made to be taken for something else
|
||||
delete(r.packets, key)
|
||||
return p, false
|
||||
}
|
||||
}
|
||||
if f.known && end > f.size || !p.more && len(f.data) > end {
|
||||
// past its end, or an end before what came
|
||||
delete(r.packets, key)
|
||||
return p, false
|
||||
}
|
||||
if !p.more {
|
||||
f.size, f.known = end, true
|
||||
}
|
||||
if len(f.data) < end {
|
||||
f.data = append(f.data, make([]byte, end-len(f.data))...)
|
||||
}
|
||||
copy(f.data[offset:], fragment)
|
||||
i := 0
|
||||
for i < len(f.parts) && f.parts[i][1] < offset {
|
||||
i++
|
||||
}
|
||||
j := i
|
||||
for ; j < len(f.parts) && f.parts[j][0] <= end; j++ {
|
||||
offset, end = min(offset, f.parts[j][0]), max(end, f.parts[j][1])
|
||||
}
|
||||
f.parts = slices.Replace(f.parts, i, j, [2]int{offset, end})
|
||||
if !f.known || f.parts[0] != [2]int{0, f.size} {
|
||||
return p, false
|
||||
}
|
||||
delete(r.packets, key)
|
||||
p.payload, p.fragment = f.data[:f.size], false
|
||||
return p, true
|
||||
}
|
||||
@@ -1,624 +1,17 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"math"
|
||||
"math/rand/v2"
|
||||
gonet "net"
|
||||
"net/netip"
|
||||
"slices"
|
||||
"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
|
||||
type Stack interface {
|
||||
// Start makes the stack read the packets of its tun
|
||||
Start() error
|
||||
Close() error
|
||||
// Input takes a packet of a tun that hands them over instead of being read. The packet is not kept,
|
||||
// but it may be written to. The packets of one connection have to come one after another
|
||||
Input(packet []byte)
|
||||
// DialTCP opens a connection to address from the one of StackOptions.Addresses that is of its family
|
||||
DialTCP(ctx context.Context, address netip.AddrPort) (net.Conn, error)
|
||||
// DialUDP opens a port on StackOptions.Addresses. What anyone sends to the port is read from it
|
||||
DialUDP() (net.PacketConn, error)
|
||||
}
|
||||
|
||||
// StackOptions for the stack implementation
|
||||
type StackOptions struct {
|
||||
Tun Tun
|
||||
MTU uint32
|
||||
IdleTimeout time.Duration
|
||||
// Addresses are what the stack opens connections from
|
||||
Addresses []netip.Addr
|
||||
// Remote is set if the tun is a tunnel to another system and not the tun of this one: what comes through it
|
||||
// has come a long way, so its checksums are looked at, nothing but that way limits the windows, and the
|
||||
// segments of TCP carry the times of both sides if the other side has them
|
||||
Remote bool
|
||||
}
|
||||
|
||||
// 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. The tun may also be a tunnel to a system that is far away, and the stack
|
||||
// the one that opens the connections
|
||||
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
|
||||
// verify is set if the checksums of what comes are looked at
|
||||
verify bool
|
||||
// stamps is set if connections carry the times of RFC 7323 when the other side does
|
||||
stamps bool
|
||||
// handle is given every new connection that the other side opens. Without it those are refused
|
||||
handle func(conn net.Conn, destination net.Destination)
|
||||
udp *udpConnectionHandler
|
||||
// addresses are what connections are opened from
|
||||
addresses []netip.Addr
|
||||
// bufs is what read reads a packet into if the tun is a segmenter, one after the other, the headers in the first.
|
||||
// One that keep took is nil. joined is for a packet that is in more than one and is needed in one piece
|
||||
bufs buf.MultiBuffer
|
||||
joined []byte
|
||||
|
||||
mu sync.Mutex
|
||||
conns map[flow]*tcpConn
|
||||
// sockets are the ports that DialUDP has opened
|
||||
sockets map[netip.AddrPort]*udpSocket
|
||||
closed bool
|
||||
// opening is how many of conns wait for the answer to their SYN or SYN-ACK
|
||||
opening atomic.Int32
|
||||
// fragments are the packets that are larger than a link on their way and come in parts.
|
||||
// identification numbers the ones that leave like that: a counter for each of a few groups of destinations,
|
||||
// each from a start of its own, so that no two of them that go one way meet, and no destination learns how much
|
||||
// goes to the others
|
||||
fragments reassembly
|
||||
identification [64]atomic.Uint32
|
||||
}
|
||||
|
||||
// NewStack builds new ip stack. Without a handler it takes no connections, only opens them
|
||||
func NewStack(ctx context.Context, options StackOptions, handler ConnectionHandler) (Stack, error) {
|
||||
s := &stack{
|
||||
ctx: ctx,
|
||||
tun: options.Tun,
|
||||
mtu: int(options.MTU),
|
||||
window: tcpWindow,
|
||||
addresses: options.Addresses,
|
||||
verify: options.Remote,
|
||||
stamps: options.Remote,
|
||||
conns: make(map[flow]*tcpConn),
|
||||
sockets: make(map[netip.AddrPort]*udpSocket),
|
||||
}
|
||||
if t, ok := options.Tun.(segmenter); ok && t.Segments() {
|
||||
s.segmenter = t
|
||||
s.window = tcpLargeWindow
|
||||
}
|
||||
if options.Remote {
|
||||
s.window = tcpLargeWindow
|
||||
}
|
||||
for i := range s.identification {
|
||||
s.identification[i].Store(rand.Uint32())
|
||||
}
|
||||
if handler != nil {
|
||||
s.handle = handler.HandleConnection
|
||||
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)
|
||||
}
|
||||
sockets := s.sockets
|
||||
s.sockets = nil
|
||||
s.mu.Unlock()
|
||||
for _, c := range conns {
|
||||
c.mu.Lock()
|
||||
if c.err == nil {
|
||||
c.reset()
|
||||
}
|
||||
c.mu.Unlock()
|
||||
}
|
||||
for _, u := range sockets {
|
||||
u.queue.close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// read takes the packets of the tun until it is closed
|
||||
func (s *stack) read() {
|
||||
var err error
|
||||
if s.segmenter != nil {
|
||||
err = s.readSegments()
|
||||
} else {
|
||||
// as large as a packet can be, whatever the MTU is
|
||||
b := make([]byte, packetRoom+1<<16)
|
||||
for err == nil {
|
||||
var p []byte
|
||||
if p, err = s.tun.ReadPacket(b); err == nil {
|
||||
s.Input(p)
|
||||
}
|
||||
}
|
||||
}
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
// readSegments is read for a tun that does not split segments and gives them as large as a packet can be.
|
||||
// They are read into buffers for a connection to keep what is large as it is, see keep
|
||||
func (s *stack) readSegments() error {
|
||||
s.bufs = make(buf.MultiBuffer, (1<<16)/buf.Size)
|
||||
defer buf.ReleaseMulti(s.bufs)
|
||||
parts := make([][]byte, len(s.bufs))
|
||||
var r room
|
||||
for {
|
||||
for i, b := range s.bufs {
|
||||
if b == nil {
|
||||
s.bufs[i] = buf.New()
|
||||
_, _ = s.bufs[i].ReadFrom(&r)
|
||||
parts[i] = r.b
|
||||
}
|
||||
}
|
||||
n, err := s.segmenter.ReadParts(parts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.input(parts[0][:min(n, buf.Size)], max(n-buf.Size, 0))
|
||||
}
|
||||
}
|
||||
|
||||
// room takes what it is given to read into as read: that is the room of a Buffer as it is, not cleared
|
||||
type room struct{ b []byte }
|
||||
|
||||
func (r *room) Read(b []byte) (int, error) {
|
||||
r.b = b
|
||||
return len(b), nil
|
||||
}
|
||||
|
||||
// Input implements Stack. Several tunnels may hand over their packets at once
|
||||
func (s *stack) Input(b []byte) {
|
||||
s.input(b, 0)
|
||||
}
|
||||
|
||||
// input takes a packet that is b and rest bytes after it, in the bufs that follow the one that b is in
|
||||
func (s *stack) input(b []byte, rest int) {
|
||||
p, ok := parsePacket(b, rest)
|
||||
if !ok || p.src.Is4In6() || p.dst.Is4In6() || p.src.IsLoopback() || p.dst.IsLoopback() || p.dst.IsUnspecified() || p.src.IsMulticast() {
|
||||
// nothing comes from many at once, and an address that stands for this machine itself is not one
|
||||
// that the other side of a tun can ask for. Nor is an IPv6 address that stands for an IPv4 one, which
|
||||
// would be dialed as that: ::ffff:0.0.0.0 is this machine as well
|
||||
return
|
||||
}
|
||||
if s.verify && b[0]>>4 == 4 && checksum(sum(b[:int(b[0]&0xf)*4], 0)) != 0 {
|
||||
return
|
||||
}
|
||||
// what was put together may be of two packets with one number, its checksum tells
|
||||
verify := s.verify || p.fragment
|
||||
if p.rest != 0 && (verify || p.proto != protoTCP) {
|
||||
// only a segment of TCP that is not looked at can stay in pieces
|
||||
p.payload, p.rest = s.whole(p.payload, p.rest), 0
|
||||
}
|
||||
if p.fragment {
|
||||
p, ok = s.fragments.add(p)
|
||||
}
|
||||
if !ok || verify && !p.verified() {
|
||||
return
|
||||
}
|
||||
switch p.proto {
|
||||
case protoTCP:
|
||||
s.handleTCP(p)
|
||||
case protoUDP:
|
||||
s.handleUDP(p)
|
||||
case protoICMPv4, protoICMPv6:
|
||||
s.handleICMP(p)
|
||||
}
|
||||
}
|
||||
|
||||
// whole returns in one piece what is b and rest bytes after it, in the bufs that follow the one that b is in
|
||||
func (s *stack) whole(b []byte, rest int) []byte {
|
||||
if rest == 0 {
|
||||
return b
|
||||
}
|
||||
s.joined = append(s.joined[:0], b...)
|
||||
for i := 1; rest > 0; i++ {
|
||||
n := min(rest, buf.Size)
|
||||
s.joined = append(s.joined, s.bufs[i].BytesTo(int32(n))...)
|
||||
rest -= n
|
||||
}
|
||||
return s.joined
|
||||
}
|
||||
|
||||
// keep adds to mb what is b and rest bytes after it, in the bufs that follow the one that b is in: nothing is copied,
|
||||
// the buffers are taken for it and no longer read into
|
||||
func (s *stack) keep(mb buf.MultiBuffer, b []byte, rest int) buf.MultiBuffer {
|
||||
// b ends where what was read into the first one does, or before it
|
||||
first := s.bufs[0]
|
||||
from := first.Cap() - int32(cap(b))
|
||||
first.Resize(from, from+int32(len(b)))
|
||||
mb, s.bufs[0] = append(mb, first), nil
|
||||
for i := 1; rest > 0; i++ {
|
||||
n := min(rest, buf.Size)
|
||||
s.bufs[i].Resize(0, int32(n))
|
||||
mb, s.bufs[i] = append(mb, s.bufs[i]), nil
|
||||
rest -= n
|
||||
}
|
||||
return mb
|
||||
}
|
||||
|
||||
// local returns the address that packets to remote are sent from
|
||||
func (s *stack) local(remote netip.Addr) (netip.Addr, error) {
|
||||
for _, a := range s.addresses {
|
||||
if a.Is4() == remote.Is4() {
|
||||
return a, nil
|
||||
}
|
||||
}
|
||||
return netip.Addr{}, errors.New("no address to reach ", remote, " from")
|
||||
}
|
||||
|
||||
// ephemeral returns a port for what is opened from here: the first that free takes, from a random one on
|
||||
func ephemeral(free func(port uint16) bool) (uint16, bool) {
|
||||
start := rand.Uint32()
|
||||
for i := range uint32(1 << 15) {
|
||||
if port := uint16(1<<15 | (start+i)&(1<<15-1)); free(port) {
|
||||
return port, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
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:],
|
||||
rest: p.rest,
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
c := s.conns[f]
|
||||
s.mu.Unlock()
|
||||
if c != nil && c.input(seg) {
|
||||
return
|
||||
}
|
||||
if seg.flags&(tcpSyn|tcpAck|tcpRst) != tcpSyn || s.handle == nil {
|
||||
if seg.flags&tcpRst == 0 {
|
||||
s.refuse(f, seg)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if s.opening.Load() >= tcpOpening {
|
||||
return
|
||||
}
|
||||
c = newTCPConn(s, f)
|
||||
c.synchronize(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.sendSyn()
|
||||
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)+seg.rest)
|
||||
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
|
||||
}
|
||||
var socket *udpSocket
|
||||
if s.handle == nil {
|
||||
// only for a port that was opened from here
|
||||
s.mu.Lock()
|
||||
socket = s.sockets[netip.AddrPortFrom(p.dst, binary.BigEndian.Uint16(u[2:]))]
|
||||
s.mu.Unlock()
|
||||
if socket == nil {
|
||||
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)))
|
||||
if socket == nil {
|
||||
s.udp.HandlePacket(src, net.UDPDestination(net.IPAddress(p.dst.AsSlice()), net.Port(binary.BigEndian.Uint16(u[2:]))), b)
|
||||
} else if b.UDP = &src; !socket.queue.push(b) {
|
||||
b.Release()
|
||||
}
|
||||
}
|
||||
|
||||
// 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())
|
||||
return s.sendUDP(payload, netip.AddrPortFrom(srcIP, uint16(src.Port)), netip.AddrPortFrom(dstIP, uint16(dst.Port)))
|
||||
}
|
||||
|
||||
func (s *stack) sendUDP(payload []byte, src, dst netip.AddrPort) error {
|
||||
srcIP, dstIP := src.Addr().Unmap(), dst.Addr().Unmap()
|
||||
if !srcIP.IsValid() || srcIP.Is4() != dstIP.Is4() || len(payload) > math.MaxUint16-udpHeaderSize {
|
||||
return errors.New("failed to write udp packet of ", len(payload), " bytes from ", src, " to ", dst)
|
||||
}
|
||||
var b [ipv6HeaderSize + udpHeaderSize]byte
|
||||
n := putIPHeader(b[:], protoUDP, srcIP, dstIP)
|
||||
u := b[n : n+udpHeaderSize]
|
||||
binary.BigEndian.PutUint16(u, src.Port())
|
||||
binary.BigEndian.PutUint16(u[2:], dst.Port())
|
||||
binary.BigEndian.PutUint16(u[4:], uint16(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.write(b[:n+udpHeaderSize], payload)
|
||||
}
|
||||
|
||||
// write completes the IP header of a packet that is in two parts and writes it to the tun, in fragments if it is
|
||||
// larger than the MTU. A segment of a connection never is, and is not written by this
|
||||
func (s *stack) write(header, payload []byte) error {
|
||||
size, last := ipv6HeaderSize, 39
|
||||
if header[0]>>4 == 4 {
|
||||
size, last = ipv4HeaderSize, 19
|
||||
}
|
||||
// the group is chosen by the last bytes of the destination
|
||||
id := s.identification[(header[last]^header[last-1]<<3)%byte(len(s.identification))].Add(1)
|
||||
if header[0]>>4 == 4 {
|
||||
// a link on the way may split it as well, and what is put together there is told apart by its number
|
||||
binary.BigEndian.PutUint16(header[4:], uint16(id))
|
||||
}
|
||||
if len(header)+len(payload) > s.mtu {
|
||||
return writeFragments(s.tun, s.mtu, id, header, payload)
|
||||
}
|
||||
setIPLength(header[:size], len(header)+len(payload))
|
||||
return s.tun.WritePacket(header, payload)
|
||||
}
|
||||
|
||||
// DialUDP implements Stack
|
||||
func (s *stack) DialUDP() (net.PacketConn, error) {
|
||||
u := &udpSocket{stack: s, queue: newPacketQueue(udpQueueLimit)}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed {
|
||||
return nil, io.ErrClosedPipe
|
||||
}
|
||||
port, ok := ephemeral(func(port uint16) bool {
|
||||
for _, a := range s.addresses {
|
||||
if s.sockets[netip.AddrPortFrom(a, port)] != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
if !ok || len(s.addresses) == 0 {
|
||||
return nil, errors.New("no port left on ", s.addresses)
|
||||
}
|
||||
u.port = port
|
||||
for _, a := range s.addresses {
|
||||
s.sockets[netip.AddrPortFrom(a, port)] = u
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// udpSocket is a UDP port that was opened from here, on every address of the stack. It is not bound to one
|
||||
// other side: what anyone sends to it is read from it, with who sent it
|
||||
type udpSocket struct {
|
||||
stack *stack
|
||||
port uint16
|
||||
queue *packetQueue
|
||||
}
|
||||
|
||||
func (u *udpSocket) ReadFrom(p []byte) (int, net.Addr, error) {
|
||||
b, ok := u.queue.pop()
|
||||
if !ok {
|
||||
return 0, nil, gonet.ErrClosed
|
||||
}
|
||||
defer b.Release()
|
||||
return copy(p, b.Bytes()), b.UDP.RawNetAddr(), nil
|
||||
}
|
||||
|
||||
func (u *udpSocket) WriteTo(p []byte, addr net.Addr) (int, error) {
|
||||
to, ok := addr.(*net.UDPAddr)
|
||||
if !ok {
|
||||
return 0, errors.New("not a udp address: ", addr)
|
||||
}
|
||||
local, err := u.stack.local(to.AddrPort().Addr().Unmap())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err := u.stack.sendUDP(p, netip.AddrPortFrom(local, u.port), to.AddrPort()); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (u *udpSocket) Close() error {
|
||||
u.stack.mu.Lock()
|
||||
for _, a := range u.stack.addresses {
|
||||
if local := netip.AddrPortFrom(a, u.port); u.stack.sockets[local] == u {
|
||||
delete(u.stack.sockets, local)
|
||||
}
|
||||
}
|
||||
u.stack.mu.Unlock()
|
||||
u.queue.close()
|
||||
return nil
|
||||
}
|
||||
|
||||
// LocalAddr implements net.PacketConn with the first address of the stack
|
||||
func (u *udpSocket) LocalAddr() net.Addr {
|
||||
return gonet.UDPAddrFromAddrPort(netip.AddrPortFrom(u.stack.addresses[0], u.port))
|
||||
}
|
||||
|
||||
func (u *udpSocket) SetDeadline(time.Time) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *udpSocket) SetReadDeadline(time.Time) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *udpSocket) SetWriteDeadline(time.Time) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleICMP answers an echo request as its destination would, and takes the word that a packet of a connection
|
||||
// was too large for a link on its way or found no way at all
|
||||
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 {
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case p.proto == protoICMPv4 && m[0] == 3 && m[1] == 4:
|
||||
s.undelivered(m[8:], max(int(binary.BigEndian.Uint16(m[6:])), ipv4SmallestMTU))
|
||||
return
|
||||
case p.proto == protoICMPv6 && m[0] == 2:
|
||||
s.undelivered(m[8:], max(int(binary.BigEndian.Uint32(m[4:])), ipv6SmallestMTU))
|
||||
return
|
||||
case p.proto == protoICMPv4 && m[0] == 3, p.proto == protoICMPv6 && m[0] == 1:
|
||||
s.undelivered(m[8:], 0)
|
||||
return
|
||||
}
|
||||
if m[0] != request || m[1] != 0 || s.handle == nil && !slices.Contains(s.addresses, p.dst) {
|
||||
// a stack that takes no connections is one host, not all of them
|
||||
return
|
||||
}
|
||||
var b [ipv6HeaderSize]byte
|
||||
n := putIPHeader(b[:], p.proto, p.dst, p.src)
|
||||
// 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.write(b[:n], m)
|
||||
}
|
||||
|
||||
// undelivered takes the start of a packet that was sent from here and did not get to where it goes. If it did not fit
|
||||
// a link on its way, which takes packets of mtu bytes, the connection that sent it goes on with smaller segments.
|
||||
// Without an mtu there is no way at all, and a connection that is being opened is not waited for
|
||||
func (s *stack) undelivered(b []byte, mtu int) {
|
||||
var proto byte
|
||||
var local, remote netip.Addr
|
||||
switch {
|
||||
case len(b) >= ipv4HeaderSize && b[0]>>4 == 4:
|
||||
proto, local, remote = b[9], netip.AddrFrom4([4]byte(b[12:16])), netip.AddrFrom4([4]byte(b[16:20]))
|
||||
b = b[min(int(b[0]&0xf)*4, len(b)):]
|
||||
case len(b) >= ipv6HeaderSize && b[0]>>4 == 6:
|
||||
proto, local, remote = b[6], netip.AddrFrom16([16]byte(b[8:24])), netip.AddrFrom16([16]byte(b[24:40]))
|
||||
b = b[ipv6HeaderSize:]
|
||||
}
|
||||
// of the segment there are the ports and the sequence number at least
|
||||
if proto != protoTCP || len(b) < 8 {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
c := s.conns[flow{
|
||||
src: netip.AddrPortFrom(remote, binary.BigEndian.Uint16(b[2:])),
|
||||
dst: netip.AddrPortFrom(local, binary.BigEndian.Uint16(b)),
|
||||
}]
|
||||
s.mu.Unlock()
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
if seq := binary.BigEndian.Uint32(b[4:]); mtu != 0 {
|
||||
c.shrink(seq, mtu)
|
||||
} else {
|
||||
c.unreachable(seq)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
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
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user