mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-10-29 22:46:58 +00:00
Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bba0ae39d1 | ||
|
|
03ee3f872f | ||
|
|
65449d4f03 | ||
|
|
d5bfb0a5c7 | ||
|
|
afa28af4e0 | ||
|
|
ecd8719d98 | ||
|
|
74456ca5e9 | ||
|
|
b408f7f0c7 | ||
|
|
ef4f4888df | ||
|
|
c2a9b074f4 | ||
|
|
9726bbc9d7 | ||
|
|
6cd0c8a414 | ||
|
|
796bbd763a | ||
|
|
e04191e65b | ||
|
|
bd28a87f0b | ||
|
|
a04770587e | ||
|
|
eb9c6030ab | ||
|
|
e4124d3dbb | ||
|
|
4c0f3a94c5 | ||
|
|
19842ed0c2 | ||
|
|
34efc32ff0 | ||
|
|
4828ed8270 | ||
|
|
e84f3065dc | ||
|
|
fa9dc21a55 | ||
|
|
590a5236bb | ||
|
|
1aae252fc3 | ||
|
|
20c4c8f956 | ||
|
|
4c571f5e06 |
@@ -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
|
||||
|
||||
@@ -82,7 +82,7 @@ jobs:
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v4.7.0
|
||||
uses: docker/login-action@v4.6.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
|
||||
@@ -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}'))
|
||||
|
||||
@@ -35,7 +35,24 @@ jobs:
|
||||
if: steps.check-assets.outputs.missing == 'true'
|
||||
run: sleep 90
|
||||
|
||||
check-format-and-proto:
|
||||
check-proto:
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||
steps:
|
||||
- name: Checkout codebase
|
||||
uses: actions/checkout@v7
|
||||
- name: Check Proto Version Header
|
||||
run: |
|
||||
head -n 4 core/config.pb.go > ref.txt
|
||||
find . -name "*.pb.go" ! -name "*_grpc.pb.go" -print0 | while IFS= read -r -d '' file; do
|
||||
if ! cmp -s ref.txt <(head -n 4 "$file"); then
|
||||
echo "Error: Header mismatch in $file"
|
||||
head -n 4 "$file"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
check-format:
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||
permissions:
|
||||
@@ -51,8 +68,6 @@ jobs:
|
||||
cache: false
|
||||
- name: Check Format
|
||||
run: go run ./infra/vformat/main.go -mode check -pwd ./
|
||||
- name: Check Protobuf
|
||||
run: go run ./infra/vprotogen/main.go -mode check -pwd ./
|
||||
|
||||
test:
|
||||
needs: check-assets
|
||||
|
||||
@@ -128,7 +128,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 +138,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 +152,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,
|
||||
@@ -191,7 +191,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)
|
||||
|
||||
+60
-40
@@ -21,10 +21,7 @@ import (
|
||||
"golang.org/x/net/http2"
|
||||
)
|
||||
|
||||
const (
|
||||
idleTimeout = 30 * time.Second
|
||||
maxDownloadSize int64 = 256 * 1024 * 1024
|
||||
)
|
||||
const idleTimeout = 30 * time.Second
|
||||
|
||||
// DO NOT EDIT. Ignored by geodata, rejected by Lua.
|
||||
const luaGuardHeader = "\x12\x01\x00"
|
||||
@@ -36,6 +33,7 @@ type stage struct {
|
||||
|
||||
type downloader struct {
|
||||
ctx context.Context
|
||||
httpClient *http.Client
|
||||
httpsClient *http.Client
|
||||
}
|
||||
|
||||
@@ -63,11 +61,12 @@ func (c *idleConn) Write(b []byte) (int, error) {
|
||||
func newDownloader(ctx context.Context, dispatcher routing.Dispatcher, outbound string) *downloader {
|
||||
return &downloader{
|
||||
ctx: ctx,
|
||||
httpsClient: newClient(ctx, dispatcher, outbound),
|
||||
httpClient: newClient(ctx, dispatcher, outbound, false),
|
||||
httpsClient: newClient(ctx, dispatcher, outbound, true),
|
||||
}
|
||||
}
|
||||
|
||||
func newClient(baseCtx context.Context, dispatcher routing.Dispatcher, outbound string) *http.Client {
|
||||
func newClient(baseCtx context.Context, dispatcher routing.Dispatcher, outbound string, isHTTPS bool) *http.Client {
|
||||
dial := func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
var conn net.Conn
|
||||
err := task.Run(ctx, func() error {
|
||||
@@ -92,33 +91,53 @@ func newClient(baseCtx context.Context, dispatcher routing.Dispatcher, outbound
|
||||
Conn: conn,
|
||||
}, nil
|
||||
}
|
||||
return &http.Client{
|
||||
Transport: &http2.Transport{
|
||||
DialTLSContext: func(ctx context.Context, network string, address string, cfg *tls.Config) (net.Conn, error) {
|
||||
conn, err := dial(ctx, network, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
host, _, _ := net.SplitHostPort(address)
|
||||
tlsConn := utls.UClient(conn, &utls.Config{ServerName: host}, utls.HelloChrome_Auto)
|
||||
handshakeCtx, cancel := context.WithTimeout(ctx, idleTimeout)
|
||||
defer cancel()
|
||||
if err := tlsConn.HandshakeContext(handshakeCtx); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
return tlsConn, nil
|
||||
if isHTTPS {
|
||||
return &http.Client{
|
||||
Transport: &http2.Transport{
|
||||
DialTLSContext: func(ctx context.Context, network string, address string, cfg *tls.Config) (net.Conn, error) {
|
||||
conn, err := dial(ctx, network, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
host, _, _ := net.SplitHostPort(address)
|
||||
tlsConn := utls.UClient(conn, &utls.Config{ServerName: host}, utls.HelloChrome_Auto)
|
||||
handshakeCtx, cancel := context.WithTimeout(ctx, idleTimeout)
|
||||
defer cancel()
|
||||
if err := tlsConn.HandshakeContext(handshakeCtx); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
return tlsConn, nil
|
||||
},
|
||||
},
|
||||
},
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if req.URL.Scheme != "https" {
|
||||
return errors.New("redirected to non-https URL: ", req.URL.String())
|
||||
}
|
||||
if len(via) >= 20 {
|
||||
return errors.New("stopped after 20 redirects")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if req.URL.Scheme != "https" {
|
||||
return errors.New("redirected to non-https URL: ", req.URL.String())
|
||||
}
|
||||
if len(via) >= 10 {
|
||||
return errors.New("stopped after 10 redirects")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
} else {
|
||||
return &http.Client{
|
||||
Transport: &http.Transport{
|
||||
Proxy: nil,
|
||||
DisableKeepAlives: true,
|
||||
DialContext: dial,
|
||||
ResponseHeaderTimeout: idleTimeout,
|
||||
},
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if req.URL.Scheme != "https" {
|
||||
return errors.New("redirected to non-https URL: ", req.URL.String())
|
||||
}
|
||||
if len(via) >= 10 {
|
||||
return errors.New("stopped after 10 redirects")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,26 +203,27 @@ func (d *downloader) fetch(rawURL string, writer io.Writer) error {
|
||||
}
|
||||
utils.TryDefaultHeadersWith(req.Header, "nav")
|
||||
|
||||
resp, err := d.httpsClient.Do(req)
|
||||
var client *http.Client
|
||||
if req.URL.Scheme == "https" {
|
||||
client = d.httpsClient
|
||||
} else {
|
||||
client = d.httpClient
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
return errors.New("unexpected status code: ", resp.StatusCode)
|
||||
}
|
||||
if resp.ContentLength > maxDownloadSize {
|
||||
return errors.New("geodata download exceeds 256 MiB")
|
||||
}
|
||||
|
||||
n, err := io.Copy(writer, io.LimitReader(resp.Body, maxDownloadSize+1))
|
||||
n, err := io.Copy(writer, resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n > maxDownloadSize {
|
||||
return errors.New("geodata download exceeds 256 MiB")
|
||||
}
|
||||
if n == 0 {
|
||||
return errors.New("empty response body")
|
||||
}
|
||||
|
||||
@@ -7,13 +7,10 @@ import (
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
commongeodata "github.com/xtls/xray-core/common/geodata"
|
||||
xlua "github.com/xtls/xray-core/common/lua"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/core"
|
||||
"github.com/yuin/gopher-lua/parse"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
@@ -34,11 +31,11 @@ func TestDownloadOneLuaGuard(t *testing.T) {
|
||||
if err := os.WriteFile(filepath.Join(dir, "asset.lua"), nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(tc.body))
|
||||
}))
|
||||
defer server.Close()
|
||||
d := &downloader{ctx: context.Background(), httpsClient: server.Client()}
|
||||
d := &downloader{ctx: context.Background(), httpClient: server.Client()}
|
||||
staged, err := d.downloadOne(&Asset{Url: server.URL, File: "asset.lua"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -74,53 +71,3 @@ func TestDownloadOneLuaGuard(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtobufConfigValidation(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("xray.location.asset", dir)
|
||||
for _, name := range []string{"asset.dat", "asset.DAT"} {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := os.Mkdir(filepath.Join(dir, "directory.dat"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server, err := core.New(&core.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = server.Close() })
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
config *Config
|
||||
wantError string
|
||||
}{
|
||||
{"minutely cron", &Config{Cron: "* * * * *"}, ""},
|
||||
{"minimum interval", &Config{Cron: "@every 1m"}, ""},
|
||||
{"short interval", &Config{Cron: "@every 59s"}, "interval must be at least 1 minute"},
|
||||
{"fractional interval", &Config{Cron: "@every 59.999s"}, "interval must be at least 1 minute"},
|
||||
{"invalid cron", &Config{Cron: "invalid"}, "invalid geodata cron"},
|
||||
{"dat extension", &Config{Cron: "@daily", Assets: []*Asset{{Url: "https://example.com/asset.dat", File: "asset.dat"}}}, ""},
|
||||
{"uppercase extension", &Config{Cron: "@daily", Assets: []*Asset{{Url: "https://example.com/asset.dat", File: "asset.DAT"}}}, ""},
|
||||
{"invalid extension", &Config{Cron: "@daily", Assets: []*Asset{{Url: "https://example.com/asset.dat", File: "asset.lua"}}}, "extension must be .dat"},
|
||||
{"missing extension", &Config{Cron: "@daily", Assets: []*Asset{{Url: "https://example.com/asset.dat", File: "asset"}}}, "extension must be .dat"},
|
||||
{"missing file", &Config{Cron: "@daily", Assets: []*Asset{{Url: "https://example.com/asset.dat", File: "missing.dat"}}}, "invalid geodata asset file"},
|
||||
{"directory", &Config{Cron: "@daily", Assets: []*Asset{{Url: "https://example.com/asset.dat", File: "directory.dat"}}}, "asset is not a regular file"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
config, err := serial.ToTypedMessage(tc.config).GetInstance()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = core.CreateObject(server, config)
|
||||
if tc.wantError == "" {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else if err == nil || !strings.Contains(err.Error(), tc.wantError) {
|
||||
t.Fatalf("CreateObject() error = %v; want %q", err, tc.wantError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+3
-23
@@ -2,16 +2,12 @@ package geodata
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/robfig/cron/v3"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
commongeodata "github.com/xtls/xray-core/common/geodata"
|
||||
"github.com/xtls/xray-core/common/platform/filesystem"
|
||||
"github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
)
|
||||
@@ -29,24 +25,6 @@ func New(ctx context.Context, config *Config) (*Instance, error) {
|
||||
if config.Cron == "" {
|
||||
return &Instance{}, nil
|
||||
}
|
||||
if len(config.Assets) > 100 {
|
||||
return nil, errors.New("geodata supports at most 100 assets")
|
||||
}
|
||||
for _, asset := range config.Assets {
|
||||
if !strings.EqualFold(filepath.Ext(asset.GetFile()), ".dat") {
|
||||
return nil, errors.New("geodata asset file extension must be .dat")
|
||||
}
|
||||
if _, err := filesystem.ResolveAsset(asset.GetFile()); err != nil {
|
||||
return nil, errors.New("invalid geodata asset file: ", asset.GetFile()).Base(err)
|
||||
}
|
||||
}
|
||||
schedule, err := cron.ParseStandard(config.Cron)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid geodata cron").Base(err)
|
||||
}
|
||||
if interval, ok := schedule.(cron.ConstantDelaySchedule); ok && interval.Delay < time.Minute {
|
||||
return nil, errors.New("geodata cron interval must be at least 1 minute")
|
||||
}
|
||||
|
||||
g := &Instance{
|
||||
assets: config.Assets,
|
||||
@@ -66,7 +44,9 @@ func New(ctx context.Context, config *Config) (*Instance, error) {
|
||||
cron.WithChain(cron.SkipIfStillRunning(cron.DiscardLogger)),
|
||||
cron.WithLogger(cron.DiscardLogger),
|
||||
)
|
||||
g.tasker.Schedule(schedule, cron.FuncJob(g.execute))
|
||||
if _, err := g.tasker.AddFunc(config.Cron, g.execute); err != nil {
|
||||
return nil, errors.New("invalid geodata cron").Base(err)
|
||||
}
|
||||
errors.LogInfo(ctx, "scheduled geodata reload with cron: ", config.Cron)
|
||||
|
||||
return g, nil
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -152,23 +152,23 @@ func (x *HealthPingMeasurementResult) GetMin() int64 {
|
||||
type OutboundStatus struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
// @Document Whether this outbound is usable
|
||||
//@Restriction ReadOnlyForUser
|
||||
// @Restriction ReadOnlyForUser
|
||||
Alive bool `protobuf:"varint,1,opt,name=alive,proto3" json:"alive,omitempty"`
|
||||
// @Document The time for probe request to finish.
|
||||
//@Type time.ms
|
||||
//@Restriction ReadOnlyForUser
|
||||
// @Type time.ms
|
||||
// @Restriction ReadOnlyForUser
|
||||
Delay int64 `protobuf:"varint,2,opt,name=delay,proto3" json:"delay,omitempty"`
|
||||
// @Document The last error caused this outbound failed to relay probe request
|
||||
//@Restriction NotMachineReadable
|
||||
// @Restriction NotMachineReadable
|
||||
LastErrorReason string `protobuf:"bytes,3,opt,name=last_error_reason,json=lastErrorReason,proto3" json:"last_error_reason,omitempty"`
|
||||
// @Document The outbound tag for this Server
|
||||
//@Type id.outboundTag
|
||||
// @Type id.outboundTag
|
||||
OutboundTag string `protobuf:"bytes,4,opt,name=outbound_tag,json=outboundTag,proto3" json:"outbound_tag,omitempty"`
|
||||
// @Document The time this outbound is known to be alive
|
||||
//@Type id.outboundTag
|
||||
// @Type id.outboundTag
|
||||
LastSeenTime int64 `protobuf:"varint,5,opt,name=last_seen_time,json=lastSeenTime,proto3" json:"last_seen_time,omitempty"`
|
||||
// @Document The time this outbound is tried
|
||||
//@Type id.outboundTag
|
||||
// @Type id.outboundTag
|
||||
LastTryTime int64 `protobuf:"varint,6,opt,name=last_try_time,json=lastTryTime,proto3" json:"last_try_time,omitempty"`
|
||||
HealthPing *HealthPingMeasurementResult `protobuf:"bytes,7,opt,name=health_ping,json=healthPing,proto3" json:"health_ping,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
@@ -257,14 +257,14 @@ func (x *OutboundStatus) GetHealthPing() *HealthPingMeasurementResult {
|
||||
type ProbeResult struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
// @Document Whether this outbound is usable
|
||||
//@Restriction ReadOnlyForUser
|
||||
// @Restriction ReadOnlyForUser
|
||||
Alive bool `protobuf:"varint,1,opt,name=alive,proto3" json:"alive,omitempty"`
|
||||
// @Document The time for probe request to finish.
|
||||
//@Type time.ms
|
||||
//@Restriction ReadOnlyForUser
|
||||
// @Type time.ms
|
||||
// @Restriction ReadOnlyForUser
|
||||
Delay int64 `protobuf:"varint,2,opt,name=delay,proto3" json:"delay,omitempty"`
|
||||
// @Document The error caused this outbound failed to relay probe request
|
||||
//@Restriction NotMachineReadable
|
||||
// @Restriction NotMachineReadable
|
||||
LastErrorReason string `protobuf:"bytes,3,opt,name=last_error_reason,json=lastErrorReason,proto3" json:"last_error_reason,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
@@ -324,7 +324,7 @@ func (x *ProbeResult) GetLastErrorReason() string {
|
||||
type Intensity struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
// @Document The time interval for a probe request in ms.
|
||||
//@Type time.ms
|
||||
// @Type time.ms
|
||||
ProbeInterval uint32 `protobuf:"varint,1,opt,name=probe_interval,json=probeInterval,proto3" json:"probe_interval,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
|
||||
@@ -34,19 +34,18 @@ message RoutingContext {
|
||||
// opened by xray-core.
|
||||
// * FieldSelectors selects a subset of fields in routing statistics to return.
|
||||
// Valid selectors:
|
||||
// - inbound: Selects connection's inbound tag.
|
||||
// - network: Selects connection's network.
|
||||
// - ip: Equivalent as "ip_source" and "ip_target", selects both source and
|
||||
// target IP.
|
||||
// - port: Equivalent as "port_source" and "port_target", selects both source
|
||||
// and target port.
|
||||
// - domain: Selects target domain.
|
||||
// - protocol: Select connection's protocol.
|
||||
// - user: Select connection's inbound user email.
|
||||
// - attributes: Select connection's additional attributes.
|
||||
// - outbound: Equivalent as "outbound" and "outbound_group", select both
|
||||
// outbound tag and outbound group tags.
|
||||
//
|
||||
// - inbound: Selects connection's inbound tag.
|
||||
// - network: Selects connection's network.
|
||||
// - ip: Equivalent as "ip_source" and "ip_target", selects both source and
|
||||
// target IP.
|
||||
// - port: Equivalent as "port_source" and "port_target", selects both source
|
||||
// and target port.
|
||||
// - domain: Selects target domain.
|
||||
// - protocol: Select connection's protocol.
|
||||
// - user: Select connection's inbound user email.
|
||||
// - attributes: Select connection's additional attributes.
|
||||
// - outbound: Equivalent as "outbound" and "outbound_group", select both
|
||||
// outbound tag and outbound group tags.
|
||||
// * If FieldSelectors is left empty, all fields will be returned.
|
||||
message SubscribeRoutingStatsRequest {
|
||||
repeated string FieldSelectors = 1;
|
||||
|
||||
@@ -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)
|
||||
|
||||
+17
-59
@@ -8,65 +8,23 @@ import (
|
||||
|
||||
var privateIPMatcher = sync.OnceValue(func() IPMatcher {
|
||||
return common.Must2(IPReg.BuildIPMatcher(common.Must2(ParseIPRules([]string{
|
||||
// https://www.iana.org/assignments/iana-ipv4-special-registry
|
||||
"0.0.0.0/8", // "This network"
|
||||
"0.0.0.0/32", // "This host on this network"
|
||||
"10.0.0.0/8", // Private-Use
|
||||
"100.64.0.0/10", // Shared Address Space
|
||||
"127.0.0.0/8", // Loopback
|
||||
"169.254.0.0/16", // Link Local
|
||||
"172.16.0.0/12", // Private-Use
|
||||
// "192.0.0.0/24", // IETF Protocol Assignments
|
||||
"192.0.0.0/29", // IPv4 Service Continuity Prefix
|
||||
"192.0.0.8/32", // IPv4 dummy address
|
||||
"192.0.0.9/32", // Port Control Protocol Anycast
|
||||
"192.0.0.10/32", // Traversal Using Relays around NAT Anycast
|
||||
"192.0.0.170/32", // NAT64/DNS64 Discovery
|
||||
"192.0.0.171/32", // NAT64/DNS64 Discovery
|
||||
"192.0.2.0/24", // Documentation (TEST-NET-1)
|
||||
// "192.31.196.0/24", // AS112-v4
|
||||
"192.52.193.0/24", // AMT
|
||||
// "192.88.99.0/24", // Deprecated (6to4 Relay Anycast)
|
||||
"192.88.99.2/32", // 6a44-relay anycast address
|
||||
"192.168.0.0/16", // Private-Use
|
||||
// "192.175.48.0/24", // Direct Delegation AS112 Service
|
||||
"198.18.0.0/15", // Benchmarking
|
||||
"198.51.100.0/24", // Documentation (TEST-NET-2)
|
||||
"203.0.113.0/24", // Documentation (TEST-NET-3)
|
||||
"240.0.0.0/4", // Reserved
|
||||
"255.255.255.255/32", // Limited Broadcast
|
||||
|
||||
// https://www.iana.org/assignments/multicast-addresses
|
||||
"224.0.0.0/4",
|
||||
|
||||
// https://www.iana.org/assignments/iana-ipv6-special-registry
|
||||
"::1/128", // Loopback Address
|
||||
"::/128", // Unspecified Address
|
||||
// "::ffff:0:0/96", // IPv4-mapped Address
|
||||
"64:ff9b::/96", // IPv4-IPv6 Translat.
|
||||
"64:ff9b:1::/48", // IPv4-IPv6 Translat.
|
||||
"100::/64", // Discard-Only Address Block
|
||||
"100:0:0:1::/64", // Dummy IPv6 Prefix
|
||||
// "2001::/23", // IETF Protocol Assignments
|
||||
"2001::/32", // TEREDO
|
||||
"2001:1::1/128", // Port Control Protocol Anycast
|
||||
"2001:1::2/128", // Traversal Using Relays around NAT Anycast
|
||||
"2001:1::3/128", // DNS-SD Service Registration Protocol Anycast
|
||||
"2001:2::/48", // Benchmarking
|
||||
"2001:3::/32", // AMT
|
||||
// "2001:4:112::/48", // AS112-v6
|
||||
// "2001:10::/28", // Deprecated (previously ORCHID)
|
||||
"2001:20::/28", // ORCHIDv2
|
||||
"2001:30::/28", // Drone Remote ID Protocol Entity Tags (DETs) Prefix
|
||||
"2001:db8::/32", // Documentation
|
||||
"2002::/16", // 6to4
|
||||
// "2620:4f:8000::/48", // Direct Delegation AS112 Service
|
||||
"3fff::/20", // Documentation
|
||||
"5f00::/16", // Segment Routing (SRv6) SIDs
|
||||
"fc00::/7", // Unique-Local
|
||||
"fe80::/10", // Link-Local Unicast
|
||||
|
||||
// https://www.iana.org/assignments/ipv6-multicast-addresses
|
||||
"0.0.0.0/8",
|
||||
"10.0.0.0/8",
|
||||
"100.64.0.0/10",
|
||||
"127.0.0.0/8",
|
||||
"169.254.0.0/16",
|
||||
"172.16.0.0/12",
|
||||
"192.0.0.0/24",
|
||||
"192.0.2.0/24",
|
||||
"192.88.99.0/24",
|
||||
"192.168.0.0/16",
|
||||
"198.18.0.0/15",
|
||||
"198.51.100.0/24",
|
||||
"203.0.113.0/24",
|
||||
"224.0.0.0/3",
|
||||
"::/127",
|
||||
"fc00::/7",
|
||||
"fe80::/10",
|
||||
"ff00::/8",
|
||||
}))))
|
||||
})
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
|
||||
"github.com/xtls/xray-core/common/base64"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/platform/filesystem"
|
||||
"github.com/xtls/xray-core/common/platform"
|
||||
glua "github.com/yuin/gopher-lua"
|
||||
"github.com/yuin/gopher-lua/parse"
|
||||
)
|
||||
@@ -36,7 +36,7 @@ func Compile(script string) (*Program, error) {
|
||||
// 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 = filesystem.ResolveLuaFile(script); err == nil {
|
||||
} 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 {
|
||||
|
||||
@@ -187,20 +187,19 @@ func TestCompileInlineDiagnostics(t *testing.T) {
|
||||
*/
|
||||
|
||||
func TestCompileFileExtension(t *testing.T) {
|
||||
for _, name := range []string{"script", "script.dat", "script.lua.txt"} {
|
||||
if program, err := Compile(name); program != nil || err == nil || !strings.Contains(err.Error(), "Lua file extension must be .lua") {
|
||||
t.Fatalf("Compile(%q) = %v, %v; want nil program and .lua extension error", name, program, err)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"script.lua", "script.LUA", "script.Lua", "script.lUa"} {
|
||||
for _, name := range []string{"script", "script.dat", "script.lua.txt", "script.LUA"} {
|
||||
path := filepath.Join(t.TempDir(), name)
|
||||
if err := os.WriteFile(path, []byte("value = 42"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if program, err := Compile(path); program == nil || err != nil {
|
||||
t.Fatalf("Compile(%q) = %v, %v; want successful compilation", path, program, err)
|
||||
if program, err := Compile(path); program != nil || err == nil || !strings.Contains(err.Error(), "Lua file extension must be .lua") {
|
||||
t.Fatalf("Compile(%q) = %v, %v; want nil program and .lua extension error", path, program, err)
|
||||
}
|
||||
}
|
||||
path := writeTestScript(t, "value = 42") + string(filepath.Separator) + "."
|
||||
if program, err := Compile(path); program == nil || err != nil {
|
||||
t.Fatalf("Compile(%q) = %v, %v; want acceptance of the resolved .lua path", path, program, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompileRejectsReadFailure(t *testing.T) {
|
||||
@@ -235,6 +234,10 @@ func writeTestScript(t *testing.T, code string) string {
|
||||
if err := os.WriteFile(path, []byte(code), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path, err := filepath.EvalSymlinks(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ package net
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
@@ -26,38 +26,36 @@ 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.")
|
||||
}
|
||||
|
||||
targetHexAddr := formatProcNetAddress(net.ParseIP(srcIP), Port(srcPort))
|
||||
|
||||
portFallback := ""
|
||||
if network == "udp" {
|
||||
portFallback = fmt.Sprintf(":%04X", srcPort)
|
||||
targetHexAddr, err := formatLittleEndianString(net.ParseIP(srcIP), Port(srcPort))
|
||||
if err != nil {
|
||||
return 0, "", "", errors.New("failed to format address: ", err)
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -84,60 +82,51 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
|
||||
return pid, procName, absPath, nil
|
||||
}
|
||||
|
||||
func formatProcNetAddress(addr net.IP, port Port) string {
|
||||
func formatLittleEndianString(addr net.IP, port Port) (string, error) {
|
||||
ip := addr
|
||||
var ipBytes []byte
|
||||
if ipv4 := addr.To4(); ipv4 != nil {
|
||||
ipBytes = ipv4
|
||||
if ip.To4() != nil {
|
||||
ipBytes = ip.To4()
|
||||
} else {
|
||||
ipBytes = addr.To16()
|
||||
ipBytes = ip.To16()
|
||||
}
|
||||
if ipBytes == nil {
|
||||
return "", errors.New("invalid IP format for ", addr, ": ", ip)
|
||||
}
|
||||
|
||||
var formatted strings.Builder
|
||||
formatted.Grow(len(ipBytes)*2 + 5)
|
||||
for i := 0; i < len(ipBytes); i += 4 {
|
||||
fmt.Fprintf(&formatted, "%08X", binary.NativeEndian.Uint32(ipBytes[i:i+4]))
|
||||
for i, j := 0, len(ipBytes)-1; i < j; i, j = i+1, j-1 {
|
||||
ipBytes[i], ipBytes[j] = ipBytes[j], ipBytes[i]
|
||||
}
|
||||
fmt.Fprintf(&formatted, ":%04X", uint16(port))
|
||||
return formatted.String()
|
||||
portHex := fmt.Sprintf("%04X", uint16(port))
|
||||
ipHex := strings.ToUpper(hex.EncodeToString(ipBytes))
|
||||
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) {
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/platform"
|
||||
@@ -27,6 +26,14 @@ func ReadFile(path string) ([]byte, error) {
|
||||
return buf.ReadAllToBytes(reader)
|
||||
}
|
||||
|
||||
func ReadAsset(file string) ([]byte, error) {
|
||||
path, _, err := getAssetFileLocation(file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ReadFile(path)
|
||||
}
|
||||
|
||||
func OpenAsset(file string) (io.ReadCloser, int64, error) {
|
||||
path, info, err := getAssetFileLocation(file)
|
||||
if err != nil {
|
||||
@@ -36,6 +43,11 @@ func OpenAsset(file string) (io.ReadCloser, int64, error) {
|
||||
return r, info.Size(), err
|
||||
}
|
||||
|
||||
func StatAsset(file string) (os.FileInfo, error) {
|
||||
_, info, err := getAssetFileLocation(file)
|
||||
return info, err
|
||||
}
|
||||
|
||||
func ResolveAsset(file string) (string, error) {
|
||||
path, _, err := getAssetFileLocation(file)
|
||||
return path, err
|
||||
@@ -67,29 +79,17 @@ func ReadCert(file string) ([]byte, error) {
|
||||
return ReadFile(platform.GetCertLocation(file))
|
||||
}
|
||||
|
||||
// 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 !strings.EqualFold(filepath.Ext(path), ".lua") {
|
||||
return "", errors.New("Lua file extension must be .lua")
|
||||
func CopyFile(dst string, src string) error {
|
||||
bytes, err := ReadFile(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if filepath.IsAbs(path) {
|
||||
return path, nil
|
||||
f, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, dir := range []string{
|
||||
platform.GetConfDirPath(),
|
||||
platform.NewEnvFlag(platform.ConfigLocation).GetValue(func() string { return "" }),
|
||||
".",
|
||||
platform.GetExecutableDir(),
|
||||
} {
|
||||
if dir != "" {
|
||||
resolved := filepath.Join(dir, path)
|
||||
if _, err := os.Stat(resolved); err == nil {
|
||||
return filepath.Abs(resolved)
|
||||
} else if !os.IsNotExist(err) {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", os.ErrNotExist
|
||||
defer f.Close()
|
||||
|
||||
_, err = f.Write(bytes)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
package filesystem_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/platform"
|
||||
. "github.com/xtls/xray-core/common/platform/filesystem"
|
||||
)
|
||||
|
||||
func TestResolveAssetRejectsInvalidPath(t *testing.T) {
|
||||
func TestStatAssetRejectsInvalidPath(t *testing.T) {
|
||||
for _, file := range []string{
|
||||
"",
|
||||
".",
|
||||
@@ -29,49 +25,8 @@ func TestResolveAssetRejectsInvalidPath(t *testing.T) {
|
||||
`nested\..\geoip.dat`,
|
||||
filepath.Join(t.TempDir(), "geoip.dat"),
|
||||
} {
|
||||
if _, err := ResolveAsset(file); err == nil {
|
||||
if _, err := StatAsset(file); err == nil {
|
||||
t.Fatalf("expected error for %q", file)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveLuaFile(t *testing.T) {
|
||||
t.Chdir(t.TempDir())
|
||||
workingDir, err := os.Getwd()
|
||||
common.Must(err)
|
||||
executable, err := os.Executable()
|
||||
common.Must(err)
|
||||
file, err := os.CreateTemp(filepath.Dir(executable), "lua-*.lua")
|
||||
common.Must(err)
|
||||
common.Must(file.Close())
|
||||
defer os.Remove(file.Name())
|
||||
|
||||
name := filepath.Base(file.Name())
|
||||
paths := []string{
|
||||
filepath.Join(t.TempDir(), name),
|
||||
filepath.Join(t.TempDir(), name),
|
||||
filepath.Join(workingDir, name),
|
||||
file.Name(),
|
||||
}
|
||||
t.Setenv(platform.ConfdirLocation, filepath.Dir(paths[0]))
|
||||
t.Setenv(platform.ConfigLocation, filepath.Dir(paths[1]))
|
||||
for _, path := range paths[:3] {
|
||||
common.Must(os.WriteFile(path, nil, 0o600))
|
||||
}
|
||||
if got, err := ResolveLuaFile(paths[2]); err != nil || got != paths[2] {
|
||||
t.Fatalf("absolute path = %q, %v; want %q", got, err, paths[2])
|
||||
}
|
||||
for i, want := range paths {
|
||||
if i == 2 {
|
||||
t.Setenv(platform.ConfdirLocation, "")
|
||||
t.Setenv(platform.ConfigLocation, "")
|
||||
}
|
||||
if got, err := ResolveLuaFile(name); err != nil || got != want {
|
||||
t.Fatalf("resolved path = %q, %v; want %q", got, err, want)
|
||||
}
|
||||
common.Must(os.Remove(want))
|
||||
}
|
||||
if _, err := ResolveLuaFile(name); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("missing file error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ func LineSeparator() string {
|
||||
|
||||
// GetAssetLocation searches for `file` in the env dir, the executable dir, and certain locations
|
||||
func GetAssetLocation(file string) string {
|
||||
assetPath := NewEnvFlag(AssetLocation).GetValue(GetExecutableDir)
|
||||
assetPath := NewEnvFlag(AssetLocation).GetValue(getExecutableDir)
|
||||
defPath := filepath.Join(assetPath, file)
|
||||
for _, p := range []string{
|
||||
defPath,
|
||||
@@ -36,6 +36,6 @@ func GetAssetLocation(file string) string {
|
||||
|
||||
// GetCertLocation searches for `file` in the env dir and the executable dir
|
||||
func GetCertLocation(file string) string {
|
||||
certPath := NewEnvFlag(CertLocation).GetValue(GetExecutableDir)
|
||||
certPath := NewEnvFlag(CertLocation).GetValue(getExecutableDir)
|
||||
return filepath.Join(certPath, file)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package platform // import "github.com/xtls/xray-core/common/platform"
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
@@ -72,7 +74,7 @@ func NormalizeEnvName(name string) string {
|
||||
return strings.ReplaceAll(strings.ToUpper(strings.TrimSpace(name)), ".", "_")
|
||||
}
|
||||
|
||||
func GetExecutableDir() string {
|
||||
func getExecutableDir() string {
|
||||
exec, err := os.Executable()
|
||||
if err != nil {
|
||||
return ""
|
||||
@@ -81,7 +83,7 @@ func GetExecutableDir() string {
|
||||
}
|
||||
|
||||
func GetConfigurationPath() string {
|
||||
configPath := NewEnvFlag(ConfigLocation).GetValue(GetExecutableDir)
|
||||
configPath := NewEnvFlag(ConfigLocation).GetValue(getExecutableDir)
|
||||
return filepath.Join(configPath, "config.json")
|
||||
}
|
||||
|
||||
@@ -90,3 +92,64 @@ func GetConfDirPath() string {
|
||||
configPath := NewEnvFlag(ConfdirLocation).GetValue(func() string { return "" })
|
||||
return configPath
|
||||
}
|
||||
|
||||
// ResolveLuaFile finds a local .lua script and returns its resolved absolute path.
|
||||
// Relative paths: XRAY_LOCATION_CONFDIR > XRAY_LOCATION_CONFIG > working dir > executable dir.
|
||||
func ResolveLuaFile(path string) (string, error) {
|
||||
if path == "" {
|
||||
return "", errors.New("Lua file path is empty")
|
||||
}
|
||||
paths := []string{path}
|
||||
if !filepath.IsAbs(path) {
|
||||
paths = nil
|
||||
for _, dir := range []string{
|
||||
GetConfDirPath(),
|
||||
NewEnvFlag(ConfigLocation).GetValue(func() string { return "" }),
|
||||
".",
|
||||
getExecutableDir(),
|
||||
} {
|
||||
if dir != "" {
|
||||
paths = append(paths, filepath.Join(dir, path))
|
||||
}
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
func resolveFile(paths []string) (string, error) {
|
||||
var tried []string
|
||||
for _, path := range paths {
|
||||
path, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to resolve file path: %w", err)
|
||||
}
|
||||
tried = append(tried, path)
|
||||
info, err := os.Stat(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to inspect file %q: %w", path, err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return "", fmt.Errorf("file is not a regular file: %s", path)
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
return "", fmt.Errorf("file not found; tried %q: %w", tried, os.ErrNotExist)
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package platform_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
@@ -64,3 +66,89 @@ func TestGetAssetLocation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveLuaFile(t *testing.T) {
|
||||
workingDir := t.TempDir()
|
||||
t.Chdir(workingDir)
|
||||
executable, err := os.Executable()
|
||||
common.Must(err)
|
||||
file, err := os.CreateTemp(filepath.Dir(executable), "lua-*.lua")
|
||||
common.Must(err)
|
||||
common.Must(file.Close())
|
||||
defer os.Remove(file.Name())
|
||||
|
||||
name := filepath.Base(file.Name())
|
||||
paths := []string{
|
||||
filepath.Join(t.TempDir(), name),
|
||||
filepath.Join(t.TempDir(), name),
|
||||
filepath.Join(workingDir, name),
|
||||
file.Name(),
|
||||
}
|
||||
t.Setenv(ConfdirLocation, filepath.Dir(paths[0]))
|
||||
t.Setenv(ConfigLocation, filepath.Dir(paths[1]))
|
||||
for _, path := range paths[:3] {
|
||||
common.Must(os.WriteFile(path, nil, 0o600))
|
||||
}
|
||||
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])
|
||||
}
|
||||
for i, want := range paths {
|
||||
if i == 2 {
|
||||
t.Setenv(ConfdirLocation, "")
|
||||
t.Setenv(ConfigLocation, "")
|
||||
}
|
||||
if got, err := ResolveLuaFile(name); err != nil || got != want {
|
||||
t.Fatalf("resolved path = %q, %v; want %q", got, err, want)
|
||||
}
|
||||
common.Must(os.Remove(want))
|
||||
}
|
||||
if _, err := ResolveLuaFile(name); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("missing file error = %v", err)
|
||||
}
|
||||
|
||||
t.Setenv(ConfdirLocation, filepath.Dir(paths[0]))
|
||||
t.Setenv(ConfigLocation, filepath.Dir(paths[1]))
|
||||
common.Must(os.Mkdir(paths[0], 0o700))
|
||||
common.Must(os.WriteFile(paths[1], nil, 0o600))
|
||||
for _, path := range []string{"", name, filepath.Join(t.TempDir(), name)} {
|
||||
if _, err := ResolveLuaFile(path); err == nil {
|
||||
t.Fatalf("accepted invalid path %q", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,12 +11,12 @@ func LineSeparator() string {
|
||||
|
||||
// GetAssetLocation searches for `file` in the env dir and the executable dir
|
||||
func GetAssetLocation(file string) string {
|
||||
assetPath := NewEnvFlag(AssetLocation).GetValue(GetExecutableDir)
|
||||
assetPath := NewEnvFlag(AssetLocation).GetValue(getExecutableDir)
|
||||
return filepath.Join(assetPath, file)
|
||||
}
|
||||
|
||||
// GetCertLocation searches for `file` in the env dir and the executable dir
|
||||
func GetCertLocation(file string) string {
|
||||
certPath := NewEnvFlag(CertLocation).GetValue(GetExecutableDir)
|
||||
certPath := NewEnvFlag(CertLocation).GetValue(getExecutableDir)
|
||||
return filepath.Join(certPath, file)
|
||||
}
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ import (
|
||||
var (
|
||||
Version_x byte = 26
|
||||
Version_y byte = 10
|
||||
Version_z byte = 29
|
||||
Version_z byte = 10
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
package core
|
||||
|
||||
//go:generate go install -v google.golang.org/protobuf/cmd/protoc-gen-go@latest
|
||||
//go:generate go install -v google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
|
||||
//go:generate go run ../infra/vprotogen/main.go -pwd ./..
|
||||
|
||||
@@ -2,7 +2,6 @@ package localdns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/netip"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -101,15 +100,6 @@ func New() *Client {
|
||||
if internet.IsSkippedDNSServer(address) {
|
||||
return nil, errors.New("skipped DNS server ", address)
|
||||
}
|
||||
// A socket of the server's IP version only needs that version bound
|
||||
// to the interface, which a dual-stack one would need both of.
|
||||
if ap, err := netip.ParseAddrPort(address); err == nil && (network == "udp" || network == "tcp") {
|
||||
if ap.Addr().Unmap().Is4() {
|
||||
network += "4"
|
||||
} else {
|
||||
network += "6"
|
||||
}
|
||||
}
|
||||
return d.DialContext(ctx, network, address)
|
||||
},
|
||||
}
|
||||
|
||||
@@ -4,36 +4,37 @@ go 1.27
|
||||
|
||||
require (
|
||||
github.com/apernet/quic-go v0.61.1-0.20260806010916-184d081eef3e
|
||||
github.com/bufbuild/protocompile v0.14.1
|
||||
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
|
||||
github.com/pion/stun/v3 v3.1.7
|
||||
github.com/pires/go-proxyproto v0.16.0
|
||||
github.com/pires/go-proxyproto v0.15.0
|
||||
github.com/refraction-networking/utls v1.8.3-0.20260301010127-aa6edf4b11af
|
||||
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/crypto/x509roots/fallback v0.0.0-20261005185213-c3db4df58582
|
||||
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.60.0
|
||||
golang.org/x/sync v0.23.0
|
||||
golang.org/x/sys v0.48.0
|
||||
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2
|
||||
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.11
|
||||
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
|
||||
@@ -41,12 +42,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
|
||||
@@ -56,15 +58,9 @@ 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/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
|
||||
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.6.0 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gvisor.dev/gvisor v0.0.0-20260122175437-89a5d21be8f0 // indirect
|
||||
)
|
||||
|
||||
tool (
|
||||
google.golang.org/grpc/cmd/protoc-gen-go-grpc
|
||||
google.golang.org/protobuf/cmd/protoc-gen-go
|
||||
)
|
||||
|
||||
@@ -1,12 +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/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw=
|
||||
github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c=
|
||||
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=
|
||||
@@ -33,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=
|
||||
@@ -61,8 +61,8 @@ github.com/pion/stun/v3 v3.1.7 h1:uRXMTlGLf89WgItGNyZ6aR5jMTX0NBbybXADpQCzn+E=
|
||||
github.com/pion/stun/v3 v3.1.7/go.mod h1:Nq77RW4aRrSNrltf2ksUJLjxWeipj4lnlgdsYIxC8g8=
|
||||
github.com/pion/transport/v4 v4.1.0 h1:8S+nF2reM2cJuqC6g78OVy2BBgmbdns+acx3jA97BvQ=
|
||||
github.com/pion/transport/v4 v4.1.0/go.mod h1:06hFI+jCFcok2X2MekVufNZ/uzNZXivGBPfviSVcjgM=
|
||||
github.com/pires/go-proxyproto v0.16.0 h1:9KYT/fM3wpjT8bdMEj/7FBcoiUG1KyzEjRYnPu+vz7A=
|
||||
github.com/pires/go-proxyproto v0.16.0/go.mod h1:n7yhg8yIfNl3KgYDCwBzmeUHNpKTVnUhcWpc7rV4RW4=
|
||||
github.com/pires/go-proxyproto v0.15.0 h1:dTshmNbFm/D+0+sbrxUuddPOZ5Y0B7c5NhtsBkm6LqI=
|
||||
github.com/pires/go-proxyproto v0.15.0/go.mod h1:OXsCrKwrK2tXS9YrI5tkHx5xaQlO8FH3lFW76orFh24=
|
||||
github.com/quic-go/go-ossfuzz-seeds v0.1.0 h1:APacT+iIaNF6fd8AGEiN3bT/Jtkd2jz4v4TzM7MFjy0=
|
||||
github.com/quic-go/go-ossfuzz-seeds v0.1.0/go.mod h1:3IOHRbJIc+L6YKMwfDtJAM9Vj9k0YY4muhuyUYk5tbk=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
@@ -81,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=
|
||||
@@ -97,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=
|
||||
@@ -109,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.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
|
||||
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.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=
|
||||
@@ -123,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=
|
||||
@@ -154,10 +152,6 @@ google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 h1:
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.84.0 h1:soMyaPJ8pAak5PIQ0DGBUir0XRo2fRoMqhNWMLlLxO0=
|
||||
google.golang.org/grpc v1.84.0/go.mod h1:ljCht0DrxQrXBDRTZp52Qxh3Ffk8CdYm2sj4O2QN2C0=
|
||||
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.6.0 h1:6Al3kEFFP9VJhRz3DID6quisgPnTeZVr4lep9kkxdPA=
|
||||
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.6.0/go.mod h1:QLvsjh0OIR0TYBeiu2bkWGTJBUNQ64st52iWj/yA93I=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
|
||||
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
|
||||
@@ -91,7 +91,6 @@ func (c *FreedomConfig) Build() (proto.Message, error) {
|
||||
}
|
||||
|
||||
if c.Fragment != nil {
|
||||
errors.PrintDeprecatedFeatureWarning(`"fragment" in Freedom`, `"fragment" in "streamSettings.finalmask.tcp"`)
|
||||
config.Fragment = new(freedom.Fragment)
|
||||
|
||||
switch strings.ToLower(c.Fragment.Packets) {
|
||||
@@ -148,7 +147,6 @@ func (c *FreedomConfig) Build() (proto.Message, error) {
|
||||
}
|
||||
|
||||
if c.Noises != nil {
|
||||
errors.PrintDeprecatedFeatureWarning(`"noises" in Freedom`, `"noise" in "streamSettings.finalmask.udp"`)
|
||||
for _, n := range c.Noises {
|
||||
NConfig, err := ParseNoise(n)
|
||||
if err != nil {
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"github.com/robfig/cron/v3"
|
||||
"github.com/xtls/xray-core/app/geodata"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/platform/filesystem"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
@@ -18,6 +19,9 @@ func (c *GeodataAssetConfig) Build() (*geodata.Asset, error) {
|
||||
if err := validateHTTPS(c.URL); err != nil {
|
||||
return nil, errors.New("invalid geodata asset url: ", c.URL).Base(err)
|
||||
}
|
||||
if _, err := filesystem.StatAsset(c.File); err != nil {
|
||||
return nil, errors.New("invalid geodata asset file: ", c.File).Base(err)
|
||||
}
|
||||
return &geodata.Asset{
|
||||
Url: c.URL,
|
||||
File: c.File,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package conf_test
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/app/geodata"
|
||||
@@ -8,6 +9,8 @@ import (
|
||||
)
|
||||
|
||||
func TestGeodataConfig(t *testing.T) {
|
||||
t.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
||||
|
||||
creator := func() Buildable {
|
||||
return new(GeodataConfig)
|
||||
}
|
||||
@@ -35,7 +38,27 @@ func TestGeodataConfig(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestGeodataAssetConfig(t *testing.T) {
|
||||
t.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
||||
|
||||
if _, err := (&GeodataAssetConfig{
|
||||
URL: "https://example.com/geoip.dat",
|
||||
File: "geoip.dat",
|
||||
}).Build(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := (&GeodataAssetConfig{
|
||||
URL: "https://example.com/geoip.dat",
|
||||
File: "missing.dat",
|
||||
}).Build(); err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeodataAssetConfigInvalidURL(t *testing.T) {
|
||||
t.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
||||
|
||||
for _, rawURL := range []string{
|
||||
"",
|
||||
"http://example.com/geoip.dat",
|
||||
|
||||
@@ -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, `"`)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -997,18 +997,6 @@ type XDriveConfig struct {
|
||||
EagerWindowMs uint32 `json:"eagerWindowMs"`
|
||||
HoleTimeoutMs uint32 `json:"holeTimeoutMs"`
|
||||
Template json.RawMessage `json:"template"`
|
||||
S3 *XDriveS3Config `json:"s3"`
|
||||
Xmux XmuxConfig `json:"xmux"`
|
||||
|
||||
// set by StreamConfig when "alpn" is ["h3"]
|
||||
h3 bool
|
||||
}
|
||||
|
||||
type XDriveS3Config struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
Region string `json:"region"`
|
||||
Bucket string `json:"bucket"`
|
||||
PathStyle *bool `json:"pathStyle"`
|
||||
}
|
||||
|
||||
// Build implements Buildable.
|
||||
@@ -1016,10 +1004,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")
|
||||
}
|
||||
@@ -1027,27 +1011,8 @@ func (c *XDriveConfig) Build() (proto.Message, error) {
|
||||
if len(c.Template) == 0 {
|
||||
return nil, errors.New(`service "template" needs a "template" object`)
|
||||
}
|
||||
case "s3":
|
||||
if c.S3 == nil {
|
||||
return nil, errors.New(`service "s3" needs an "s3" object`)
|
||||
}
|
||||
default:
|
||||
return nil, errors.New(`unknown "service": "`, c.Service, `", use "google-drive", "template", "s3" 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,
|
||||
@@ -1062,25 +1027,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,
|
||||
},
|
||||
}
|
||||
if c.Service == "s3" {
|
||||
config.S3 = &xdrive.S3Config{
|
||||
Endpoint: c.S3.Endpoint,
|
||||
Region: c.S3.Region,
|
||||
Bucket: c.S3.Bucket,
|
||||
PathStyle: c.S3.PathStyle == nil || *c.S3.PathStyle,
|
||||
}
|
||||
if err := xdrive.ValidateS3Config(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
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", "s3" 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")
|
||||
}
|
||||
}
|
||||
|
||||
+15
-10
@@ -6,7 +6,9 @@ import (
|
||||
"math/big"
|
||||
"net"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/proxy/tun"
|
||||
@@ -37,22 +39,25 @@ func (v *TunConfig) Build() (proto.Message, error) {
|
||||
AutoSystemRoutingTable: v.AutoSystemRoutingTable,
|
||||
AutoSystemDnsToGateway: v.AutoSystemDnsToGateway,
|
||||
}
|
||||
leaks, err := tun.ExpandWfpBlockLeak(v.AutoSystemWfpBlockLeak)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
for _, leak := range v.AutoSystemWfpBlockLeak {
|
||||
switch leak := strings.ToLower(leak); leak {
|
||||
case "dns", "misconfigtun":
|
||||
config.AutoSystemWfpBlockLeak = append(config.AutoSystemWfpBlockLeak, leak)
|
||||
default:
|
||||
return nil, errors.New("unknown autoSystemWfpBlockLeak value: ", leak)
|
||||
}
|
||||
}
|
||||
config.AutoSystemWfpBlockLeak = leaks
|
||||
// Each option needs other settings on the system it takes effect on: the
|
||||
// filters go along with the routes of autoSystemRoutingTable, keeping the
|
||||
// system's DNS inside the TUN needs DNS servers on it, and
|
||||
// autoSystemDnsToGateway points the system DNS at the gateway.
|
||||
// filters go along with the routes of autoSystemRoutingTable, "dns" lets
|
||||
// DNS through the TUN only, and autoSystemDnsToGateway points the system
|
||||
// DNS at the gateway.
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
if len(leaks) > 0 && len(v.AutoSystemRoutingTable) == 0 {
|
||||
if len(config.AutoSystemWfpBlockLeak) > 0 && len(v.AutoSystemRoutingTable) == 0 {
|
||||
return nil, errors.New("autoSystemWfpBlockLeak needs autoSystemRoutingTable to be set")
|
||||
}
|
||||
if tun.BlocksSystemDNS(leaks) && len(v.DNS) == 0 {
|
||||
return nil, errors.New(`autoSystemWfpBlockLeak "dns", "udp/53", "tcp/53" or "windnsclient" needs dns to be set`)
|
||||
if slices.Contains(config.AutoSystemWfpBlockLeak, "dns") && len(v.DNS) == 0 {
|
||||
return nil, errors.New(`autoSystemWfpBlockLeak "dns" needs dns to be set`)
|
||||
}
|
||||
case "linux", "freebsd":
|
||||
if v.AutoSystemDnsToGateway && len(v.Gateway) == 0 {
|
||||
|
||||
+8
-18
@@ -29,17 +29,12 @@ func TestTunConfigAutoSystem(t *testing.T) {
|
||||
{
|
||||
Input: `{"name": "xray0", "dns": ["1.1.1.1"], "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["dns", "misconfigtun"]}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &tun.Config{Name: "xray0", Desc: "Wintun", MTU: 1500, DNS: []string{"1.1.1.1"}, AutoSystemRoutingTable: []string{"0.0.0.0/0"}, AutoOutboundsInterface: "auto", AutoSystemWfpBlockLeak: []string{"udp/53", "tcp/53", "windnsclient", "tcp/853", "udp/853", "misconfigtun"}},
|
||||
Output: &tun.Config{Name: "xray0", Desc: "Wintun", MTU: 1500, DNS: []string{"1.1.1.1"}, AutoSystemRoutingTable: []string{"0.0.0.0/0"}, AutoOutboundsInterface: "auto", AutoSystemWfpBlockLeak: []string{"dns", "misconfigtun"}},
|
||||
},
|
||||
{
|
||||
Input: `{"name": "xray0", "dns": ["1.1.1.1"], "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["DNS"]}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &tun.Config{Name: "xray0", Desc: "Wintun", MTU: 1500, DNS: []string{"1.1.1.1"}, AutoSystemRoutingTable: []string{"0.0.0.0/0"}, AutoOutboundsInterface: "auto", AutoSystemWfpBlockLeak: []string{"udp/53", "tcp/53", "windnsclient", "tcp/853", "udp/853"}},
|
||||
},
|
||||
{
|
||||
Input: `{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["TCP/853", "udp/853", "tcp/0853"]}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &tun.Config{Name: "xray0", Desc: "Wintun", MTU: 1500, AutoSystemRoutingTable: []string{"0.0.0.0/0"}, AutoOutboundsInterface: "auto", AutoSystemWfpBlockLeak: []string{"tcp/853", "udp/853"}},
|
||||
Output: &tun.Config{Name: "xray0", Desc: "Wintun", MTU: 1500, DNS: []string{"1.1.1.1"}, AutoSystemRoutingTable: []string{"0.0.0.0/0"}, AutoOutboundsInterface: "auto", AutoSystemWfpBlockLeak: []string{"dns"}},
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -54,9 +49,6 @@ func TestTunConfigAutoSystemNeeds(t *testing.T) {
|
||||
{`{"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", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["udp/53"]}`, []string{"windows"}},
|
||||
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["windnsclient"]}`, []string{"windows"}},
|
||||
{`{"name": "xray0", "autoSystemRoutingTable": ["0.0.0.0/0"], "autoSystemWfpBlockLeak": ["tcp/853", "udp/853"]}`, nil},
|
||||
{`{"name": "xray0", "autoSystemDnsToGateway": true}`, []string{"linux", "freebsd"}},
|
||||
} {
|
||||
config := new(TunConfig)
|
||||
@@ -70,13 +62,11 @@ func TestTunConfigAutoSystemNeeds(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestTunConfigAutoSystemWfpBlockLeakUnknown(t *testing.T) {
|
||||
for _, value := range []string{"ip", "tcp/0", "icmp/1"} {
|
||||
config := new(TunConfig)
|
||||
if err := json.Unmarshal([]byte(`{"name": "xray0", "autoSystemWfpBlockLeak": ["dns", "`+value+`"]}`), config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := config.Build(); err == nil {
|
||||
t.Errorf("autoSystemWfpBlockLeak value %q was accepted", value)
|
||||
}
|
||||
config := new(TunConfig)
|
||||
if err := json.Unmarshal([]byte(`{"name": "xray0", "autoSystemWfpBlockLeak": ["dns", "ip"]}`), config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := config.Build(); err == nil {
|
||||
t.Error("an unknown autoSystemWfpBlockLeak value was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
+3
-64
@@ -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,
|
||||
@@ -237,11 +230,10 @@ type OutboundDetourConfig struct {
|
||||
|
||||
func requiresTransportSecurity(address *Address) bool {
|
||||
if address == nil || address.Address == nil {
|
||||
return true
|
||||
return false
|
||||
}
|
||||
if address.Family().IsIP() {
|
||||
ip := address.IP()
|
||||
return !ip.IsPrivate() && !ip.IsLoopback() && !ip.IsLinkLocalUnicast()
|
||||
return !geodata.GetPrivateIPMatcher().Match(address.IP())
|
||||
}
|
||||
domain := strings.TrimSuffix(strings.ToLower(address.Domain()), ".")
|
||||
return !geodata.GetPrivateDomainMatcher().MatchAny(domain)
|
||||
@@ -270,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 {
|
||||
@@ -396,9 +340,6 @@ 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
|
||||
}
|
||||
@@ -609,6 +550,7 @@ func (c *Config) Build() (*core.Config, error) {
|
||||
config := &core.Config{
|
||||
App: []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&dispatcher.Config{}),
|
||||
serial.ToTypedMessage(&proxyman.InboundConfig{}),
|
||||
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
|
||||
},
|
||||
}
|
||||
@@ -718,9 +660,6 @@ func (c *Config) Build() (*core.Config, error) {
|
||||
config.App = append(config.App, serial.ToTypedMessage(r))
|
||||
}
|
||||
|
||||
// Initialize the inbound module last to ensure inbound connections are handled correctly.
|
||||
config.App = append(config.App, serial.ToTypedMessage(&proxyman.InboundConfig{}))
|
||||
|
||||
var inbounds []InboundDetourConfig
|
||||
|
||||
if len(c.InboundConfigs) > 0 {
|
||||
|
||||
@@ -90,6 +90,7 @@ func TestXrayConfig(t *testing.T) {
|
||||
AccessLogPath: "/var/log/xray/access.log",
|
||||
}),
|
||||
serial.ToTypedMessage(&dispatcher.Config{}),
|
||||
serial.ToTypedMessage(&proxyman.InboundConfig{}),
|
||||
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
|
||||
serial.ToTypedMessage(&router.Config{
|
||||
DomainStrategy: router.Config_AsIs,
|
||||
@@ -110,7 +111,6 @@ func TestXrayConfig(t *testing.T) {
|
||||
},
|
||||
},
|
||||
}),
|
||||
serial.ToTypedMessage(&proxyman.InboundConfig{}),
|
||||
},
|
||||
Inbound: []*core.InboundHandlerConfig{
|
||||
{
|
||||
|
||||
+200
-179
@@ -1,87 +1,149 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"go/build"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/bufbuild/protocompile"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/reflect/protodesc"
|
||||
"google.golang.org/protobuf/reflect/protoreflect"
|
||||
"google.golang.org/protobuf/types/descriptorpb"
|
||||
"google.golang.org/protobuf/types/pluginpb"
|
||||
)
|
||||
|
||||
var (
|
||||
directory = flag.String("pwd", "", "Working directory of Xray vprotogen.")
|
||||
mode = flag.String("mode", "generate", "Execution mode. 'generate' (default) compiles and saves changes. 'check' reports out-of-date files and exits with non-zero.")
|
||||
)
|
||||
var directory = flag.String("pwd", "", "Working directory of Xray vprotogen.")
|
||||
|
||||
// topoSort sorts file descriptors so each dependency appears before files importing it.
|
||||
func topoSort(files []protoreflect.FileDescriptor) []*descriptorpb.FileDescriptorProto {
|
||||
fileMap := make(map[string]protoreflect.FileDescriptor)
|
||||
for _, f := range files {
|
||||
fileMap[f.Path()] = f
|
||||
}
|
||||
|
||||
visited := make(map[string]bool)
|
||||
var sorted []*descriptorpb.FileDescriptorProto
|
||||
|
||||
var visit func(fd protoreflect.FileDescriptor)
|
||||
visit = func(fd protoreflect.FileDescriptor) {
|
||||
if visited[fd.Path()] {
|
||||
return
|
||||
// envFile returns the name of the Go environment configuration file.
|
||||
// Copy from https://github.com/golang/go/blob/c4f2a9788a7be04daf931ac54382fbe2cb754938/src/cmd/go/internal/cfg/cfg.go#L150-L166
|
||||
func envFile() (string, error) {
|
||||
if file := os.Getenv("GOENV"); file != "" {
|
||||
if file == "off" {
|
||||
return "", errors.New("GOENV=off")
|
||||
}
|
||||
visited[fd.Path()] = true
|
||||
|
||||
imports := fd.Imports()
|
||||
for i := 0; i < imports.Len(); i++ {
|
||||
if dep, ok := fileMap[imports.Get(i).Path()]; ok {
|
||||
visit(dep)
|
||||
}
|
||||
}
|
||||
sorted = append(sorted, protodesc.ToFileDescriptorProto(fd))
|
||||
return file, nil
|
||||
}
|
||||
|
||||
for _, f := range files {
|
||||
visit(f)
|
||||
dir, err := os.UserConfigDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return sorted
|
||||
if dir == "" {
|
||||
return "", errors.New("missing user-config dir")
|
||||
}
|
||||
return filepath.Join(dir, "go", "env"), nil
|
||||
}
|
||||
|
||||
func runPlugin(pluginName, pwd string, req *pluginpb.CodeGeneratorRequest) (*pluginpb.CodeGeneratorResponse, error) {
|
||||
reqBytes, err := proto.Marshal(req)
|
||||
// GetRuntimeEnv returns the value of runtime environment variable,
|
||||
// that is set by running following command: `go env -w key=value`.
|
||||
func GetRuntimeEnv(key string) (string, error) {
|
||||
file, err := envFile()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return "", err
|
||||
}
|
||||
if file == "" {
|
||||
return "", errors.New("missing runtime env file")
|
||||
}
|
||||
var data []byte
|
||||
var runtimeEnv string
|
||||
data, readErr := os.ReadFile(file)
|
||||
if readErr != nil {
|
||||
return "", readErr
|
||||
}
|
||||
envStrings := strings.Split(string(data), "\n")
|
||||
for _, envItem := range envStrings {
|
||||
envItem = strings.TrimSuffix(envItem, "\r")
|
||||
envKeyValue := strings.Split(envItem, "=")
|
||||
if strings.EqualFold(strings.TrimSpace(envKeyValue[0]), key) {
|
||||
runtimeEnv = strings.TrimSpace(envKeyValue[1])
|
||||
}
|
||||
}
|
||||
return runtimeEnv, nil
|
||||
}
|
||||
|
||||
cmd := exec.Command("go", "tool", pluginName)
|
||||
cmd.Dir = pwd
|
||||
cmd.Stdin = bytes.NewReader(reqBytes)
|
||||
cmd.Env = os.Environ()
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
// GetGOBIN returns GOBIN environment variable as a string. It will NOT be empty.
|
||||
func GetGOBIN() string {
|
||||
// The one set by user explicitly by `export GOBIN=/path` or `env GOBIN=/path command`
|
||||
GOBIN := os.Getenv("GOBIN")
|
||||
if GOBIN == "" {
|
||||
var err error
|
||||
// The one set by user by running `go env -w GOBIN=/path`
|
||||
GOBIN, err = GetRuntimeEnv("GOBIN")
|
||||
if err != nil {
|
||||
// The default one that Golang uses
|
||||
return filepath.Join(build.Default.GOPATH, "bin")
|
||||
}
|
||||
if GOBIN == "" {
|
||||
return filepath.Join(build.Default.GOPATH, "bin")
|
||||
}
|
||||
return GOBIN
|
||||
}
|
||||
return GOBIN
|
||||
}
|
||||
|
||||
if err := cmd.Run(); err != nil {
|
||||
return nil, fmt.Errorf("%v: %s", err, stderr.String())
|
||||
}
|
||||
func whichProtoc(suffix, targetedVersion string) (string, error) {
|
||||
protoc := "protoc" + suffix
|
||||
|
||||
var resp pluginpb.CodeGeneratorResponse
|
||||
if err := proto.Unmarshal(stdout.Bytes(), &resp); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal response: %w", err)
|
||||
path, err := exec.LookPath(protoc)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf(`
|
||||
Command "%s" not found.
|
||||
Make sure that %s is in your system path or current path.
|
||||
Download %s v%s or later from https://github.com/protocolbuffers/protobuf/releases
|
||||
`, protoc, protoc, protoc, targetedVersion)
|
||||
}
|
||||
if resp.GetError() != "" {
|
||||
return nil, fmt.Errorf("%s", resp.GetError())
|
||||
return path, nil
|
||||
}
|
||||
|
||||
func getProjectProtocVersion(url string) (string, error) {
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return "", errors.New("can not get the version of protobuf used in xray project")
|
||||
}
|
||||
return &resp, nil
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", errors.New("can not read from body")
|
||||
}
|
||||
versionRegexp := regexp.MustCompile(`\/\/\s*protoc\s*v\d+\.(\d+\.\d+)`)
|
||||
matched := versionRegexp.FindStringSubmatch(string(body))
|
||||
return matched[1], nil
|
||||
}
|
||||
|
||||
func getInstalledProtocVersion(protocPath string) (string, error) {
|
||||
cmd := exec.Command(protocPath, "--version")
|
||||
cmd.Env = append(cmd.Env, os.Environ()...)
|
||||
output, cmdErr := cmd.CombinedOutput()
|
||||
if cmdErr != nil {
|
||||
return "", cmdErr
|
||||
}
|
||||
versionRegexp := regexp.MustCompile(`protoc\s*(\d+\.\d+)`)
|
||||
matched := versionRegexp.FindStringSubmatch(string(output))
|
||||
return matched[1], nil
|
||||
}
|
||||
|
||||
func parseVersion(s string, width int) int64 {
|
||||
strList := strings.Split(s, ".")
|
||||
format := fmt.Sprintf("%%s%%0%ds", width)
|
||||
v := ""
|
||||
for _, value := range strList {
|
||||
v = fmt.Sprintf(format, v, value)
|
||||
}
|
||||
var result int64
|
||||
var err error
|
||||
if result, err = strconv.ParseInt(v, 10, 64); err != nil {
|
||||
return 0
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needToUpdate(targetedVersion, installedVersion string) bool {
|
||||
vt := parseVersion(targetedVersion, 4)
|
||||
vi := parseVersion(installedVersion, 4)
|
||||
return vt > vi
|
||||
}
|
||||
|
||||
func main() {
|
||||
@@ -92,147 +154,106 @@ func main() {
|
||||
flag.Parse()
|
||||
|
||||
if !filepath.IsAbs(*directory) {
|
||||
pwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
pwd, wdErr := os.Getwd()
|
||||
if wdErr != nil {
|
||||
fmt.Println("Can not get current working directory.")
|
||||
os.Exit(1)
|
||||
}
|
||||
*directory = filepath.Join(pwd, *directory)
|
||||
}
|
||||
pwd := *directory
|
||||
|
||||
isCheck := false
|
||||
switch *mode {
|
||||
case "generate", "":
|
||||
isCheck = false
|
||||
case "check":
|
||||
isCheck = true
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "Unrecognized 'mode': %s. Use 'generate' or 'check'.\n", *mode)
|
||||
pwd := *directory
|
||||
GOBIN := GetGOBIN()
|
||||
binPath := os.Getenv("PATH")
|
||||
pathSlice := []string{pwd, GOBIN, binPath}
|
||||
binPath = strings.Join(pathSlice, string(os.PathListSeparator))
|
||||
os.Setenv("PATH", binPath)
|
||||
|
||||
suffix := ""
|
||||
if runtime.GOOS == "windows" {
|
||||
suffix = ".exe"
|
||||
}
|
||||
|
||||
/*
|
||||
targetedVersion, err := getProjectProtocVersion("https://raw.githubusercontent.com/XTLS/Xray-core/HEAD/core/config.pb.go")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
*/
|
||||
targetedVersion := ""
|
||||
|
||||
protoc, err := whichProtoc(suffix, targetedVersion)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if isCheck {
|
||||
fmt.Println("Checking for out-of-date Protobuf generated files...")
|
||||
installedVersion, err := getInstalledProtocVersion(protoc)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
var protoFiles []string
|
||||
var pbCount int
|
||||
err := filepath.WalkDir(pwd, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil || d.IsDir() {
|
||||
if needToUpdate(targetedVersion, installedVersion) {
|
||||
fmt.Printf(`
|
||||
You are using an old protobuf version, please update to v%s or later.
|
||||
Download it from https://github.com/protocolbuffers/protobuf/releases
|
||||
|
||||
* Protobuf version used in xray project: v%s
|
||||
* Protobuf version you have installed: v%s
|
||||
|
||||
`, targetedVersion, targetedVersion, installedVersion)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
protoFilesMap := make(map[string][]string)
|
||||
walkErr := filepath.Walk(pwd, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return err
|
||||
}
|
||||
if strings.HasSuffix(d.Name(), ".proto") {
|
||||
rel, _ := filepath.Rel(pwd, path)
|
||||
protoFiles = append(protoFiles, filepath.ToSlash(rel))
|
||||
|
||||
if info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
if strings.HasSuffix(d.Name(), ".pb.go") {
|
||||
pbCount++
|
||||
|
||||
dir := filepath.Dir(path)
|
||||
filename := filepath.Base(path)
|
||||
if strings.HasSuffix(filename, ".proto") {
|
||||
path = path[len(pwd)+1:]
|
||||
protoFilesMap[dir] = append(protoFilesMap[dir], path)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Println("Walk error:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if len(protoFiles) == 0 {
|
||||
if isCheck && pbCount > 0 {
|
||||
fmt.Fprintf(os.Stderr, "Found %d .pb.go files without any .proto files. Remove these orphaned files.\n", pbCount)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
compiler := protocompile.Compiler{
|
||||
Resolver: protocompile.WithStandardImports(&protocompile.SourceResolver{
|
||||
ImportPaths: []string{pwd},
|
||||
}),
|
||||
SourceInfoMode: protocompile.SourceInfoStandard,
|
||||
}
|
||||
|
||||
linkedFiles, err := compiler.Compile(context.Background(), protoFiles...)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Protobuf compilation failed:\n%v\n", err)
|
||||
if walkErr != nil {
|
||||
fmt.Println(walkErr)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
var fdList []protoreflect.FileDescriptor
|
||||
for _, f := range linkedFiles {
|
||||
fdList = append(fdList, f)
|
||||
}
|
||||
|
||||
req := &pluginpb.CodeGeneratorRequest{
|
||||
FileToGenerate: protoFiles,
|
||||
Parameter: proto.String("paths=source_relative"),
|
||||
ProtoFile: topoSort(fdList),
|
||||
// TODO: replace with unknown in the future
|
||||
CompilerVersion: &pluginpb.Version{
|
||||
Major: proto.Int32(6),
|
||||
Minor: proto.Int32(33),
|
||||
Patch: proto.Int32(5),
|
||||
},
|
||||
}
|
||||
|
||||
var diffCount int
|
||||
generatedFiles := make(map[string]struct{})
|
||||
for _, plugin := range []string{"protoc-gen-go", "protoc-gen-go-grpc"} {
|
||||
resp, err := runPlugin(plugin, pwd, req)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%s failed: %v\n", plugin, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
for _, f := range resp.File {
|
||||
targetPath := filepath.Join(pwd, filepath.FromSlash(f.GetName()))
|
||||
generatedFiles[targetPath] = struct{}{}
|
||||
content := []byte(f.GetContent())
|
||||
|
||||
hasDiff := false
|
||||
existing, err := os.ReadFile(targetPath)
|
||||
if err != nil {
|
||||
hasDiff = true
|
||||
} else {
|
||||
oldNorm := bytes.ReplaceAll(existing, []byte("\r\n"), []byte("\n"))
|
||||
newNorm := bytes.ReplaceAll(content, []byte("\r\n"), []byte("\n"))
|
||||
if !bytes.Equal(oldNorm, newNorm) {
|
||||
hasDiff = true
|
||||
}
|
||||
for _, files := range protoFilesMap {
|
||||
for _, relProtoFile := range files {
|
||||
args := []string{
|
||||
"--go_out", pwd,
|
||||
"--go_opt", "paths=source_relative",
|
||||
"--go-grpc_out", pwd,
|
||||
"--go-grpc_opt", "paths=source_relative",
|
||||
"--plugin", "protoc-gen-go=" + filepath.Join(GOBIN, "protoc-gen-go"+suffix),
|
||||
"--plugin", "protoc-gen-go-grpc=" + filepath.Join(GOBIN, "protoc-gen-go-grpc"+suffix),
|
||||
}
|
||||
|
||||
if hasDiff {
|
||||
diffCount++
|
||||
fmt.Println(targetPath)
|
||||
|
||||
if isCheck {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(targetPath), 0o755); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error creating directory: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
mode := os.FileMode(0o644)
|
||||
if stat, err := os.Stat(targetPath); err == nil {
|
||||
mode = stat.Mode().Perm()
|
||||
}
|
||||
if err := os.WriteFile(targetPath, content, mode); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error writing %s: %v\n", targetPath, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
args = append(args, relProtoFile)
|
||||
cmd := exec.Command(protoc, args...)
|
||||
cmd.Env = append(cmd.Env, os.Environ()...)
|
||||
cmd.Dir = pwd
|
||||
output, cmdErr := cmd.CombinedOutput()
|
||||
if len(output) > 0 {
|
||||
fmt.Println(string(output))
|
||||
}
|
||||
if cmdErr != nil {
|
||||
fmt.Println(cmdErr)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if isCheck {
|
||||
if pbCount != len(generatedFiles) {
|
||||
fmt.Printf("Protobuf file count mismatch: found %d, expected %d. Remove orphaned files and regenerate.\n", pbCount, len(generatedFiles))
|
||||
diffCount++
|
||||
}
|
||||
if diffCount > 0 {
|
||||
fmt.Println("Protobuf generated file problem(s) found.")
|
||||
fmt.Println("Please run 'go run ./infra/vprotogen' to regenerate them.")
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Println("All Protobuf generated file check has been passed.")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,8 +92,6 @@ func executeAddRules(cmd *base.Command, args []string) {
|
||||
if err != nil {
|
||||
base.Fatalf("failed to perform AddRule: %s", err)
|
||||
}
|
||||
// if multiple files are specified, use append to merge them instead of overriding previous one
|
||||
shouldAppend = true
|
||||
showJSONResponse(resp)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package lua
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
xlua "github.com/xtls/xray-core/common/lua"
|
||||
"github.com/xtls/xray-core/main/commands/base"
|
||||
@@ -33,13 +32,14 @@ func executeSign(cmd *base.Command, args []string) {
|
||||
cmd.Usage()
|
||||
}
|
||||
|
||||
if !strings.EqualFold(filepath.Ext(args[0]), ".lua") {
|
||||
base.Fatalf("Lua file extension must be .lua")
|
||||
}
|
||||
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)
|
||||
@@ -67,7 +67,14 @@ func executeSign(cmd *base.Command, args []string) {
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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()))
|
||||
}
|
||||
|
||||
Vendored
+10
-2
@@ -58,10 +58,18 @@ func readConfigFile(file *os.File) ([]byte, error) {
|
||||
return nil, err
|
||||
}
|
||||
if info.Mode().IsRegular() {
|
||||
switch strings.ToLower(filepath.Ext(file.Name())) {
|
||||
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: ", file.Name())
|
||||
return nil, errors.New("unsupported config file extension: ", path)
|
||||
}
|
||||
}
|
||||
return io.ReadAll(file)
|
||||
|
||||
@@ -381,13 +381,6 @@ func (h *Handler) handleIPQuery(id uint16, qType dnsmessage.Type, domain string,
|
||||
errors.LogInfoInner(context.Background(), err, "pack message")
|
||||
b.Release()
|
||||
timer.SetTimeout(0)
|
||||
return
|
||||
}
|
||||
if len(msgBytes) > buf.Size {
|
||||
b.Release()
|
||||
timer.SetTimeout(0)
|
||||
errors.LogError(context.Background(), "DNS response message too large")
|
||||
return
|
||||
}
|
||||
b.Resize(0, int32(len(msgBytes)))
|
||||
|
||||
|
||||
+22
-22
@@ -23,14 +23,14 @@ const (
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
RewriteAddress *net.IPOrDomain `protobuf:"bytes,1,opt,name=rewrite_address,json=rewriteAddress,proto3" json:"rewrite_address,omitempty"`
|
||||
RewritePort uint32 `protobuf:"varint,2,opt,name=rewrite_port,json=rewritePort,proto3" json:"rewrite_port,omitempty"`
|
||||
PortMap map[string]string `protobuf:"bytes,3,rep,name=port_map,json=portMap,proto3" json:"port_map,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
|
||||
// List of networks that the Dokodemo accepts.
|
||||
AllowedNetworks []net.Network `protobuf:"varint,7,rep,packed,name=allowed_networks,json=allowedNetworks,proto3,enum=xray.common.net.Network" json:"allowed_networks,omitempty"`
|
||||
RewriteAddress *net.IPOrDomain `protobuf:"bytes,1,opt,name=rewrite_address,json=rewriteAddress,proto3" json:"rewrite_address,omitempty"`
|
||||
RewritePort uint32 `protobuf:"varint,2,opt,name=rewrite_port,json=rewritePort,proto3" json:"rewrite_port,omitempty"`
|
||||
PortMap map[string]string `protobuf:"bytes,3,rep,name=port_map,json=portMap,proto3" json:"port_map,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
|
||||
FollowRedirect bool `protobuf:"varint,5,opt,name=follow_redirect,json=followRedirect,proto3" json:"follow_redirect,omitempty"`
|
||||
UserLevel uint32 `protobuf:"varint,6,opt,name=user_level,json=userLevel,proto3" json:"user_level,omitempty"`
|
||||
AllowedNetworks []net.Network `protobuf:"varint,7,rep,packed,name=allowed_networks,json=allowedNetworks,proto3,enum=xray.common.net.Network" json:"allowed_networks,omitempty"`
|
||||
FollowRedirect bool `protobuf:"varint,5,opt,name=follow_redirect,json=followRedirect,proto3" json:"follow_redirect,omitempty"`
|
||||
UserLevel uint32 `protobuf:"varint,6,opt,name=user_level,json=userLevel,proto3" json:"user_level,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -65,13 +65,6 @@ func (*Config) Descriptor() ([]byte, []int) {
|
||||
return file_proxy_dokodemo_config_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *Config) GetAllowedNetworks() []net.Network {
|
||||
if x != nil {
|
||||
return x.AllowedNetworks
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Config) GetRewriteAddress() *net.IPOrDomain {
|
||||
if x != nil {
|
||||
return x.RewriteAddress
|
||||
@@ -93,6 +86,13 @@ func (x *Config) GetPortMap() map[string]string {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Config) GetAllowedNetworks() []net.Network {
|
||||
if x != nil {
|
||||
return x.AllowedNetworks
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Config) GetFollowRedirect() bool {
|
||||
if x != nil {
|
||||
return x.FollowRedirect
|
||||
@@ -112,11 +112,11 @@ var File_proxy_dokodemo_config_proto protoreflect.FileDescriptor
|
||||
const file_proxy_dokodemo_config_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"\x1bproxy/dokodemo/config.proto\x12\x13xray.proxy.dokodemo\x1a\x18common/net/address.proto\x1a\x18common/net/network.proto\"\xff\x02\n" +
|
||||
"\x06Config\x12C\n" +
|
||||
"\x10allowed_networks\x18\a \x03(\x0e2\x18.xray.common.net.NetworkR\x0fallowedNetworks\x12D\n" +
|
||||
"\x06Config\x12D\n" +
|
||||
"\x0frewrite_address\x18\x01 \x01(\v2\x1b.xray.common.net.IPOrDomainR\x0erewriteAddress\x12!\n" +
|
||||
"\frewrite_port\x18\x02 \x01(\rR\vrewritePort\x12C\n" +
|
||||
"\bport_map\x18\x03 \x03(\v2(.xray.proxy.dokodemo.Config.PortMapEntryR\aportMap\x12'\n" +
|
||||
"\bport_map\x18\x03 \x03(\v2(.xray.proxy.dokodemo.Config.PortMapEntryR\aportMap\x12C\n" +
|
||||
"\x10allowed_networks\x18\a \x03(\x0e2\x18.xray.common.net.NetworkR\x0fallowedNetworks\x12'\n" +
|
||||
"\x0ffollow_redirect\x18\x05 \x01(\bR\x0efollowRedirect\x12\x1d\n" +
|
||||
"\n" +
|
||||
"user_level\x18\x06 \x01(\rR\tuserLevel\x1a:\n" +
|
||||
@@ -141,13 +141,13 @@ var file_proxy_dokodemo_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
|
||||
var file_proxy_dokodemo_config_proto_goTypes = []any{
|
||||
(*Config)(nil), // 0: xray.proxy.dokodemo.Config
|
||||
nil, // 1: xray.proxy.dokodemo.Config.PortMapEntry
|
||||
(net.Network)(0), // 2: xray.common.net.Network
|
||||
(*net.IPOrDomain)(nil), // 3: xray.common.net.IPOrDomain
|
||||
(*net.IPOrDomain)(nil), // 2: xray.common.net.IPOrDomain
|
||||
(net.Network)(0), // 3: xray.common.net.Network
|
||||
}
|
||||
var file_proxy_dokodemo_config_proto_depIdxs = []int32{
|
||||
2, // 0: xray.proxy.dokodemo.Config.allowed_networks:type_name -> xray.common.net.Network
|
||||
3, // 1: xray.proxy.dokodemo.Config.rewrite_address:type_name -> xray.common.net.IPOrDomain
|
||||
1, // 2: xray.proxy.dokodemo.Config.port_map:type_name -> xray.proxy.dokodemo.Config.PortMapEntry
|
||||
2, // 0: xray.proxy.dokodemo.Config.rewrite_address:type_name -> xray.common.net.IPOrDomain
|
||||
1, // 1: xray.proxy.dokodemo.Config.port_map:type_name -> xray.proxy.dokodemo.Config.PortMapEntry
|
||||
3, // 2: xray.proxy.dokodemo.Config.allowed_networks:type_name -> xray.common.net.Network
|
||||
3, // [3:3] is the sub-list for method output_type
|
||||
3, // [3:3] is the sub-list for method input_type
|
||||
3, // [3:3] is the sub-list for extension type_name
|
||||
|
||||
@@ -229,19 +229,14 @@ func (h *Handler) blockDelay(rule *FinalRule) time.Duration {
|
||||
func (h *Handler) blackhole(ctx context.Context, input buf.Reader, output buf.Writer, rule *FinalRule, dest *net.Destination) error {
|
||||
delay := h.blockDelay(rule)
|
||||
errors.LogInfo(ctx, "blocked target: ", *dest, ", blackholing connection for ", delay)
|
||||
defer common.Close(output)
|
||||
done := make(chan struct{})
|
||||
go func() { // a DispatchLink inbound's reader ignores Interrupt, so don't wait for this copy
|
||||
_ = buf.Copy(input, buf.Discard)
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(delay):
|
||||
timer := time.AfterFunc(delay, func() {
|
||||
common.Interrupt(input)
|
||||
common.Interrupt(output)
|
||||
errors.LogInfo(ctx, "closed blackholed connection to blocked target: ", *dest)
|
||||
}
|
||||
})
|
||||
defer timer.Stop()
|
||||
defer common.Close(output)
|
||||
_ = buf.Copy(input, buf.Discard)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
+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))
|
||||
|
||||
@@ -327,7 +327,7 @@ 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
|
||||
}
|
||||
|
||||
+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 {
|
||||
|
||||
+4
-15
@@ -23,10 +23,6 @@ For more advanced routing policies or rules, OS level configuration can still ma
|
||||
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.
|
||||
|
||||
Packets are handled by Xray-core's own lightweight TCP/IP stack, which replaced gVisor (XTLS/Xray-core#7130).
|
||||
|
||||
With `autoSystemRoutingTable`, Xray's own connections are kept out of the TUN through `autoOutboundsInterface` (then `"auto"` by default): each of their sockets is bound to another interface, the one named there, or with `"auto"` the one of the default route (Android needs the name). Linux and Android bind with `SO_BINDTODEVICE`, Windows with `IP_UNICAST_IF` and `IPV6_UNICAST_IF`, macOS and iOS with `IP_BOUND_IF` and `IPV6_BOUND_IF`, and FreeBSD switches them to another routing table (see [FreeBSD SUPPORT](#freebsd-support)). Connections to loopback addresses, TCP and UDP, stay unbound. If a socket cannot be bound, the connection fails rather than leave unbound, where it could loop back into the TUN (XTLS/Xray-core#7173).
|
||||
|
||||
### SYSTEM DNS ON LINUX AND FREEBSD (`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).
|
||||
@@ -219,16 +215,12 @@ All in all systemd-networkd and its derivatives (like netplan or NetworkManager)
|
||||
Windows version of the same functionality is implemented through Wintun library. \
|
||||
To make it start, wintun.dll specific for your Windows/arch must be present next to Xray.exe binary.
|
||||
|
||||
After the start network adapter with the name you chose in the config will be created in the system, and exist while Xray is running. A Wintun adapter that already has that name is reused.
|
||||
|
||||
With IPv6 disabled system-wide (the `DisabledComponents` registry value), the adapter has no IPv6, and the TUN starts with IPv4 only, unless `gateway` or `autoSystemRoutingTable` has IPv6 entries, which then keep it from starting.
|
||||
After the start network adapter with the name you chose in the config will be created in the system, and exist while Xray is running.
|
||||
|
||||
When `dns` is set, those servers are applied to the adapter. Windows is kept from registering the TUN's addresses in DNS, and its DNS cache is flushed when the TUN starts and stops.
|
||||
|
||||
With `autoSystemWfpBlockLeak`, which needs `autoSystemRoutingTable` (the config is rejected otherwise), Xray also adds Windows Filtering Platform filters that keep traffic of every program but Xray itself from leaving outside the TUN, each kind chosen by a value in the list, e.g. `"autoSystemWfpBlockLeak": ["dns", "misconfigtun"]`:
|
||||
- `"tcp/<port>"`, `"udp/<port>"`: connections to that TCP or UDP port only go through the TUN, e.g. `"tcp/853"`.
|
||||
- `"windnsclient"`: Windows' DNS Client service cannot connect outside the TUN at all, except for name resolution on the local network (LLMNR, mDNS). On Windows 11 and Server 2022 and later, it may send name queries over HTTPS or TLS, to any port. Earlier versions only query port 53, so there it does nothing.
|
||||
- `"dns"`: stands for `"udp/53"`, `"tcp/53"`, `"windnsclient"`, `"tcp/853"` (DNS over TLS) and `"udp/853"` (DNS over QUIC). Windows keeps sending name queries to the DNS servers of the other interfaces as well, out through those interfaces whatever the routes say, and other programs reach a resolver on the local network (e.g. `192.168.1.1` handed out by DHCP) through its more specific LAN route instead of the TUN. Keeping the system's DNS inside the TUN like this, with `"dns"`, `"udp/53"`, `"tcp/53"` or `"windnsclient"`, needs `dns` (the config is rejected otherwise). The `dns` servers then have to lie within `gateway` or `autoSystemRoutingTable` (a warning is logged otherwise), and DNS servers that should be reached directly belong in Xray's own `dns` settings.
|
||||
With `autoSystemWfpBlockLeak`, which needs `autoSystemRoutingTable` (the config is rejected otherwise), Xray also adds Windows Filtering Platform filters that keep two kinds of traffic of every program but Xray itself from leaving outside the TUN, each chosen by a value in the list, e.g. `"autoSystemWfpBlockLeak": ["dns", "misconfigtun"]`:
|
||||
- `"dns"` (needs `dns`, the config is rejected otherwise): DNS (port 53) only goes through the TUN. Windows keeps sending name queries to the DNS servers of the other interfaces as well, out through those interfaces whatever the routes say, and other programs reach a resolver on the local network (e.g. `192.168.1.1` handed out by DHCP) through its more specific LAN route instead of the TUN. On Windows 11 and Server 2022 and later, where those queries may also go over HTTPS or TLS, Windows' DNS Client service cannot connect outside the TUN at all, except for name resolution on the local network (LLMNR, mDNS). The `dns` servers therefore have to lie within `gateway` or `autoSystemRoutingTable` (a warning is logged otherwise), and DNS servers that should be reached directly belong in Xray's own `dns` settings.
|
||||
- `"misconfigtun"`: an IP version without routes in `autoSystemRoutingTable`, IPv4 or IPv6, is blocked entirely, in both directions, as it would bypass the TUN. Only loopback and what Windows itself needs on the local link (DHCP, and for IPv6 neighbor and multicast listener discovery) remain allowed. An address of that version in `gateway` is not needed: without one, Windows gives the TUN link-local addresses itself, an IPv6 one at once and an IPv4 one from `169.254.0.0/16` after some seconds (until then, IPv4 routed to the TUN is unreachable), and what is routed to the TUN goes through it with those.
|
||||
|
||||
With the filters in place, Xray's own connections out also get past Windows Firewall's block rules (other firewalls may still block them), while connections to Xray's inbounds stay subject to them.
|
||||
@@ -241,8 +233,6 @@ If the filters cannot be added, Xray does not start. They are removed when Xray
|
||||
|
||||
`autoOutboundsInterface` (the default with `autoSystemRoutingTable`) keeps Xray's own connections out of the TUN by binding them to another interface, which Windows only honors while that interface has weak host send and forwarding off for the IP versions routed to the TUN. Otherwise, Windows sends them into the TUN, from that interface's address, and they stall. While the TUN runs, Xray therefore turns weak host send off on that interface, and on again when it stops or another interface takes over. Forwarding cannot be turned off this way, as Mobile Hotspot and Internet Connection Sharing need it, so a warning is logged while it is on. Having the hotspot share the TUN instead of that interface (Settings, Mobile hotspot, Share my internet connection from) moves forwarding to the TUN, where it does no harm, and sends the hotspot's devices through Xray as well.
|
||||
|
||||
An outbound interface with only IPv4 or only IPv6 works as well: a UDP socket opened for both IP versions, which such an interface cannot be bound to, is opened again for the destination's version only, and IPv6 TCP is bound for IPv6 alone, so connections of the missing version fail rather than leave through another interface (XTLS/Xray-core#7214).
|
||||
|
||||
You can give the adapter ip address manually, you can live Windows to give it autogenerated ip address (which take few seconds), it doesn't matter, the traffic going _through_ the interface will be forwarded into the app for proxying. \
|
||||
Minimal configuration that will work for local machine is routing passing the traffic on-link through the interface.
|
||||
You will need the interface id for that, unfortunately it is going to change with every Xray start due to implementation ambiguity between Xray and wintun driver.
|
||||
@@ -317,7 +307,6 @@ sudo route add -inet6 -host 2606:4700:4700::1111 -iface utun10
|
||||
sudo route add -inet6 -host 2606:4700:4700::1001 -iface utun10
|
||||
```
|
||||
Alternatively, configure `autoSystemRoutingTable` and Xray will add and remove those system routes while it is running.
|
||||
Xray's own connections are then kept out of the TUN through `autoOutboundsInterface`: an IPv4 socket is bound with `IP_BOUND_IF`, an IPv6 or dual-stack one with `IPV6_BOUND_IF`, which covers the IPv4 traffic of a dual-stack socket as well, since macOS rejects `IP_BOUND_IF` on IPv6 sockets (XTLS/Xray-core#7230).
|
||||
Important to remember that everything written above about Linux routing concept, also apply to Mac OS X. If you simply route default route through utun interface, that will result network loop and immediate network failure.
|
||||
|
||||
## ANDROID SUPPORT
|
||||
@@ -349,7 +338,7 @@ let tunFd = ((0 ... 1024).first { (_ fd: Int32) -> Bool in var len = socklen_t(b
|
||||
}!
|
||||
```
|
||||
|
||||
Set the environment variable `xray.tun.fd` (or `XRAY_TUN_FD`) to the fd number before starting Xray. This can be done from Swift/Objective-C or by exposing a Go function via gomobile bindings. Xray works on a duplicate of the fd and closes only that, so the fd itself stays NetworkExtension's (XTLS/Xray-core#6883).
|
||||
Set the environment variable `xray.tun.fd` (or `XRAY_TUN_FD`) to the fd number before starting Xray. This can be done from Swift/Objective-C or by exposing a Go function via gomobile bindings.
|
||||
|
||||
Build using gomobile for iOS framework integration:
|
||||
```
|
||||
|
||||
@@ -7,11 +7,12 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
unsafe "unsafe"
|
||||
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
+12
-18
@@ -56,21 +56,20 @@ 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
|
||||
// tunTCPWriter is the writing side of a TCP connection for the dispatcher. It has no Close: the outbound closes
|
||||
// its writer when the other side has no more to send, and the system may still be sending
|
||||
type tunTCPWriter struct {
|
||||
writer buf.Writer
|
||||
counter stats.Counter
|
||||
}
|
||||
|
||||
func (w *TCPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
func (w *tunTCPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
size := mb.Len()
|
||||
if err := w.Writer.WriteMultiBuffer(mb); err != nil {
|
||||
if err := w.writer.WriteMultiBuffer(mb); err != nil {
|
||||
return err
|
||||
}
|
||||
if w.Counter != nil {
|
||||
w.Counter.Add(int64(size))
|
||||
if w.counter != nil {
|
||||
w.counter.Add(int64(size))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -144,8 +143,7 @@ func (t *Handler) Start() error {
|
||||
errors.LogInfo(context.Background(), "[tun] falied to set interface > iface == nil")
|
||||
return errors.New("iface not found")
|
||||
}
|
||||
var controlErr, sockErr error
|
||||
controlErr = c.Control(func(fd uintptr) {
|
||||
return c.Control(func(fd uintptr) {
|
||||
addrPort, _ := netip.ParseAddrPort(address)
|
||||
// skip loopback
|
||||
if addrPort.Addr().IsLoopback() || strings.HasPrefix(strings.ToLower(address), "localhost:") {
|
||||
@@ -153,13 +151,9 @@ func (t *Handler) Start() error {
|
||||
}
|
||||
err := setinterface(network, address, fd, iface)
|
||||
if err != nil {
|
||||
sockErr = errors.New("[tun] falied to set interface").Base(err)
|
||||
errors.LogInfoInner(context.Background(), err, "[tun] falied to set interface")
|
||||
}
|
||||
})
|
||||
if sockErr != nil {
|
||||
return sockErr
|
||||
}
|
||||
return controlErr
|
||||
})
|
||||
}
|
||||
|
||||
@@ -249,7 +243,7 @@ func (t *Handler) HandleConnection(conn net.Conn, destination net.Destination) {
|
||||
reader := &buf.TimeoutWrapperReader{Reader: buf.NewReader(conn), Counter: t.uplinkCounter}
|
||||
writer := buf.NewWriter(conn)
|
||||
if destination.Network != net.Network_UDP {
|
||||
writer = &TCPWriter{Writer: writer, Counter: t.downlinkCounter}
|
||||
writer = &tunTCPWriter{writer: writer, counter: t.downlinkCounter}
|
||||
} else if t.downlinkCounter != nil {
|
||||
writer = &tunUDPStatsWriter{writer: writer, counter: t.downlinkCounter}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
+7
-237
@@ -2,14 +2,8 @@ package tun
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"math"
|
||||
"math/bits"
|
||||
"net/netip"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -22,38 +16,18 @@ const (
|
||||
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 is what follows the IP header
|
||||
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) {
|
||||
// parsePacket reads the IP header of b. Fragments are not accepted: what the system sends to the tun fits its MTU
|
||||
func parsePacket(b []byte) (p packet, ok bool) {
|
||||
if len(b) < ipv4HeaderSize {
|
||||
return p, false
|
||||
}
|
||||
@@ -61,28 +35,25 @@ func parsePacket(b []byte, rest int) (p packet, ok bool) {
|
||||
case 4:
|
||||
size := int(b[0]&0xf) * 4
|
||||
total := int(binary.BigEndian.Uint16(b[2:]))
|
||||
if size < ipv4HeaderSize || total < size || total > len(b)+rest {
|
||||
if size < ipv4HeaderSize || total < size || total > len(b) || binary.BigEndian.Uint16(b[6:])&0x3fff != 0 {
|
||||
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)
|
||||
p.payload = b[size:total]
|
||||
case 6:
|
||||
if len(b) < ipv6HeaderSize {
|
||||
return p, false
|
||||
}
|
||||
total := ipv6HeaderSize + int(binary.BigEndian.Uint16(b[4:]))
|
||||
if total > len(b)+rest {
|
||||
if total > len(b) {
|
||||
return p, false
|
||||
}
|
||||
p.proto = b[6]
|
||||
p.src = netip.AddrFrom16([16]byte(b[8:24]))
|
||||
p.dst = netip.AddrFrom16([16]byte(b[24:40]))
|
||||
p.payload, p.rest = b[ipv6HeaderSize:min(total, len(b))], max(total-len(b), 0)
|
||||
p.payload = b[ipv6HeaderSize:total]
|
||||
// hop-by-hop options, routing, destination options
|
||||
for p.proto == 0 || p.proto == 43 || p.proto == 60 {
|
||||
if len(p.payload) < 8 {
|
||||
@@ -94,55 +65,12 @@ func parsePacket(b []byte, rest int) (p packet, ok bool) {
|
||||
}
|
||||
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() {
|
||||
@@ -231,161 +159,3 @@ func checksum(s uint64) uint16 {
|
||||
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
|
||||
}
|
||||
|
||||
+53
-397
@@ -3,12 +3,7 @@ package tun
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"math"
|
||||
"math/rand/v2"
|
||||
gonet "net"
|
||||
"net/netip"
|
||||
"slices"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -20,16 +15,8 @@ import (
|
||||
|
||||
// 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
|
||||
@@ -37,12 +24,6 @@ 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
|
||||
@@ -52,8 +33,7 @@ type flow struct {
|
||||
|
||||
// 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
|
||||
// what others send, see tcpConn
|
||||
type stack struct {
|
||||
ctx context.Context
|
||||
tun Tun
|
||||
@@ -62,62 +42,32 @@ type stack struct {
|
||||
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 is given every new connection
|
||||
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
|
||||
mu sync.Mutex
|
||||
conns map[flow]*tcpConn
|
||||
closed bool
|
||||
// opening is how many of conns wait for the answer to their SYN-ACK
|
||||
opening atomic.Int32
|
||||
// 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) {
|
||||
// NewStack builds new ip stack
|
||||
func NewStack(ctx context.Context, options StackOptions, handler *Handler) (Stack, error) {
|
||||
s := &stack{
|
||||
ctx: ctx,
|
||||
tun: options.Tun,
|
||||
mtu: int(options.MTU),
|
||||
window: tcpWindow,
|
||||
addresses: options.Addresses,
|
||||
verify: options.Remote,
|
||||
stamps: options.Remote,
|
||||
conns: make(map[flow]*tcpConn),
|
||||
sockets: make(map[netip.AddrPort]*udpSocket),
|
||||
ctx: ctx,
|
||||
tun: options.Tun,
|
||||
mtu: int(options.MTU),
|
||||
window: tcpWindow,
|
||||
handle: handler.HandleConnection,
|
||||
conns: make(map[flow]*tcpConn),
|
||||
}
|
||||
if t, ok := options.Tun.(segmenter); ok && t.Segments() {
|
||||
s.segmenter = t
|
||||
s.window = tcpLargeWindow
|
||||
}
|
||||
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)
|
||||
}
|
||||
s.udp = newUdpConnectionHandler(s.handle, s.writeUDP)
|
||||
return s, nil
|
||||
}
|
||||
|
||||
@@ -135,8 +85,6 @@ func (s *stack) Close() error {
|
||||
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()
|
||||
@@ -145,155 +93,37 @@ func (s *stack) Close() error {
|
||||
}
|
||||
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
|
||||
// a tun that does not split segments gives them as large as a packet can be
|
||||
b := make([]byte, packetRoom+1<<16)
|
||||
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)
|
||||
b, err := s.tun.ReadPacket(b)
|
||||
if err != nil {
|
||||
return err
|
||||
s.mu.Lock()
|
||||
closed := s.closed
|
||||
s.mu.Unlock()
|
||||
if !closed {
|
||||
errors.LogErrorInner(s.ctx, err, "[tun] failed to read a packet, no more are read")
|
||||
}
|
||||
return
|
||||
}
|
||||
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
|
||||
p, ok := parsePacket(b)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
switch p.proto {
|
||||
case protoTCP:
|
||||
s.handleTCP(p)
|
||||
case protoUDP:
|
||||
s.handleUDP(p)
|
||||
case protoICMPv4, protoICMPv6:
|
||||
s.handleICMP(p)
|
||||
}
|
||||
}
|
||||
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) {
|
||||
@@ -316,7 +146,6 @@ func (s *stack) handleTCP(p packet) {
|
||||
window: binary.BigEndian.Uint16(t[14:]),
|
||||
options: t[tcpHeaderSize:size],
|
||||
payload: t[size:],
|
||||
rest: p.rest,
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
@@ -325,7 +154,7 @@ func (s *stack) handleTCP(p packet) {
|
||||
if c != nil && c.input(seg) {
|
||||
return
|
||||
}
|
||||
if seg.flags&(tcpSyn|tcpAck|tcpRst) != tcpSyn || s.handle == nil {
|
||||
if seg.flags&(tcpSyn|tcpAck|tcpRst) != tcpSyn {
|
||||
if seg.flags&tcpRst == 0 {
|
||||
s.refuse(f, seg)
|
||||
}
|
||||
@@ -335,8 +164,7 @@ func (s *stack) handleTCP(p packet) {
|
||||
if s.opening.Load() >= tcpOpening {
|
||||
return
|
||||
}
|
||||
c = newTCPConn(s, f)
|
||||
c.synchronize(seg)
|
||||
c = newTCPConn(s, f, seg)
|
||||
s.mu.Lock()
|
||||
if s.closed {
|
||||
s.mu.Unlock()
|
||||
@@ -346,7 +174,7 @@ func (s *stack) handleTCP(p packet) {
|
||||
s.mu.Unlock()
|
||||
s.opening.Add(1)
|
||||
c.mu.Lock()
|
||||
c.sendSyn()
|
||||
c.sendSynAck()
|
||||
c.arm(tcpTick)
|
||||
c.mu.Unlock()
|
||||
}
|
||||
@@ -363,7 +191,7 @@ func (s *stack) refuse(f flow, seg segment) {
|
||||
binary.BigEndian.PutUint32(t[4:], seg.ack)
|
||||
t[13] = tcpRst
|
||||
} else {
|
||||
ack := seg.seq + uint32(len(seg.payload)+seg.rest)
|
||||
ack := seg.seq + uint32(len(seg.payload))
|
||||
if seg.flags&(tcpSyn|tcpFin) != 0 {
|
||||
ack++
|
||||
}
|
||||
@@ -396,189 +224,51 @@ func (s *stack) handleUDP(p packet) {
|
||||
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()
|
||||
}
|
||||
dst := net.UDPDestination(net.IPAddress(p.dst.AsSlice()), net.Port(binary.BigEndian.Uint16(u[2:])))
|
||||
s.udp.HandlePacket(src, dst, b)
|
||||
}
|
||||
|
||||
// writeUDP writes a packet with the payload from src to dst to the tun
|
||||
func (s *stack) writeUDP(payload []byte, src net.Destination, dst net.Destination) error {
|
||||
srcIP, _ := netip.AddrFromSlice(src.Address.IP())
|
||||
dstIP, _ := netip.AddrFromSlice(dst.Address.IP())
|
||||
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)
|
||||
srcIP, dstIP = srcIP.Unmap(), dstIP.Unmap()
|
||||
if !srcIP.IsValid() || srcIP.Is4() != dstIP.Is4() {
|
||||
return errors.New("failed to write udp packet from ", src, " to ", dst)
|
||||
}
|
||||
var b [ipv6HeaderSize + udpHeaderSize]byte
|
||||
n := putIPHeader(b[:], protoUDP, srcIP, dstIP)
|
||||
u := b[n : n+udpHeaderSize]
|
||||
binary.BigEndian.PutUint16(u, src.Port())
|
||||
binary.BigEndian.PutUint16(u[2:], dst.Port())
|
||||
binary.BigEndian.PutUint16(u, uint16(src.Port))
|
||||
binary.BigEndian.PutUint16(u[2:], uint16(dst.Port))
|
||||
binary.BigEndian.PutUint16(u[4:], uint16(udpHeaderSize+len(payload)))
|
||||
setIPLength(b[:n], n+udpHeaderSize+len(payload))
|
||||
check := transportChecksum(b[:n], protoUDP, u, payload)
|
||||
if check == 0 {
|
||||
// zero stands for no checksum
|
||||
check = 0xffff
|
||||
}
|
||||
binary.BigEndian.PutUint16(u[6:], check)
|
||||
return s.write(b[:n+udpHeaderSize], payload)
|
||||
return s.tun.WritePacket(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
|
||||
// handleICMP answers an echo request as its destination would
|
||||
func (s *stack) handleICMP(p packet) {
|
||||
m := p.payload
|
||||
request, reply := byte(8), byte(0)
|
||||
if p.proto == protoICMPv6 {
|
||||
request, reply = 128, 129
|
||||
}
|
||||
if len(m) < 8 {
|
||||
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
|
||||
if len(m) < 8 || m[0] != request || m[1] != 0 {
|
||||
return
|
||||
}
|
||||
var b [ipv6HeaderSize]byte
|
||||
n := putIPHeader(b[:], p.proto, p.dst, p.src)
|
||||
setIPLength(b[:n], n+len(m))
|
||||
// the reply is the request with another type
|
||||
m[0], m[2], m[3] = reply, 0, 0
|
||||
if p.proto == protoICMPv6 {
|
||||
@@ -586,39 +276,5 @@ func (s *stack) handleICMP(p packet) {
|
||||
} 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)
|
||||
}
|
||||
_ = s.tun.WritePacket(b[:n], m)
|
||||
}
|
||||
|
||||
+159
-1571
File diff suppressed because it is too large
Load Diff
+46
-308
@@ -1,12 +1,10 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"math"
|
||||
"math/rand/v2"
|
||||
"net/netip"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -39,9 +37,7 @@ const (
|
||||
tcpHeld = 1024
|
||||
// tcpSmallest is the smallest mss that the system is believed, the one of Linux
|
||||
tcpSmallest = 48
|
||||
// tcpStamps is what the times of both sides take of the options of every segment that carries them (RFC 7323)
|
||||
tcpStamps = 12
|
||||
// tcpOpening is how many connections that the other side opens can be waiting for the answer to their SYN-ACK
|
||||
// tcpOpening is how many connections can be waiting for the answer to their SYN-ACK
|
||||
tcpOpening = 65535
|
||||
// tcpStart is how many segments are sent before any of them is acknowledged
|
||||
tcpStart = 10
|
||||
@@ -49,24 +45,15 @@ const (
|
||||
// tcpParts of how many parts of what was written it is made at most
|
||||
tcpSegment = math.MaxUint16 - ipv6HeaderSize - tcpHeaderSize
|
||||
tcpParts = 7
|
||||
// tcpKept is how large a payload is at least for the buffers that it was read into to be kept. A smaller one
|
||||
// is copied to where the one before it ends, for a reader to get buffers that are full
|
||||
tcpKept = buf.Size / 2
|
||||
|
||||
// tcpTick is how often a connection that waits for something looks at what it waits for
|
||||
tcpTick = 100 * time.Millisecond
|
||||
// ticks without anything acknowledged before it is sent again, twice as many every next time, a minute at most,
|
||||
// while an open connection that waits sends again every two seconds at most or as often as an answer takes,
|
||||
// twice as seldom every next minute: when its way was away for a while it goes on soon after the way is back,
|
||||
// and the next segment still waits the doubled time, so that its answer can be timed
|
||||
// ticks without anything acknowledged before it is sent again, twice as many every next time, a minute at most
|
||||
tcpRetransmitTicks = 3
|
||||
tcpRetransmitTicksOpen = 20
|
||||
tcpRetransmitTicksMost = 600
|
||||
tcpMinuteTicks = int(time.Minute / tcpTick)
|
||||
// an open connection is given up after four minutes of ticks without an acknowledgment since the timer first sent
|
||||
// it again, as what is behind a wireless link may be away for a while (ticks, so that the time a computer sleeps
|
||||
// is not counted), and one that never answered after it was sent again that many times, after twenty seconds
|
||||
tcpGiveUpTicks = 4 * tcpMinuteTicks
|
||||
// how many times it is sent again before the connection is given up: that is after four minutes, as what is
|
||||
// behind a wireless link may be away for a while, and after twenty seconds for one that never answered
|
||||
tcpRetransmits = 10
|
||||
tcpSynRetransmits = 5
|
||||
// ticks between the probes of a window that stays closed
|
||||
tcpProbeTicks = 10
|
||||
@@ -75,24 +62,17 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
errTCPReset = errors.New("connection reset")
|
||||
errTCPTimeout = errors.New("connection timed out")
|
||||
errTCPRefused = errors.New("connection refused")
|
||||
errTCPUnreachable = errors.New("destination unreachable")
|
||||
errTCPReset = errors.New("connection reset")
|
||||
errTCPTimeout = errors.New("connection timed out")
|
||||
)
|
||||
|
||||
// tcpStarted is where the times that segments carry count from
|
||||
var tcpStarted = time.Now()
|
||||
|
||||
// segment is a TCP segment that came from the tun
|
||||
type segment struct {
|
||||
seq, ack uint32
|
||||
flags byte
|
||||
window uint16
|
||||
options []byte
|
||||
// payload is without its last rest bytes when those are in other buffers of the stack, see stack.whole
|
||||
payload []byte
|
||||
rest int
|
||||
payload []byte
|
||||
}
|
||||
|
||||
// nextOption returns the first option of o and what follows it, kind is zero when there is none
|
||||
@@ -112,7 +92,7 @@ type held struct {
|
||||
data *buf.Buffer
|
||||
}
|
||||
|
||||
// tcpConn is a TCP connection that the system opened through the tun, or one that was opened to it by DialTCP.
|
||||
// tcpConn is a TCP connection that the system opened through the tun.
|
||||
// Mostly the two are on the same machine, with nothing but the queue of the tun in between, which drops what
|
||||
// does not fit. But the system may also pass on what others send, as a router does, and then the link to them
|
||||
// is in between. So a connection has windows that are small enough, keeps what came after a lost segment,
|
||||
@@ -134,19 +114,12 @@ type tcpConn struct {
|
||||
sndShift, rcvShift uint8
|
||||
// sack is set if the system takes selective acknowledgments
|
||||
sack bool
|
||||
// stamps is set if every segment carries the time of this side and the last one that came of the other side,
|
||||
// which sees by it how long its segments take, also the ones that it sent again (RFC 7323).
|
||||
// stampBase is what the time of this side starts from, stampSent the one that the last segment carried
|
||||
stamps bool
|
||||
stampBase, stampSent uint32
|
||||
|
||||
mu sync.Mutex
|
||||
readable sync.Cond
|
||||
writable sync.Cond
|
||||
|
||||
established bool
|
||||
// opened is there while DialTCP waits for the answer to its SYN, and closed when that wait is over
|
||||
opened chan struct{}
|
||||
// closed is set when Close is called
|
||||
closed bool
|
||||
// err is why the connection is gone
|
||||
@@ -167,8 +140,6 @@ type tcpConn struct {
|
||||
rcvHeld []held
|
||||
// rcvLast is the seq of the last one that was put into rcvHeld
|
||||
rcvLast uint32
|
||||
// stamp is the time of the other side that is sent back to it
|
||||
stamp uint32
|
||||
|
||||
sndUna, sndNxt uint32
|
||||
sndWnd uint32
|
||||
@@ -194,9 +165,6 @@ type tcpConn struct {
|
||||
recover uint32
|
||||
// lost is the end of what is lost past the last of sacked, resent the end of what was sent again since then
|
||||
lost, resent uint32
|
||||
// headAt is when the segment at sndUna was sent again, or took that place while something was lost.
|
||||
// It is zero when that segment is not sent once more for the system still asking for it: it was already
|
||||
headAt time.Time
|
||||
// timed is the end of a segment that was sent at timedAt and not again, to see how long its acknowledgment takes.
|
||||
// The first one is the SYN-ACK
|
||||
timed uint32
|
||||
@@ -208,17 +176,17 @@ type tcpConn struct {
|
||||
armed bool
|
||||
// stalled counts ticks without an acknowledgment of what waits for one
|
||||
stalled, retransmitTicks, retransmits int
|
||||
// lostTicks counts the ticks since the timer sent again the first time since something was acknowledged
|
||||
lostTicks int
|
||||
lingered bool
|
||||
lingered bool
|
||||
}
|
||||
|
||||
func newTCPConn(s *stack, f flow) *tcpConn {
|
||||
func newTCPConn(s *stack, f flow, syn segment) *tcpConn {
|
||||
c := &tcpConn{
|
||||
stack: s,
|
||||
flow: f,
|
||||
src: net.TCPDestination(net.IPAddress(f.src.Addr().AsSlice()), net.Port(f.src.Port())),
|
||||
dst: net.TCPDestination(net.IPAddress(f.dst.Addr().AsSlice()), net.Port(f.dst.Port())),
|
||||
rcvNxt: syn.seq + 1,
|
||||
sndWnd: uint32(syn.window),
|
||||
window: s.window,
|
||||
ssthresh: uint32(s.window),
|
||||
timedAt: time.Now(),
|
||||
@@ -228,17 +196,6 @@ func newTCPConn(s *stack, f flow) *tcpConn {
|
||||
c.writable.L = &c.mu
|
||||
c.ipSize = putIPHeader(c.ip[:], protoTCP, f.dst.Addr(), f.src.Addr())
|
||||
c.mss = s.mtu - c.ipSize - tcpHeaderSize
|
||||
c.sndUna = rand.Uint32()
|
||||
c.sndNxt = c.sndUna + 1
|
||||
c.stampBase = rand.Uint32()
|
||||
return c
|
||||
}
|
||||
|
||||
// synchronize takes what the SYN of the other side says. c.mu is held, or nobody else has c yet
|
||||
func (c *tcpConn) synchronize(syn segment) {
|
||||
c.rcvNxt = syn.seq + 1
|
||||
c.sndWnd = uint32(syn.window)
|
||||
c.sack, c.stamps, c.sndShift, c.rcvShift = false, false, 0, 0
|
||||
for kind, value, o := nextOption(syn.options); kind != 0; kind, value, o = nextOption(o) {
|
||||
switch {
|
||||
case kind == 2 && len(value) == 2:
|
||||
@@ -248,77 +205,20 @@ func (c *tcpConn) synchronize(syn segment) {
|
||||
c.rcvShift = tcpWindowShift
|
||||
case kind == 4:
|
||||
c.sack = true
|
||||
case kind == 8 && len(value) == 8 && c.stack.stamps:
|
||||
c.stamps, c.stamp = true, binary.BigEndian.Uint32(value)
|
||||
}
|
||||
}
|
||||
if c.stamps {
|
||||
c.mss -= tcpStamps
|
||||
}
|
||||
c.mss = max(c.mss, tcpSmallest)
|
||||
c.cwnd = tcpStart * uint32(c.mss)
|
||||
}
|
||||
|
||||
// DialTCP implements Stack
|
||||
func (s *stack) DialTCP(ctx context.Context, remote netip.AddrPort) (net.Conn, error) {
|
||||
remote = netip.AddrPortFrom(remote.Addr().Unmap(), remote.Port())
|
||||
local, err := s.local(remote.Addr())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opened := make(chan struct{})
|
||||
s.mu.Lock()
|
||||
if s.closed {
|
||||
s.mu.Unlock()
|
||||
return nil, io.ErrClosedPipe
|
||||
}
|
||||
f := flow{src: remote}
|
||||
port, ok := ephemeral(func(port uint16) bool {
|
||||
f.dst = netip.AddrPortFrom(local, port)
|
||||
return s.conns[f] == nil
|
||||
})
|
||||
if !ok {
|
||||
s.mu.Unlock()
|
||||
return nil, errors.New("no port left to reach ", remote, " from")
|
||||
}
|
||||
f.dst = netip.AddrPortFrom(local, port)
|
||||
c := newTCPConn(s, f)
|
||||
// what the SYN offers, until the answer says what of it is taken
|
||||
c.sack, c.stamps, c.rcvShift, c.opened = true, s.stamps, tcpWindowShift, opened
|
||||
s.conns[f] = c
|
||||
s.mu.Unlock()
|
||||
s.opening.Add(1)
|
||||
c.mu.Lock()
|
||||
if c.err == nil {
|
||||
c.sendSyn()
|
||||
c.arm(tcpTick)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
|
||||
select {
|
||||
case <-opened:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if !c.established {
|
||||
if c.err == nil {
|
||||
c.abort(ctx.Err())
|
||||
}
|
||||
return nil, c.err
|
||||
}
|
||||
return c, nil
|
||||
c.sndUna = rand.Uint32()
|
||||
c.sndNxt = c.sndUna + 1
|
||||
return c
|
||||
}
|
||||
|
||||
// header writes the headers of a segment with size bytes of payload into b and returns their size.
|
||||
// The checksum of the segment is left to write. c.mu is held
|
||||
func (c *tcpConn) header(b []byte, seq uint32, flags byte, options []byte, size int) int {
|
||||
n := copy(b, c.ip[:c.ipSize])
|
||||
stamps := 0
|
||||
if c.stamps {
|
||||
stamps = tcpStamps
|
||||
}
|
||||
t := b[n : n+tcpHeaderSize+stamps+len(options)]
|
||||
t := b[n : n+tcpHeaderSize+len(options)]
|
||||
binary.BigEndian.PutUint16(t, c.flow.dst.Port())
|
||||
binary.BigEndian.PutUint16(t[2:], c.flow.src.Port())
|
||||
binary.BigEndian.PutUint32(t[4:], seq)
|
||||
@@ -333,18 +233,7 @@ func (c *tcpConn) header(b []byte, seq uint32, flags byte, options []byte, size
|
||||
binary.BigEndian.PutUint16(t[14:], uint16(min(window>>c.rcvShift, math.MaxUint16)))
|
||||
}
|
||||
t[16], t[17], t[18], t[19] = 0, 0, 0, 0
|
||||
if c.stamps {
|
||||
o := t[tcpHeaderSize:]
|
||||
o[0], o[1], o[2], o[3] = 1, 1, 8, 10
|
||||
if !c.sending {
|
||||
// what is sent while WriteMultiBuffer writes a segment has the time of that one: it may get to the tun
|
||||
// first, and the other side drops a segment with a time before the last one that it took
|
||||
c.stampSent = c.stampBase + uint32(time.Since(tcpStarted)/time.Millisecond)
|
||||
}
|
||||
binary.BigEndian.PutUint32(o[4:], c.stampSent)
|
||||
binary.BigEndian.PutUint32(o[8:], c.stamp)
|
||||
}
|
||||
copy(t[tcpHeaderSize+stamps:], options)
|
||||
copy(t[tcpHeaderSize:], options)
|
||||
setIPLength(b[:n], n+len(t)+size)
|
||||
c.rcvAcked = c.rcvNxt
|
||||
c.rcvAdvertised = window
|
||||
@@ -365,8 +254,7 @@ func (c *tcpConn) send(seq uint32, flags byte, options, payload []byte) {
|
||||
c.write(b[:c.header(b[:], seq, flags, options, len(payload))], payload)
|
||||
}
|
||||
|
||||
// sendSyn sends the answer to the SYN of the other side, or the SYN of a connection that is opened from here
|
||||
func (c *tcpConn) sendSyn() {
|
||||
func (c *tcpConn) sendSynAck() {
|
||||
options := [12]byte{2, 4}
|
||||
binary.BigEndian.PutUint16(options[2:], uint16(c.stack.mtu-c.ipSize-tcpHeaderSize))
|
||||
n := 4
|
||||
@@ -376,11 +264,7 @@ func (c *tcpConn) sendSyn() {
|
||||
if c.rcvShift != 0 {
|
||||
n += copy(options[n:], []byte{1, 3, 3, c.rcvShift})
|
||||
}
|
||||
flags := byte(tcpSyn | tcpAck)
|
||||
if c.opened != nil {
|
||||
flags = tcpSyn
|
||||
}
|
||||
c.send(c.sndUna, flags, options[:n], nil)
|
||||
c.send(c.sndUna, tcpSyn|tcpAck, options[:n], nil)
|
||||
}
|
||||
|
||||
// sendAck acknowledges what was received, and tells what of rcvHeld waits for a lost segment
|
||||
@@ -394,12 +278,8 @@ func (c *tcpConn) sendAck() {
|
||||
c.send(c.sndNxt, tcpAck, nil, nil)
|
||||
return
|
||||
}
|
||||
// the block with the segment that came last goes first. Next to the times there is room for one less
|
||||
var room [4][2]uint32
|
||||
blocks := room[:]
|
||||
if c.stamps {
|
||||
blocks = room[:3]
|
||||
}
|
||||
// the block with the segment that came last goes first
|
||||
var blocks [4][2]uint32
|
||||
n, last := 1, false
|
||||
for i := 0; i < len(c.rcvHeld); {
|
||||
start, end, recent := c.rcvHeld[i].seq, c.rcvHeld[i].seq, false
|
||||
@@ -426,22 +306,6 @@ func (c *tcpConn) sendAck() {
|
||||
c.send(c.sndNxt, tcpAck, options[:4+8*len(list)], nil)
|
||||
}
|
||||
|
||||
// stamped keeps the time that a segment of the other side carries, to send it back. It is the one of the segment
|
||||
// that the stream goes on with, so that the other side sees how long that one took, and not one of what came
|
||||
// before it. c.mu is held
|
||||
func (c *tcpConn) stamped(s segment) {
|
||||
if int32(s.seq-c.rcvAcked) > 0 {
|
||||
return
|
||||
}
|
||||
for kind, value, o := nextOption(s.options); kind != 0; kind, value, o = nextOption(o) {
|
||||
if kind == 8 && len(value) == 8 {
|
||||
if stamp := binary.BigEndian.Uint32(value); int32(stamp-c.stamp) > 0 {
|
||||
c.stamp = stamp
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// input takes a segment of the connection. It returns false if the connection is gone
|
||||
// and the segment is the start of another one
|
||||
func (c *tcpConn) input(s segment) bool {
|
||||
@@ -450,32 +314,6 @@ func (c *tcpConn) input(s segment) bool {
|
||||
if c.err != nil {
|
||||
return s.flags&(tcpSyn|tcpAck|tcpRst) != tcpSyn
|
||||
}
|
||||
if c.opened != nil {
|
||||
// only the answer to the SYN is waited for, or the word that nobody takes it
|
||||
switch {
|
||||
case s.flags&tcpAck == 0:
|
||||
case s.ack != c.sndNxt:
|
||||
// of a connection that the other side still has from before: it is told that there is none
|
||||
if s.flags&tcpRst == 0 {
|
||||
c.stack.refuse(c.flow, s)
|
||||
}
|
||||
case s.flags&tcpRst != 0:
|
||||
c.abort(errTCPRefused)
|
||||
case s.flags&tcpSyn != 0:
|
||||
c.synchronize(s)
|
||||
c.established = true
|
||||
c.sndUna, c.sndBase = s.ack, s.ack
|
||||
c.stalled, c.retransmits = 0, 0
|
||||
if !c.timedAt.IsZero() {
|
||||
c.clocked()
|
||||
}
|
||||
c.stack.opening.Add(-1)
|
||||
close(c.opened)
|
||||
c.opened = nil
|
||||
c.sendAck()
|
||||
}
|
||||
return true
|
||||
}
|
||||
if s.flags&tcpRst != 0 {
|
||||
// from where the system is, or was before its FIN, not from someone who knows no more than the addresses
|
||||
if s.seq-c.rcvNxt <= uint32(c.window) || c.rcvFin && s.seq+1 == c.rcvNxt {
|
||||
@@ -486,12 +324,9 @@ func (c *tcpConn) input(s segment) bool {
|
||||
if s.flags&tcpSyn != 0 {
|
||||
switch {
|
||||
case !c.established && s.seq+1 == c.rcvNxt:
|
||||
c.sendSyn()
|
||||
c.sendSynAck()
|
||||
c.timedAt = time.Time{}
|
||||
case c.closed && s.flags&tcpAck == 0 && !c.stack.verify:
|
||||
// the system of this machine opens the same ports again: it has let the old connection go.
|
||||
// What comes through a tunnel is answered with what is expected instead, as anyone who knows
|
||||
// the addresses could send it, and the other side answers that with a reset if it is gone
|
||||
case c.closed && s.flags&tcpAck == 0:
|
||||
c.abort(errTCPReset)
|
||||
return false
|
||||
default:
|
||||
@@ -502,9 +337,6 @@ func (c *tcpConn) input(s segment) bool {
|
||||
if s.flags&tcpAck == 0 {
|
||||
return true
|
||||
}
|
||||
if c.stamps {
|
||||
c.stamped(s)
|
||||
}
|
||||
if !c.established {
|
||||
if s.ack != c.sndNxt {
|
||||
return true
|
||||
@@ -553,7 +385,6 @@ func (c *tcpConn) acknowledge(s segment) {
|
||||
if !c.timedAt.IsZero() && int32(c.sndUna-c.timed) >= 0 {
|
||||
c.clocked()
|
||||
}
|
||||
recovering := c.recovering
|
||||
switch {
|
||||
case c.recovering && int32(c.sndUna-c.recover) >= 0:
|
||||
c.recovering = false
|
||||
@@ -562,18 +393,11 @@ func (c *tcpConn) acknowledge(s segment) {
|
||||
if end := c.sndUna + min(uint32(c.mss), c.recover-c.sndUna); int32(end-c.lost) > 0 {
|
||||
c.lost = end
|
||||
}
|
||||
c.headAt = time.Now()
|
||||
}
|
||||
// the way takes more if what it was given has arrived, as long as it was given about as much as it takes
|
||||
if sent >= c.cwnd/2 {
|
||||
if c.cwnd < c.ssthresh {
|
||||
grow := acked
|
||||
if recovering {
|
||||
// after a timeout: one segment that is sent again can acknowledge all that came after it,
|
||||
// which says nothing about how much the way takes at once
|
||||
grow = min(grow, 2*uint32(c.mss))
|
||||
}
|
||||
c.cwnd = min(c.cwnd+grow, c.ssthresh)
|
||||
c.cwnd = min(c.cwnd+acked, c.ssthresh)
|
||||
} else if !c.recovering {
|
||||
// a segment more for every cwnd that arrives
|
||||
c.cwnd = min(c.cwnd+max(uint32(uint64(c.mss)*uint64(acked)/uint64(c.cwnd)), 1), uint32(c.window))
|
||||
@@ -593,22 +417,12 @@ func (c *tcpConn) acknowledge(s segment) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if !c.recovering && c.sndUna != c.sndNxt && (len(c.sacked) > 0 || !c.sack && c.dupAcks >= 3) {
|
||||
// the system has something past sndUna, or says the same for the third time when it cannot say what it has:
|
||||
// the segment at sndUna is lost. One that can say it repeats itself also for what it got twice
|
||||
if !c.recovering && c.sndUna != c.sndNxt && (len(c.sacked) > 0 || c.dupAcks >= 3) {
|
||||
// the system has something past sndUna, or says the same for the third time: the segment at sndUna is lost
|
||||
c.congested()
|
||||
c.lost = c.sndUna + min(uint32(c.mss), c.sndNxt-c.sndUna)
|
||||
}
|
||||
if c.recovering {
|
||||
if acked == 0 && c.srtt != 0 && !c.headAt.IsZero() && time.Since(c.headAt) > max(c.srtt+max(c.srtt/4, 4*c.rttvar), tcpTick/4) {
|
||||
// the segment that the system waits for was sent again longer ago than an answer takes, and the system
|
||||
// still answers what comes after it: that one was lost as well. It is sent once more, and only once:
|
||||
// the timer would find it too, but late, and then nothing is known anymore of how much the way takes
|
||||
if start, end := c.hole(c.sndUna); start == c.sndUna && start != end {
|
||||
c.retransmit(start, start+min(end-start, uint32(c.mss)))
|
||||
c.headAt, c.stalled = time.Time{}, 0
|
||||
}
|
||||
}
|
||||
c.resend()
|
||||
}
|
||||
c.sndWnd = window
|
||||
@@ -637,12 +451,7 @@ func (c *tcpConn) clocked() {
|
||||
c.rttvar += ((c.srtt - d).Abs() - c.rttvar) / 4
|
||||
c.srtt += (d - c.srtt) / 8
|
||||
}
|
||||
c.retransmitTicks = c.answerTicks()
|
||||
}
|
||||
|
||||
// answerTicks is how many ticks an acknowledgment is waited for as long as nothing was sent again. c.mu is held
|
||||
func (c *tcpConn) answerTicks() int {
|
||||
return max(tcpRetransmitTicks, int((c.srtt+4*c.rttvar)/tcpTick)+2)
|
||||
c.retransmitTicks = max(tcpRetransmitTicks, int((c.srtt+4*c.rttvar)/tcpTick)+2)
|
||||
}
|
||||
|
||||
// sackAdd puts what the system says it has into sacked. c.mu is held
|
||||
@@ -672,7 +481,7 @@ func (c *tcpConn) congested() {
|
||||
c.ssthresh = max(min(c.cwnd, c.sndNxt-c.sndUna)/2, 2*uint32(c.mss))
|
||||
c.cwnd = c.ssthresh
|
||||
c.recovering, c.recover, c.resent = true, c.sndNxt, c.sndUna
|
||||
c.timedAt, c.headAt = time.Time{}, time.Time{}
|
||||
c.timedAt = time.Time{}
|
||||
}
|
||||
|
||||
// hole returns the first part at or after seq of what is lost: what the system does not have
|
||||
@@ -734,10 +543,6 @@ func (c *tcpConn) resend() {
|
||||
room = c.cwnd - flight
|
||||
}
|
||||
end = start + min(end-start, room)
|
||||
if start == c.sndUna {
|
||||
// its answer is waited for from now on
|
||||
c.headAt, c.stalled = time.Now(), 0
|
||||
}
|
||||
c.retransmit(start, end)
|
||||
c.resent = end
|
||||
}
|
||||
@@ -754,12 +559,6 @@ func (c *tcpConn) space() uint32 {
|
||||
|
||||
// receive takes the payload of a segment. c.mu is held
|
||||
func (c *tcpConn) receive(s segment) {
|
||||
// what is large, the next and all taken stays in the buffers that it was read into
|
||||
size := len(s.payload) + s.rest
|
||||
keep := c.stack.bufs != nil && size >= tcpKept && s.seq == c.rcvNxt && size <= int(c.window-c.rcvLen)
|
||||
if !keep {
|
||||
s.payload = c.stack.whole(s.payload, s.rest)
|
||||
}
|
||||
seq, payload, fin := s.seq, s.payload, s.flags&tcpFin != 0
|
||||
if len(payload) == 0 && !fin {
|
||||
if int32(c.rcvNxt-seq) > 0 {
|
||||
@@ -800,14 +599,9 @@ func (c *tcpConn) receive(s segment) {
|
||||
return
|
||||
}
|
||||
|
||||
if keep {
|
||||
c.rcvQueue = c.stack.keep(c.rcvQueue, payload, s.rest)
|
||||
} else {
|
||||
size = len(payload)
|
||||
c.rcvQueue = buf.MergeBytes(c.rcvQueue, payload)
|
||||
}
|
||||
c.rcvLen += int32(size)
|
||||
c.rcvNxt += uint32(size)
|
||||
c.rcvQueue = buf.MergeBytes(c.rcvQueue, payload)
|
||||
c.rcvLen += int32(len(payload))
|
||||
c.rcvNxt += uint32(len(payload))
|
||||
for !fin && len(c.rcvHeld) > 0 && int32(c.rcvNxt-c.rcvHeld[0].seq) >= 0 {
|
||||
h := c.rcvHeld[0]
|
||||
if before := int32(c.rcvNxt - h.seq); before < h.data.Len() {
|
||||
@@ -825,7 +619,7 @@ func (c *tcpConn) receive(s segment) {
|
||||
c.readable.Signal()
|
||||
// the reader acknowledges what it takes, with one segment for all that came by then.
|
||||
// It is not waited for when it does not read for long
|
||||
if fin || now || c.rcvNxt-c.rcvAcked >= uint32(c.window/4) {
|
||||
if fin || now || c.rcvNxt-c.rcvAcked >= tcpWindow/4 {
|
||||
c.sendAck()
|
||||
} else {
|
||||
c.arm(tcpTick)
|
||||
@@ -848,9 +642,9 @@ func (c *tcpConn) release() {
|
||||
|
||||
// hold keeps a segment that is not the next one. c.mu is held
|
||||
func (c *tcpConn) hold(seq uint32, payload []byte) {
|
||||
i := len(c.rcvHeld)
|
||||
for i > 0 && int32(c.rcvHeld[i-1].seq-seq) >= 0 {
|
||||
i--
|
||||
i := 0
|
||||
for i < len(c.rcvHeld) && int32(c.rcvHeld[i].seq-seq) < 0 {
|
||||
i++
|
||||
}
|
||||
// without what the one before and the one after have
|
||||
if i > 0 {
|
||||
@@ -872,9 +666,8 @@ func (c *tcpConn) hold(seq uint32, payload []byte) {
|
||||
if len(payload) == 0 || len(c.rcvHeld) == tcpHeld {
|
||||
return
|
||||
}
|
||||
// as much memory as it carries: the room that is left counts bytes, and a thousand tiny segments in pooled
|
||||
// buffers would take two megabytes
|
||||
b := buf.FromBytes(slices.Clone(payload))
|
||||
b := buf.NewWithSize(int32(len(payload)))
|
||||
b.Write(payload)
|
||||
c.rcvHeld = slices.Insert(c.rcvHeld, i, held{seq, b})
|
||||
c.rcvLast = seq
|
||||
}
|
||||
@@ -923,38 +716,6 @@ func (c *tcpConn) queued(parts [][]byte, seq uint32, size int) ([][]byte, int) {
|
||||
return parts, n
|
||||
}
|
||||
|
||||
// shrink makes the segments fit a link on the way that takes packets of mtu bytes, when the one at seq did not.
|
||||
// None of what is on its way fits: it is sent again, the first segment at once and the others as they are
|
||||
// acknowledged. Only what is said about a segment that was sent and is not acknowledged is believed
|
||||
func (c *tcpConn) shrink(seq uint32, mtu int) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
mss := mtu - c.ipSize - tcpHeaderSize
|
||||
if c.stamps {
|
||||
mss -= tcpStamps
|
||||
}
|
||||
mss = max(mss, tcpSmallest)
|
||||
if c.err != nil || !c.established || seq-c.sndUna >= c.sndNxt-c.sndUna || mss >= c.mss {
|
||||
return
|
||||
}
|
||||
c.mss = mss
|
||||
// as what is lost, without the way taking less for it: it is the size that it did not take
|
||||
c.recovering, c.recover, c.lost = true, c.sndNxt, c.sndNxt
|
||||
c.timedAt = time.Time{}
|
||||
c.resent = c.sndUna + min(uint32(mss), c.sndNxt-c.sndUna)
|
||||
c.headAt = time.Now()
|
||||
c.retransmit(c.sndUna, c.resent)
|
||||
}
|
||||
|
||||
// unreachable ends the wait for the answer to the SYN at seq, which a router on the way could not deliver
|
||||
func (c *tcpConn) unreachable(seq uint32) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.err == nil && c.opened != nil && seq == c.sndUna {
|
||||
c.abort(errTCPUnreachable)
|
||||
}
|
||||
}
|
||||
|
||||
// arm makes tick run after d, unless it is going to run already. c.mu is held
|
||||
func (c *tcpConn) arm(d time.Duration) {
|
||||
if c.armed {
|
||||
@@ -981,34 +742,19 @@ func (c *tcpConn) tick() {
|
||||
}
|
||||
switch {
|
||||
case c.sndUna != c.sndNxt:
|
||||
c.stalled++
|
||||
due := c.stalled >= c.retransmitTicks
|
||||
if c.established && c.retransmits > 0 {
|
||||
due = due || c.stalled >= max(tcpRetransmitTicksOpen, c.answerTicks())<<(c.lostTicks/tcpMinuteTicks)
|
||||
}
|
||||
if due {
|
||||
if c.retransmits++; c.retransmits == 1 {
|
||||
c.lostTicks = 0
|
||||
} else {
|
||||
c.lostTicks += c.stalled
|
||||
}
|
||||
if c.established && c.lostTicks > tcpGiveUpTicks || !c.established && c.retransmits > tcpSynRetransmits {
|
||||
if c.stalled++; c.stalled >= c.retransmitTicks {
|
||||
if c.retransmits++; c.retransmits > tcpRetransmits || !c.established && c.retransmits > tcpSynRetransmits {
|
||||
c.abort(errTCPTimeout)
|
||||
return
|
||||
}
|
||||
c.stalled = 0
|
||||
c.retransmitTicks = min(c.retransmitTicks*2, tcpRetransmitTicksMost)
|
||||
if !c.established {
|
||||
c.sendSyn()
|
||||
c.sendSynAck()
|
||||
c.timedAt = time.Time{}
|
||||
} else {
|
||||
// what the system does not say it has is lost, and the way to it is tried with a segment again.
|
||||
// It takes half of what it took before the loss, not half of that again if the loss was seen already
|
||||
ssthresh, recovering := c.ssthresh, c.recovering
|
||||
// what the system does not say it has is lost, and the way to it is tried with a segment again
|
||||
c.congested()
|
||||
if recovering {
|
||||
c.ssthresh = ssthresh
|
||||
}
|
||||
c.cwnd, c.lost = uint32(c.mss), c.sndNxt
|
||||
c.resend()
|
||||
}
|
||||
@@ -1046,10 +792,6 @@ func (c *tcpConn) abort(err error) {
|
||||
if c.timer != nil {
|
||||
c.timer.Stop()
|
||||
}
|
||||
if c.opened != nil {
|
||||
close(c.opened)
|
||||
c.opened = nil
|
||||
}
|
||||
for _, h := range c.rcvHeld {
|
||||
h.data.Release()
|
||||
}
|
||||
@@ -1137,9 +879,9 @@ func (c *tcpConn) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
c.writing = len(mb)
|
||||
// a segment is one part of a Buffer, or as much as there is to send if the tun splits it by itself
|
||||
var room [tcpParts][]byte
|
||||
parts := room[:0:1]
|
||||
limit, parts := c.mss, room[:0:1]
|
||||
if c.stack.segmenter != nil {
|
||||
parts = room[:0]
|
||||
limit, parts = tcpSegment, room[:0]
|
||||
}
|
||||
for end := c.sndNxt + size; c.sndNxt != end; {
|
||||
// not a part of a segment when all of it can go later, with what is acknowledged by then
|
||||
@@ -1155,11 +897,7 @@ func (c *tcpConn) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
if c.err != nil {
|
||||
break
|
||||
}
|
||||
// the mss may have become smaller while the last segment was written
|
||||
most := min(c.mss, int(c.space()))
|
||||
if c.stack.segmenter != nil {
|
||||
most = min(tcpSegment, int(c.space()))
|
||||
}
|
||||
most := min(limit, int(c.space()))
|
||||
if most > c.mss {
|
||||
// the same for what the tun splits
|
||||
most -= most % c.mss
|
||||
@@ -1169,7 +907,7 @@ func (c *tcpConn) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
if c.sndNxt+uint32(n) == end {
|
||||
flags |= tcpPsh
|
||||
}
|
||||
var b [ipv6HeaderSize + tcpHeaderSize + tcpStamps]byte
|
||||
var b [ipv6HeaderSize + tcpHeaderSize]byte
|
||||
h := b[:c.header(b[:], c.sndNxt, flags, nil, n)]
|
||||
if c.sndUna == c.sndNxt {
|
||||
// the ticks without an acknowledgment are counted from the first segment that waits for one
|
||||
|
||||
+2
-5
@@ -16,13 +16,10 @@ type Tun interface {
|
||||
}
|
||||
|
||||
// segmenter is a tun whose other side takes TCP segments that are larger than the MTU,
|
||||
// splits them only if it has to send them on, and completes their checksum then.
|
||||
// What it sends comes as it is too, not split to the MTU
|
||||
// splits them only if it has to send them on, and completes their checksum then
|
||||
type segmenter interface {
|
||||
// Segments reports whether ReadParts and WriteSegment can be used
|
||||
// Segments reports whether WriteSegment can be used
|
||||
Segments() bool
|
||||
// ReadParts waits for a packet, reads it into parts, one after the other, and returns its size
|
||||
ReadParts(parts [][]byte) (int, error)
|
||||
// WriteSegment writes a packet with a TCP segment whose payload is in parts, to be sent on with mss bytes
|
||||
// of it at most in one. Its checksum is that of the pseudo-header only, not inverted
|
||||
WriteSegment(header []byte, payload [][]byte, mss int) error
|
||||
|
||||
@@ -558,16 +558,19 @@ func ioctlPtr(fd int, req uint, arg unsafe.Pointer) error {
|
||||
}
|
||||
|
||||
func setinterface(network, address string, fd uintptr, iface *net.Interface) error {
|
||||
var err1, err2 error
|
||||
|
||||
switch network {
|
||||
case "tcp6", "udp6", "ip6":
|
||||
// IPV6_BOUND_IF binds the IPv4 traffic of a dual-stack socket as
|
||||
// well, and an IPv6 socket rejects IP_BOUND_IF with EINVAL.
|
||||
return unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_BOUND_IF, iface.Index)
|
||||
err1 = unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_BOUND_IF, iface.Index)
|
||||
fallthrough
|
||||
case "tcp4", "udp4", "ip4":
|
||||
return unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_BOUND_IF, iface.Index)
|
||||
err2 = unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_BOUND_IF, iface.Index)
|
||||
default:
|
||||
panic(network + " " + address)
|
||||
}
|
||||
|
||||
return errors.Join(err1, err2)
|
||||
}
|
||||
|
||||
func findOutboundInterface(tunIndex int, fixedName string) (*net.Interface, error) {
|
||||
|
||||
@@ -3,10 +3,7 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -234,40 +231,3 @@ func TestWaitKqueueReportsPersistentFailure(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetinterfaceSocketFamilies binds each kind of socket Xray's dialers
|
||||
// open to lo0, including the dual-stack one Go opens for UDP.
|
||||
func TestSetinterfaceSocketFamilies(t *testing.T) {
|
||||
lo, err := net.InterfaceByName("lo0")
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
lc := net.ListenConfig{Control: func(network, address string, c syscall.RawConn) error {
|
||||
var err error
|
||||
if controlErr := c.Control(func(fd uintptr) {
|
||||
err = setinterface(network, address, fd, lo)
|
||||
}); controlErr != nil {
|
||||
return controlErr
|
||||
}
|
||||
return err
|
||||
}}
|
||||
for _, s := range []struct{ network, address string }{
|
||||
{"udp", "0.0.0.0:0"}, // dual-stack
|
||||
{"udp4", "127.0.0.1:0"},
|
||||
{"udp6", "[::1]:0"},
|
||||
{"tcp4", "127.0.0.1:0"},
|
||||
{"tcp6", "[::1]:0"},
|
||||
} {
|
||||
var closer interface{ Close() error }
|
||||
if s.network[:3] == "udp" {
|
||||
closer, err = lc.ListenPacket(context.Background(), s.network, s.address)
|
||||
} else {
|
||||
closer, err = lc.Listen(context.Background(), s.network, s.address)
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("%s %s: %v", s.network, s.address, err)
|
||||
continue
|
||||
}
|
||||
closer.Close()
|
||||
}
|
||||
}
|
||||
|
||||
+1
-43
@@ -6,8 +6,6 @@ import (
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"sync"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
@@ -24,14 +22,6 @@ type fdTun struct {
|
||||
// vnet is the size of the virtio_net_hdr in front of every packet, zero if the tun has none.
|
||||
// With it the system does not split what it sends to the tun and takes what is not split from it
|
||||
vnet int
|
||||
// raw is file for ReadParts, readv what it calls when there may be a packet, iovecs where that reads to:
|
||||
// header, which takes the virtio_net_hdr, and the parts. read and readErr are what came of it
|
||||
raw syscall.RawConn
|
||||
readv func(fd uintptr) bool
|
||||
header [packetRoom]byte
|
||||
iovecs []unix.Iovec
|
||||
read int
|
||||
readErr error
|
||||
|
||||
writeLock sync.RWMutex
|
||||
closed bool
|
||||
@@ -39,25 +29,7 @@ type fdTun struct {
|
||||
|
||||
// newFdTun takes a file descriptor that does not block
|
||||
func newFdTun(fd, vnet int) *fdTun {
|
||||
t := &fdTun{fd: fd, file: os.NewFile(uintptr(fd), "/dev/net/tun"), vnet: vnet}
|
||||
t.raw, _ = t.file.SyscallConn()
|
||||
t.readv = func(fd uintptr) bool {
|
||||
for {
|
||||
n, _, errno := unix.Syscall(unix.SYS_READV, fd, uintptr(unsafe.Pointer(&t.iovecs[0])), uintptr(len(t.iovecs)))
|
||||
switch errno {
|
||||
case 0:
|
||||
t.read, t.readErr = int(n), nil
|
||||
case unix.EINTR:
|
||||
continue
|
||||
case unix.EAGAIN:
|
||||
return false
|
||||
default:
|
||||
t.read, t.readErr = 0, errno
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
return t
|
||||
return &fdTun{fd: fd, file: os.NewFile(uintptr(fd), "/dev/net/tun"), vnet: vnet}
|
||||
}
|
||||
|
||||
func (t *fdTun) ReadPacket(b []byte) ([]byte, error) {
|
||||
@@ -66,20 +38,6 @@ func (t *fdTun) ReadPacket(b []byte) ([]byte, error) {
|
||||
return b[min(t.vnet, n):n], err
|
||||
}
|
||||
|
||||
// ReadParts implements segmenter
|
||||
func (t *fdTun) ReadParts(parts [][]byte) (int, error) {
|
||||
t.iovecs = append(t.iovecs[:0], unix.Iovec{Base: &t.header[0]})
|
||||
t.iovecs[0].SetLen(t.vnet)
|
||||
for i, p := range parts {
|
||||
t.iovecs = append(t.iovecs, unix.Iovec{Base: &p[0]})
|
||||
t.iovecs[i+1].SetLen(len(p))
|
||||
}
|
||||
if err := t.raw.Read(t.readv); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return max(t.read-t.vnet, 0), t.readErr
|
||||
}
|
||||
|
||||
func (t *fdTun) WritePacket(header, payload []byte) error {
|
||||
// a virtio_net_hdr of zeros leaves nothing to the system
|
||||
var vnet [packetRoom]byte
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
//go:build linux
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// A tun with a virtio_net_hdr reads one packet at a time into parts, without the header, waits for the next one,
|
||||
// and stops waiting when it is closed.
|
||||
func TestReadParts(t *testing.T) {
|
||||
// what a tun is like: one packet for every read, and a file descriptor that does not block
|
||||
fds, err := unix.Socketpair(unix.AF_UNIX, unix.SOCK_SEQPACKET|unix.SOCK_NONBLOCK|unix.SOCK_CLOEXEC, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer unix.Close(fds[1])
|
||||
tun := newFdTun(fds[0], vnetSize)
|
||||
defer tun.closeFile()
|
||||
|
||||
large := make([]byte, 20000)
|
||||
rand.Read(large)
|
||||
parts := [][]byte{make([]byte, 8192), make([]byte, 8192), make([]byte, 8192)}
|
||||
send := func(packet []byte) {
|
||||
if _, err := unix.Write(fds[1], append(bytes.Repeat([]byte{0xee}, vnetSize), packet...)); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
send(large)
|
||||
send([]byte("small"))
|
||||
for _, packet := range [][]byte{large, []byte("small")} {
|
||||
n, err := tun.ReadParts(parts)
|
||||
if err != nil || n != len(packet) || !bytes.Equal(bytes.Join(parts, nil)[:n], packet) {
|
||||
t.Fatal("read ", n, " bytes of ", len(packet), ", error: ", err)
|
||||
}
|
||||
}
|
||||
|
||||
go func() {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
send([]byte("later"))
|
||||
}()
|
||||
if n, err := tun.ReadParts(parts); err != nil || string(parts[0][:n]) != "later" {
|
||||
t.Fatal("read ", parts[0][:n], " after waiting, error: ", err)
|
||||
}
|
||||
|
||||
read := make(chan error)
|
||||
go func() {
|
||||
_, err := tun.ReadParts(parts)
|
||||
read <- err
|
||||
}()
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
tun.closeFile()
|
||||
select {
|
||||
case err := <-read:
|
||||
if err == nil {
|
||||
t.Fatal("read after the tun was closed")
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("still waits after the tun was closed")
|
||||
}
|
||||
}
|
||||
+23
-48
@@ -247,31 +247,30 @@ startOver:
|
||||
}
|
||||
|
||||
// With autoSystemWfpBlockLeak, once the system routes lead to the TUN,
|
||||
// keep connections to the ports given ("dns" stands for those of DNS),
|
||||
// Windows' DNS Client service, and an IP version no route of which leads
|
||||
// to the TUN ("misconfigtun"), from leaving through the other interfaces.
|
||||
// Addresses do not matter: without one of a version in gateway, Windows
|
||||
// gives the TUN a link-local one.
|
||||
leaks, err := ExpandWfpBlockLeak(t.options.AutoSystemWfpBlockLeak)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
block := newLeakFilters(leaks, route4, route6)
|
||||
if route4 || route6 {
|
||||
if slices.Contains(leaks, "windnsclient") && !block.dnsClient {
|
||||
errors.LogInfo(context.Background(), "[tun] windnsclient skipped: before Windows 11 and Server 2022, the DNS Client service only queries port 53")
|
||||
}
|
||||
if block.systemDNS() && len(dns) == 0 {
|
||||
return errors.New("keeping the system's DNS inside the TUN needs dns to be set")
|
||||
}
|
||||
}
|
||||
if blocked := block.String(); (route4 || route6) && blocked != "" {
|
||||
if t.wfp, err = blockLeaks(t.luid, block); err != nil {
|
||||
// keep DNS ("dns", if dns is set), and an IP version no route of which
|
||||
// leads to the TUN ("misconfigtun"), from leaving through the other
|
||||
// interfaces. Addresses do not matter: without one of a version in
|
||||
// gateway, Windows gives the TUN a link-local one.
|
||||
leaks := t.options.AutoSystemWfpBlockLeak
|
||||
blockDNS := slices.Contains(leaks, "dns") && len(dns) > 0
|
||||
blockIPv4 := slices.Contains(leaks, "misconfigtun") && !route4
|
||||
blockIPv6 := slices.Contains(leaks, "misconfigtun") && !route6
|
||||
if (route4 || route6) && (blockDNS || blockIPv4 || blockIPv6) {
|
||||
if t.wfp, err = blockLeaks(t.luid, blockDNS, blockIPv4, blockIPv6); err != nil {
|
||||
var blocked []string
|
||||
for _, b := range []struct {
|
||||
on bool
|
||||
what string
|
||||
}{{blockDNS, "DNS"}, {blockIPv4, "IPv4"}, {blockIPv6, "IPv6"}} {
|
||||
if b.on {
|
||||
blocked = append(blocked, b.what)
|
||||
}
|
||||
}
|
||||
// Rather no TUN than a leaking one.
|
||||
return errors.New("unable to block ", blocked, " outside the TUN (remove autoSystemWfpBlockLeak to run without)").Base(err)
|
||||
return errors.New("unable to block ", strings.Join(blocked, " and "), " outside the TUN (remove autoSystemWfpBlockLeak to run without)").Base(err)
|
||||
}
|
||||
errors.LogInfo(context.Background(), "[tun] blocked outside the TUN: ", blocked)
|
||||
if block.systemDNS() {
|
||||
errors.LogInfo(context.Background(), "[tun] outside the TUN, blocked DNS: ", blockDNS, ", blocked IPv4: ", blockIPv4, ", blocked IPv6: ", blockIPv6)
|
||||
if blockDNS {
|
||||
covered := slices.Clone(addresses)
|
||||
for _, route := range routesData {
|
||||
covered = append(covered, route.Destination)
|
||||
@@ -402,15 +401,6 @@ func resolveOnOwn() *savedResolver {
|
||||
if internet.IsSkippedDNSServer(address) {
|
||||
return nil, errors.New("skipped DNS server ", address)
|
||||
}
|
||||
// A socket of the server's IP version only needs that version bound
|
||||
// to the interface, which a dual-stack one would need both of.
|
||||
if ap, err := netip.ParseAddrPort(address); err == nil && (network == "udp" || network == "tcp") {
|
||||
if ap.Addr().Unmap().Is4() {
|
||||
network += "4"
|
||||
} else {
|
||||
network += "6"
|
||||
}
|
||||
}
|
||||
return dialer.DialContext(ctx, network, address)
|
||||
}
|
||||
net.DefaultResolver.PreferGo = true
|
||||
@@ -568,22 +558,10 @@ func setinterface(network, address string, fd uintptr, iface *net.Interface) err
|
||||
|
||||
switch network {
|
||||
case "tcp6", "udp6", "ip6":
|
||||
dualStack := false
|
||||
if network == "udp6" {
|
||||
ipv6Only, err := windows.GetsockoptInt(windows.Handle(fd), windows.IPPROTO_IPV6, windows.IPV6_V6ONLY)
|
||||
if err != nil {
|
||||
return internet.NewBindError(err)
|
||||
}
|
||||
dualStack = ipv6Only == 0
|
||||
}
|
||||
err1 = windows.SetsockoptInt(windows.Handle(fd), windows.IPPROTO_IPV6, IPV6_UNICAST_IF, iface.Index)
|
||||
if network == "udp6" {
|
||||
err2 = windows.SetsockoptInt(windows.Handle(fd), windows.IPPROTO_IPV6, windows.IPV6_MULTICAST_IF, iface.Index)
|
||||
}
|
||||
// Only dual-stack UDP can send to both IPv4 and IPv6 destinations.
|
||||
if !dualStack {
|
||||
break
|
||||
}
|
||||
fallthrough
|
||||
case "tcp4", "udp4", "ip4":
|
||||
err3 = windows.SetsockoptInt(windows.Handle(fd), windows.IPPROTO_IP, IP_UNICAST_IF, *(*int)(unsafe.Pointer(&index[0])))
|
||||
@@ -594,10 +572,7 @@ func setinterface(network, address string, fd uintptr, iface *net.Interface) err
|
||||
panic(network + " " + address)
|
||||
}
|
||||
|
||||
if err := errors.Combine(err1, err2, err3, err4); err != nil {
|
||||
return internet.NewBindError(err)
|
||||
}
|
||||
return nil
|
||||
return errors.Combine(err1, err2, err3, err4)
|
||||
}
|
||||
|
||||
func findOutboundInterface(tunIndex int, fixedName string) (*net.Interface, error) {
|
||||
|
||||
+40
-105
@@ -7,7 +7,6 @@ import (
|
||||
"os"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"unsafe"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
@@ -171,79 +170,19 @@ func condition(field *windows.GUID, typ uint32, value uintptr) fwpmFilterConditi
|
||||
}
|
||||
}
|
||||
|
||||
// leakFilters is what blockLeaks keeps from leaving outside the TUN.
|
||||
type leakFilters struct {
|
||||
ports []leakPort // connections to these ports
|
||||
dnsClient bool // Windows' DNS Client service
|
||||
ipv4, ipv6 bool // an IP version altogether
|
||||
}
|
||||
|
||||
// newLeakFilters turns expanded autoSystemWfpBlockLeak values into the filters
|
||||
// for a TUN that the routes of route4 (IPv4) and route6 (IPv6) lead to.
|
||||
func newLeakFilters(leaks []string, route4, route6 bool) leakFilters {
|
||||
var block leakFilters
|
||||
for _, leak := range leaks {
|
||||
switch leak {
|
||||
case "windnsclient":
|
||||
block.dnsClient = dnsClientUsesAnyPort()
|
||||
case "misconfigtun":
|
||||
block.ipv4, block.ipv6 = !route4, !route6
|
||||
default:
|
||||
if port, ok := parseLeakPort(leak); ok {
|
||||
block.ports = append(block.ports, port)
|
||||
}
|
||||
}
|
||||
}
|
||||
return block
|
||||
}
|
||||
|
||||
// String lists what block keeps inside the TUN, or is empty for nothing.
|
||||
func (block leakFilters) String() string {
|
||||
var blocked []string
|
||||
for _, port := range block.ports {
|
||||
blocked = append(blocked, port.String())
|
||||
}
|
||||
for _, b := range []struct {
|
||||
on bool
|
||||
what string
|
||||
}{{block.dnsClient, "windnsclient"}, {block.ipv4, "IPv4"}, {block.ipv6, "IPv6"}} {
|
||||
if b.on {
|
||||
blocked = append(blocked, b.what)
|
||||
}
|
||||
}
|
||||
return strings.Join(blocked, ", ")
|
||||
}
|
||||
|
||||
// systemDNS tells whether block keeps the system's DNS inside the TUN.
|
||||
func (block leakFilters) systemDNS() bool {
|
||||
return block.dnsClient || slices.ContainsFunc(block.ports, func(port leakPort) bool { return port.port == 53 })
|
||||
}
|
||||
|
||||
// dnsClientUsesAnyPort tells whether Windows' DNS Client service may send its
|
||||
// queries over HTTPS or TLS, and so to any port, which it does since Windows 11
|
||||
// and Server 2022 (build 20348). Earlier versions only query port 53, and may
|
||||
// run the service in one process with others, which its filters would catch
|
||||
// as well.
|
||||
func dnsClientUsesAnyPort() bool {
|
||||
_, _, build := windows.RtlGetNtVersionNumbers()
|
||||
return build >= 20348
|
||||
}
|
||||
|
||||
// blockLeaks keeps traffic from leaving through interfaces other than tun,
|
||||
// for every program but Xray itself, whose outbounds (DNS included) use the
|
||||
// other interfaces on purpose:
|
||||
//
|
||||
// - ports: connections to these TCP or UDP ports may only go through the
|
||||
// TUN, those of DNS (53), DNS over TLS (TCP 853) and DNS over QUIC (UDP
|
||||
// 853) with "dns". Windows sends a name query to the DNS servers of all
|
||||
// interfaces, not only to those of the TUN: to the first server of each
|
||||
// interface, then to all of them when no answer arrives within a second or
|
||||
// two. It sends the queries for the servers of an interface out through
|
||||
// that interface, whatever the routes say, and other programs reach an
|
||||
// on-link resolver, like 192.168.1.1 from DHCP, through its LAN route,
|
||||
// which is more specific than the TUN's default route.
|
||||
// - dnsClient: since Windows 11 and Server 2022, Windows may also send its
|
||||
// queries over HTTPS or TLS, to any port, so its DNS Client service may not
|
||||
// - dns: DNS (port 53) may only go through the TUN. Windows sends a name
|
||||
// query to the DNS servers of all interfaces, not only to those of the TUN:
|
||||
// to the first server of each interface, then to all of them when no answer
|
||||
// arrives within a second or two. It sends the queries for the servers of
|
||||
// an interface out through that interface, whatever the routes say, and
|
||||
// other programs reach an on-link resolver, like 192.168.1.1 from DHCP,
|
||||
// through its LAN route, which is more specific than the TUN's default
|
||||
// route. Since Windows 11 and Server 2022, Windows may also send its
|
||||
// queries over HTTPS or TLS, so there its DNS Client service may not
|
||||
// connect outside the TUN at all, except for name resolution on the local
|
||||
// link (mDNS, LLMNR).
|
||||
// - ipv4, ipv6: no IPv4, or no IPv6, at all, in either direction, for a TUN
|
||||
@@ -257,7 +196,7 @@ func dnsClientUsesAnyPort() bool {
|
||||
//
|
||||
// The filters live in a dynamic WFP session: closing the returned engine handle
|
||||
// with closeWFPEngine deletes them, and so does Windows when the process dies.
|
||||
func blockLeaks(tun winipcfg.LUID, block leakFilters) (windows.Handle, error) {
|
||||
func blockLeaks(tun winipcfg.LUID, dns, ipv4, ipv6 bool) (windows.Handle, error) {
|
||||
engine, err := openWFPEngine()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
@@ -266,7 +205,7 @@ func blockLeaks(tun winipcfg.LUID, block leakFilters) (windows.Handle, error) {
|
||||
closeWFPEngine(engine)
|
||||
return 0, errors.New("FwpmTransactionBegin0 failed").Base(err)
|
||||
}
|
||||
err = addLeakFilters(engine, tun, block)
|
||||
err = addLeakFilters(engine, tun, dns, ipv4, ipv6)
|
||||
if err == nil {
|
||||
if err = fwpmResult(procFwpmTransactionCommit0.Call(uintptr(engine))); err != nil {
|
||||
err = errors.New("FwpmTransactionCommit0 failed").Base(err)
|
||||
@@ -303,7 +242,7 @@ func closeWFPEngine(engine windows.Handle) {
|
||||
|
||||
// addLeakFilters adds the filters of blockLeaks in a sublayer of their own.
|
||||
// blockLeaks runs it in a transaction, so that they take effect all at once.
|
||||
func addLeakFilters(engine windows.Handle, tun winipcfg.LUID, block leakFilters) error {
|
||||
func addLeakFilters(engine windows.Handle, tun winipcfg.LUID, dns, ipv4, ipv6 bool) error {
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -346,55 +285,51 @@ func addLeakFilters(engine windows.Handle, tun winipcfg.LUID, block leakFilters)
|
||||
// hard permit. Connections from outside to Xray get an ordinary one, so
|
||||
// that firewalls keep guarding its inbounds.
|
||||
self := condition(&fwpmConditionALEAppID, fwpByteBlobType, uintptr(unsafe.Pointer(appID)))
|
||||
// A connection goes through the TUN when its local address is the TUN's,
|
||||
// and it also leaves, or arrives, through the TUN. The local address alone
|
||||
dns53 := condition(&fwpmConditionIPRemotePort, fwpUint16, 53)
|
||||
// DNS goes through the TUN when its local address is the TUN's, and it
|
||||
// also leaves, or arrives, through the TUN. The local address alone
|
||||
// decides by default, but with weak host sending or receiving enabled,
|
||||
// packets of the TUN's address can use other interfaces. (The next hop,
|
||||
// the interface replies would leave by, is not known for arriving ones.)
|
||||
onTUN := func(field *windows.GUID) fwpmFilterCondition0 {
|
||||
return condition(field, fwpUint64, uintptr(unsafe.Pointer(tunLUID)))
|
||||
}
|
||||
out := []fwpmFilterCondition0{dns53, onTUN(&fwpmConditionIPLocalInterface), onTUN(&fwpmConditionIPNexthopInterface)}
|
||||
in := []fwpmFilterCondition0{dns53, onTUN(&fwpmConditionIPLocalInterface), onTUN(&fwpmConditionIPArrivalInterface)}
|
||||
for _, layer := range []struct {
|
||||
key *windows.GUID
|
||||
selfFlags uint32
|
||||
via *windows.GUID // the interface that has to be the TUN as well
|
||||
key *windows.GUID
|
||||
selfFlags uint32
|
||||
throughTUN []fwpmFilterCondition0
|
||||
}{
|
||||
{&fwpmLayerALEAuthConnectV4, fwpmFilterFlagClearActionRight, &fwpmConditionIPNexthopInterface},
|
||||
{&fwpmLayerALEAuthRecvAcceptV4, 0, &fwpmConditionIPArrivalInterface},
|
||||
{&fwpmLayerALEAuthConnectV6, fwpmFilterFlagClearActionRight, &fwpmConditionIPNexthopInterface},
|
||||
{&fwpmLayerALEAuthRecvAcceptV6, 0, &fwpmConditionIPArrivalInterface},
|
||||
{&fwpmLayerALEAuthConnectV4, fwpmFilterFlagClearActionRight, out},
|
||||
{&fwpmLayerALEAuthRecvAcceptV4, 0, in},
|
||||
{&fwpmLayerALEAuthConnectV6, fwpmFilterFlagClearActionRight, out},
|
||||
{&fwpmLayerALEAuthRecvAcceptV6, 0, in},
|
||||
} {
|
||||
if err := add(layer.key, "permit Xray", layer.selfFlags, fwpActionPermit, 4, self); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, port := range block.ports {
|
||||
protocol := uintptr(windows.IPPROTO_UDP)
|
||||
if port.tcp {
|
||||
protocol = windows.IPPROTO_TCP
|
||||
}
|
||||
toPort := []fwpmFilterCondition0{
|
||||
condition(&fwpmConditionIPProtocol, fwpUint8, protocol),
|
||||
condition(&fwpmConditionIPRemotePort, fwpUint16, uintptr(port.port)),
|
||||
}
|
||||
throughTUN := slices.Concat(toPort, []fwpmFilterCondition0{onTUN(&fwpmConditionIPLocalInterface), onTUN(layer.via)})
|
||||
if err := add(layer.key, "permit "+port.String()+" through the TUN", 0, fwpActionPermit, 3, throughTUN...); err != nil {
|
||||
if dns {
|
||||
if err := add(layer.key, "permit DNS through the TUN", 0, fwpActionPermit, 3, layer.throughTUN...); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := add(layer.key, "block "+port.String(), 0, fwpActionBlock, 2, toPort...); err != nil {
|
||||
if err := add(layer.key, "block DNS", 0, fwpActionBlock, 2, dns53); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Since Windows 11 and Server 2022, the DNS Client service may also send
|
||||
// the queries for an interface's servers over HTTPS or TLS, out through
|
||||
// that interface and to any port. So there it may only connect through
|
||||
// the TUN, except for mDNS and LLMNR, which stay on the local link (over
|
||||
// an IP version only while it is not blocked altogether). Like Windows
|
||||
// Firewall's rules for it, the filters recognize the service by its SID,
|
||||
// Since Windows 11 and Server 2022 (build 20348), the DNS Client service
|
||||
// may also send the queries for an interface's servers over HTTPS or TLS,
|
||||
// out through that interface and to any port. So there it may only
|
||||
// connect through the TUN, except for mDNS and LLMNR, which stay on the
|
||||
// local link (over an IP version only while it is not blocked altogether).
|
||||
// Earlier versions only query port 53, and may run the service in one
|
||||
// process with others, which the filters would catch as well. Like
|
||||
// Windows Firewall's rules for it, they recognize the service by its SID,
|
||||
// which Windows puts in the token of its process: the security descriptor
|
||||
// grants that SID the right to match (FWP_ACTRL_MATCH_FILTER, CC in SDDL).
|
||||
if block.dnsClient {
|
||||
if _, _, build := windows.RtlGetNtVersionNumbers(); dns && build >= 20348 {
|
||||
sd, err := windows.SecurityDescriptorFromString("O:SYG:SYD:(A;;CCRC;;;" + dnsClientSID + ")")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -408,8 +343,8 @@ func addLeakFilters(engine windows.Handle, tun winipcfg.LUID, block leakFilters)
|
||||
key *windows.GUID
|
||||
localLink bool
|
||||
}{
|
||||
{&fwpmLayerALEAuthConnectV4, !block.ipv4},
|
||||
{&fwpmLayerALEAuthConnectV6, !block.ipv6},
|
||||
{&fwpmLayerALEAuthConnectV4, !ipv4},
|
||||
{&fwpmLayerALEAuthConnectV6, !ipv6},
|
||||
} {
|
||||
if err := add(layer.key, "permit the DNS Client service through the TUN", 0, fwpActionPermit, 3, dnsClient, onTUN(&fwpmConditionIPLocalInterface), onTUN(&fwpmConditionIPNexthopInterface)); err != nil {
|
||||
return err
|
||||
@@ -432,7 +367,7 @@ func addLeakFilters(engine windows.Handle, tun winipcfg.LUID, block leakFilters)
|
||||
matchType: fwpMatchFlagsAllSet,
|
||||
conditionValue: fwpValue0{typ: fwpUint32, value: fwpConditionFlagIsLoopback},
|
||||
}
|
||||
if block.ipv4 {
|
||||
if ipv4 {
|
||||
// DHCP keeps the addresses of the other interfaces, which Xray's own
|
||||
// connections use.
|
||||
dhcp := []fwpmFilterCondition0{
|
||||
@@ -452,7 +387,7 @@ func addLeakFilters(engine windows.Handle, tun winipcfg.LUID, block leakFilters)
|
||||
}
|
||||
}
|
||||
}
|
||||
if block.ipv6 {
|
||||
if ipv6 {
|
||||
// Neighbor and multicast listener discovery, ICMPv6 130-137 and 143,
|
||||
// whose type and code sit where the local and remote port are.
|
||||
discovery := []fwpmFilterCondition0{condition(&fwpmConditionIPProtocol, fwpUint8, windows.IPPROTO_ICMPV6)}
|
||||
|
||||
@@ -114,38 +114,11 @@ func TestLeakFiltersAccepted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
leaks, err := ExpandWfpBlockLeak([]string{"dns", "misconfigtun", "tcp/443"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
block := newLeakFilters(leaks, false, false)
|
||||
block.dnsClient = true // whatever the Windows version
|
||||
if err := addLeakFilters(engine, loopback, block); err != nil {
|
||||
if err := addLeakFilters(engine, loopback, true, true, true); err != nil {
|
||||
skipUnlessElevated(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewLeakFilters(t *testing.T) {
|
||||
leaks, err := ExpandWfpBlockLeak([]string{"dns", "misconfigtun"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
block := newLeakFilters(leaks, true, false)
|
||||
want := "udp/53, tcp/53, tcp/853, udp/853, IPv6"
|
||||
if dnsClientUsesAnyPort() {
|
||||
want = "udp/53, tcp/53, tcp/853, udp/853, windnsclient, IPv6"
|
||||
}
|
||||
if got := block.String(); got != want {
|
||||
t.Errorf("String() = %q, want %q", got, want)
|
||||
}
|
||||
if !block.systemDNS() {
|
||||
t.Error("systemDNS() = false with dns")
|
||||
}
|
||||
if block := newLeakFilters([]string{"tcp/853", "udp/853", "misconfigtun"}, true, true); block.String() != "tcp/853, udp/853" || block.systemDNS() {
|
||||
t.Errorf("tcp/853, udp/853: %q, systemDNS() = %v", block.String(), block.systemDNS())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSClientSID(t *testing.T) {
|
||||
sid, _, _, err := windows.LookupSID("", `NT SERVICE\Dnscache`)
|
||||
if err != nil {
|
||||
|
||||
+16
-76
@@ -39,7 +39,9 @@ func (u *udpConnectionHandler) HandlePacket(src net.Destination, dst net.Destina
|
||||
u.RLock()
|
||||
conn, found := u.udpConns[src]
|
||||
if found {
|
||||
if !conn.queue.push(data) {
|
||||
select {
|
||||
case conn.egress <- data:
|
||||
default:
|
||||
errors.LogDebug(context.Background(), "drop udp with size ", data.Len(), " to ", dst.NetAddr(), " original ", conn.dst.NetAddr(), " > queue full")
|
||||
data.Release()
|
||||
}
|
||||
@@ -53,14 +55,17 @@ func (u *udpConnectionHandler) HandlePacket(src net.Destination, dst net.Destina
|
||||
|
||||
conn, found = u.udpConns[src]
|
||||
if !found {
|
||||
conn = &udpConn{handler: u, queue: newPacketQueue(udpQueueLimit), src: src, dst: dst}
|
||||
egress := make(chan *buf.Buffer, 1024)
|
||||
conn = &udpConn{handler: u, egress: egress, src: src, dst: dst}
|
||||
u.udpConns[src] = conn
|
||||
|
||||
go u.handleConnection(conn, dst)
|
||||
}
|
||||
|
||||
// queue the packet for the reader of the connection, or discard it
|
||||
if !conn.queue.push(data) {
|
||||
// send packet data to the egress channel, if it has buffer, or discard
|
||||
select {
|
||||
case conn.egress <- data:
|
||||
default:
|
||||
errors.LogDebug(context.Background(), "drop udp with size ", data.Len(), " to ", dst.NetAddr(), " original ", conn.dst.NetAddr(), " > queue full 2")
|
||||
data.Release()
|
||||
}
|
||||
@@ -71,7 +76,7 @@ func (u *udpConnectionHandler) connectionFinished(conn *udpConn) {
|
||||
// Close runs twice per flow; a newer conn may already own this src.
|
||||
if u.udpConns[conn.src] == conn {
|
||||
delete(u.udpConns, conn.src)
|
||||
conn.queue.close()
|
||||
close(conn.egress)
|
||||
}
|
||||
u.Unlock()
|
||||
}
|
||||
@@ -80,13 +85,13 @@ func (u *udpConnectionHandler) connectionFinished(conn *udpConn) {
|
||||
type udpConn struct {
|
||||
handler *udpConnectionHandler
|
||||
|
||||
queue *packetQueue
|
||||
src net.Destination
|
||||
dst net.Destination
|
||||
egress chan *buf.Buffer
|
||||
src net.Destination
|
||||
dst net.Destination
|
||||
}
|
||||
|
||||
func (c *udpConn) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
b, ok := c.queue.pop()
|
||||
b, ok := <-c.egress
|
||||
if !ok {
|
||||
return nil, io.EOF
|
||||
}
|
||||
@@ -95,7 +100,7 @@ func (c *udpConn) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
|
||||
// Read packets from the connection
|
||||
func (c *udpConn) Read(p []byte) (int, error) {
|
||||
b, ok := c.queue.pop()
|
||||
b, ok := <-c.egress
|
||||
if !ok {
|
||||
return 0, io.EOF
|
||||
}
|
||||
@@ -132,7 +137,7 @@ func (c *udpConn) Write(p []byte) (int, error) {
|
||||
// sending packets back mean sending payload with source/destination reversed
|
||||
err := c.handler.writePacket(p, c.dst, c.src)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
return len(p), nil
|
||||
@@ -163,68 +168,3 @@ func (c *udpConn) SetReadDeadline(t time.Time) error {
|
||||
func (c *udpConn) SetWriteDeadline(t time.Time) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// udpQueueLimit bounds the packets waiting for one UDP flow; more are dropped.
|
||||
const udpQueueLimit = 1024
|
||||
|
||||
// packetQueue holds the packets waiting for one UDP flow. Unlike a buffered
|
||||
// channel of the same bound it only allocates for packets actually queued, so
|
||||
// the many idle flows kept until the idle timeout cost next to nothing.
|
||||
type packetQueue struct {
|
||||
mu sync.Mutex
|
||||
items []*buf.Buffer
|
||||
limit int
|
||||
notify chan struct{}
|
||||
closed bool
|
||||
}
|
||||
|
||||
func newPacketQueue(limit int) *packetQueue {
|
||||
return &packetQueue{limit: limit, notify: make(chan struct{}, 1)}
|
||||
}
|
||||
|
||||
// push queues b and reports whether it was accepted.
|
||||
func (q *packetQueue) push(b *buf.Buffer) bool {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
if q.closed || len(q.items) >= q.limit {
|
||||
return false
|
||||
}
|
||||
q.items = append(q.items, b)
|
||||
select {
|
||||
case q.notify <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// pop blocks until a packet is queued or the queue is closed and drained.
|
||||
func (q *packetQueue) pop() (*buf.Buffer, bool) {
|
||||
for {
|
||||
q.mu.Lock()
|
||||
if len(q.items) > 0 {
|
||||
b := q.items[0]
|
||||
q.items[0] = nil
|
||||
q.items = q.items[1:]
|
||||
if len(q.items) == 0 {
|
||||
q.items = nil
|
||||
}
|
||||
q.mu.Unlock()
|
||||
return b, true
|
||||
}
|
||||
if q.closed {
|
||||
q.mu.Unlock()
|
||||
return nil, false
|
||||
}
|
||||
q.mu.Unlock()
|
||||
<-q.notify
|
||||
}
|
||||
}
|
||||
|
||||
func (q *packetQueue) close() {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
if !q.closed {
|
||||
q.closed = true
|
||||
close(q.notify)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
)
|
||||
|
||||
// dnsLeaks is what "dns" in autoSystemWfpBlockLeak stands for: DNS over UDP and
|
||||
// TCP, Windows' DNS Client service, which may also use other protocols and
|
||||
// ports, DNS over TLS, and DNS over QUIC.
|
||||
var dnsLeaks = []string{"udp/53", "tcp/53", "windnsclient", "tcp/853", "udp/853"}
|
||||
|
||||
// leakPort is a "tcp/<port>" or "udp/<port>" value of autoSystemWfpBlockLeak:
|
||||
// connections to that port may only go through the TUN.
|
||||
type leakPort struct {
|
||||
tcp bool
|
||||
port uint16
|
||||
}
|
||||
|
||||
func (p leakPort) String() string {
|
||||
if p.tcp {
|
||||
return "tcp/" + strconv.Itoa(int(p.port))
|
||||
}
|
||||
return "udp/" + strconv.Itoa(int(p.port))
|
||||
}
|
||||
|
||||
// parseLeakPort parses a lower case "tcp/<port>" or "udp/<port>" value.
|
||||
func parseLeakPort(value string) (leakPort, bool) {
|
||||
protocol, port, ok := strings.Cut(value, "/")
|
||||
if !ok || protocol != "tcp" && protocol != "udp" {
|
||||
return leakPort{}, false
|
||||
}
|
||||
n, err := strconv.ParseUint(port, 10, 16)
|
||||
if err != nil || n == 0 {
|
||||
return leakPort{}, false
|
||||
}
|
||||
return leakPort{tcp: protocol == "tcp", port: uint16(n)}, true
|
||||
}
|
||||
|
||||
// ExpandWfpBlockLeak checks the values of autoSystemWfpBlockLeak and returns
|
||||
// them in lower case, in order and without duplicates, with "dns" replaced by
|
||||
// what it stands for.
|
||||
func ExpandWfpBlockLeak(values []string) ([]string, error) {
|
||||
var leaks []string
|
||||
add := func(leak string) {
|
||||
if !slices.Contains(leaks, leak) {
|
||||
leaks = append(leaks, leak)
|
||||
}
|
||||
}
|
||||
for _, value := range values {
|
||||
switch value = strings.ToLower(value); value {
|
||||
case "dns":
|
||||
for _, leak := range dnsLeaks {
|
||||
add(leak)
|
||||
}
|
||||
case "windnsclient", "misconfigtun":
|
||||
add(value)
|
||||
default:
|
||||
port, ok := parseLeakPort(value)
|
||||
if !ok {
|
||||
return nil, errors.New("unknown autoSystemWfpBlockLeak value: ", value)
|
||||
}
|
||||
add(port.String())
|
||||
}
|
||||
}
|
||||
return leaks, nil
|
||||
}
|
||||
|
||||
// BlocksSystemDNS tells whether expanded autoSystemWfpBlockLeak values keep the
|
||||
// system's DNS (port 53, or Windows' DNS Client service) inside the TUN, which
|
||||
// then needs DNS servers of its own.
|
||||
func BlocksSystemDNS(leaks []string) bool {
|
||||
return slices.ContainsFunc(leaks, func(leak string) bool {
|
||||
return leak == "udp/53" || leak == "tcp/53" || leak == "windnsclient"
|
||||
})
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestExpandWfpBlockLeak(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
values []string
|
||||
leaks []string
|
||||
systemDNS bool
|
||||
}{
|
||||
{nil, nil, false},
|
||||
{[]string{"dns"}, []string{"udp/53", "tcp/53", "windnsclient", "tcp/853", "udp/853"}, true},
|
||||
{[]string{"DNS", "MisconfigTUN"}, []string{"udp/53", "tcp/53", "windnsclient", "tcp/853", "udp/853", "misconfigtun"}, true},
|
||||
{[]string{"tcp/853", "dns", "TCP/0853"}, []string{"tcp/853", "udp/53", "tcp/53", "windnsclient", "udp/853"}, true},
|
||||
{[]string{"tcp/853", "udp/853", "misconfigtun"}, []string{"tcp/853", "udp/853", "misconfigtun"}, false},
|
||||
{[]string{"udp/65535", "tcp/1"}, []string{"udp/65535", "tcp/1"}, false},
|
||||
{[]string{"tcp/53"}, []string{"tcp/53"}, true},
|
||||
{[]string{"windnsclient"}, []string{"windnsclient"}, true},
|
||||
} {
|
||||
leaks, err := ExpandWfpBlockLeak(c.values)
|
||||
if err != nil {
|
||||
t.Errorf("%v: %v", c.values, err)
|
||||
continue
|
||||
}
|
||||
if !slices.Equal(leaks, c.leaks) {
|
||||
t.Errorf("%v: got %v, want %v", c.values, leaks, c.leaks)
|
||||
}
|
||||
if got := BlocksSystemDNS(leaks); got != c.systemDNS {
|
||||
t.Errorf("%v: BlocksSystemDNS() = %v", c.values, got)
|
||||
}
|
||||
}
|
||||
for _, value := range []string{"", "ip", "tcp", "tcp/", "tcp/0", "udp/65536", "tcp/-1", "tcp/+53", "tcp/53/1", "udp/abc", "icmp/1", "tcp:53", " dns"} {
|
||||
if _, err := ExpandWfpBlockLeak([]string{value}); err == nil {
|
||||
t.Errorf("%q was accepted", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,11 @@ import (
|
||||
gotls "crypto/tls"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/xtls/xray-core/app/dispatcher"
|
||||
"github.com/xtls/xray-core/app/reverse"
|
||||
@@ -546,7 +548,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
|
||||
}
|
||||
|
||||
var input *bytes.Reader
|
||||
var rawInput **bytes.Buffer
|
||||
var rawInput *bytes.Buffer
|
||||
switch requestAddons.Flow {
|
||||
case vless.XRV:
|
||||
if account.Flow == requestAddons.Flow {
|
||||
@@ -558,23 +560,30 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
|
||||
inbound.CanSpliceCopy = 3
|
||||
fallthrough // we will break Mux connections that contain TCP requests
|
||||
case protocol.RequestCommandTCP:
|
||||
var target net.Conn
|
||||
var t reflect.Type
|
||||
var p uintptr
|
||||
if commonConn, ok := connection.(*encryption.CommonConn); ok {
|
||||
if _, ok := commonConn.Conn.(*encryption.XorConn); ok || !proxy.IsRAWTransportWithoutSecurity(iConn) {
|
||||
inbound.CanSpliceCopy = 3 // full-random xorConn / non-RAW transport / another securityConn should not be penetrated
|
||||
}
|
||||
target = commonConn
|
||||
t = reflect.TypeOf(commonConn).Elem()
|
||||
p = uintptr(unsafe.Pointer(commonConn))
|
||||
} else if tlsConn, ok := iConn.(*tls.Conn); ok {
|
||||
if tlsConn.ConnectionState().Version != gotls.VersionTLS13 {
|
||||
return errors.New(`failed to use `+requestAddons.Flow+`, found outer tls version `, tlsConn.ConnectionState().Version)
|
||||
}
|
||||
target = tlsConn.Conn
|
||||
t = reflect.TypeOf(tlsConn.Conn).Elem()
|
||||
p = uintptr(unsafe.Pointer(tlsConn.Conn))
|
||||
} else if realityConn, ok := iConn.(*reality.Conn); ok {
|
||||
target = realityConn.Conn
|
||||
t = reflect.TypeOf(realityConn.Conn).Elem()
|
||||
p = uintptr(unsafe.Pointer(realityConn.Conn))
|
||||
} else {
|
||||
return errors.New("XTLS only supports TLS and REALITY directly for now.")
|
||||
}
|
||||
input, rawInput = vless.AccessTLSBuffers(target)
|
||||
i, _ := t.FieldByName("input")
|
||||
r, _ := t.FieldByName("rawInput")
|
||||
input = (*bytes.Reader)(unsafe.Pointer(p + i.Offset))
|
||||
rawInput = (*bytes.Buffer)(unsafe.Pointer(p + r.Offset))
|
||||
}
|
||||
} else {
|
||||
return errors.New("account " + account.ID.String() + " is not able to use the flow " + requestAddons.Flow)
|
||||
|
||||
@@ -5,9 +5,11 @@ import (
|
||||
"context"
|
||||
gotls "crypto/tls"
|
||||
"encoding/base64"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
utls "github.com/refraction-networking/utls"
|
||||
proxymanConfig "github.com/xtls/xray-core/app/proxyman"
|
||||
@@ -242,7 +244,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
}
|
||||
|
||||
var input *bytes.Reader
|
||||
var rawInput **bytes.Buffer
|
||||
var rawInput *bytes.Buffer
|
||||
allowUDP443 := false
|
||||
switch requestAddons.Flow {
|
||||
case vless.XRV + "-udp443":
|
||||
@@ -259,22 +261,30 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
case protocol.RequestCommandMux:
|
||||
fallthrough // let server break Mux connections that contain TCP requests
|
||||
case protocol.RequestCommandTCP, protocol.RequestCommandRvs:
|
||||
var target net.Conn
|
||||
var t reflect.Type
|
||||
var p uintptr
|
||||
if commonConn, ok := conn.(*encryption.CommonConn); ok {
|
||||
if _, ok := commonConn.Conn.(*encryption.XorConn); ok || !proxy.IsRAWTransportWithoutSecurity(iConn) {
|
||||
ob.CanSpliceCopy = 3 // full-random xorConn / non-RAW transport / another securityConn should not be penetrated
|
||||
}
|
||||
target = commonConn
|
||||
t = reflect.TypeOf(commonConn).Elem()
|
||||
p = uintptr(unsafe.Pointer(commonConn))
|
||||
} else if tlsConn, ok := iConn.(*tls.Conn); ok {
|
||||
target = tlsConn.Conn
|
||||
t = reflect.TypeOf(tlsConn.Conn).Elem()
|
||||
p = uintptr(unsafe.Pointer(tlsConn.Conn))
|
||||
} else if utlsConn, ok := iConn.(*tls.UConn); ok {
|
||||
target = utlsConn.Conn
|
||||
t = reflect.TypeOf(utlsConn.Conn).Elem()
|
||||
p = uintptr(unsafe.Pointer(utlsConn.Conn))
|
||||
} else if realityConn, ok := iConn.(*reality.UConn); ok {
|
||||
target = realityConn.Conn
|
||||
t = reflect.TypeOf(realityConn.Conn).Elem()
|
||||
p = uintptr(unsafe.Pointer(realityConn.Conn))
|
||||
} else {
|
||||
return errors.New("XTLS only supports TLS and REALITY directly for now.")
|
||||
}
|
||||
input, rawInput = vless.AccessTLSBuffers(target)
|
||||
i, _ := t.FieldByName("input")
|
||||
r, _ := t.FieldByName("rawInput")
|
||||
input = (*bytes.Reader)(unsafe.Pointer(p + i.Offset))
|
||||
rawInput = (*bytes.Buffer)(unsafe.Pointer(p + r.Offset))
|
||||
default:
|
||||
panic("unknown VLESS request command")
|
||||
}
|
||||
|
||||
@@ -5,28 +5,7 @@
|
||||
// clients with 'socks' for proxying.
|
||||
package vless
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net"
|
||||
"reflect"
|
||||
|
||||
"github.com/xtls/xray-core/common/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
None = "none"
|
||||
XRV = "xtls-rprx-vision"
|
||||
)
|
||||
|
||||
// Old TLS lib holds bytes.Buffer, but new TLS lib holds *bytes.Buffer
|
||||
// Since Xray has 3 TLS libraries (std, utls, REALITY server)
|
||||
// we detect the type of rawInput and return the appropriate pointer
|
||||
func AccessTLSBuffers(conn net.Conn) (*bytes.Reader, **bytes.Buffer) {
|
||||
input := utils.AccessField[bytes.Reader](conn, "input")
|
||||
field := reflect.ValueOf(conn).Elem().FieldByName("rawInput")
|
||||
if field.Kind() == reflect.Pointer {
|
||||
return input, utils.AccessField[*bytes.Buffer](conn, "rawInput")
|
||||
}
|
||||
raw := utils.AccessField[bytes.Buffer](conn, "rawInput")
|
||||
return input, &raw
|
||||
}
|
||||
|
||||
+14
-11
@@ -16,9 +16,8 @@ import (
|
||||
)
|
||||
|
||||
type bind struct {
|
||||
ctx context.Context
|
||||
resolveFunc func(host string) (net.IP, error)
|
||||
listenFunc func(ctx context.Context) (net.PacketConn, error)
|
||||
listenFunc func() (net.PacketConn, error)
|
||||
downFunc func() error
|
||||
reserved []byte
|
||||
|
||||
@@ -27,12 +26,6 @@ type bind struct {
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (b *bind) SetCtx(ctx context.Context) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.ctx = ctx
|
||||
}
|
||||
|
||||
func (b *bind) Open(port uint16) (fns []conn.ReceiveFunc, actualPort uint16, err error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
@@ -41,7 +34,7 @@ func (b *bind) Open(port uint16) (fns []conn.ReceiveFunc, actualPort uint16, err
|
||||
return nil, 0, conn.ErrBindAlreadyOpen
|
||||
}
|
||||
|
||||
c, err := b.listenFunc(b.ctx)
|
||||
c, err := b.listenFunc()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
@@ -59,9 +52,12 @@ func (b *bind) Open(port uint16) (fns []conn.ReceiveFunc, actualPort uint16, err
|
||||
case <-ch:
|
||||
default:
|
||||
errors.LogErrorInner(context.Background(), err, "unexpected closed")
|
||||
if b.downFunc != nil {
|
||||
b.mu.Lock()
|
||||
downFunc := b.downFunc
|
||||
b.mu.Unlock()
|
||||
if downFunc != nil {
|
||||
go func() {
|
||||
common.Must(b.downFunc())
|
||||
common.Must(downFunc())
|
||||
}()
|
||||
}
|
||||
}
|
||||
@@ -83,6 +79,13 @@ func (b *bind) Open(port uint16) (fns []conn.ReceiveFunc, actualPort uint16, err
|
||||
}, uint16(c.LocalAddr().(*net.UDPAddr).Port), nil
|
||||
}
|
||||
|
||||
// setDownFunc sets downFunc after the device is created, since the device may already be using the bind.
|
||||
func (b *bind) setDownFunc(f func() error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.downFunc = f
|
||||
}
|
||||
|
||||
func (b *bind) Close() error {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
+151
-167
@@ -7,7 +7,6 @@ import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"golang.zx2c4.com/wireguard/tun"
|
||||
@@ -32,14 +31,18 @@ import (
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
p policy.Manager
|
||||
conf *DeviceConfig
|
||||
policyManager policy.Manager
|
||||
dns dns.Client
|
||||
|
||||
canup *atomic.Bool
|
||||
tnet *Net
|
||||
bind *bind
|
||||
dev *device.Device
|
||||
ipc string
|
||||
mu sync.Mutex
|
||||
streamSettings *internet.MemoryStreamConfig
|
||||
uplinkCounter stats.Counter
|
||||
downlinkCounter stats.Counter
|
||||
|
||||
tun tun.Device
|
||||
tnet *Net
|
||||
dev *device.Device
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func NewClient(ctx context.Context, conf *DeviceConfig) (*Handler, error) {
|
||||
@@ -114,93 +117,24 @@ func NewClient(ctx context.Context, conf *DeviceConfig) (*Handler, error) {
|
||||
errors.LogWarning(context.Background(), "Using kernel TUN")
|
||||
tun, tnet, err = createKernelTun(localAddresses, dnses, int(conf.Mtu))
|
||||
} else {
|
||||
errors.LogWarning(context.Background(), "Using built-in TCP/IP stack")
|
||||
tun, tnet, err = CreateNetTUN(localAddresses, dnses, int(conf.Mtu), nil)
|
||||
errors.LogWarning(context.Background(), "Using gVisor TUN")
|
||||
tun, tnet, _, err = CreateNetTUN(localAddresses, dnses, int(conf.Mtu), true)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
blockup := newblockup(tun)
|
||||
bind := &bind{}
|
||||
logger := &device.Logger{
|
||||
Verbosef: func(format string, args ...any) {
|
||||
log.Record(&log.GeneralMessage{
|
||||
Severity: log.Severity_Debug,
|
||||
Content: fmt.Sprintf(format, args...),
|
||||
})
|
||||
},
|
||||
Errorf: func(format string, args ...any) {
|
||||
log.Record(&log.GeneralMessage{
|
||||
Severity: log.Severity_Error,
|
||||
Content: fmt.Sprintf(format, args...),
|
||||
})
|
||||
},
|
||||
}
|
||||
dev := device.NewDevice(blockup, bind, logger)
|
||||
bind.ctx = context.Background()
|
||||
bind.resolveFunc = MakeResolveLocal(d, streamSettings)
|
||||
bind.listenFunc = func(ctx context.Context) (net.PacketConn, error) {
|
||||
dest, err := net.ParseDestination("udp:" + conf.Peers[0].Endpoint)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var pktConn net.PacketConn
|
||||
if streamSettings.FinalMask != nil {
|
||||
conn, err := streamSettings.FinalMask.DialUDP(ctx, dest)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to dial to dest").Base(err)
|
||||
}
|
||||
pktConn = conn.(*net.PacketConnWrapper).PacketConn
|
||||
} else {
|
||||
conn, err := internet.DialSystem(ctx, dest, streamSettings.SocketSettings)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to dial to dest").Base(err)
|
||||
}
|
||||
switch c := conn.(type) {
|
||||
case *net.PacketConnWrapper:
|
||||
pktConn = c.PacketConn
|
||||
case *cnc.Connection:
|
||||
pktConn = &internet.FakePacketConn{Conn: c}
|
||||
default:
|
||||
panic(reflect.TypeOf(c))
|
||||
}
|
||||
}
|
||||
if uplinkCounter != nil || downlinkCounter != nil {
|
||||
pktConn = &PacketCounterConnection{
|
||||
PacketConn: pktConn,
|
||||
ReadCounter: downlinkCounter,
|
||||
WriteCounter: uplinkCounter,
|
||||
}
|
||||
}
|
||||
return pktConn, nil
|
||||
}
|
||||
bind.downFunc = dev.Down
|
||||
bind.reserved = conf.Reserved
|
||||
var cfg strings.Builder
|
||||
cfg.WriteString("private_key=" + conf.SecretKey + "\n")
|
||||
for _, peer := range conf.Peers {
|
||||
cfg.WriteString("public_key=" + peer.PublicKey + "\n")
|
||||
if peer.PreSharedKey != "" {
|
||||
cfg.WriteString("preshared_key=" + peer.PreSharedKey + "\n")
|
||||
}
|
||||
cfg.WriteString("endpoint=" + peer.Endpoint + "\n")
|
||||
for _, ip := range peer.AllowedIps {
|
||||
cfg.WriteString("allowed_ip=" + ip + "\n")
|
||||
}
|
||||
if peer.KeepAlive != "" {
|
||||
cfg.WriteString("persistent_keepalive_interval=" + peer.KeepAlive + "\n")
|
||||
}
|
||||
}
|
||||
|
||||
return &Handler{
|
||||
p: p,
|
||||
conf: conf,
|
||||
policyManager: p,
|
||||
dns: d,
|
||||
|
||||
canup: blockup.canup,
|
||||
tnet: tnet,
|
||||
bind: bind,
|
||||
dev: dev,
|
||||
ipc: cfg.String(),
|
||||
streamSettings: streamSettings,
|
||||
uplinkCounter: uplinkCounter,
|
||||
downlinkCounter: downlinkCounter,
|
||||
|
||||
tun: tun,
|
||||
tnet: tnet,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -215,7 +149,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
ob.CanSpliceCopy = 3
|
||||
dialer.SetOutboundGateway(ctx, ob)
|
||||
|
||||
if err := h.up(ctx); err != nil {
|
||||
if err := h.init(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -225,7 +159,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
newCtx, newCancel = context.WithCancel(context.Background())
|
||||
}
|
||||
|
||||
sessionPolicy := h.p.ForLevel(0)
|
||||
sessionPolicy := h.policyManager.ForLevel(0)
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
timer := signal.CancelAfterInactivity(ctx, func() {
|
||||
cancel()
|
||||
@@ -300,72 +234,150 @@ func (h *Handler) Close() (err error) {
|
||||
if h.dev != nil {
|
||||
h.dev.Close()
|
||||
h.dev = nil
|
||||
h.tun = nil
|
||||
} else if h.tun != nil {
|
||||
h.tun.Close()
|
||||
h.tun = nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Handler) up(ctx context.Context) error {
|
||||
func (h *Handler) init(ctx context.Context) error {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.dev == nil {
|
||||
if h.tun == nil {
|
||||
return errors.New("closed")
|
||||
}
|
||||
h.bind.SetCtx(ctx)
|
||||
if !h.canup.Load() {
|
||||
h.canup.Store(true)
|
||||
if h.dev != nil {
|
||||
return h.dev.Up()
|
||||
}
|
||||
if len(h.ipc) > 0 {
|
||||
if err := h.dev.IpcSet(h.ipc); err != nil {
|
||||
return err
|
||||
}
|
||||
h.ipc = ""
|
||||
}
|
||||
return h.dev.Up()
|
||||
}
|
||||
|
||||
func MakeResolveLocal(d dns.Client, streamSettings *internet.MemoryStreamConfig) func(host string) (net.IP, error) {
|
||||
return func(host string) (net.IP, error) {
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
return ip, nil
|
||||
}
|
||||
ips, _, err := d.LookupIP(host, dns.IPOption{IPv4Enable: true, IPv6Enable: true})
|
||||
resolveFunc := h.resolveLocal
|
||||
listenFunc := func() (net.PacketConn, error) {
|
||||
dest, err := net.ParseDestination("udp:" + h.conf.Peers[0].Endpoint)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
got := ips
|
||||
if streamSettings.SocketSettings != nil {
|
||||
var got4, got6 []net.IP
|
||||
for _, ip := range ips {
|
||||
if ip.To4() != nil {
|
||||
got4 = append(got4, ip)
|
||||
} else {
|
||||
got6 = append(got6, ip)
|
||||
}
|
||||
var pktConn net.PacketConn
|
||||
if h.streamSettings.FinalMask != nil {
|
||||
conn, err := h.streamSettings.FinalMask.DialUDP(ctx, dest)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to dial to dest").Base(err)
|
||||
}
|
||||
switch streamSettings.SocketSettings.DomainStrategy {
|
||||
case internet.DomainStrategy_AS_IS, internet.DomainStrategy_USE_IP, internet.DomainStrategy_FORCE_IP:
|
||||
got = ips
|
||||
case internet.DomainStrategy_USE_IP4, internet.DomainStrategy_FORCE_IP4:
|
||||
got = got4
|
||||
case internet.DomainStrategy_USE_IP6, internet.DomainStrategy_FORCE_IP6:
|
||||
got = got6
|
||||
case internet.DomainStrategy_USE_IP46, internet.DomainStrategy_FORCE_IP46:
|
||||
got = got4
|
||||
if len(got) == 0 {
|
||||
got = got6
|
||||
}
|
||||
case internet.DomainStrategy_USE_IP64, internet.DomainStrategy_FORCE_IP64:
|
||||
got = got6
|
||||
if len(got) == 0 {
|
||||
got = got4
|
||||
}
|
||||
pktConn = conn.(*net.PacketConnWrapper).PacketConn
|
||||
} else {
|
||||
conn, err := internet.DialSystem(ctx, dest, h.streamSettings.SocketSettings)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to dial to dest").Base(err)
|
||||
}
|
||||
if len(got) == 0 {
|
||||
return nil, dns.ErrEmptyResponse
|
||||
switch c := conn.(type) {
|
||||
case *net.PacketConnWrapper:
|
||||
pktConn = c.PacketConn
|
||||
case *cnc.Connection:
|
||||
pktConn = &internet.FakePacketConn{Conn: c}
|
||||
default:
|
||||
panic(reflect.TypeOf(c))
|
||||
}
|
||||
}
|
||||
return got[dice.Roll(len(got))], nil
|
||||
if h.uplinkCounter != nil || h.downlinkCounter != nil {
|
||||
pktConn = &PacketCounterConnection{
|
||||
PacketConn: pktConn,
|
||||
ReadCounter: h.downlinkCounter,
|
||||
WriteCounter: h.uplinkCounter,
|
||||
}
|
||||
}
|
||||
return pktConn, nil
|
||||
}
|
||||
// device.NewDevice may use the bind right away (Up -> BindUpdate -> Open),
|
||||
// so everything it reads must be set before creating the device.
|
||||
bind := &bind{
|
||||
resolveFunc: resolveFunc,
|
||||
listenFunc: listenFunc,
|
||||
reserved: h.conf.Reserved,
|
||||
}
|
||||
logger := &device.Logger{
|
||||
Verbosef: func(format string, args ...any) {
|
||||
log.Record(&log.GeneralMessage{
|
||||
Severity: log.Severity_Debug,
|
||||
Content: fmt.Sprintf(format, args...),
|
||||
})
|
||||
},
|
||||
Errorf: func(format string, args ...any) {
|
||||
log.Record(&log.GeneralMessage{
|
||||
Severity: log.Severity_Error,
|
||||
Content: fmt.Sprintf(format, args...),
|
||||
})
|
||||
},
|
||||
}
|
||||
dev := device.NewDevice(h.tun, bind, logger)
|
||||
bind.setDownFunc(dev.Down)
|
||||
var cfg strings.Builder
|
||||
cfg.WriteString("private_key=" + h.conf.SecretKey + "\n")
|
||||
for _, peer := range h.conf.Peers {
|
||||
cfg.WriteString("public_key=" + peer.PublicKey + "\n")
|
||||
if peer.PreSharedKey != "" {
|
||||
cfg.WriteString("preshared_key=" + peer.PreSharedKey + "\n")
|
||||
}
|
||||
cfg.WriteString("endpoint=" + peer.Endpoint + "\n")
|
||||
for _, ip := range peer.AllowedIps {
|
||||
cfg.WriteString("allowed_ip=" + ip + "\n")
|
||||
}
|
||||
if peer.KeepAlive != "" {
|
||||
cfg.WriteString("persistent_keepalive_interval=" + peer.KeepAlive + "\n")
|
||||
}
|
||||
}
|
||||
err := dev.IpcSet(cfg.String())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = dev.Up()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h.dev = dev
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Handler) resolveLocal(host string) (net.IP, error) {
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
return ip, nil
|
||||
}
|
||||
ips, _, err := h.dns.LookupIP(host, dns.IPOption{IPv4Enable: true, IPv6Enable: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
got := ips
|
||||
if h.streamSettings.SocketSettings != nil {
|
||||
var got4, got6 []net.IP
|
||||
for _, ip := range ips {
|
||||
if ip.To4() != nil {
|
||||
got4 = append(got4, ip)
|
||||
} else {
|
||||
got6 = append(got6, ip)
|
||||
}
|
||||
}
|
||||
switch h.streamSettings.SocketSettings.DomainStrategy {
|
||||
case internet.DomainStrategy_AS_IS, internet.DomainStrategy_USE_IP, internet.DomainStrategy_FORCE_IP:
|
||||
got = ips
|
||||
case internet.DomainStrategy_USE_IP4, internet.DomainStrategy_FORCE_IP4:
|
||||
got = got4
|
||||
case internet.DomainStrategy_USE_IP6, internet.DomainStrategy_FORCE_IP6:
|
||||
got = got6
|
||||
case internet.DomainStrategy_USE_IP46, internet.DomainStrategy_FORCE_IP46:
|
||||
got = got4
|
||||
if len(got) == 0 {
|
||||
got = got6
|
||||
}
|
||||
case internet.DomainStrategy_USE_IP64, internet.DomainStrategy_FORCE_IP64:
|
||||
got = got6
|
||||
if len(got) == 0 {
|
||||
got = got4
|
||||
}
|
||||
}
|
||||
if len(got) == 0 {
|
||||
return nil, dns.ErrEmptyResponse
|
||||
}
|
||||
}
|
||||
return got[dice.Roll(len(got))], nil
|
||||
}
|
||||
|
||||
type UDPConnClient struct {
|
||||
@@ -498,31 +510,3 @@ func (c *cache) Cache(host string, saddr []string, ttl uint32) {
|
||||
deadline: time.Now().Add(time.Second * time.Duration(ttl)),
|
||||
}
|
||||
}
|
||||
|
||||
type blockup struct {
|
||||
tun.Device
|
||||
ch chan tun.Event
|
||||
canup *atomic.Bool
|
||||
}
|
||||
|
||||
func newblockup(t tun.Device) *blockup {
|
||||
ch := make(chan tun.Event, cap(t.Events()))
|
||||
canup := &atomic.Bool{}
|
||||
go func() {
|
||||
for e := range t.Events() {
|
||||
if e&tun.EventUp != 0 && !canup.Load() {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case ch <- e:
|
||||
default:
|
||||
}
|
||||
}
|
||||
close(ch)
|
||||
}()
|
||||
return &blockup{Device: t, ch: ch, canup: canup}
|
||||
}
|
||||
|
||||
func (b *blockup) Events() <-chan tun.Event {
|
||||
return b.ch
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package wireguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"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"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/transport/icmp"
|
||||
)
|
||||
|
||||
// CreateICMPEchoResponder answers ICMP echo requests from peers locally, the way
|
||||
// the TUN inbound does: ICMP is not proxied, but ping and connectivity checks
|
||||
// through the tunnel get a reply instead of timing out.
|
||||
//
|
||||
// In promiscuous mode gVisor skips its own IPv4 echo reply for addresses that are
|
||||
// not assigned to the NIC and leaves it to a custom handler; IPv6 is registered
|
||||
// too so both families behave the same.
|
||||
func CreateICMPEchoResponder(gstack *stack.Stack) {
|
||||
gstack.SetTransportProtocolHandler(icmp.ProtocolNumber4, func(id stack.TransportEndpointID, pkt *stack.PacketBuffer) bool {
|
||||
return handleICMPEcho(gstack, header.IPv4ProtocolNumber, id, pkt)
|
||||
})
|
||||
gstack.SetTransportProtocolHandler(icmp.ProtocolNumber6, func(id stack.TransportEndpointID, pkt *stack.PacketBuffer) bool {
|
||||
return handleICMPEcho(gstack, header.IPv6ProtocolNumber, id, pkt)
|
||||
})
|
||||
}
|
||||
|
||||
func handleICMPEcho(gstack *stack.Stack, 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
|
||||
}
|
||||
|
||||
headerBytes := pkt.TransportHeader().Slice()
|
||||
payloadBytes := pkt.Data().AsRange().ToSlice()
|
||||
message := make([]byte, len(headerBytes)+len(payloadBytes))
|
||||
copy(message, headerBytes)
|
||||
copy(message[len(headerBytes):], payloadBytes)
|
||||
|
||||
if _, _, ok := tunicmp.ParseEchoRequest(netProto, message); !ok {
|
||||
return true
|
||||
}
|
||||
|
||||
reply, err := tunicmp.BuildLocalEchoReply(netProto, message, dstIP, srcIP)
|
||||
if err != nil {
|
||||
errors.LogInfoInner(context.Background(), err, "failed to build local icmp echo reply")
|
||||
return true
|
||||
}
|
||||
if err := writeRawICMPPacket(gstack, netProto, reply, dstIP, srcIP); err != nil {
|
||||
errors.LogInfoInner(context.Background(), err, "failed to write local icmp echo reply")
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func writeRawICMPPacket(gstack *stack.Stack, netProto tcpip.NetworkProtocolNumber, message []byte, srcIP, dstIP tcpip.Address) error {
|
||||
pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
|
||||
ReserveHeaderBytes: header.IPv6MinimumSize,
|
||||
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(header.ICMPv4ProtocolNumber),
|
||||
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: header.ICMPv6ProtocolNumber,
|
||||
HopLimit: 64,
|
||||
SrcAddr: srcIP,
|
||||
DstAddr: dstIP,
|
||||
})
|
||||
}
|
||||
|
||||
if err := gstack.WriteRawPacket(1, netProto, buffer.MakeWithView(pkt.ToView())); err != nil {
|
||||
return errors.New("failed to write raw icmp packet back to stack ", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package wireguard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"gvisor.dev/gvisor/pkg/tcpip"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/checksum"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/header"
|
||||
)
|
||||
|
||||
func newICMPTestStack(t *testing.T) *netTun {
|
||||
t.Helper()
|
||||
dev, _, gstack, err := CreateNetTUN([]netip.Addr{
|
||||
netip.MustParseAddr("10.66.0.1"),
|
||||
netip.MustParseAddr("fd00::1"),
|
||||
}, nil, 1420, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { dev.Close() })
|
||||
CreateForwarder(gstack, func(conn net.Conn, dest net.Destination) { conn.Close() })
|
||||
CreateICMPEchoResponder(gstack)
|
||||
return dev.(*netTun)
|
||||
}
|
||||
|
||||
// startReader must run before the request is written: the stack may answer
|
||||
// synchronously inside Write, and netTun hands packets over an unbuffered channel.
|
||||
func startReader(dev *netTun) <-chan []byte {
|
||||
got := make(chan []byte, 1)
|
||||
go func() {
|
||||
buf := make([]byte, 2048)
|
||||
sizes := make([]int, 1)
|
||||
if _, err := dev.Read([][]byte{buf}, sizes, 0); err == nil {
|
||||
got <- buf[:sizes[0]]
|
||||
}
|
||||
}()
|
||||
return got
|
||||
}
|
||||
|
||||
func awaitPacket(t *testing.T, got <-chan []byte) []byte {
|
||||
t.Helper()
|
||||
select {
|
||||
case p := <-got:
|
||||
return p
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("no echo reply from the stack")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func TestICMPv4EchoReply(t *testing.T) {
|
||||
dev := newICMPTestStack(t)
|
||||
src := tcpip.AddrFrom4([4]byte{10, 66, 0, 2})
|
||||
dst := tcpip.AddrFrom4([4]byte{1, 1, 1, 1})
|
||||
payload := []byte("xray wireguard ping")
|
||||
|
||||
icmpMsg := make([]byte, header.ICMPv4MinimumSize+len(payload))
|
||||
req := header.ICMPv4(icmpMsg)
|
||||
req.SetType(header.ICMPv4Echo)
|
||||
req.SetIdent(0x1234)
|
||||
req.SetSequence(7)
|
||||
copy(req.Payload(), payload)
|
||||
req.SetChecksum(header.ICMPv4Checksum(req[:header.ICMPv4MinimumSize], checksum.Checksum(payload, 0)))
|
||||
|
||||
pkt := make([]byte, header.IPv4MinimumSize+len(icmpMsg))
|
||||
ip := header.IPv4(pkt)
|
||||
ip.Encode(&header.IPv4Fields{
|
||||
TotalLength: uint16(len(pkt)),
|
||||
TTL: 64,
|
||||
Protocol: uint8(header.ICMPv4ProtocolNumber),
|
||||
SrcAddr: src,
|
||||
DstAddr: dst,
|
||||
})
|
||||
ip.SetChecksum(^ip.CalculateChecksum())
|
||||
copy(pkt[header.IPv4MinimumSize:], icmpMsg)
|
||||
|
||||
got := startReader(dev)
|
||||
if _, err := dev.Write([][]byte{pkt}, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
reply := header.IPv4(awaitPacket(t, got))
|
||||
if !reply.IsValid(len(reply)) {
|
||||
t.Fatal("invalid ipv4 reply")
|
||||
}
|
||||
if reply.SourceAddress() != dst || reply.DestinationAddress() != src {
|
||||
t.Fatalf("reply addresses %v -> %v, want %v -> %v", reply.SourceAddress(), reply.DestinationAddress(), dst, src)
|
||||
}
|
||||
if reply.TransportProtocol() != header.ICMPv4ProtocolNumber {
|
||||
t.Fatalf("reply protocol %v, want icmpv4", reply.TransportProtocol())
|
||||
}
|
||||
echo := header.ICMPv4(reply.Payload())
|
||||
if echo.Type() != header.ICMPv4EchoReply {
|
||||
t.Fatalf("reply type %v, want echo reply", echo.Type())
|
||||
}
|
||||
if echo.Ident() != 0x1234 || echo.Sequence() != 7 {
|
||||
t.Fatalf("reply ident/seq %#x/%d, want 0x1234/7", echo.Ident(), echo.Sequence())
|
||||
}
|
||||
if !bytes.Equal(echo.Payload(), payload) {
|
||||
t.Fatalf("reply payload %q, want %q", echo.Payload(), payload)
|
||||
}
|
||||
if checksum.Checksum(echo, 0) != 0xffff {
|
||||
t.Fatal("bad icmpv4 checksum")
|
||||
}
|
||||
}
|
||||
|
||||
func TestICMPv6EchoReply(t *testing.T) {
|
||||
dev := newICMPTestStack(t)
|
||||
src := tcpip.AddrFrom16([16]byte{0xfd, 15: 2})
|
||||
dst := tcpip.AddrFrom16([16]byte{0x26, 0x06, 0x47, 0x00, 0x47, 0x00, 15: 0x11})
|
||||
payload := []byte("xray wireguard ping6")
|
||||
|
||||
icmpMsg := make([]byte, header.ICMPv6MinimumSize+len(payload))
|
||||
req := header.ICMPv6(icmpMsg)
|
||||
req.SetType(header.ICMPv6EchoRequest)
|
||||
req.SetIdent(0x4321)
|
||||
req.SetSequence(9)
|
||||
copy(req.Payload(), payload)
|
||||
req.SetChecksum(header.ICMPv6Checksum(header.ICMPv6ChecksumParams{
|
||||
Header: req[:header.ICMPv6MinimumSize],
|
||||
Src: src,
|
||||
Dst: dst,
|
||||
PayloadCsum: checksum.Checksum(payload, 0),
|
||||
PayloadLen: len(payload),
|
||||
}))
|
||||
|
||||
pkt := make([]byte, header.IPv6MinimumSize+len(icmpMsg))
|
||||
ip := header.IPv6(pkt)
|
||||
ip.Encode(&header.IPv6Fields{
|
||||
PayloadLength: uint16(len(icmpMsg)),
|
||||
TransportProtocol: header.ICMPv6ProtocolNumber,
|
||||
HopLimit: 64,
|
||||
SrcAddr: src,
|
||||
DstAddr: dst,
|
||||
})
|
||||
copy(pkt[header.IPv6MinimumSize:], icmpMsg)
|
||||
|
||||
got := startReader(dev)
|
||||
if _, err := dev.Write([][]byte{pkt}, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
reply := header.IPv6(awaitPacket(t, got))
|
||||
if !reply.IsValid(len(reply)) {
|
||||
t.Fatal("invalid ipv6 reply")
|
||||
}
|
||||
if reply.SourceAddress() != dst || reply.DestinationAddress() != src {
|
||||
t.Fatalf("reply addresses %v -> %v, want %v -> %v", reply.SourceAddress(), reply.DestinationAddress(), dst, src)
|
||||
}
|
||||
echo := header.ICMPv6(reply.Payload())
|
||||
if echo.Type() != header.ICMPv6EchoReply {
|
||||
t.Fatalf("reply type %v, want echo reply", echo.Type())
|
||||
}
|
||||
if echo.Ident() != 0x4321 || echo.Sequence() != 9 {
|
||||
t.Fatalf("reply ident/seq %#x/%d, want 0x4321/9", echo.Ident(), echo.Sequence())
|
||||
}
|
||||
if !bytes.Equal(echo.Payload(), payload) {
|
||||
t.Fatalf("reply payload %q, want %q", echo.Payload(), payload)
|
||||
}
|
||||
zeroed := header.ICMPv6(append([]byte(nil), echo[:header.ICMPv6MinimumSize]...))
|
||||
zeroed.SetChecksum(0)
|
||||
want := header.ICMPv6Checksum(header.ICMPv6ChecksumParams{
|
||||
Header: zeroed,
|
||||
Src: dst,
|
||||
Dst: src,
|
||||
PayloadCsum: checksum.Checksum(echo.Payload(), 0),
|
||||
PayloadLen: len(echo.Payload()),
|
||||
})
|
||||
if echo.Checksum() != want {
|
||||
t.Fatalf("icmpv6 checksum %#x, want %#x", echo.Checksum(), want)
|
||||
}
|
||||
}
|
||||
+146
-82
@@ -10,6 +10,7 @@ import (
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/netip"
|
||||
@@ -17,63 +18,101 @@ import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
xnet "github.com/xtls/xray-core/common/net"
|
||||
xtun "github.com/xtls/xray-core/proxy/tun"
|
||||
"golang.zx2c4.com/wireguard/tun"
|
||||
|
||||
"golang.org/x/net/dns/dnsmessage"
|
||||
"gvisor.dev/gvisor/pkg/buffer"
|
||||
"gvisor.dev/gvisor/pkg/tcpip"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/header"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/link/channel"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
|
||||
"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"
|
||||
)
|
||||
|
||||
// netTunQueue is how many packets of the stack can wait to be read from its device
|
||||
const netTunQueue = 1024
|
||||
|
||||
// netTun is the device of a TCP/IP stack of Xray: what is written to it goes to the stack,
|
||||
// and what the stack sends is read from it
|
||||
type netTun struct {
|
||||
stack xtun.Stack
|
||||
events chan tun.Event
|
||||
// packets are what the stack has sent and Read has not taken yet
|
||||
packets chan *buf.Buffer
|
||||
closed chan struct{}
|
||||
closeOnce sync.Once
|
||||
mtu int
|
||||
ep *channel.Endpoint
|
||||
stack *stack.Stack
|
||||
events chan tun.Event
|
||||
notifyHandle *channel.NotificationHandle
|
||||
incomingPacket chan *buffer.View
|
||||
closed chan struct{}
|
||||
mtu int
|
||||
dnsServers []netip.Addr
|
||||
hasV4, hasV6 bool
|
||||
}
|
||||
|
||||
// CreateNetTUN returns a device with a TCP/IP stack on it, and what opens connections through that from
|
||||
// localAddresses. With a handler the stack takes every connection that comes from the device, for any address.
|
||||
// Without one it takes none
|
||||
func CreateNetTUN(localAddresses, dnsServers []netip.Addr, mtu int, handler xtun.ConnectionHandler) (tun.Device, *Net, error) {
|
||||
func CreateNetTUN(localAddresses, dnsServers []netip.Addr, mtu int, handleLocal bool) (tun.Device, *Net, *stack.Stack, error) {
|
||||
opts := stack.Options{
|
||||
NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
|
||||
TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol, icmp.NewProtocol6, icmp.NewProtocol4},
|
||||
HandleLocal: handleLocal,
|
||||
}
|
||||
dev := &netTun{
|
||||
events: make(chan tun.Event, 10),
|
||||
packets: make(chan *buf.Buffer, netTunQueue),
|
||||
closed: make(chan struct{}),
|
||||
mtu: mtu,
|
||||
ep: channel.New(1024, uint32(mtu), ""),
|
||||
stack: stack.New(opts),
|
||||
events: make(chan tun.Event, 10),
|
||||
incomingPacket: make(chan *buffer.View),
|
||||
closed: make(chan struct{}),
|
||||
dnsServers: dnsServers,
|
||||
mtu: mtu,
|
||||
}
|
||||
stack, err := xtun.NewStack(context.Background(), xtun.StackOptions{Tun: dev, MTU: uint32(mtu), Addresses: localAddresses, Remote: true}, handler)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
sackEnabledOpt := tcpip.TCPSACKEnabled(true) // TCP SACK is disabled by default
|
||||
tcpipErr := dev.stack.SetTransportProtocolOption(tcp.ProtocolNumber, &sackEnabledOpt)
|
||||
if tcpipErr != nil {
|
||||
return nil, nil, nil, fmt.Errorf("could not enable TCP SACK: %v", tcpipErr)
|
||||
}
|
||||
dev.stack = stack
|
||||
|
||||
tnet := &Net{
|
||||
DialContextTCPAddrPort: stack.DialTCP,
|
||||
DialUDPAddrPort: dev.DialUDPAddrPort,
|
||||
dnsServers: dnsServers,
|
||||
dev.notifyHandle = dev.ep.AddNotify(dev)
|
||||
tcpipErr = dev.stack.CreateNIC(1, dev.ep)
|
||||
if tcpipErr != nil {
|
||||
return nil, nil, nil, fmt.Errorf("CreateNIC: %v", tcpipErr)
|
||||
}
|
||||
for _, ip := range localAddresses {
|
||||
var protoNumber tcpip.NetworkProtocolNumber
|
||||
if ip.Is4() {
|
||||
tnet.hasV4 = true
|
||||
protoNumber = ipv4.ProtocolNumber
|
||||
} else if ip.Is6() {
|
||||
tnet.hasV6 = true
|
||||
protoNumber = ipv6.ProtocolNumber
|
||||
}
|
||||
protoAddr := tcpip.ProtocolAddress{
|
||||
Protocol: protoNumber,
|
||||
AddressWithPrefix: tcpip.AddrFromSlice(ip.AsSlice()).WithPrefix(),
|
||||
}
|
||||
tcpipErr := dev.stack.AddProtocolAddress(1, protoAddr, stack.AddressProperties{})
|
||||
if tcpipErr != nil {
|
||||
return nil, nil, nil, fmt.Errorf("AddProtocolAddress(%v): %v", ip, tcpipErr)
|
||||
}
|
||||
if ip.Is4() {
|
||||
dev.hasV4 = true
|
||||
} else if ip.Is6() {
|
||||
dev.hasV6 = true
|
||||
}
|
||||
}
|
||||
if dev.hasV4 {
|
||||
dev.stack.AddRoute(tcpip.Route{Destination: header.IPv4EmptySubnet, NIC: 1})
|
||||
}
|
||||
if dev.hasV6 {
|
||||
dev.stack.AddRoute(tcpip.Route{Destination: header.IPv6EmptySubnet, NIC: 1})
|
||||
}
|
||||
|
||||
tnet := &Net{
|
||||
DialContextTCPAddrPort: dev.DialContextTCPAddrPort,
|
||||
DialUDPAddrPort: dev.DialUDPAddrPort,
|
||||
dnsServers: dev.dnsServers,
|
||||
hasV4: dev.hasV4,
|
||||
hasV6: dev.hasV6,
|
||||
}
|
||||
|
||||
dev.events <- tun.EventUp
|
||||
return dev, tnet, nil
|
||||
return dev, tnet, dev.stack, nil
|
||||
}
|
||||
|
||||
func (tun *netTun) Name() (string, error) {
|
||||
@@ -89,62 +128,73 @@ func (tun *netTun) Events() <-chan tun.Event {
|
||||
}
|
||||
|
||||
func (tun *netTun) Read(buf [][]byte, sizes []int, offset int) (int, error) {
|
||||
var view *buffer.View
|
||||
select {
|
||||
case packet := <-tun.packets:
|
||||
sizes[0] = copy(buf[0][offset:], packet.Bytes())
|
||||
packet.Release()
|
||||
return 1, nil
|
||||
case view = <-tun.incomingPacket:
|
||||
case <-tun.closed:
|
||||
return 0, os.ErrClosed
|
||||
}
|
||||
|
||||
n, err := view.Read(buf[0][offset:])
|
||||
view.Release()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
sizes[0] = n
|
||||
return 1, nil
|
||||
}
|
||||
|
||||
func (tun *netTun) Write(buf [][]byte, offset int) (int, error) {
|
||||
for _, buf := range buf {
|
||||
tun.stack.Input(buf[offset:])
|
||||
packet := buf[offset:]
|
||||
if len(packet) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
pkb := stack.NewPacketBuffer(stack.PacketBufferOptions{Payload: buffer.MakeWithData(packet)})
|
||||
switch packet[0] >> 4 {
|
||||
case 4:
|
||||
tun.ep.InjectInbound(header.IPv4ProtocolNumber, pkb)
|
||||
case 6:
|
||||
tun.ep.InjectInbound(header.IPv6ProtocolNumber, pkb)
|
||||
default:
|
||||
return 0, syscall.EAFNOSUPPORT
|
||||
}
|
||||
}
|
||||
return len(buf), nil
|
||||
}
|
||||
|
||||
// WritePacket implements xtun.Tun. The packet is in the hands of the stack only until this returns, so it is copied
|
||||
// for Read. The stack does not wait for the one who reads the device, unless that one is far behind: it answers
|
||||
// what it is written inside Write, and whoever writes would wait with it and lose what comes meanwhile
|
||||
func (tun *netTun) WritePacket(header, payload []byte) error {
|
||||
packet := buf.NewWithSize(int32(len(header) + len(payload)))
|
||||
packet.Write(header)
|
||||
packet.Write(payload)
|
||||
func (tun *netTun) WriteNotify() {
|
||||
pkt := tun.ep.Read()
|
||||
if pkt == nil {
|
||||
return
|
||||
}
|
||||
|
||||
view := pkt.ToView()
|
||||
pkt.DecRef()
|
||||
|
||||
select {
|
||||
case tun.packets <- packet:
|
||||
return nil
|
||||
case tun.incomingPacket <- view:
|
||||
case <-tun.closed:
|
||||
packet.Release()
|
||||
return os.ErrClosed
|
||||
view.Release()
|
||||
}
|
||||
}
|
||||
|
||||
// ReadPacket implements xtun.Tun. It is not called: the packets are handed to the stack by Write
|
||||
func (tun *netTun) ReadPacket([]byte) ([]byte, error) {
|
||||
<-tun.closed
|
||||
return nil, os.ErrClosed
|
||||
}
|
||||
|
||||
// Start implements xtun.Tun
|
||||
func (tun *netTun) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Index implements xtun.Tun
|
||||
func (tun *netTun) Index() (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (tun *netTun) Close() error {
|
||||
tun.closeOnce.Do(func() {
|
||||
// before the stack ends its connections: nobody may be reading anymore what it writes for that
|
||||
close(tun.closed)
|
||||
tun.stack.Close()
|
||||
tun.stack.RemoveNIC(1)
|
||||
tun.stack.Close()
|
||||
tun.ep.RemoveNotify(tun.notifyHandle)
|
||||
tun.ep.Close()
|
||||
|
||||
if tun.events != nil {
|
||||
close(tun.events)
|
||||
})
|
||||
}
|
||||
|
||||
// we don't close incomingPacket, because WriteNotify may be mid-send on it (DNS lookup) and would panic.
|
||||
if tun.closed != nil {
|
||||
close(tun.closed)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -156,8 +206,17 @@ func (tun *netTun) BatchSize() int {
|
||||
return 1
|
||||
}
|
||||
|
||||
func (tun *netTun) DialContextTCPAddrPort(ctx context.Context, addr netip.AddrPort) (net.Conn, error) {
|
||||
fa, pn := convertToFullAddr(addr)
|
||||
return gonet.DialContextTCP(ctx, tun.stack, fa, pn)
|
||||
}
|
||||
|
||||
func (tun *netTun) DialUDPAddrPort(laddr, raddr netip.AddrPort) (net.Conn, error) {
|
||||
conn, err := tun.stack.DialUDP()
|
||||
var pn tcpip.NetworkProtocolNumber = ipv6.ProtocolNumber
|
||||
if raddr.IsValid() || raddr.Port() > 0 {
|
||||
_, pn = convertToFullAddr(raddr)
|
||||
}
|
||||
conn, err := gonet.DialUDP(tun.stack, nil, nil, pn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -175,6 +234,20 @@ type Net struct {
|
||||
cache cache
|
||||
}
|
||||
|
||||
func convertToFullAddr(endpoint netip.AddrPort) (tcpip.FullAddress, tcpip.NetworkProtocolNumber) {
|
||||
var protoNumber tcpip.NetworkProtocolNumber
|
||||
if endpoint.Addr().Is4() {
|
||||
protoNumber = ipv4.ProtocolNumber
|
||||
} else {
|
||||
protoNumber = ipv6.ProtocolNumber
|
||||
}
|
||||
return tcpip.FullAddress{
|
||||
NIC: 1,
|
||||
Addr: tcpip.AddrFromSlice(endpoint.Addr().AsSlice()),
|
||||
Port: endpoint.Port(),
|
||||
}, protoNumber
|
||||
}
|
||||
|
||||
var (
|
||||
errNoSuchHost = errors.New("no such host")
|
||||
errLameReferral = errors.New("lame referral")
|
||||
@@ -378,8 +451,6 @@ func (tnet *Net) exchange(ctx context.Context, server netip.Addr, q dnsmessage.Q
|
||||
return dnsmessage.Parser{}, dnsmessage.Header{}, err
|
||||
}
|
||||
}
|
||||
// what is opened through the stack of Xray takes no deadline, it ends when it is closed
|
||||
stop := context.AfterFunc(ctx, func() { c.Close() })
|
||||
var p dnsmessage.Parser
|
||||
var h dnsmessage.Header
|
||||
if useUDP {
|
||||
@@ -387,15 +458,8 @@ func (tnet *Net) exchange(ctx context.Context, server netip.Addr, q dnsmessage.Q
|
||||
} else {
|
||||
p, h, err = dnsStreamRoundTrip(c, id, q, tcpReq)
|
||||
}
|
||||
stop()
|
||||
c.Close()
|
||||
if err != nil {
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
// as from a connection that takes a deadline
|
||||
err = &net.OpError{Op: "read", Net: c.RemoteAddr().Network(), Err: os.ErrDeadlineExceeded}
|
||||
} else if ctx.Err() != nil {
|
||||
err = ctx.Err()
|
||||
}
|
||||
if err == context.Canceled {
|
||||
err = errCanceled
|
||||
} else if err == context.DeadlineExceeded {
|
||||
|
||||
@@ -1,310 +0,0 @@
|
||||
package wireguard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
gonet "net"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"golang.org/x/net/dns/dnsmessage"
|
||||
"golang.zx2c4.com/wireguard/tun"
|
||||
)
|
||||
|
||||
type closeHandler struct{}
|
||||
|
||||
func (closeHandler) HandleConnection(conn net.Conn, _ net.Destination) { conn.Close() }
|
||||
|
||||
// onesSum is the Internet checksum of b on top of initial, not inverted.
|
||||
func onesSum(b []byte, initial uint32) uint16 {
|
||||
sum := initial
|
||||
for ; len(b) >= 2; b = b[2:] {
|
||||
sum += uint32(binary.BigEndian.Uint16(b))
|
||||
}
|
||||
if len(b) == 1 {
|
||||
sum += uint32(b[0]) << 8
|
||||
}
|
||||
for sum>>16 != 0 {
|
||||
sum = sum>>16 + sum&0xffff
|
||||
}
|
||||
return uint16(sum)
|
||||
}
|
||||
|
||||
// The inbound answers ICMP echo requests from peers locally, the way the TUN
|
||||
// inbound does: ICMP is not proxied, but ping and connectivity checks through
|
||||
// the tunnel get a reply instead of timing out. The request goes in through
|
||||
// Write and the reply comes out of Read, as the WireGuard device uses them.
|
||||
func TestNetTUNEchoReply(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
src, dst string
|
||||
request byte
|
||||
reply byte
|
||||
}{
|
||||
{"10.66.0.2", "1.1.1.1", 8, 0},
|
||||
{"fd00::2", "2606:4700:4700::1111", 128, 129},
|
||||
} {
|
||||
dev, _, err := CreateNetTUN([]netip.Addr{netip.MustParseAddr("10.66.0.1"), netip.MustParseAddr("fd00::1")}, nil, 1420, closeHandler{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src, dst := netip.MustParseAddr(test.src), netip.MustParseAddr(test.dst)
|
||||
payload := []byte("xray wireguard ping")
|
||||
message := append([]byte{test.request, 0, 0, 0, 0x12, 0x34, 0, 7}, payload...)
|
||||
|
||||
// The stack drops what has a wrong checksum, as what comes through a tunnel has come a long way.
|
||||
var pkt []byte
|
||||
if src.Is4() {
|
||||
pkt = make([]byte, 20, 20+len(message))
|
||||
pkt[0] = 0x45
|
||||
binary.BigEndian.PutUint16(pkt[2:], uint16(20+len(message)))
|
||||
pkt[8], pkt[9] = 64, 1
|
||||
copy(pkt[12:], src.AsSlice())
|
||||
copy(pkt[16:], dst.AsSlice())
|
||||
binary.BigEndian.PutUint16(pkt[10:], ^onesSum(pkt, 0))
|
||||
binary.BigEndian.PutUint16(message[2:], ^onesSum(message, 0))
|
||||
} else {
|
||||
pkt = make([]byte, 40, 40+len(message))
|
||||
pkt[0] = 0x60
|
||||
binary.BigEndian.PutUint16(pkt[4:], uint16(len(message)))
|
||||
pkt[6], pkt[7] = 58, 64
|
||||
copy(pkt[8:], src.AsSlice())
|
||||
copy(pkt[24:], dst.AsSlice())
|
||||
binary.BigEndian.PutUint16(message[2:], ^onesSum(message, uint32(onesSum(pkt[8:40], uint32(len(message))+58))))
|
||||
}
|
||||
pkt = append(pkt, message...)
|
||||
damaged := bytes.Clone(pkt)
|
||||
damaged[len(damaged)-1] ^= 1
|
||||
|
||||
// The stack answers inside Write, the reply waits for whoever reads the device.
|
||||
got := make(chan []byte, 1)
|
||||
const offset = 16
|
||||
go func() {
|
||||
b := make([]byte, 2048)
|
||||
sizes := make([]int, 1)
|
||||
if _, err := dev.Read([][]byte{b}, sizes, offset); err == nil {
|
||||
got <- b[offset : offset+sizes[0]]
|
||||
}
|
||||
}()
|
||||
if _, err := dev.Write([][]byte{append(make([]byte, offset), damaged...), append(make([]byte, offset), pkt...)}, offset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var reply []byte
|
||||
select {
|
||||
case reply = <-got:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("no echo reply from the stack")
|
||||
}
|
||||
|
||||
header := len(pkt) - len(message)
|
||||
if len(reply) != len(pkt) || reply[0] != pkt[0] {
|
||||
t.Fatalf("reply of %d bytes, version byte %#x", len(reply), reply[0])
|
||||
}
|
||||
var replySrc, replyDst netip.Addr
|
||||
pseudo := uint32(0)
|
||||
if src.Is4() {
|
||||
replySrc, replyDst = netip.AddrFrom4([4]byte(reply[12:16])), netip.AddrFrom4([4]byte(reply[16:20]))
|
||||
if onesSum(reply[:20], 0) != 0xffff || reply[9] != 1 {
|
||||
t.Fatal("bad ipv4 header in the reply")
|
||||
}
|
||||
} else {
|
||||
replySrc, replyDst = netip.AddrFrom16([16]byte(reply[8:24])), netip.AddrFrom16([16]byte(reply[24:40]))
|
||||
if reply[6] != 58 {
|
||||
t.Fatalf("reply protocol %d, want icmpv6", reply[6])
|
||||
}
|
||||
pseudo = uint32(onesSum(reply[8:40], uint32(len(message))+58))
|
||||
}
|
||||
if replySrc != dst || replyDst != src {
|
||||
t.Fatalf("reply addresses %v -> %v, want %v -> %v", replySrc, replyDst, dst, src)
|
||||
}
|
||||
echo := reply[header:]
|
||||
if echo[0] != test.reply || echo[1] != 0 {
|
||||
t.Fatalf("reply type %d code %d, want echo reply", echo[0], echo[1])
|
||||
}
|
||||
// A reply to the damaged request, which came first, would not have this payload.
|
||||
if !bytes.Equal(echo[4:], message[4:]) {
|
||||
t.Fatalf("reply ident, seq and payload %x, want %x", echo[4:], message[4:])
|
||||
}
|
||||
if onesSum(echo, pseudo) != 0xffff {
|
||||
t.Fatal("bad icmp checksum in the reply")
|
||||
}
|
||||
|
||||
dev.Close()
|
||||
dev.Close()
|
||||
if _, err := dev.Read([][]byte{make([]byte, 2048)}, make([]int, 1), 0); err == nil {
|
||||
t.Fatal("read from a closed device")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// testServer answers what comes through the device of a server: names over UDP port 53, except those that
|
||||
// start with "silent", and everything else with what it was sent.
|
||||
type testServer struct{}
|
||||
|
||||
func (testServer) HandleConnection(conn net.Conn, dest net.Destination) {
|
||||
defer conn.Close()
|
||||
b := make([]byte, 4096)
|
||||
for {
|
||||
n, err := conn.Read(b)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
answer := b[:n]
|
||||
if dest.Network == net.Network_UDP && dest.Port == 53 {
|
||||
var parser dnsmessage.Parser
|
||||
header, err := parser.Start(b[:n])
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
question, err := parser.Question()
|
||||
if err != nil || strings.HasPrefix(question.Name.String(), "silent") {
|
||||
continue
|
||||
}
|
||||
builder := dnsmessage.NewBuilder(nil, dnsmessage.Header{ID: header.ID, Response: true, RecursionAvailable: true})
|
||||
builder.StartQuestions()
|
||||
builder.Question(question)
|
||||
builder.StartAnswers()
|
||||
builder.AResource(dnsmessage.ResourceHeader{Name: question.Name, Class: dnsmessage.ClassINET, TTL: 60}, dnsmessage.AResource{A: [4]byte{192, 0, 2, 1}})
|
||||
if answer, err = builder.Finish(); err != nil {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if _, err := conn.Write(answer); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A client and a server, each with a stack on its device and the two devices joined as a tunnel joins them:
|
||||
// names are resolved, and TCP and UDP go through, as the outbound and the inbound use them.
|
||||
func TestNetTUNClientAndServer(t *testing.T) {
|
||||
server, _, err := CreateNetTUN([]netip.Addr{netip.MustParseAddr("10.66.0.1")}, nil, 1420, testServer{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client, tnet, err := CreateNetTUN([]netip.Addr{netip.MustParseAddr("10.66.0.2")}, []netip.Addr{netip.MustParseAddr("10.66.0.53")}, 1420, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer server.Close()
|
||||
defer client.Close()
|
||||
// As in a tunnel, what reads a device does not wait for the other end to take the packet: a stack answers
|
||||
// inside Write, and its answer has to be read meanwhile.
|
||||
for _, pair := range [][2]tun.Device{{client, server}, {server, client}} {
|
||||
packets := make(chan []byte, 1024)
|
||||
go func() {
|
||||
defer close(packets)
|
||||
bufs, sizes := [][]byte{make([]byte, 2048)}, make([]int, 1)
|
||||
for {
|
||||
if _, err := pair[0].Read(bufs, sizes, 0); err != nil {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case packets <- bytes.Clone(bufs[0][:sizes[0]]):
|
||||
default:
|
||||
}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
for packet := range packets {
|
||||
pair[1].Write([][]byte{packet}, 0)
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if addrs, err := tnet.LookupContextHost(ctx, "xray.example"); err != nil || len(addrs) != 1 || addrs[0] != "192.0.2.1" {
|
||||
t.Fatal("resolved to ", addrs, ", error: ", err)
|
||||
}
|
||||
// a server that does not answer is not waited for longer than the one who asks wants to wait
|
||||
short, cancelShort := context.WithTimeout(ctx, 200*time.Millisecond)
|
||||
start := time.Now()
|
||||
var timeout *gonet.DNSError
|
||||
if addrs, err := tnet.LookupContextHost(short, "silent.example"); !errors.As(err, &timeout) || !timeout.IsTimeout || time.Since(start) > 3*time.Second {
|
||||
t.Fatal("resolved to ", addrs, " after ", time.Since(start), ", error: ", err)
|
||||
}
|
||||
cancelShort()
|
||||
|
||||
sent := make([]byte, 1<<20)
|
||||
rand.Read(sent)
|
||||
for _, network := range []string{"tcp", "udp"} {
|
||||
conn, err := tnet.DialContext(ctx, network, "xray.example:7")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
size := len(sent)
|
||||
if network == "udp" {
|
||||
// more than the tunnel takes in one packet
|
||||
size = 3000
|
||||
}
|
||||
go conn.Write(sent[:size])
|
||||
received := make([]byte, size)
|
||||
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := io.ReadFull(conn, received)
|
||||
done <- err
|
||||
}()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil || !bytes.Equal(received, sent[:size]) {
|
||||
t.Fatal(network, ": received something else than what was sent, error: ", err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal(network, ": what was sent did not come back")
|
||||
}
|
||||
conn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// A packet of the stack is in its hands only until WritePacket returns, Read gets it as it was then.
|
||||
// A device that is closed is not waited for, also not by a stack that has something to send when it is closed.
|
||||
func TestNetTUNWritePacket(t *testing.T) {
|
||||
dev, tnet, err := CreateNetTUN([]netip.Addr{netip.MustParseAddr("10.66.0.2")}, nil, 1420, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, sizes := make([]byte, 16), make([]int, 1)
|
||||
for i := range 1000 {
|
||||
header, payload := []byte{byte(i), 1, 2, 3}, []byte{4, 5, 6, byte(i)}
|
||||
go func() {
|
||||
dev.(*netTun).WritePacket(header, payload)
|
||||
clear(header)
|
||||
clear(payload)
|
||||
}()
|
||||
if _, err := dev.Read([][]byte{b}, sizes, 0); err != nil || !bytes.Equal(b[:sizes[0]], []byte{byte(i), 1, 2, 3, 4, 5, 6, byte(i)}) {
|
||||
t.Fatal("read ", b[:sizes[0]], " of packet ", i, ", error: ", err)
|
||||
}
|
||||
}
|
||||
|
||||
// nobody reads now, and no more can wait to be read: a connection waits to send its SYN
|
||||
for range netTunQueue {
|
||||
dev.(*netTun).WritePacket([]byte{1}, nil)
|
||||
}
|
||||
dialed := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := tnet.DialContextTCPAddrPort(context.Background(), netip.MustParseAddrPort("192.0.2.1:80"))
|
||||
dialed <- err
|
||||
}()
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
closed := make(chan struct{})
|
||||
go func() {
|
||||
dev.Close()
|
||||
close(closed)
|
||||
}()
|
||||
select {
|
||||
case <-closed:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the device is not closed while a packet waits to be read")
|
||||
}
|
||||
if err := <-dialed; err == nil {
|
||||
t.Fatal("a connection through a closed device")
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,16 @@
|
||||
package tun
|
||||
package wireguard
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
)
|
||||
|
||||
const benchBatch = 64
|
||||
|
||||
// Raw cost of queueing and draining a small burst, as one flow's reader does.
|
||||
func BenchmarkQueueBurstChan(b *testing.B) {
|
||||
ch := make(chan *buf.Buffer, udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
ch := make(chan *packet, udpQueueLimit)
|
||||
p := &packet{}
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
for j := 0; j < benchBatch; j++ {
|
||||
@@ -26,7 +24,7 @@ func BenchmarkQueueBurstChan(b *testing.B) {
|
||||
|
||||
func BenchmarkQueueBurstPacketQueue(b *testing.B) {
|
||||
q := newPacketQueue(udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
p := &packet{}
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
for j := 0; j < benchBatch; j++ {
|
||||
@@ -41,8 +39,8 @@ func BenchmarkQueueBurstPacketQueue(b *testing.B) {
|
||||
// Producer and consumer on different goroutines; the producer yields when the
|
||||
// queue is full instead of spinning, like a blocking channel send would.
|
||||
func BenchmarkQueueStreamChan(b *testing.B) {
|
||||
ch := make(chan *buf.Buffer, udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
ch := make(chan *packet, udpQueueLimit)
|
||||
p := &packet{}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
for range ch {
|
||||
@@ -60,7 +58,7 @@ func BenchmarkQueueStreamChan(b *testing.B) {
|
||||
|
||||
func BenchmarkQueueStreamPacketQueue(b *testing.B) {
|
||||
q := newPacketQueue(udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
p := &packet{}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
for {
|
||||
+18
-16
@@ -21,13 +21,13 @@ import (
|
||||
"github.com/xtls/xray-core/features/policy"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
"github.com/xtls/xray-core/features/stats"
|
||||
xtun "github.com/xtls/xray-core/proxy/tun"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/internet/stat"
|
||||
"golang.org/x/crypto/curve25519"
|
||||
"golang.zx2c4.com/wireguard/device"
|
||||
"golang.zx2c4.com/wireguard/tun"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/stack"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
@@ -43,9 +43,10 @@ type Server struct {
|
||||
uplinkCounter stats.Counter
|
||||
downlinkCounter stats.Counter
|
||||
|
||||
tun tun.Device
|
||||
dev *device.Device
|
||||
mu sync.Mutex
|
||||
tun tun.Device
|
||||
stack *stack.Stack
|
||||
dev *device.Device
|
||||
mu sync.Mutex
|
||||
|
||||
pub [32]byte
|
||||
users *sync.Map
|
||||
@@ -94,6 +95,11 @@ func NewServer(ctx context.Context, conf *DeviceConfig) (*Server, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tun, _, stack, err := CreateNetTUN(localAddresses, nil, int(conf.Mtu), false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pri := common.Must2(ParseKey(conf.SecretKey))
|
||||
var pub [32]byte
|
||||
curve25519.ScalarBaseMult(&pub, pri)
|
||||
@@ -120,15 +126,15 @@ func NewServer(ctx context.Context, conf *DeviceConfig) (*Server, error) {
|
||||
uplinkCounter: uplinkCounter,
|
||||
downlinkCounter: downlinkCounter,
|
||||
|
||||
tun: tun,
|
||||
stack: stack,
|
||||
|
||||
pub: pub,
|
||||
users: users,
|
||||
}
|
||||
// The stack hands its connections to s from the first packet on, which the device delivers after Start -> dev.Up.
|
||||
tun, _, err := CreateNetTUN(localAddresses, nil, int(conf.Mtu), s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.tun = tun
|
||||
// Install the stack's protocol handlers before the device can deliver packets to it (Start -> dev.Up).
|
||||
CreateForwarder(stack, s.HandleConnection)
|
||||
CreateICMPEchoResponder(stack)
|
||||
return s, nil
|
||||
}
|
||||
|
||||
@@ -255,7 +261,7 @@ func (s *Server) Start() error {
|
||||
if s.src.Address.Family().IsDomain() {
|
||||
return errors.New("address is domain")
|
||||
}
|
||||
listenFunc := func(context.Context) (net.PacketConn, error) {
|
||||
listenFunc := func() (net.PacketConn, error) {
|
||||
var pktConn net.PacketConn
|
||||
var err error
|
||||
if s.streamSettings.FinalMask != nil {
|
||||
@@ -373,13 +379,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))
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
package wireguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/netip"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
|
||||
// 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, 0, 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}
|
||||
users := &sync.Map{}
|
||||
users.Store([32]byte{1}, &protocol.MemoryUser{
|
||||
Email: "love@xray.com",
|
||||
Account: &MemoryAccount{AllowedIPs: []netip.Prefix{netip.MustParsePrefix("10.0.0.2/32")}},
|
||||
})
|
||||
s := &Server{ctx: context.Background(), dispatcher: dispatcher, users: users}
|
||||
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 peer may still be sending")
|
||||
}
|
||||
if got := conn.closed.Load(); got != 1 {
|
||||
t.Fatalf("connection closed %d times, want 1", got)
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,27 @@
|
||||
package wireguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"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/stack"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/transport/udp"
|
||||
"gvisor.dev/gvisor/pkg/waiter"
|
||||
)
|
||||
|
||||
func CalculateInterfaceName(name string) (tunName string) {
|
||||
@@ -33,3 +48,334 @@ func CalculateInterfaceName(name string) (tunName string) {
|
||||
tunName = fmt.Sprintf("%s%d", tunName, tunIndex)
|
||||
return
|
||||
}
|
||||
|
||||
func CreateForwarder(gstack *stack.Stack, handler func(conn net.Conn, dest net.Destination)) {
|
||||
gstack.SetPromiscuousMode(1, true)
|
||||
gstack.SetSpoofing(1, true)
|
||||
|
||||
tcpForwarder := tcp.NewForwarder(gstack, 0, 65535, func(r *tcp.ForwarderRequest) {
|
||||
go func(r *tcp.ForwarderRequest) {
|
||||
var wq waiter.Queue
|
||||
id := r.ID()
|
||||
|
||||
ep, err := r.CreateEndpoint(&wq)
|
||||
if err != nil {
|
||||
errors.LogError(context.Background(), err.String())
|
||||
r.Complete(true)
|
||||
return
|
||||
}
|
||||
|
||||
options := ep.SocketOptions()
|
||||
options.SetKeepAlive(false)
|
||||
options.SetReuseAddress(true)
|
||||
options.SetReusePort(true)
|
||||
|
||||
handler(gonet.NewTCPConn(&wq, ep), net.TCPDestination(net.IPAddress(id.LocalAddress.AsSlice()), net.Port(id.LocalPort)))
|
||||
|
||||
ep.Close()
|
||||
r.Complete(false)
|
||||
}(r)
|
||||
})
|
||||
gstack.SetTransportProtocolHandler(tcp.ProtocolNumber, tcpForwarder.HandlePacket)
|
||||
|
||||
manager := &udpManager{
|
||||
stack: gstack,
|
||||
handler: handler,
|
||||
m: make(map[string]*udpConn),
|
||||
}
|
||||
|
||||
gstack.SetTransportProtocolHandler(udp.ProtocolNumber, func(id stack.TransportEndpointID, pkt *stack.PacketBuffer) bool {
|
||||
data := pkt.Data().AsRange().ToSlice()
|
||||
// if len(data) == 0 {
|
||||
// return false
|
||||
// }
|
||||
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))
|
||||
manager.feed(src, dst, data)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
type udpManager struct {
|
||||
stack *stack.Stack
|
||||
handler func(conn net.Conn, dest net.Destination)
|
||||
m map[string]*udpConn
|
||||
mutex sync.RWMutex
|
||||
}
|
||||
|
||||
func (m *udpManager) feed(src net.Destination, dst net.Destination, data []byte) {
|
||||
m.mutex.RLock()
|
||||
uc, ok := m.m[src.NetAddr()]
|
||||
if ok {
|
||||
if !uc.queue.push(&packet{p: data, dest: &dst}) {
|
||||
errors.LogDebug(context.Background(), "drop udp with size ", len(data), " to ", dst.NetAddr(), " original ", uc.dst.NetAddr(), " > queue full")
|
||||
}
|
||||
m.mutex.RUnlock()
|
||||
return
|
||||
}
|
||||
m.mutex.RUnlock()
|
||||
|
||||
m.mutex.Lock()
|
||||
defer m.mutex.Unlock()
|
||||
|
||||
uc, ok = m.m[src.NetAddr()]
|
||||
if !ok {
|
||||
uc = &udpConn{
|
||||
queue: newPacketQueue(udpQueueLimit),
|
||||
src: src,
|
||||
dst: dst,
|
||||
}
|
||||
uc.writeFunc = m.writeRawUDPPacket
|
||||
uc.closeFunc = func() {
|
||||
m.mutex.Lock()
|
||||
m.close(uc)
|
||||
m.mutex.Unlock()
|
||||
}
|
||||
m.m[src.NetAddr()] = uc
|
||||
go m.handler(uc, dst)
|
||||
}
|
||||
|
||||
if !uc.queue.push(&packet{p: data, dest: &dst}) {
|
||||
errors.LogDebug(context.Background(), "drop udp with size ", len(data), " to ", dst.NetAddr(), " original ", uc.dst.NetAddr(), " > queue full 2")
|
||||
}
|
||||
}
|
||||
|
||||
func (m *udpManager) close(uc *udpConn) {
|
||||
if !uc.closed {
|
||||
uc.closed = true
|
||||
uc.queue.close()
|
||||
delete(m.m, uc.src.NetAddr())
|
||||
}
|
||||
}
|
||||
|
||||
func (m *udpManager) 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 := m.stack.WriteRawPacket(1, ipProtocol, buffer.MakeWithView(pkt.ToView()))
|
||||
if err != nil {
|
||||
return errors.New("failed to write raw udp packet back to stack err ", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type packet struct {
|
||||
p []byte
|
||||
dest *net.Destination
|
||||
}
|
||||
|
||||
type udpConn struct {
|
||||
queue *packetQueue
|
||||
src net.Destination
|
||||
dst net.Destination
|
||||
writeFunc func(payload []byte, src net.Destination, dst net.Destination) error
|
||||
closeFunc func()
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (c *udpConn) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
for {
|
||||
q, ok := c.queue.pop()
|
||||
if !ok {
|
||||
return nil, io.EOF
|
||||
}
|
||||
|
||||
b := buf.New()
|
||||
if _, err := b.Write(q.p); err != nil {
|
||||
errors.LogErrorInner(context.Background(), err, "drop packet to ", q.dest, " with size ", len(q.p))
|
||||
b.Release()
|
||||
continue
|
||||
}
|
||||
|
||||
b.UDP = q.dest
|
||||
|
||||
return buf.MultiBuffer{b}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *udpConn) Read(p []byte) (int, error) {
|
||||
q, ok := c.queue.pop()
|
||||
if !ok {
|
||||
return 0, io.EOF
|
||||
}
|
||||
n := copy(p, q.p)
|
||||
if n != len(q.p) {
|
||||
return 0, io.ErrShortBuffer
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (c *udpConn) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
for i, b := range mb {
|
||||
dst := c.dst
|
||||
if b.UDP != nil {
|
||||
if b.UDP.Address.Family().IsDomain() {
|
||||
errors.LogError(context.Background(), "impossible domain packet ", b.UDP, " reply via original target ", dst)
|
||||
} else {
|
||||
dst = *b.UDP
|
||||
}
|
||||
}
|
||||
err := c.writeFunc(b.Bytes(), dst, c.src)
|
||||
if err != nil {
|
||||
buf.ReleaseMulti(mb[i:])
|
||||
return err
|
||||
}
|
||||
b.Release()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *udpConn) Write(p []byte) (int, error) {
|
||||
err := c.writeFunc(p, c.dst, c.src)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (c *udpConn) Close() error {
|
||||
c.closeFunc()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *udpConn) LocalAddr() net.Addr {
|
||||
return c.dst.RawNetAddr()
|
||||
}
|
||||
|
||||
func (c *udpConn) RemoteAddr() net.Addr {
|
||||
return c.src.RawNetAddr()
|
||||
}
|
||||
|
||||
func (c *udpConn) SetDeadline(t time.Time) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *udpConn) SetReadDeadline(t time.Time) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *udpConn) SetWriteDeadline(t time.Time) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// udpQueueLimit bounds the packets waiting for one UDP flow; more are dropped.
|
||||
const udpQueueLimit = 1024
|
||||
|
||||
// packetQueue holds the packets waiting for one UDP flow. Unlike a buffered
|
||||
// channel of the same bound it only allocates for packets actually queued, so
|
||||
// the many idle flows kept until the idle timeout cost next to nothing.
|
||||
type packetQueue struct {
|
||||
mu sync.Mutex
|
||||
items []*packet
|
||||
limit int
|
||||
notify chan struct{}
|
||||
closed bool
|
||||
}
|
||||
|
||||
func newPacketQueue(limit int) *packetQueue {
|
||||
return &packetQueue{limit: limit, notify: make(chan struct{}, 1)}
|
||||
}
|
||||
|
||||
// push queues p and reports whether it was accepted.
|
||||
func (q *packetQueue) push(p *packet) bool {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
if q.closed || len(q.items) >= q.limit {
|
||||
return false
|
||||
}
|
||||
q.items = append(q.items, p)
|
||||
select {
|
||||
case q.notify <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// pop blocks until a packet is queued or the queue is closed and drained.
|
||||
func (q *packetQueue) pop() (*packet, bool) {
|
||||
for {
|
||||
q.mu.Lock()
|
||||
if len(q.items) > 0 {
|
||||
p := q.items[0]
|
||||
q.items[0] = nil
|
||||
q.items = q.items[1:]
|
||||
if len(q.items) == 0 {
|
||||
q.items = nil
|
||||
}
|
||||
q.mu.Unlock()
|
||||
return p, true
|
||||
}
|
||||
if q.closed {
|
||||
q.mu.Unlock()
|
||||
return nil, false
|
||||
}
|
||||
q.mu.Unlock()
|
||||
<-q.notify
|
||||
}
|
||||
}
|
||||
|
||||
func (q *packetQueue) close() {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
if !q.closed {
|
||||
q.closed = true
|
||||
close(q.notify)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,48 +1,48 @@
|
||||
package tun
|
||||
package wireguard
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
)
|
||||
|
||||
// BenchmarkUDPNewSession measures what one new UDP flow costs the
|
||||
// BenchmarkUDPManagerNewSession measures what one new UDP flow costs the
|
||||
// inbound while it stays open: QUIC and DNS open many short flows, and each
|
||||
// one lives until the connection idle timeout.
|
||||
func BenchmarkUDPNewSession(b *testing.B) {
|
||||
u := newUdpConnectionHandler(func(conn net.Conn, dest net.Destination) {}, nil)
|
||||
func BenchmarkUDPManagerNewSession(b *testing.B) {
|
||||
m := &udpManager{
|
||||
handler: func(conn net.Conn, dest net.Destination) {},
|
||||
m: make(map[string]*udpConn),
|
||||
}
|
||||
dst := net.UDPDestination(net.ParseAddress("1.1.1.1"), 443)
|
||||
payload := make([]byte, 1200)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
src := net.UDPDestination(net.IPAddress([]byte{10, byte(i >> 16), byte(i >> 8), byte(i)}), net.Port(1024+i%60000))
|
||||
u.HandlePacket(src, dst, &buf.Buffer{})
|
||||
m.feed(src, dst, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPacketQueueOrderAndClose(t *testing.T) {
|
||||
q := newPacketQueue(udpQueueLimit)
|
||||
for i := 0; i < 3; i++ {
|
||||
b := buf.New()
|
||||
b.WriteByte(byte(i))
|
||||
if !q.push(b) {
|
||||
if !q.push(&packet{p: []byte{byte(i)}}) {
|
||||
t.Fatalf("push %d rejected", i)
|
||||
}
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
b, ok := q.pop()
|
||||
if !ok || b.Byte(0) != byte(i) {
|
||||
t.Fatalf("pop %d: got %v, %v", i, b, ok)
|
||||
p, ok := q.pop()
|
||||
if !ok || p.p[0] != byte(i) {
|
||||
t.Fatalf("pop %d: got %v, %v", i, p, ok)
|
||||
}
|
||||
b.Release()
|
||||
}
|
||||
q.close()
|
||||
if _, ok := q.pop(); ok {
|
||||
t.Fatal("pop after close returned a packet")
|
||||
}
|
||||
if q.push(&buf.Buffer{}) {
|
||||
if q.push(&packet{}) {
|
||||
t.Fatal("push after close accepted")
|
||||
}
|
||||
}
|
||||
@@ -50,11 +50,11 @@ func TestPacketQueueOrderAndClose(t *testing.T) {
|
||||
func TestPacketQueueLimit(t *testing.T) {
|
||||
q := newPacketQueue(udpQueueLimit)
|
||||
for i := 0; i < udpQueueLimit; i++ {
|
||||
if !q.push(&buf.Buffer{}) {
|
||||
if !q.push(&packet{}) {
|
||||
t.Fatalf("push %d rejected below the limit", i)
|
||||
}
|
||||
}
|
||||
if q.push(&buf.Buffer{}) {
|
||||
if q.push(&packet{}) {
|
||||
t.Fatal("push above the limit accepted")
|
||||
}
|
||||
}
|
||||
@@ -80,7 +80,7 @@ func TestPacketQueueCloseUnblocksReader(t *testing.T) {
|
||||
func TestPacketQueueDropsDrainedStorage(t *testing.T) {
|
||||
q := newPacketQueue(udpQueueLimit)
|
||||
for i := 0; i < 100; i++ {
|
||||
q.push(&buf.Buffer{})
|
||||
q.push(&packet{})
|
||||
}
|
||||
for i := 0; i < 100; i++ {
|
||||
q.pop()
|
||||
@@ -16,10 +16,8 @@ import (
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/proxy/dokodemo"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
v2http "github.com/xtls/xray-core/proxy/http"
|
||||
v2httptest "github.com/xtls/xray-core/testing/servers/http"
|
||||
@@ -379,88 +377,3 @@ func TestHttpBasicAuth(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Server-first protocols (SMTP, FTP, MySQL) send nothing from the client until the server's
|
||||
// greeting arrives, so the HTTP outbound must not wait for a first payload before dialing.
|
||||
func TestHTTPOutboundServerFirst(t *testing.T) {
|
||||
tcpServer := tcp.Server{
|
||||
MsgProcessor: xor,
|
||||
SendFirst: []byte("send first"),
|
||||
}
|
||||
dest, err := tcpServer.Start()
|
||||
common.Must(err)
|
||||
defer tcpServer.Close()
|
||||
|
||||
serverPort := tcp.PickPort()
|
||||
serverConfig := &core.Config{
|
||||
Inbound: []*core.InboundHandlerConfig{
|
||||
{
|
||||
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(serverPort)}},
|
||||
Listen: net.NewIPOrDomain(net.LocalHostIP),
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&v2http.ServerConfig{}),
|
||||
},
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||
}),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
clientPort := tcp.PickPort()
|
||||
clientConfig := &core.Config{
|
||||
Inbound: []*core.InboundHandlerConfig{
|
||||
{
|
||||
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(clientPort)}},
|
||||
Listen: net.NewIPOrDomain(net.LocalHostIP),
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
|
||||
RewriteAddress: net.NewIPOrDomain(dest.Address),
|
||||
RewritePort: uint32(dest.Port),
|
||||
AllowedNetworks: []net.Network{net.Network_TCP},
|
||||
}),
|
||||
},
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&v2http.ClientConfig{
|
||||
Server: &protocol.ServerEndpoint{
|
||||
Address: net.NewIPOrDomain(net.LocalHostIP),
|
||||
Port: uint32(serverPort),
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
|
||||
common.Must(err)
|
||||
defer CloseAllServers(servers)
|
||||
|
||||
conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{
|
||||
IP: []byte{127, 0, 0, 1},
|
||||
Port: int(clientPort),
|
||||
})
|
||||
common.Must(err)
|
||||
defer conn.Close()
|
||||
|
||||
common.Must(conn.SetReadDeadline(time.Now().Add(5 * time.Second)))
|
||||
response := make([]byte, 1024)
|
||||
nBytes, err := conn.Read(response)
|
||||
if err != nil {
|
||||
t.Fatal("no server greeting through HTTP outbound: ", err)
|
||||
}
|
||||
if string(response[:nBytes]) != "send first" {
|
||||
t.Fatal("unexpected first response: ", string(response[:nBytes]))
|
||||
}
|
||||
common.Must(conn.SetReadDeadline(time.Time{}))
|
||||
|
||||
if err := testTCPConn2(conn, 1024, time.Second*5)(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user