Snapshot uncommitted work: proxy UI, sing-box integration, socks bridge
- Lab app: proxy panel, node editor, configuration and detail pages, responsive layout, and related tests - Add meshport-socks crate and sing-box bridge scripts/docs - Add singbox_flutter binding and meshport_client_core package - FFI, VPN helper (unified mac path), and Android/macOS runner updates - Docs for architecture, client runtime, UI design, and validation - UI design output artifacts under outputs/ui Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Haiku 5.5
parent
10b10e5bdf
commit
2f185f914d
@@ -0,0 +1,15 @@
|
||||
# MeshPort sing-box 接入
|
||||
|
||||
固定依赖 sing-box 1.14.3。当前提供本机 SOCKS 入口、受管理的 IPv4 组网分流、MeshPort SOCKS 出口及启停控制;完整 APP/TUN、互联网代理配置与订阅尚未接入。
|
||||
|
||||
从项目根目录执行:
|
||||
|
||||
```sh
|
||||
sh scripts/go-local.sh test -race ./...
|
||||
sh scripts/build-singbox.sh
|
||||
sh scripts/test-singbox-bridge.sh
|
||||
```
|
||||
|
||||
Go API:bridge.Engine.Start(context, bridge.Config)、Stop()、Snapshot()。调用方生成有效配置投影并拥有生命周期,停止或上下文取消后需调用 Stop。
|
||||
|
||||
完整接入方式、验证及限制见 [项目文档](../../docs/singbox-integration.md),上游许可证见 [LICENSE 副本](../../docs/upstream/sing-box-LICENSE)。
|
||||
@@ -0,0 +1,228 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
D "github.com/miekg/dns"
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing/common/json/badoption"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
box "github.com/sagernet/sing-box"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
sjson "github.com/sagernet/sing/common/json"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
)
|
||||
|
||||
func TestEncryptedResolversAndRemoteRuleSetsDecode(t *testing.T) {
|
||||
c := Config{ListenPort: 12345, Feature: "proxy", Mode: "rule", DefaultAction: "direct", DirectDNS: "https://dns.example/dns-query", ProxyDNS: "tls://dns.example:853", Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": 12346}, RuleSets: []RuleSet{{Tag: "private-sites", Enabled: true, URL: "https://rules.example/test.srs", Format: "binary", Action: "proxy", UpdateHours: 6, DownloadDetour: "direct"}}}
|
||||
data, err := c.managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := registryContext(context.Background())
|
||||
options, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
instance, err := box.New(box.Options{Context: ctx, Options: options})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer instance.Close()
|
||||
var result map[string]any
|
||||
json.Unmarshal(data, &result)
|
||||
servers := result["dns"].(map[string]any)["servers"].([]any)
|
||||
if len(servers) != 3 || servers[1].(map[string]any)["type"] != "https" || servers[2].(map[string]any)["detour"] != "proxy" {
|
||||
t.Fatal("encrypted DNS transport/detour missing")
|
||||
}
|
||||
for _, v := range []string{"http://dns.example/dns-query", "tls://dns.example/path", "https://user:pass@dns.example", "https://dns.example:0", "https://dns.example/dns-query?x=1"} {
|
||||
c.DirectDNS = v
|
||||
if _, err := c.managedJSON(); err == nil {
|
||||
t.Fatalf("accepted invalid resolver %q", v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInlineRuleSetsRouteAndPreserveMeshPriority(t *testing.T) {
|
||||
mesh, meshCount := socksEcho(t)
|
||||
defer mesh.Close()
|
||||
proxy, proxyCount := socksEcho(t)
|
||||
defer proxy.Close()
|
||||
listener, port := reservePort(t)
|
||||
listener.Close()
|
||||
c := Config{ListenPort: port, Feature: "combined", Mode: "rule", DefaultAction: "reject", MeshSOCKS: mesh.Addr().String(), MeshCIDRs: []string{"10.23.0.0/24"}, Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}, RuleSets: []RuleSet{{Tag: "test", Enabled: true, Action: "proxy", Rules: []map[string]any{{"ip_cidr": []string{"10.23.0.0/24", "198.51.100.0/24"}}}}}}
|
||||
engine := &Engine{}
|
||||
if err := engine.Start(context.Background(), c); err != nil {
|
||||
t.Fatalf("start: %v / %v", err, engine.startupCause)
|
||||
}
|
||||
defer engine.Close()
|
||||
echoThrough(t, port, M.ParseSocksaddr("198.51.100.1:1234"), true)
|
||||
echoThrough(t, port, M.ParseSocksaddr("10.23.0.1:1234"), true)
|
||||
if proxyCount.Load() != 1 || meshCount.Load() != 1 {
|
||||
t.Fatal("rule set overrode protected mesh precedence")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDoHAndDoTExchangeWithCertificateVerification(t *testing.T) {
|
||||
answer := func(r *D.Msg) *D.Msg {
|
||||
m := new(D.Msg)
|
||||
m.SetReply(r)
|
||||
m.Answer = []D.RR{&D.A{Hdr: D.RR_Header{Name: r.Question[0].Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: 60}, A: net.ParseIP("203.0.113.7")}}
|
||||
return m
|
||||
}
|
||||
var count atomic.Int32
|
||||
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var data []byte
|
||||
var err error
|
||||
if r.Method == "POST" {
|
||||
data, err = io.ReadAll(io.LimitReader(r.Body, 65536))
|
||||
} else {
|
||||
data, err = base64.RawURLEncoding.DecodeString(r.URL.Query().Get("dns"))
|
||||
}
|
||||
request := new(D.Msg)
|
||||
if err != nil || request.Unpack(data) != nil {
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
count.Add(1)
|
||||
reply, _ := answer(request).Pack()
|
||||
w.Header().Set("Content-Type", "application/dns-message")
|
||||
w.Write(reply)
|
||||
}))
|
||||
defer server.Close()
|
||||
listener, err := tls.Listen("tcp4", "127.0.0.1:0", &tls.Config{Certificates: server.TLS.Certificates, MinVersion: tls.VersionTLS12})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dnsServer := &D.Server{Listener: listener, Handler: D.HandlerFunc(func(w D.ResponseWriter, r *D.Msg) { count.Add(1); w.WriteMsg(answer(r)) })}
|
||||
go dnsServer.ActivateAndServe()
|
||||
defer dnsServer.Shutdown()
|
||||
certificate := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}))
|
||||
for _, url := range []string{server.URL + "/dns-query", "tls://" + listener.Addr().String()} {
|
||||
t.Run(url, func(t *testing.T) {
|
||||
upstream, proxyCount := socksEcho(t)
|
||||
defer upstream.Close()
|
||||
socket, port := reservePort(t)
|
||||
socket.Close()
|
||||
c := Config{ListenPort: port, Feature: "proxy", Mode: "global", DirectDNS: url, Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": upstream.Addr().(*net.TCPAddr).Port}}
|
||||
data, err := c.managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := registryContext(context.Background())
|
||||
opts, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A test-only trust root is installed in this isolated box, never the OS.
|
||||
opts.Certificate = &option.CertificateOptions{Store: "none", Certificate: []string{certificate}}
|
||||
instance, err := box.New(box.Options{Context: ctx, Options: opts})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer instance.Close()
|
||||
if err = instance.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := count.Load()
|
||||
echoThrough(t, port, M.ParseSocksaddr("encrypted.example.test:1234"), true)
|
||||
if count.Load() <= before || proxyCount.Load() != 1 {
|
||||
t.Fatal("encrypted DNS path not used")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteRuleSetRefreshKeepsLastGoodRulesOnFailure(t *testing.T) {
|
||||
var stage atomic.Int32
|
||||
var requests atomic.Int32
|
||||
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests.Add(1)
|
||||
if stage.Load() == 2 {
|
||||
w.WriteHeader(503)
|
||||
return
|
||||
}
|
||||
prefix := "198.51.100.0/24"
|
||||
if stage.Load() == 1 {
|
||||
prefix = "203.0.113.0/24"
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]any{"version": 3, "rules": []any{map[string]any{"ip_cidr": []string{prefix}}}})
|
||||
}))
|
||||
defer server.Close()
|
||||
upstream, _ := socksEcho(t)
|
||||
defer upstream.Close()
|
||||
socket, port := reservePort(t)
|
||||
socket.Close()
|
||||
c := Config{ListenPort: port, Feature: "proxy", Mode: "rule", DefaultAction: "reject", Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": upstream.Addr().(*net.TCPAddr).Port}, RuleSets: []RuleSet{{Tag: "remote", Enabled: true, URL: server.URL + "/rules.json", Format: "source", Action: "proxy", UpdateHours: 1}}}
|
||||
data, err := c.managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := registryContext(context.Background())
|
||||
opts, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
opts.Certificate = &option.CertificateOptions{Store: "none", Certificate: []string{string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}))}}
|
||||
opts.Route.RuleSet[0].RemoteOptions.UpdateInterval = badoption.Duration(100 * time.Millisecond)
|
||||
instance, err := box.New(box.Options{Context: ctx, Options: opts})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer instance.Close()
|
||||
if err = instance.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
echoThrough(t, port, M.ParseSocksaddr("198.51.100.1:1234"), true)
|
||||
stage.Store(1)
|
||||
set, ok := instance.Router().RuleSet("remote")
|
||||
if !ok {
|
||||
t.Fatal("remote set missing")
|
||||
}
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for !set.Match(&adapter.InboundContext{Destination: M.ParseSocksaddr("203.0.113.1:1234")}) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("remote rules did not refresh")
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
echoThrough(t, port, M.ParseSocksaddr("203.0.113.1:1234"), true)
|
||||
echoThrough(t, port, M.ParseSocksaddr("198.51.100.1:1234"), false)
|
||||
stage.Store(2)
|
||||
before := requests.Load()
|
||||
deadline = time.Now().Add(3 * time.Second)
|
||||
for requests.Load() <= before {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("failed refresh not attempted")
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
echoThrough(t, port, M.ParseSocksaddr("203.0.113.1:1234"), true)
|
||||
}
|
||||
|
||||
func TestDirectModePausesProxyDNSAndRemoteRuleSets(t *testing.T) {
|
||||
c := Config{ListenPort: 12345, Feature: "proxy", Mode: "direct", ProxyDNS: "tls://dns.example", RuleSets: []RuleSet{{Tag: "remote", Enabled: true, URL: "https://rules.example/test.srs", Format: "binary", Action: "proxy", DownloadDetour: "proxy"}}}
|
||||
data, err := c.managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var result map[string]any
|
||||
json.Unmarshal(data, &result)
|
||||
if _, ok := result["route"].(map[string]any)["rule_set"]; ok {
|
||||
t.Fatal("direct mode still loads rule sets")
|
||||
}
|
||||
if len(result["dns"].(map[string]any)["servers"].([]any)) != 1 {
|
||||
t.Fatal("direct mode still depends on proxy DNS")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
D "github.com/miekg/dns"
|
||||
box "github.com/sagernet/sing-box"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing/protocol/socks"
|
||||
"github.com/sagernet/sing/protocol/socks/socks5"
|
||||
|
||||
"github.com/sagernet/sing-box/option"
|
||||
sjson "github.com/sagernet/sing/common/json"
|
||||
)
|
||||
|
||||
func TestBypassChinaPresetAndGlobalIsolation(t *testing.T) {
|
||||
for _, fake := range []bool{false, true} {
|
||||
c := Config{ListenPort: 12345, Feature: "combined", Mode: "bypass_cn", FakeIP: fake,
|
||||
MeshSOCKS: "127.0.0.1:12346", MeshCIDRs: []string{"10.77.0.0/24"}, ProtectedCIDRs: []string{"10.88.0.0/24"},
|
||||
DefaultAction: "reject", Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": 12347},
|
||||
Rules: []Rule{{Type: "ip_cidr", Value: "0.0.0.0/0", Action: "reject"}},
|
||||
RuleSets: []RuleSet{{Tag: "custom", Enabled: true, Action: "reject", Rules: []map[string]any{{"ip_cidr": []string{"0.0.0.0/0"}}}}}}
|
||||
data, err := c.managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = sjson.UnmarshalExtendedContext[option.Options](registryContext(context.Background()), data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var result map[string]any
|
||||
json.Unmarshal(data, &result)
|
||||
route := result["route"].(map[string]any)
|
||||
if route["final"] != "proxy" {
|
||||
t.Fatal("preset did not force proxy fallback")
|
||||
}
|
||||
sets := route["rule_set"].([]any)
|
||||
set := sets[0].(map[string]any)
|
||||
if len(sets) != 1 || set["tag"] != "meshport-geoip-cn" || set["format"] != "binary" || set["download_detour"] != "proxy" || set["update_interval"] != "24h" {
|
||||
t.Fatal("managed GeoIP update missing")
|
||||
}
|
||||
rules := route["rules"].([]any)
|
||||
// DNS hijack/real-IP resolution precede mesh, withdrawn-prefix protection,
|
||||
// ordinary private addresses and finally the China IP rule.
|
||||
if len(rules) != 6 || rules[1].(map[string]any)["action"] != "resolve" || rules[2].(map[string]any)["outbound"] != "meshport" || rules[3].(map[string]any)["action"] != "reject" || rules[4].(map[string]any)["ip_is_private"] != true || rules[5].(map[string]any)["outbound"] != "direct" {
|
||||
t.Fatal("GeoIP or mesh priority broken")
|
||||
}
|
||||
if len(c.Rules) != 1 || c.RuleSets[0].Tag != "custom" {
|
||||
t.Fatal("preset modified saved custom rules")
|
||||
}
|
||||
c.Mode = "global"
|
||||
data, err = c.managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
json.Unmarshal(data, &result)
|
||||
route = result["route"].(map[string]any)
|
||||
if _, ok := route["rule_set"]; ok {
|
||||
t.Fatal("global mode still loads GeoIP")
|
||||
}
|
||||
if len(route["rules"].([]any)) != 4 || route["final"] != "proxy" {
|
||||
t.Fatal("global mode contains ordinary bypass rules")
|
||||
}
|
||||
c.Mode = "bypass_cn"
|
||||
c.Proxy = nil
|
||||
if _, err = c.managedJSON(); err == nil {
|
||||
t.Fatal("preset accepted missing proxy node")
|
||||
}
|
||||
c.Feature = "mesh"
|
||||
c.MeshDNS = nil
|
||||
if _, err = c.managedJSON(); fake && err == nil {
|
||||
t.Fatal("mesh-only accepted FakeIP")
|
||||
} else if !fake && err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Use documentation IPs and isolated SOCKS counters in place of physical
|
||||
// exits, so real-IP/FakeIP policy is exercised without public connections.
|
||||
func TestBypassChinaRealIPAndFakeIPRouting(t *testing.T) {
|
||||
for _, fake := range []bool{false, true} {
|
||||
direct, dc := socksEcho(t)
|
||||
defer direct.Close()
|
||||
proxy, pc := socksEcho(t)
|
||||
defer proxy.Close()
|
||||
socket, err := net.ListenPacket("udp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := &D.Server{PacketConn: socket, Handler: D.HandlerFunc(func(w D.ResponseWriter, r *D.Msg) {
|
||||
m := new(D.Msg)
|
||||
m.SetReply(r)
|
||||
ip := "203.0.113.7"
|
||||
if r.Question[0].Name == "china.test." {
|
||||
ip = "198.51.100.7"
|
||||
}
|
||||
if r.Question[0].Qtype == D.TypeA {
|
||||
m.Answer = []D.RR{&D.A{Hdr: D.RR_Header{Name: r.Question[0].Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: 60}, A: net.ParseIP(ip)}}
|
||||
}
|
||||
w.WriteMsg(m)
|
||||
})}
|
||||
go server.ActivateAndServe()
|
||||
defer server.Shutdown()
|
||||
listener, port := reservePort(t)
|
||||
listener.Close()
|
||||
c := Config{ListenPort: port, Feature: "proxy", Mode: "bypass_cn", FakeIP: fake, DNS: socket.LocalAddr().String(), Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}}
|
||||
data, err := c.managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var generated map[string]any
|
||||
json.Unmarshal(data, &generated)
|
||||
route := generated["route"].(map[string]any)
|
||||
route["rule_set"] = []any{map[string]any{"type": "inline", "tag": "meshport-geoip-cn", "rules": []any{map[string]any{"ip_cidr": []string{"198.51.100.0/24"}}}}}
|
||||
outbounds := generated["outbounds"].([]any)
|
||||
outbounds[0] = map[string]any{"type": "socks", "tag": "direct", "server": "127.0.0.1", "server_port": direct.Addr().(*net.TCPAddr).Port}
|
||||
data, _ = json.Marshal(generated)
|
||||
ctx := registryContext(context.Background())
|
||||
options, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
instance, err := box.New(box.Options{Context: ctx, Options: options})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = instance.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, domain := range []string{"china.test", "foreign.test"} {
|
||||
target := domain
|
||||
if fake {
|
||||
conn, err := net.Dial("tcp4", net.JoinHostPort("127.0.0.1", jsonNumber(int(port))))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
_, err = socks.ClientHandshake5(conn, socks5.CommandConnect, M.ParseSocksaddr("1.1.1.1:53"), "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dnsConn := &D.Conn{Conn: conn}
|
||||
msg := new(D.Msg)
|
||||
msg.SetQuestion(D.Fqdn(domain), D.TypeA)
|
||||
if err = dnsConn.WriteMsg(msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
answer, err := dnsConn.ReadMsg()
|
||||
conn.Close()
|
||||
if err != nil || len(answer.Answer) != 1 {
|
||||
t.Fatalf("FakeIP answer: %v / %v", answer, err)
|
||||
}
|
||||
target = answer.Answer[0].(*D.A).A.String()
|
||||
}
|
||||
echoThrough(t, port, M.ParseSocksaddr(net.JoinHostPort(target, "443")), true)
|
||||
}
|
||||
if dc.Load() != 1 || pc.Load() != 1 {
|
||||
t.Fatalf("fake=%v direct=%d proxy=%d", fake, dc.Load(), pc.Load())
|
||||
}
|
||||
instance.Close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,572 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Only node fields may be imported. Route, DNS and TUN ownership remain managed.
|
||||
type Rule struct {
|
||||
Type string `json:"type"`
|
||||
Value string `json:"value"`
|
||||
Action string `json:"action"`
|
||||
}
|
||||
type MeshDNS struct {
|
||||
Suffix string `json:"suffix"`
|
||||
Server string `json:"server"`
|
||||
}
|
||||
type TunConfig struct {
|
||||
FD int `json:"fd"`
|
||||
Name string `json:"name"`
|
||||
Interface string `json:"physical_interface"`
|
||||
Index int `json:"physical_index"`
|
||||
}
|
||||
type RuleSet struct {
|
||||
Tag string `json:"tag"`
|
||||
Enabled bool `json:"enabled"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Format string `json:"format,omitempty"`
|
||||
Rules []map[string]any `json:"rules,omitempty"`
|
||||
Action string `json:"action"`
|
||||
DownloadDetour string `json:"download_detour,omitempty"`
|
||||
UpdateHours int `json:"update_hours,omitempty"`
|
||||
}
|
||||
type Config struct {
|
||||
DNSProtection bool `json:"dns_protection,omitempty"`
|
||||
RuleSets []RuleSet `json:"rule_sets,omitempty"`
|
||||
DirectDNS string `json:"direct_dns_server,omitempty"`
|
||||
ListenPort uint16 `json:"listen_port"`
|
||||
MeshSOCKS string `json:"mesh_socks"`
|
||||
MeshCIDRs []string `json:"mesh_cidrs"`
|
||||
ProtectedCIDRs []string `json:"protected_cidrs,omitempty"`
|
||||
Feature string `json:"feature,omitempty"`
|
||||
Mode string `json:"mode,omitempty"`
|
||||
Proxy map[string]any `json:"proxy,omitempty"`
|
||||
Rules []Rule `json:"rules,omitempty"`
|
||||
DefaultAction string `json:"default_action,omitempty"`
|
||||
DNS string `json:"dns_server,omitempty"`
|
||||
ProxyDNS string `json:"proxy_dns_server,omitempty"`
|
||||
MeshDNS []MeshDNS `json:"mesh_dns,omitempty"`
|
||||
FakeIP bool `json:"fakeip,omitempty"`
|
||||
FakeIPExclude []string `json:"fakeip_exclude,omitempty"`
|
||||
DesktopTun bool `json:"desktop_tun,omitempty"`
|
||||
PhysicalInterface string `json:"physical_interface,omitempty"`
|
||||
Tun *TunConfig `json:"tun,omitempty"`
|
||||
}
|
||||
|
||||
// Diagnostics are restricted to the privileged, mesh-only local fixture. They
|
||||
// cannot enable logging of a user's ordinary proxy nodes or network traffic.
|
||||
func (c Config) selfTestTrace() bool {
|
||||
if os.Getenv("MESHPORT_SELF_TEST_TRACE") != "1" || os.Geteuid() != 0 ||
|
||||
!c.DesktopTun || c.Feature != "mesh" || c.Proxy != nil || len(c.MeshCIDRs) == 0 {
|
||||
return false
|
||||
}
|
||||
fixture := netip.MustParsePrefix("10.253.88.0/24")
|
||||
for _, value := range append(append([]string{}, c.MeshCIDRs...), c.ProtectedCIDRs...) {
|
||||
prefix, err := netip.ParsePrefix(value)
|
||||
if err != nil || prefix.Bits() < fixture.Bits() || !fixture.Contains(prefix.Addr()) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func prefixes(values []string) ([]string, error) {
|
||||
if len(values) > 128 {
|
||||
return nil, errors.New("too many mesh prefixes")
|
||||
}
|
||||
set := map[string]bool{}
|
||||
for _, v := range values {
|
||||
p, e := netip.ParsePrefix(v)
|
||||
if e != nil || !p.Addr().Is4() || p.Bits() < 16 || !p.Addr().IsPrivate() {
|
||||
return nil, errors.New("invalid or unsupported mesh prefix")
|
||||
}
|
||||
set[p.Masked().String()] = true
|
||||
}
|
||||
result := make([]string, 0, len(set))
|
||||
for p := range set {
|
||||
result = append(result, p)
|
||||
}
|
||||
sort.Strings(result)
|
||||
return result, nil
|
||||
}
|
||||
func domain(v string) bool {
|
||||
if len(v) > 253 || v == "" || strings.ContainsAny(v, " /:@*\r\n") {
|
||||
return false
|
||||
}
|
||||
for _, label := range strings.Split(v, ".") {
|
||||
if len(label) == 0 || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
|
||||
return false
|
||||
}
|
||||
for _, c := range label {
|
||||
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func proxyNode(node map[string]any) (map[string]any, error) {
|
||||
kind, _ := node["type"].(string)
|
||||
fields := map[string]string{"socks": "version,username,password", "http": "username,password,tls", "shadowsocks": "method,password", "vmess": "uuid,security,alter_id,tls,transport", "vless": "uuid,flow,tls,transport", "trojan": "password,tls,transport"}
|
||||
extra, ok := fields[kind]
|
||||
if !ok {
|
||||
return nil, errors.New("unsupported proxy protocol")
|
||||
}
|
||||
allowed := ",type,server,server_port," + extra + ","
|
||||
result := map[string]any{"tag": "proxy"}
|
||||
for key, value := range node {
|
||||
if !strings.Contains(allowed, ","+key+",") {
|
||||
return nil, errors.New("unsupported proxy node field")
|
||||
}
|
||||
result[key] = value
|
||||
}
|
||||
host, ok := node["server"].(string)
|
||||
if !ok {
|
||||
return nil, errors.New("proxy server required")
|
||||
}
|
||||
if _, err := netip.ParseAddr(host); err != nil && !domain(host) {
|
||||
return nil, errors.New("invalid proxy server")
|
||||
}
|
||||
raw, _ := json.Marshal(node["server_port"])
|
||||
var port uint16
|
||||
if json.Unmarshal(raw, &port) != nil || port == 0 {
|
||||
return nil, errors.New("invalid proxy port")
|
||||
}
|
||||
// Nested transport/TLS options are validated by the fixed upstream registry;
|
||||
// they cannot supply route, DNS, dialer or arbitrary outbound configuration.
|
||||
if tls, ok := node["tls"].(map[string]any); ok {
|
||||
for k := range tls {
|
||||
if !strings.Contains(",enabled,server_name,alpn,reality,utls,", ","+k+",") {
|
||||
return nil, errors.New("unsupported TLS option")
|
||||
}
|
||||
}
|
||||
}
|
||||
if tr, ok := node["transport"].(map[string]any); ok {
|
||||
for k := range tr {
|
||||
if !strings.Contains(",type,path,headers,service_name,host,", ","+k+",") {
|
||||
return nil, errors.New("unsupported transport option")
|
||||
}
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
func dnsAddress(value string) (string, uint16, error) {
|
||||
if ip, e := netip.ParseAddr(value); e == nil {
|
||||
return ip.String(), 53, nil
|
||||
}
|
||||
if addr, e := netip.ParseAddrPort(value); e == nil && addr.Port() > 0 {
|
||||
return addr.Addr().String(), addr.Port(), nil
|
||||
}
|
||||
return "", 0, errors.New("DNS server must be an IP with optional port")
|
||||
}
|
||||
|
||||
// Encrypted resolver hostnames use the independent IP bootstrap resolver.
|
||||
func resolver(value, tag, detour string) (map[string]any, error) {
|
||||
result := map[string]any{"tag": tag}
|
||||
if !strings.Contains(value, "://") {
|
||||
host, port, err := dnsAddress(value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result["type"], result["server"], result["server_port"] = "udp", host, port
|
||||
} else {
|
||||
u, err := url.Parse(value)
|
||||
if err != nil || u.Hostname() == "" || u.User != nil || u.Fragment != "" || u.RawQuery != "" || (u.Scheme != "https" && u.Scheme != "tls") {
|
||||
return nil, errors.New("invalid encrypted DNS URL")
|
||||
}
|
||||
host := u.Hostname()
|
||||
if _, err := netip.ParseAddr(host); err != nil && !domain(host) {
|
||||
return nil, errors.New("invalid DNS host")
|
||||
}
|
||||
port := uint16(443)
|
||||
kind := "https"
|
||||
if u.Scheme == "tls" {
|
||||
port, kind = 853, "tls"
|
||||
if u.Path != "" && u.Path != "/" {
|
||||
return nil, errors.New("DoT does not accept a path")
|
||||
}
|
||||
}
|
||||
if u.Port() != "" {
|
||||
if _, err := fmt.Sscanf(u.Port(), "%d", &port); err != nil || port == 0 {
|
||||
return nil, errors.New("invalid DNS port")
|
||||
}
|
||||
}
|
||||
result["type"], result["server"], result["server_port"] = kind, host, port
|
||||
result["tls"] = map[string]any{"enabled": true, "server_name": host}
|
||||
if _, err := netip.ParseAddr(host); err != nil {
|
||||
result["domain_resolver"] = map[string]any{"server": "bootstrap"}
|
||||
}
|
||||
if kind == "https" {
|
||||
path := u.EscapedPath()
|
||||
if path == "" {
|
||||
path = "/dns-query"
|
||||
}
|
||||
result["path"] = path
|
||||
}
|
||||
}
|
||||
if detour != "" {
|
||||
result["detour"] = detour
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
func (c Config) managedJSON() ([]byte, error) {
|
||||
feature := c.Feature
|
||||
if feature == "" {
|
||||
feature = "mesh"
|
||||
}
|
||||
if feature != "mesh" && feature != "proxy" && feature != "combined" {
|
||||
return nil, errors.New("invalid feature")
|
||||
}
|
||||
mesh := feature != "proxy"
|
||||
internet := feature != "mesh"
|
||||
mode := c.Mode
|
||||
if mode == "" {
|
||||
mode = "rule"
|
||||
}
|
||||
if mode != "rule" && mode != "global" && mode != "direct" && mode != "bypass_cn" {
|
||||
return nil, errors.New("invalid proxy mode")
|
||||
}
|
||||
// A managed preset must not inherit custom rules that could override GeoIP.
|
||||
bypassCN := mode == "bypass_cn"
|
||||
if bypassCN {
|
||||
mode = "rule"
|
||||
c.DefaultAction = "proxy"
|
||||
c.Rules = nil
|
||||
c.RuleSets = []RuleSet{{Tag: "meshport-geoip-cn", Enabled: true,
|
||||
URL: "https://raw.githubusercontent.com/SagerNet/sing-geoip/rule-set/geoip-cn.srs",
|
||||
Format: "binary", Action: "direct", DownloadDetour: "proxy", UpdateHours: 24}}
|
||||
}
|
||||
active, err := prefixes(c.MeshCIDRs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
protected, err := prefixes(c.ProtectedCIDRs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c.ListenPort == 0 {
|
||||
return nil, errors.New("listen port required")
|
||||
}
|
||||
outbounds := []any{}
|
||||
if mesh {
|
||||
endpoint, e := netip.ParseAddrPort(c.MeshSOCKS)
|
||||
if e != nil || !endpoint.Addr().Is4() || !endpoint.Addr().IsLoopback() || endpoint.Port() == 0 {
|
||||
return nil, errors.New("mesh SOCKS must be an IPv4 loopback endpoint with a port")
|
||||
}
|
||||
if len(active) == 0 && len(protected) == 0 {
|
||||
return nil, errors.New("effective mesh prefixes required")
|
||||
}
|
||||
meshOutbound := map[string]any{"type": "socks", "tag": "meshport", "server": endpoint.Addr().String(), "server_port": endpoint.Port(), "version": "5", "udp_over_tcp": false}
|
||||
// The Rust bridge is local. The internet default_interface must not
|
||||
// bind this loopback connection to a physical network adapter.
|
||||
if c.DesktopTun {
|
||||
meshOutbound["bind_interface"] = "lo0"
|
||||
}
|
||||
outbounds = append(outbounds, meshOutbound)
|
||||
}
|
||||
if internet {
|
||||
outbounds = append(outbounds, map[string]any{"type": "direct", "tag": "direct"})
|
||||
if c.Proxy != nil {
|
||||
node, e := proxyNode(c.Proxy)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
// Only the proxy endpoint may bootstrap outside the proxy.
|
||||
node["domain_resolver"] = map[string]any{"server": "bootstrap"}
|
||||
outbounds = append(outbounds, node)
|
||||
}
|
||||
}
|
||||
action := c.DefaultAction
|
||||
if action == "" {
|
||||
action = "proxy"
|
||||
}
|
||||
if action != "proxy" && action != "direct" && action != "reject" {
|
||||
return nil, errors.New("invalid default action")
|
||||
}
|
||||
if internet && mode == "global" {
|
||||
action = "proxy"
|
||||
}
|
||||
if internet && mode == "direct" {
|
||||
action = "direct"
|
||||
}
|
||||
routeRules := []any{}
|
||||
dns := map[string]any{}
|
||||
defaultResolver := "bootstrap"
|
||||
if internet {
|
||||
server := c.DNS
|
||||
if server == "" {
|
||||
server = "1.1.1.1"
|
||||
}
|
||||
server, dnsPort, e := dnsAddress(server)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
dnsServers := []any{map[string]any{"type": "udp", "tag": "bootstrap", "server": server, "server_port": dnsPort}}
|
||||
dnsFinal := "bootstrap"
|
||||
if c.DirectDNS != "" {
|
||||
server, e := resolver(c.DirectDNS, "direct-dns", "")
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
dnsServers = append(dnsServers, server)
|
||||
dnsFinal = "direct-dns"
|
||||
}
|
||||
if c.DNSProtection && mode != "direct" {
|
||||
if c.Proxy == nil {
|
||||
return nil, errors.New("DNS protection requires a selected proxy node; use direct mode for direct-only traffic")
|
||||
}
|
||||
if c.ProxyDNS == "" {
|
||||
return nil, errors.New("DNS protection requires an explicitly configured proxy DNS server")
|
||||
}
|
||||
}
|
||||
if c.ProxyDNS != "" && mode != "direct" {
|
||||
if c.Proxy == nil {
|
||||
return nil, errors.New("proxy DNS requires proxy node")
|
||||
}
|
||||
server, e := resolver(c.ProxyDNS, "proxy-dns", "proxy")
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
dnsServers = append(dnsServers, server)
|
||||
if mode != "direct" {
|
||||
dnsFinal = "proxy-dns"
|
||||
}
|
||||
}
|
||||
dnsRules := []any{}
|
||||
for i, m := range c.MeshDNS {
|
||||
ip, e := netip.ParseAddr(m.Server)
|
||||
activeDNS, knownDNS := false, false
|
||||
for _, v := range active {
|
||||
if netip.MustParsePrefix(v).Contains(ip) {
|
||||
activeDNS = true
|
||||
}
|
||||
}
|
||||
for _, v := range protected {
|
||||
if netip.MustParsePrefix(v).Contains(ip) {
|
||||
knownDNS = true
|
||||
}
|
||||
}
|
||||
if !mesh || !domain(m.Suffix) || e != nil || !(activeDNS || knownDNS) {
|
||||
return nil, errors.New("mesh DNS requires a known mesh server and valid suffix")
|
||||
}
|
||||
if !activeDNS {
|
||||
dnsRules = append(dnsRules, map[string]any{"domain_suffix": []string{m.Suffix}, "action": "reject"})
|
||||
continue
|
||||
}
|
||||
tag := "mesh-dns-" + strings.Repeat("x", i+1)
|
||||
dnsServers = append(dnsServers, map[string]any{"type": "udp", "tag": tag, "server": m.Server, "detour": "meshport"})
|
||||
dnsRules = append(dnsRules, map[string]any{"domain_suffix": []string{m.Suffix}, "action": "route", "server": tag})
|
||||
}
|
||||
if c.FakeIP {
|
||||
if len(c.FakeIPExclude) > 128 {
|
||||
return nil, errors.New("too many FakeIP exclusions")
|
||||
}
|
||||
excluded := []string{"localhost", "local", "lan"}
|
||||
for _, v := range c.FakeIPExclude {
|
||||
if !domain(v) {
|
||||
return nil, errors.New("invalid FakeIP exclusion")
|
||||
}
|
||||
excluded = append(excluded, v)
|
||||
}
|
||||
dnsRules = append(dnsRules, map[string]any{"domain_suffix": excluded, "action": "route", "server": dnsFinal})
|
||||
dnsServers = append(dnsServers, map[string]any{"type": "fakeip", "tag": "fakeip", "inet4_range": "198.18.0.0/15", "inet6_range": "fc00::/18"})
|
||||
dnsRules = append(dnsRules, map[string]any{"query_type": []string{"A", "AAAA"}, "action": "route", "server": "fakeip"})
|
||||
}
|
||||
defaultResolver = dnsFinal
|
||||
dns = map[string]any{"servers": dnsServers, "rules": dnsRules, "final": dnsFinal, "strategy": "ipv4_only"}
|
||||
routeRules = append(routeRules, map[string]any{"port": 53, "action": "hijack-dns"}, map[string]any{"action": "resolve", "strategy": "ipv4_only"})
|
||||
} else {
|
||||
routeRules = append(routeRules, map[string]any{"domain_regex": []string{".+"}, "action": "reject"})
|
||||
}
|
||||
if mesh && internet {
|
||||
for _, rule := range c.MeshDNS {
|
||||
routeRules = append(routeRules, map[string]any{"domain_suffix": []string{rule.Suffix}, "action": "route", "outbound": "meshport"})
|
||||
}
|
||||
}
|
||||
|
||||
if mesh && len(active) > 0 {
|
||||
routeRules = append(routeRules, map[string]any{"ip_cidr": active, "action": "route", "outbound": "meshport"})
|
||||
}
|
||||
if mesh && len(protected) > 0 {
|
||||
routeRules = append(routeRules, map[string]any{"ip_cidr": protected, "action": "reject"})
|
||||
}
|
||||
if internet && bypassCN {
|
||||
routeRules = append(routeRules, map[string]any{"ip_is_private": true, "action": "route", "outbound": "direct"})
|
||||
}
|
||||
usedProxy := internet && action == "proxy"
|
||||
if internet && mode == "rule" {
|
||||
if len(c.Rules) > 256 {
|
||||
return nil, errors.New("too many rules")
|
||||
}
|
||||
for _, r := range c.Rules {
|
||||
item := map[string]any{}
|
||||
switch r.Type {
|
||||
case "domain", "domain_suffix":
|
||||
if !domain(r.Value) {
|
||||
return nil, errors.New("invalid rule domain")
|
||||
}
|
||||
item[r.Type] = []string{r.Value}
|
||||
case "ip_cidr":
|
||||
p, e := netip.ParsePrefix(r.Value)
|
||||
if e != nil {
|
||||
return nil, errors.New("invalid rule CIDR")
|
||||
}
|
||||
item[r.Type] = []string{p.Masked().String()}
|
||||
default:
|
||||
return nil, errors.New("unsupported rule type")
|
||||
}
|
||||
switch r.Action {
|
||||
case "reject":
|
||||
item["action"] = "reject"
|
||||
case "direct", "proxy":
|
||||
item["action"] = "route"
|
||||
item["outbound"] = r.Action
|
||||
if r.Action == "proxy" {
|
||||
usedProxy = true
|
||||
}
|
||||
default:
|
||||
return nil, errors.New("invalid rule action")
|
||||
}
|
||||
routeRules = append(routeRules, item)
|
||||
}
|
||||
}
|
||||
ruleSets := []any{}
|
||||
if len(c.RuleSets) > 32 {
|
||||
return nil, errors.New("too many rule sets")
|
||||
}
|
||||
tags := map[string]bool{}
|
||||
for _, set := range c.RuleSets {
|
||||
if !set.Enabled || !internet || mode != "rule" {
|
||||
continue
|
||||
}
|
||||
if !domain(set.Tag) || tags[set.Tag] {
|
||||
return nil, errors.New("invalid or duplicate rule set tag")
|
||||
}
|
||||
tags[set.Tag] = true
|
||||
if set.Action != "proxy" && set.Action != "direct" && set.Action != "reject" {
|
||||
return nil, errors.New("invalid rule set action")
|
||||
}
|
||||
item := map[string]any{"tag": set.Tag}
|
||||
if set.URL != "" {
|
||||
u, err := url.Parse(set.URL)
|
||||
if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.Fragment != "" || len(set.Rules) != 0 {
|
||||
return nil, errors.New("invalid remote rule set URL")
|
||||
}
|
||||
if set.Format != "source" && set.Format != "binary" {
|
||||
return nil, errors.New("invalid rule set format")
|
||||
}
|
||||
hours := set.UpdateHours
|
||||
if hours == 0 {
|
||||
hours = 24
|
||||
}
|
||||
if hours < 1 || hours > 168 {
|
||||
return nil, errors.New("invalid rule set interval")
|
||||
}
|
||||
detour := set.DownloadDetour
|
||||
if detour == "" {
|
||||
detour = "direct"
|
||||
}
|
||||
if detour != "proxy" && detour != "direct" {
|
||||
return nil, errors.New("invalid rule set download detour")
|
||||
}
|
||||
if detour == "proxy" && c.Proxy == nil {
|
||||
return nil, errors.New("rule set download requires proxy")
|
||||
}
|
||||
item["type"], item["format"], item["url"] = "remote", set.Format, set.URL
|
||||
item["update_interval"], item["download_detour"] = fmt.Sprintf("%dh", hours), detour
|
||||
} else {
|
||||
if len(set.Rules) == 0 || len(set.Rules) > 256 {
|
||||
return nil, errors.New("invalid inline rule set")
|
||||
}
|
||||
item["type"], item["rules"] = "inline", set.Rules
|
||||
}
|
||||
if internet && mode == "rule" {
|
||||
ruleSets = append(ruleSets, item)
|
||||
match := map[string]any{"rule_set": []string{set.Tag}, "action": "route", "outbound": set.Action}
|
||||
if set.Action == "reject" {
|
||||
delete(match, "outbound")
|
||||
match["action"] = "reject"
|
||||
}
|
||||
if set.Action == "proxy" {
|
||||
usedProxy = true
|
||||
}
|
||||
routeRules = append(routeRules, match)
|
||||
}
|
||||
}
|
||||
if usedProxy && c.Proxy == nil {
|
||||
return nil, errors.New("selected proxy node required")
|
||||
}
|
||||
final := "meshport"
|
||||
if internet && action != "reject" {
|
||||
final = action
|
||||
} else {
|
||||
routeRules = append(routeRules, map[string]any{"action": "reject"})
|
||||
if internet {
|
||||
final = "direct"
|
||||
}
|
||||
}
|
||||
if c.FakeIP && !internet {
|
||||
return nil, errors.New("FakeIP requires ordinary proxy feature")
|
||||
}
|
||||
inbounds := []any{map[string]any{"type": "socks", "tag": "local", "listen": "127.0.0.1", "listen_port": c.ListenPort}}
|
||||
route := map[string]any{"rules": routeRules, "final": final}
|
||||
if len(ruleSets) > 0 {
|
||||
route["rule_set"] = ruleSets
|
||||
}
|
||||
if internet {
|
||||
route["default_domain_resolver"] = map[string]any{"server": defaultResolver}
|
||||
}
|
||||
if c.DesktopTun {
|
||||
if c.Tun != nil || c.PhysicalInterface == "" || strings.ContainsAny(c.PhysicalInterface, " /\\\t\r\n") {
|
||||
return nil, errors.New("desktop TUN requires physical interface")
|
||||
}
|
||||
route["default_interface"] = c.PhysicalInterface
|
||||
routes := []string{"0.0.0.0/1", "128.0.0.0/1", "::/1", "8000::/1"}
|
||||
if !internet {
|
||||
// Active prefixes also belong to the session's protection set.
|
||||
// Duplicate routes make Darwin delete the same entry twice on close,
|
||||
// which breaks subsequent announcement-driven engine restarts.
|
||||
captureSet := make(map[string]bool)
|
||||
for _, prefix := range append(append([]string{}, active...), protected...) {
|
||||
captureSet[prefix] = true
|
||||
}
|
||||
capture := make([]string, 0, len(captureSet))
|
||||
for prefix := range captureSet {
|
||||
capture = append(capture, prefix)
|
||||
}
|
||||
routes, err = prefixes(capture)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
dnsMode := "native"
|
||||
addresses := []string{"172.19.0.1/30", "fdfe:dcba:9876::1/126"}
|
||||
if !internet {
|
||||
dnsMode = "disabled"
|
||||
// No accepted IPv6 mesh prefixes exist yet. Giving Darwin an IPv6
|
||||
// address with auto_route and no IPv6 route_address captures its
|
||||
// IPv6 default route, even in the subnet-only mode.
|
||||
addresses = []string{"172.19.0.1/30"}
|
||||
}
|
||||
inbounds = append(inbounds, map[string]any{"type": "tun", "tag": "unified-tun", "address": addresses, "mtu": 1280, "auto_route": true, "route_address": routes, "stack": "system", "dns_mode": dnsMode})
|
||||
}
|
||||
if c.Tun != nil {
|
||||
if c.Tun.FD <= 0 || c.Tun.Name == "" || c.Tun.Interface == "" || c.Tun.Index <= 0 {
|
||||
return nil, errors.New("valid platform TUN and physical network required")
|
||||
}
|
||||
route["auto_detect_interface"] = true
|
||||
inbounds = append(inbounds, map[string]any{"type": "tun", "tag": "unified-tun", "interface_name": c.Tun.Name, "address": []string{"172.19.0.1/30", "fdfe:dcba:9876::1/126"}, "mtu": 1280, "auto_route": false, "stack": "system", "dns_mode": "disabled"})
|
||||
}
|
||||
result := map[string]any{"log": map[string]any{"disabled": !c.selfTestTrace(), "level": "debug"}, "inbounds": inbounds, "outbounds": outbounds, "route": route}
|
||||
if internet {
|
||||
result["dns"] = dns
|
||||
}
|
||||
return json.Marshal(result)
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"github.com/sagernet/sing/protocol/socks"
|
||||
"github.com/sagernet/sing/protocol/socks/socks5"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
D "github.com/miekg/dns"
|
||||
box "github.com/sagernet/sing-box"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
sjson "github.com/sagernet/sing/common/json"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
)
|
||||
|
||||
func TestDNSProtectionRequiresExplicitResolverAndKeepsBootstrapNarrow(t *testing.T) {
|
||||
c := Config{ListenPort: 12345, Feature: "proxy", Mode: "global", DNSProtection: true, Proxy: map[string]any{"type": "socks", "server": "proxy.example", "server_port": 1080}}
|
||||
if _, err := c.managedJSON(); err == nil {
|
||||
t.Fatal("silently chose a DNS provider")
|
||||
}
|
||||
c.ProxyDNS = "tls://resolver.example"
|
||||
data, err := c.managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var v map[string]any
|
||||
json.Unmarshal(data, &v)
|
||||
if v["dns"].(map[string]any)["final"] != "proxy-dns" || v["route"].(map[string]any)["default_domain_resolver"].(map[string]any)["server"] != "proxy-dns" {
|
||||
t.Fatal("ordinary lookup escapes proxy DNS")
|
||||
}
|
||||
outbounds := v["outbounds"].([]any)
|
||||
if outbounds[1].(map[string]any)["domain_resolver"].(map[string]any)["server"] != "bootstrap" {
|
||||
t.Fatal("proxy endpoint resolution loops")
|
||||
}
|
||||
c.Mode = "direct"
|
||||
c.Proxy = nil
|
||||
c.ProxyDNS = ""
|
||||
if _, err := c.managedJSON(); err != nil {
|
||||
t.Fatal("direct mode required proxy DNS", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSProtectionNoDirectFallbackOnProxyFailure(t *testing.T) {
|
||||
// All addresses and trust are isolated test fixtures, not public DNS providers.
|
||||
fixture := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
defer fixture.Close()
|
||||
for _, fake := range []bool{false, true} {
|
||||
for _, fail := range []bool{false, true} {
|
||||
var proxiedQueries, bootQueries atomic.Int32
|
||||
proxy, _ := socksFixture(t, func(conn net.Conn) {
|
||||
if fail {
|
||||
return
|
||||
}
|
||||
stream := tls.Server(conn, &tls.Config{Certificates: fixture.TLS.Certificates, MinVersion: tls.VersionTLS12})
|
||||
dc := &D.Conn{Conn: stream}
|
||||
for {
|
||||
request, err := dc.ReadMsg()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
proxiedQueries.Add(1)
|
||||
response := new(D.Msg)
|
||||
response.SetReply(request)
|
||||
response.Answer = []D.RR{&D.A{Hdr: D.RR_Header{Name: request.Question[0].Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: 60}, A: net.ParseIP("203.0.113.7")}}
|
||||
if dc.WriteMsg(response) != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
defer proxy.Close()
|
||||
socket, err := net.ListenPacket("udp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bootstrap := &D.Server{PacketConn: socket, Handler: D.HandlerFunc(func(w D.ResponseWriter, r *D.Msg) { bootQueries.Add(1); m := new(D.Msg); m.SetReply(r); w.WriteMsg(m) })}
|
||||
go bootstrap.ActivateAndServe()
|
||||
defer bootstrap.Shutdown()
|
||||
l, port := reservePort(t)
|
||||
l.Close()
|
||||
c := Config{ListenPort: port, Feature: "proxy", Mode: "rule", DefaultAction: "reject", DNS: socket.LocalAddr().String(), DNSProtection: true, FakeIP: fake,
|
||||
ProxyDNS: "tls://127.0.0.1:853", Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}}
|
||||
data, err := c.managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := registryContext(context.Background())
|
||||
opts, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
opts.Certificate = &option.CertificateOptions{Store: "none", Certificate: []string{string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: fixture.Certificate().Raw}))}}
|
||||
instance, err := box.New(box.Options{Context: ctx, Options: opts})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = instance.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
target := "private-query.test"
|
||||
if fake {
|
||||
conn, err := net.Dial("tcp4", net.JoinHostPort("127.0.0.1", jsonNumber(int(port))))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
_, err = socks.ClientHandshake5(conn, socks5.CommandConnect, M.ParseSocksaddr("1.1.1.1:53"), "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dc := &D.Conn{Conn: conn}
|
||||
msg := new(D.Msg)
|
||||
msg.SetQuestion("private-query.test.", D.TypeA)
|
||||
if err = dc.WriteMsg(msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
answer, err := dc.ReadMsg()
|
||||
conn.Close()
|
||||
if err != nil || len(answer.Answer) != 1 {
|
||||
t.Fatalf("FakeIP query: %v / %v", answer, err)
|
||||
}
|
||||
target = answer.Answer[0].(*D.A).A.String()
|
||||
}
|
||||
echoThrough(t, port, M.ParseSocksaddr(net.JoinHostPort(target, "443")), false)
|
||||
instance.Close()
|
||||
if bootQueries.Load() != 0 {
|
||||
t.Fatal("target query leaked to bootstrap DNS")
|
||||
}
|
||||
if !fail && proxiedQueries.Load() == 0 {
|
||||
t.Fatal("proxy DNS wasn't used")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
// Package bridge provides an explicitly managed sing-box lifecycle. Platform
|
||||
// TUN integration and ordinary internet proxy profiles are separate milestones.
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing/common/control"
|
||||
"github.com/sagernet/sing/service"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
box "github.com/sagernet/sing-box"
|
||||
"github.com/sagernet/sing-box/adapter/certificate"
|
||||
"github.com/sagernet/sing-box/adapter/endpoint"
|
||||
"github.com/sagernet/sing-box/adapter/inbound"
|
||||
"github.com/sagernet/sing-box/adapter/outbound"
|
||||
boxservice "github.com/sagernet/sing-box/adapter/service"
|
||||
"github.com/sagernet/sing-box/dns"
|
||||
"github.com/sagernet/sing-box/dns/transport"
|
||||
"github.com/sagernet/sing-box/dns/transport/fakeip"
|
||||
"github.com/sagernet/sing-box/dns/transport/local"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing-box/protocol/direct"
|
||||
"github.com/sagernet/sing-box/protocol/http"
|
||||
"github.com/sagernet/sing-box/protocol/shadowsocks"
|
||||
"github.com/sagernet/sing-box/protocol/trojan"
|
||||
"github.com/sagernet/sing-box/protocol/tun"
|
||||
"github.com/sagernet/sing-box/protocol/vless"
|
||||
"github.com/sagernet/sing-box/protocol/vmess"
|
||||
sjson "github.com/sagernet/sing/common/json"
|
||||
)
|
||||
|
||||
func registryContext(ctx context.Context) context.Context {
|
||||
in := inbound.NewRegistry()
|
||||
registerTrackedInbound(in)
|
||||
tun.RegisterInbound(in)
|
||||
out := outbound.NewRegistry()
|
||||
registerMeshOutbound(out)
|
||||
shadowsocks.RegisterOutbound(out)
|
||||
vmess.RegisterOutbound(out)
|
||||
vless.RegisterOutbound(out)
|
||||
trojan.RegisterOutbound(out)
|
||||
http.RegisterOutbound(out)
|
||||
direct.RegisterOutbound(out) // Required for sing-box's internal defaults.
|
||||
dnsRegistry := dns.NewTransportRegistry()
|
||||
local.RegisterTransport(dnsRegistry)
|
||||
transport.RegisterUDP(dnsRegistry)
|
||||
transport.RegisterHTTPS(dnsRegistry)
|
||||
transport.RegisterTLS(dnsRegistry)
|
||||
fakeip.RegisterTransport(dnsRegistry)
|
||||
return box.Context(ctx, in, out, endpoint.NewRegistry(), dnsRegistry,
|
||||
boxservice.NewRegistry(), certificate.NewRegistry())
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
State string `json:"state"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
type Engine struct {
|
||||
selfTestTrace bool
|
||||
startupCause error // Private diagnostic for package tests; never returned over ABI.
|
||||
// Protector must be installed before starting a host TUN.
|
||||
CacheRoot string
|
||||
cacheDir string
|
||||
Protect func(int) error
|
||||
mu sync.Mutex
|
||||
box *box.Box
|
||||
state string
|
||||
cancel context.CancelFunc
|
||||
ctx context.Context
|
||||
desktopTun bool
|
||||
}
|
||||
|
||||
func (e *Engine) Snapshot() Snapshot {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
state := e.state
|
||||
if state == "" {
|
||||
state = "Stopped"
|
||||
}
|
||||
if state == "Running" && e.ctx.Err() != nil {
|
||||
state = "Failed"
|
||||
}
|
||||
return Snapshot{State: state, Version: "1.14.3"}
|
||||
}
|
||||
|
||||
func (e *Engine) Start(parent context.Context, config Config) error {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
if e.box != nil {
|
||||
return errors.New("engine already started; stop before applying configuration")
|
||||
}
|
||||
if parent.Err() != nil {
|
||||
return errors.New("engine context is canceled")
|
||||
}
|
||||
if config.DesktopTun && (runtime.GOOS != "darwin" || os.Geteuid() != 0) {
|
||||
return errors.New("desktop TUN requires macOS privileged helper")
|
||||
}
|
||||
if config.DesktopTun {
|
||||
attached, err := desktopTunAddressAttached()
|
||||
if err != nil {
|
||||
return errors.New("cannot inspect desktop TUN address")
|
||||
}
|
||||
if attached {
|
||||
return errors.New("desktop TUN address already in use")
|
||||
}
|
||||
}
|
||||
data, err := config.managedJSON()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
e.selfTestTrace = config.selfTestTrace()
|
||||
e.desktopTun = config.DesktopTun
|
||||
e.state = "Starting"
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
ctx = registryContext(ctx)
|
||||
if config.Tun != nil {
|
||||
if e.Protect == nil {
|
||||
cancel()
|
||||
e.state = "Failed"
|
||||
return errors.New("platform socket protection required")
|
||||
}
|
||||
physical := &control.Interface{Name: config.Tun.Interface, Index: config.Tun.Index, MTU: 1500, Flags: net.FlagUp}
|
||||
ctx = service.ContextWith[adapter.PlatformInterface](ctx, &hostPlatform{config: *config.Tun, protect: e.Protect, monitor: &hostMonitor{physical: physical}})
|
||||
}
|
||||
options, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
|
||||
if err != nil {
|
||||
cancel()
|
||||
e.state = "Failed"
|
||||
return errors.New("invalid managed engine configuration")
|
||||
}
|
||||
if config.FakeIP || len(config.RuleSets) > 0 {
|
||||
if e.cacheDir == "" {
|
||||
e.cacheDir, err = os.MkdirTemp(e.CacheRoot, "meshport-fakeip-")
|
||||
if err != nil {
|
||||
cancel()
|
||||
e.state = "Failed"
|
||||
return errors.New("cannot create private DNS cache")
|
||||
}
|
||||
}
|
||||
options.Experimental = &option.ExperimentalOptions{CacheFile: &option.CacheFileOptions{Enabled: true, Path: filepath.Join(e.cacheDir, "fakeip.db"), StoreFakeIP: config.FakeIP}}
|
||||
}
|
||||
instance, err := box.New(box.Options{Options: options, Context: ctx})
|
||||
if err != nil {
|
||||
e.startupCause = err
|
||||
cancel()
|
||||
e.state = "Failed"
|
||||
return errors.New("cannot initialize proxy engine")
|
||||
}
|
||||
if err = instance.Start(); err != nil {
|
||||
e.startupCause = err
|
||||
_ = instance.Close()
|
||||
cancel()
|
||||
e.state = "Failed"
|
||||
return errors.New("cannot start proxy engine")
|
||||
}
|
||||
e.box, e.cancel, e.ctx, e.state = instance, cancel, ctx, "Running"
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *Engine) Stop() error {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
if e.box == nil {
|
||||
e.state = "Stopped"
|
||||
return nil
|
||||
}
|
||||
e.state = "Stopping"
|
||||
err := e.box.Close()
|
||||
e.cancel()
|
||||
e.box, e.cancel, e.ctx = nil, nil, nil
|
||||
if e.desktopTun && err == nil {
|
||||
// Darwin can retain the utun address until its last kernel reference
|
||||
// drains. Reusing that address immediately can attach the new routes
|
||||
// to the retiring interface and remove them when it finally disappears.
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for {
|
||||
attached, inspectErr := desktopTunAddressAttached()
|
||||
if inspectErr != nil {
|
||||
err = inspectErr
|
||||
break
|
||||
}
|
||||
if !attached {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
err = errors.New("desktop TUN address did not detach")
|
||||
break
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
e.state = "Failed"
|
||||
if e.selfTestTrace {
|
||||
fmt.Fprintf(os.Stderr, "self-test cleanup cause: %v\n", err)
|
||||
}
|
||||
return errors.New("proxy engine cleanup failed")
|
||||
}
|
||||
e.state = "Stopped"
|
||||
return nil
|
||||
}
|
||||
|
||||
func desktopTunAddressAttached() (bool, error) {
|
||||
addresses, err := net.InterfaceAddrs()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, address := range addresses {
|
||||
ip, _, err := net.ParseCIDR(address.String())
|
||||
if err == nil && ip.Equal(net.ParseIP("172.19.0.1")) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Close releases the session's private cache only after the engine is stopped.
|
||||
func (e *Engine) Close() error {
|
||||
err := e.Stop()
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
if e.cacheDir != "" {
|
||||
removeErr := os.RemoveAll(e.cacheDir)
|
||||
e.cacheDir = ""
|
||||
if err == nil {
|
||||
err = removeErr
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
"github.com/sagernet/sing/protocol/socks"
|
||||
"github.com/sagernet/sing/protocol/socks/socks5"
|
||||
"io"
|
||||
"net"
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func reservePort(t *testing.T) (net.Listener, uint16) {
|
||||
t.Helper()
|
||||
l, err := net.Listen("tcp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return l, uint16(l.Addr().(*net.TCPAddr).Port)
|
||||
}
|
||||
|
||||
func TestUnconfiguredTargetsAndDomainsAreRejected(t *testing.T) {
|
||||
bridgeListener, _ := reservePort(t)
|
||||
defer bridgeListener.Close()
|
||||
entry, port := reservePort(t)
|
||||
entry.Close()
|
||||
var engine Engine
|
||||
if err := engine.Start(context.Background(), Config{ListenPort: port, MeshSOCKS: bridgeListener.Addr().String(), MeshCIDRs: []string{"10.77.0.0/24"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer engine.Stop()
|
||||
for _, destination := range []M.Socksaddr{
|
||||
M.SocksaddrFrom(netip.MustParseAddr("127.0.0.1"), uint16(bridgeListener.Addr().(*net.TCPAddr).Port)),
|
||||
M.SocksaddrFrom(netip.MustParseAddr("10.78.0.1"), 1234),
|
||||
M.ParseSocksaddr("must-not-resolve.invalid:1234"),
|
||||
} {
|
||||
conn, err := net.Dial("tcp4", entry.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
_, err = socks.ClientHandshake5(conn, socks5.CommandConnect, destination, "", "")
|
||||
conn.Close()
|
||||
if err == nil {
|
||||
t.Fatal("unconfigured target accepted:", destination)
|
||||
}
|
||||
if timeout, ok := err.(net.Error); ok && timeout.Timeout() {
|
||||
t.Fatal("rejection timed out:", destination)
|
||||
}
|
||||
}
|
||||
bridgeListener.(*net.TCPListener).SetDeadline(time.Now().Add(100 * time.Millisecond))
|
||||
if conn, err := bridgeListener.Accept(); err == nil {
|
||||
conn.Close()
|
||||
t.Fatal("rejected request reached mesh bridge")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigurationRejectsUnsupportedEndpointsAndPrefixes(t *testing.T) {
|
||||
base := Config{ListenPort: 1080, MeshSOCKS: "127.0.0.1:1234", MeshCIDRs: []string{"10.77.0.0/24"}}
|
||||
for _, endpoint := range []string{"example.com:1080", "0.0.0.0:1080", "10.0.0.1:1080", "127.0.0.1:0", "[::1]:1080"} {
|
||||
c := base
|
||||
c.MeshSOCKS = endpoint
|
||||
if _, err := c.managedJSON(); err == nil {
|
||||
t.Errorf("accepted endpoint %s", endpoint)
|
||||
}
|
||||
}
|
||||
for _, prefix := range []string{"0.0.0.0/0", "10.0.0.0/8", "1.1.1.0/24", "127.0.0.0/24", "fd00::/64", "invalid"} {
|
||||
c := base
|
||||
c.MeshCIDRs = []string{prefix}
|
||||
if _, err := c.managedJSON(); err == nil {
|
||||
t.Errorf("accepted prefix %s", prefix)
|
||||
}
|
||||
}
|
||||
c := base
|
||||
c.MeshCIDRs = nil
|
||||
if _, err := c.managedJSON(); err == nil {
|
||||
t.Error("accepted empty projection")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEngineLifecycleAndFailedStartRecovery(t *testing.T) {
|
||||
occupied, port := reservePort(t)
|
||||
defer occupied.Close()
|
||||
c := Config{ListenPort: port, MeshSOCKS: "127.0.0.1:1234", MeshCIDRs: []string{"10.77.0.11/24", "10.77.0.0/24"}}
|
||||
var engine Engine
|
||||
if engine.Snapshot().State != "Stopped" {
|
||||
t.Fatal("initial state")
|
||||
}
|
||||
if engine.Start(context.Background(), c) == nil {
|
||||
t.Fatal("started on occupied port")
|
||||
}
|
||||
if engine.Snapshot().State != "Failed" {
|
||||
t.Fatal("failed start state")
|
||||
}
|
||||
occupied.Close()
|
||||
if err := engine.Start(context.Background(), c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer engine.Stop()
|
||||
if engine.Snapshot().State != "Running" {
|
||||
t.Fatal("running state")
|
||||
}
|
||||
if engine.Start(context.Background(), c) == nil {
|
||||
t.Fatal("duplicate start accepted")
|
||||
}
|
||||
conn, err := net.Dial("tcp4", occupied.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
if _, err := conn.Write([]byte{5, 1, 0}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var reply [2]byte
|
||||
if _, err := io.ReadFull(conn, reply[:]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reply != [2]byte{5, 0} {
|
||||
t.Fatal("unexpected negotiation", reply)
|
||||
}
|
||||
if err := engine.Stop(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := engine.Stop(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if engine.Snapshot().State != "Stopped" {
|
||||
t.Fatal("stop state")
|
||||
}
|
||||
if n, err := conn.Read(reply[:]); n != 0 {
|
||||
t.Fatal("active connection retained after stop")
|
||||
} else if timeout, ok := err.(net.Error); ok && timeout.Timeout() {
|
||||
t.Fatal("active connection only closed by client timeout")
|
||||
}
|
||||
l, err := net.Listen("tcp4", occupied.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal("listener leaked:", err)
|
||||
}
|
||||
l.Close()
|
||||
if err := engine.Start(context.Background(), c); err != nil {
|
||||
t.Fatal("restart:", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/adapter/inbound"
|
||||
"github.com/sagernet/sing-box/common/listener"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing-box/protocol/socks"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
)
|
||||
|
||||
// Track accepted controls before SOCKS negotiation, including connections that
|
||||
// have not entered sing-box's routed connection manager yet.
|
||||
type connectionSet struct {
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
connections map[*trackedConnection]struct{}
|
||||
}
|
||||
|
||||
type trackedConnection struct {
|
||||
net.Conn
|
||||
owner *connectionSet
|
||||
}
|
||||
|
||||
func (c *trackedConnection) Close() error {
|
||||
err := c.Conn.Close()
|
||||
c.owner.mu.Lock()
|
||||
delete(c.owner.connections, c)
|
||||
c.owner.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *connectionSet) track(conn net.Conn) *trackedConnection {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed || len(s.connections) >= 128 {
|
||||
return nil
|
||||
}
|
||||
c := &trackedConnection{Conn: conn, owner: s}
|
||||
s.connections[c] = struct{}{}
|
||||
return c
|
||||
}
|
||||
|
||||
func (s *connectionSet) closeAll() {
|
||||
s.mu.Lock()
|
||||
s.closed = true
|
||||
connections := make([]*trackedConnection, 0, len(s.connections))
|
||||
for conn := range s.connections {
|
||||
connections = append(connections, conn)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
for _, conn := range connections {
|
||||
_ = conn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
type trackedInbound struct {
|
||||
*socks.Inbound
|
||||
listener *listener.Listener
|
||||
connections connectionSet
|
||||
}
|
||||
|
||||
func registerTrackedInbound(registry *inbound.Registry) {
|
||||
inbound.Register[option.SocksInboundOptions](registry, C.TypeSOCKS,
|
||||
func(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.SocksInboundOptions) (adapter.Inbound, error) {
|
||||
delegate, err := socks.NewInbound(ctx, router, logger, tag, options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tracked := &trackedInbound{Inbound: delegate.(*socks.Inbound), connections: connectionSet{connections: make(map[*trackedConnection]struct{})}}
|
||||
// The delegate only handles the protocol. This listener owns the
|
||||
// accepted TCP controls; its options also constrain UDP association
|
||||
// allocation through the delegate's original packet-listener helper.
|
||||
tracked.listener = listener.New(listener.Options{Context: ctx, Logger: logger, Network: []string{N.NetworkTCP}, Listen: options.ListenOptions, ConnectionHandler: tracked})
|
||||
return tracked, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (h *trackedInbound) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
if stage != adapter.StartStateStart {
|
||||
return nil
|
||||
}
|
||||
if err := h.listener.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
scope.Add(func() error {
|
||||
err := h.listener.Close()
|
||||
h.connections.closeAll()
|
||||
return err
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *trackedInbound) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
|
||||
tracked := h.connections.track(conn)
|
||||
if tracked == nil {
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
h.Inbound.NewConnection(ctx, tracked, metadata, onClose)
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/netip"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/adapter/outbound"
|
||||
"github.com/sagernet/sing-box/common/dialer"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
boxsocks "github.com/sagernet/sing-box/protocol/socks"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
"github.com/sagernet/sing/common/varbin"
|
||||
"github.com/sagernet/sing/protocol/socks"
|
||||
"github.com/sagernet/sing/protocol/socks/socks5"
|
||||
)
|
||||
|
||||
type meshOutbound struct {
|
||||
adapter.Outbound
|
||||
dialer N.Dialer
|
||||
server M.Socksaddr
|
||||
logger log.ContextLogger
|
||||
}
|
||||
|
||||
func registerMeshOutbound(registry *outbound.Registry) {
|
||||
outbound.Register[option.SOCKSOutboundOptions](registry, C.TypeSOCKS,
|
||||
func(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.SOCKSOutboundOptions) (adapter.Outbound, error) {
|
||||
delegate, err := boxsocks.NewOutbound(ctx, router, logger, tag, options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if tag != "meshport" {
|
||||
return delegate, nil
|
||||
}
|
||||
d, err := dialer.New(ctx, options.DialerOptions, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &meshOutbound{Outbound: delegate, dialer: d, server: options.ServerOptions.Build(), logger: logger}, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (o *meshOutbound) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||
if N.NetworkName(network) == N.NetworkUDP {
|
||||
return o.associate(ctx, destination)
|
||||
}
|
||||
return o.Outbound.DialContext(ctx, network, destination)
|
||||
}
|
||||
|
||||
func (o *meshOutbound) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||
return o.associate(ctx, destination)
|
||||
}
|
||||
|
||||
// RFC 1928 UDP ASSOCIATE names the client's expected UDP endpoint, not the
|
||||
// remote destination. That endpoint is not yet allocated, so request 0.0.0.0:0.
|
||||
// Keep this normalization in our adapter instead of weakening the Rust bridge's
|
||||
// source IP/port isolation to accept another client's private-address heuristic.
|
||||
func (o *meshOutbound) associate(ctx context.Context, destination M.Socksaddr) (packet *socks.AssociatePacketConn, err error) {
|
||||
control, err := o.dialer.DialContext(ctx, N.NetworkTCP, o.server)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
_ = control.Close()
|
||||
}
|
||||
}()
|
||||
stopCancel := context.AfterFunc(ctx, func() { _ = control.Close() })
|
||||
defer func() {
|
||||
if !stopCancel() {
|
||||
if packet != nil {
|
||||
_ = packet.Close()
|
||||
packet = nil
|
||||
}
|
||||
err = ctx.Err()
|
||||
}
|
||||
}()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
if d, ok := ctx.Deadline(); ok && d.Before(deadline) {
|
||||
deadline = d
|
||||
}
|
||||
if err = control.SetDeadline(deadline); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reader := varbin.StubReader(control)
|
||||
if err = socks5.WriteAuthRequest(control, socks5.AuthRequest{Methods: []byte{socks5.AuthTypeNotRequired}}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
auth, err := socks5.ReadAuthResponse(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if auth.Method != socks5.AuthTypeNotRequired {
|
||||
return nil, errors.New("mesh bridge rejected authentication method")
|
||||
}
|
||||
if err = socks5.WriteRequest(control, socks5.Request{Command: socks5.CommandUDPAssociate, Destination: M.SocksaddrFrom(netip.IPv4Unspecified(), 0)}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
o.logger.DebugContext(ctx, "mesh UDP association requested")
|
||||
response, err := socks5.ReadResponse(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if response.ReplyCode != socks5.ReplyCodeSuccess || !response.Bind.Addr.Is4() || response.Bind.Addr != o.server.Addr || response.Bind.Port == 0 {
|
||||
return nil, errors.New("mesh bridge rejected UDP association or returned an invalid endpoint")
|
||||
}
|
||||
if err = control.SetDeadline(time.Time{}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
udp, err := o.dialer.DialContext(ctx, N.NetworkUDP, response.Bind)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
o.logger.DebugContext(ctx, "mesh UDP association ready: ", udp.LocalAddr(), " -> ", response.Bind)
|
||||
return socks.NewAssociatePacketConn(udp, destination, control), nil
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/netip"
|
||||
"sync"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing-tun"
|
||||
"github.com/sagernet/sing/common/control"
|
||||
"github.com/sagernet/sing/common/logger"
|
||||
"github.com/sagernet/sing/common/x/list"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// This adapter owns a duplicate of the host's TUN. It never creates OS routes.
|
||||
// All optional platform capabilities explicitly remain unavailable.
|
||||
type hostPlatform struct {
|
||||
config TunConfig
|
||||
protect func(int) error
|
||||
monitor *hostMonitor
|
||||
}
|
||||
|
||||
func (p *hostPlatform) Initialize(adapter.NetworkManager) error { return nil }
|
||||
func (p *hostPlatform) UsePlatformAutoDetectInterfaceControl() bool { return true }
|
||||
func (p *hostPlatform) AutoDetectInterfaceControl(fd int) error {
|
||||
if p.protect == nil {
|
||||
return errors.New("socket protector missing")
|
||||
}
|
||||
return p.protect(fd)
|
||||
}
|
||||
func (p *hostPlatform) UsePlatformInterface() bool { return true }
|
||||
func (p *hostPlatform) OpenInterface(o *tun.Options, _ option.TunPlatformOptions) (tun.Tun, error) {
|
||||
fd, e := unix.Dup(p.config.FD)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
unix.CloseOnExec(fd)
|
||||
o.FileDescriptor = fd
|
||||
o.Name = p.config.Name
|
||||
p.monitor.RegisterMyInterface(o.Name)
|
||||
result, e := tun.New(*o)
|
||||
if e != nil {
|
||||
unix.Close(fd)
|
||||
}
|
||||
return result, e
|
||||
}
|
||||
func (*hostPlatform) ProcessPlatformOptions(option.TunPlatformOptions) error { return nil }
|
||||
func (*hostPlatform) UsePlatformDefaultInterfaceMonitor() bool { return true }
|
||||
func (p *hostPlatform) CreateDefaultInterfaceMonitor(logger.Logger) tun.DefaultInterfaceMonitor {
|
||||
return p.monitor
|
||||
}
|
||||
func (*hostPlatform) UsePlatformNetworkInterfaces() bool { return true }
|
||||
func (p *hostPlatform) NetworkInterfaces() ([]adapter.NetworkInterface, error) {
|
||||
return []adapter.NetworkInterface{{Interface: *p.monitor.physical}, {Interface: control.Interface{Name: "lo", Index: 1, MTU: 65536, Flags: net.FlagUp | net.FlagLoopback, Addresses: []netip.Prefix{netip.MustParsePrefix("127.0.0.1/8")}}}}, nil
|
||||
}
|
||||
func (*hostPlatform) UnderNetworkExtension() bool { return false }
|
||||
func (*hostPlatform) NetworkExtensionIncludeAllNetworks() bool { return false }
|
||||
func (*hostPlatform) ClearDNSCache() {}
|
||||
func (*hostPlatform) RequestPermissionForWIFIState() error { return errors.New("unsupported") }
|
||||
func (*hostPlatform) ReadWIFIState(context.Context) adapter.WIFIState { return adapter.WIFIState{} }
|
||||
func (*hostPlatform) UsePlatformConnectionOwnerFinder() bool { return false }
|
||||
func (*hostPlatform) FindConnectionOwner(*adapter.FindConnectionOwnerRequest) (*adapter.ConnectionOwner, error) {
|
||||
return nil, errors.New("unsupported")
|
||||
}
|
||||
func (*hostPlatform) UsePlatformWIFIMonitor() bool { return false }
|
||||
func (*hostPlatform) UsePlatformNotification() bool { return false }
|
||||
func (*hostPlatform) SendNotification(*adapter.Notification) error { return errors.New("unsupported") }
|
||||
func (*hostPlatform) CancelNotification(string, int32) error { return errors.New("unsupported") }
|
||||
func (*hostPlatform) MyInterfaceAddress() []netip.Addr {
|
||||
return []netip.Addr{netip.MustParseAddr("172.19.0.1"), netip.MustParseAddr("fdfe:dcba:9876::1")}
|
||||
}
|
||||
func (*hostPlatform) UsePlatformNeighborResolver() bool { return false }
|
||||
func (*hostPlatform) StartNeighborMonitor(adapter.NeighborUpdateListener) error {
|
||||
return errors.New("unsupported")
|
||||
}
|
||||
func (*hostPlatform) CloseNeighborMonitor(adapter.NeighborUpdateListener) error { return nil }
|
||||
func (*hostPlatform) UsePlatformShell() bool { return false }
|
||||
func (*hostPlatform) CheckPlatformShell() error { return errors.New("unsupported") }
|
||||
func (*hostPlatform) OpenShellSession(*adapter.PlatformUser, string, []string, string, int32, int32) (adapter.ShellSession, error) {
|
||||
return nil, errors.New("unsupported")
|
||||
}
|
||||
func (*hostPlatform) LookupUser(string) (*adapter.PlatformUser, error) {
|
||||
return nil, errors.New("unsupported")
|
||||
}
|
||||
func (*hostPlatform) LookupSFTPServer() (string, error) { return "", errors.New("unsupported") }
|
||||
func (*hostPlatform) ReadSystemSSHHostKey() ([]byte, error) { return nil, errors.New("unsupported") }
|
||||
func (*hostPlatform) TailscaleHostname() string { return "" }
|
||||
func (*hostPlatform) UsePlatformBridge() bool { return false }
|
||||
func (*hostPlatform) CreateBridge(adapter.BridgeOptions) (adapter.BridgeSession, error) {
|
||||
return nil, errors.New("unsupported")
|
||||
}
|
||||
|
||||
type hostMonitor struct {
|
||||
physical *control.Interface
|
||||
mu sync.Mutex
|
||||
names []string
|
||||
callbacks list.List[tun.DefaultInterfaceUpdateCallback]
|
||||
}
|
||||
|
||||
func (*hostMonitor) Start() error { return nil }
|
||||
func (*hostMonitor) Close() error { return nil }
|
||||
func (m *hostMonitor) DefaultInterface() *control.Interface { return m.physical }
|
||||
func (*hostMonitor) OverrideAndroidVPN() bool { return true }
|
||||
func (*hostMonitor) AndroidVPNEnabled() bool { return false }
|
||||
func (m *hostMonitor) RegisterCallback(c tun.DefaultInterfaceUpdateCallback) *list.Element[tun.DefaultInterfaceUpdateCallback] {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.callbacks.PushBack(c)
|
||||
}
|
||||
func (m *hostMonitor) UnregisterCallback(e *list.Element[tun.DefaultInterfaceUpdateCallback]) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.callbacks.Remove(e)
|
||||
}
|
||||
func (m *hostMonitor) RegisterMyInterface(n string) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.names = append(m.names, n)
|
||||
}
|
||||
func (m *hostMonitor) MyInterfaces() []string {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return append([]string{}, m.names...)
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
"net/netip"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
D "github.com/miekg/dns"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
"github.com/sagernet/sing/protocol/socks"
|
||||
"github.com/sagernet/sing/protocol/socks/socks5"
|
||||
)
|
||||
|
||||
// A real SOCKS5 fixture echoes through the selected outlet; a request counter
|
||||
// distinguishes route selection from mere successful engine startup.
|
||||
func socksEcho(t *testing.T) (net.Listener, *atomic.Int32) {
|
||||
return socksFixture(t, func(c net.Conn) { io.Copy(c, c) })
|
||||
}
|
||||
func socksFixture(t *testing.T, handler func(net.Conn)) (net.Listener, *atomic.Int32) {
|
||||
l, _ := reservePort(t)
|
||||
counter := &atomic.Int32{}
|
||||
go func() {
|
||||
for {
|
||||
c, e := l.Accept()
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer c.Close()
|
||||
c.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
var greeting [2]byte
|
||||
if _, e := io.ReadFull(c, greeting[:]); e != nil {
|
||||
return
|
||||
}
|
||||
methods := make([]byte, int(greeting[1]))
|
||||
if _, e := io.ReadFull(c, methods); e != nil {
|
||||
return
|
||||
}
|
||||
c.Write([]byte{5, 0})
|
||||
var req [4]byte
|
||||
if _, e := io.ReadFull(c, req[:]); e != nil {
|
||||
return
|
||||
}
|
||||
n := 4
|
||||
if req[3] == 3 {
|
||||
var size [1]byte
|
||||
if _, e := io.ReadFull(c, size[:]); e != nil {
|
||||
return
|
||||
}
|
||||
n = int(size[0])
|
||||
} else if req[3] == 4 {
|
||||
n = 16
|
||||
}
|
||||
if _, e := io.ReadFull(c, make([]byte, n+2)); e != nil {
|
||||
return
|
||||
}
|
||||
counter.Add(1)
|
||||
c.Write([]byte{5, 0, 0, 1, 127, 0, 0, 1, 0, 1})
|
||||
handler(c)
|
||||
}()
|
||||
}
|
||||
}()
|
||||
return l, counter
|
||||
}
|
||||
func echoThrough(t *testing.T, port uint16, target M.Socksaddr, want bool) {
|
||||
t.Helper()
|
||||
c, e := net.Dial("tcp4", net.JoinHostPort("127.0.0.1", jsonNumber(int(port))))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer c.Close()
|
||||
c.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
_, e = socks.ClientHandshake5(c, socks5.CommandConnect, target, "", "")
|
||||
if !want {
|
||||
if e == nil {
|
||||
c.Write([]byte("x"))
|
||||
var b [1]byte
|
||||
n, readErr := c.Read(b[:])
|
||||
if n != 0 || readErr == nil {
|
||||
t.Fatal("protected target passed")
|
||||
}
|
||||
if ne, ok := readErr.(net.Error); ok && ne.Timeout() {
|
||||
t.Fatal("rejection timed out")
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
c.Write([]byte("route-echo"))
|
||||
result := make([]byte, 10)
|
||||
if _, e := io.ReadFull(c, result); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if string(result) != "route-echo" {
|
||||
t.Fatal(string(result))
|
||||
}
|
||||
}
|
||||
func jsonNumber(n int) string { raw, _ := json.Marshal(n); return string(raw) }
|
||||
func TestModesAndMeshPriority(t *testing.T) {
|
||||
proxy, count := socksEcho(t)
|
||||
defer proxy.Close()
|
||||
mesh, meshCount := socksEcho(t)
|
||||
defer mesh.Close()
|
||||
direct, _ := reservePort(t)
|
||||
defer direct.Close()
|
||||
go func() {
|
||||
for {
|
||||
c, e := direct.Accept()
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
go func() { defer c.Close(); io.Copy(c, c) }()
|
||||
}
|
||||
}()
|
||||
for _, mode := range []string{"rule", "global", "direct"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
entry, port := reservePort(t)
|
||||
entry.Close()
|
||||
var engine Engine
|
||||
config := Config{ListenPort: port, Feature: "combined", Mode: mode, MeshSOCKS: mesh.Addr().String(), MeshCIDRs: []string{"10.77.0.0/24"}, ProtectedCIDRs: []string{"10.88.0.0/24"}, Proxy: map[string]any{"type": "socks", "version": "5", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}, Rules: []Rule{{Type: "ip_cidr", Value: "127.0.0.0/8", Action: "direct"}}}
|
||||
if e := engine.Start(context.Background(), config); e != nil {
|
||||
t.Fatalf("%v: %v", e, engine.startupCause)
|
||||
}
|
||||
defer engine.Stop()
|
||||
before := count.Load()
|
||||
beforeMesh := meshCount.Load()
|
||||
echoThrough(t, port, M.SocksaddrFrom(netip.MustParseAddr("127.0.0.1"), uint16(direct.Addr().(*net.TCPAddr).Port)), true)
|
||||
expected := int32(0)
|
||||
if mode == "global" {
|
||||
expected = 1
|
||||
}
|
||||
if count.Load()-before != expected {
|
||||
t.Fatal("wrong internet outlet")
|
||||
}
|
||||
echoThrough(t, port, M.ParseSocksaddr("10.77.0.2:1234"), true)
|
||||
if meshCount.Load()-beforeMesh != 1 {
|
||||
t.Fatal("mesh priority lost")
|
||||
}
|
||||
before = count.Load()
|
||||
echoThrough(t, port, M.ParseSocksaddr("10.88.0.2:1234"), false)
|
||||
if count.Load() != before {
|
||||
t.Fatal("protected destination leaked to proxy")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestDNSAndDomainRule(t *testing.T) {
|
||||
upstream, count := socksEcho(t)
|
||||
defer upstream.Close()
|
||||
dnsSock, e := net.ListenPacket("udp4", "127.0.0.1:0")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
dnsServer := &D.Server{PacketConn: dnsSock, Handler: D.HandlerFunc(func(w D.ResponseWriter, r *D.Msg) {
|
||||
m := new(D.Msg)
|
||||
m.SetReply(r)
|
||||
m.Answer = []D.RR{&D.A{Hdr: D.RR_Header{Name: r.Question[0].Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: 60}, A: net.ParseIP("203.0.113.7")}}
|
||||
w.WriteMsg(m)
|
||||
})}
|
||||
go dnsServer.ActivateAndServe()
|
||||
defer dnsServer.Shutdown()
|
||||
entry, port := reservePort(t)
|
||||
entry.Close()
|
||||
var engine Engine
|
||||
config := Config{ListenPort: port, Feature: "proxy", Mode: "rule", DNS: dnsSock.LocalAddr().String(), DefaultAction: "reject", Proxy: map[string]any{"type": "socks", "version": "5", "server": "127.0.0.1", "server_port": upstream.Addr().(*net.TCPAddr).Port}, Rules: []Rule{{Type: "domain_suffix", Value: "example.test", Action: "proxy"}}}
|
||||
if e := engine.Start(context.Background(), config); e != nil {
|
||||
t.Fatalf("%v: %v", e, engine.startupCause)
|
||||
}
|
||||
defer engine.Stop()
|
||||
echoThrough(t, port, M.ParseSocksaddr("sub.example.test:1234"), true)
|
||||
if count.Load() != 1 {
|
||||
t.Fatal("domain rule not selected")
|
||||
}
|
||||
echoThrough(t, port, M.ParseSocksaddr("blocked.invalid:1234"), false)
|
||||
if count.Load() != 1 {
|
||||
t.Fatal("default reject bypassed")
|
||||
}
|
||||
}
|
||||
func TestImportedNodeCannotReplaceManagedDialer(t *testing.T) {
|
||||
for _, field := range []string{"detour", "bind_interface", "routing_mark", "domain_resolver", "tag", "route"} {
|
||||
node := map[string]any{"type": "socks", "server": "example.test", "server_port": 1080, field: "unmanaged"}
|
||||
if _, e := proxyNode(node); e == nil {
|
||||
t.Fatal("injected field accepted", field)
|
||||
}
|
||||
}
|
||||
var engine Engine
|
||||
config := Config{ListenPort: 10818, Feature: "proxy", Mode: "direct", Tun: &TunConfig{FD: 123, Name: "tun0", Interface: "eth0", Index: 2}}
|
||||
if e := engine.Start(context.Background(), config); e == nil {
|
||||
engine.Stop()
|
||||
t.Fatal("unprotected platform TUN accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithdrawnMeshDNSIsRejectedWithoutFallback(t *testing.T) {
|
||||
upstream, count := socksEcho(t)
|
||||
defer upstream.Close()
|
||||
entry, port := reservePort(t)
|
||||
entry.Close()
|
||||
var engine Engine
|
||||
config := Config{ListenPort: port, Feature: "combined", Mode: "global", MeshSOCKS: "127.0.0.1:9", ProtectedCIDRs: []string{"10.77.0.0/24"}, MeshDNS: []MeshDNS{{Suffix: "mesh.test", Server: "10.77.0.2"}}, Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": upstream.Addr().(*net.TCPAddr).Port}}
|
||||
if e := engine.Start(context.Background(), config); e != nil {
|
||||
t.Fatalf("%v: %v", e, engine.startupCause)
|
||||
}
|
||||
defer engine.Stop()
|
||||
echoThrough(t, port, M.ParseSocksaddr("secret.mesh.test:1234"), false)
|
||||
if count.Load() != 0 {
|
||||
t.Fatal("mesh DNS failed open to proxy")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFakeIPMappingAndMeshExclusion(t *testing.T) {
|
||||
dnsSock, err := net.ListenPacket("udp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dnsServer := &D.Server{PacketConn: dnsSock, Handler: D.HandlerFunc(func(w D.ResponseWriter, r *D.Msg) {
|
||||
m := new(D.Msg)
|
||||
m.SetReply(r)
|
||||
m.Answer = []D.RR{&D.A{Hdr: D.RR_Header{Name: r.Question[0].Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: 60}, A: net.ParseIP("203.0.113.7")}}
|
||||
w.WriteMsg(m)
|
||||
})}
|
||||
go dnsServer.ActivateAndServe()
|
||||
defer dnsServer.Shutdown()
|
||||
proxy, count := socksEcho(t)
|
||||
defer proxy.Close()
|
||||
listener, port := reservePort(t)
|
||||
listener.Close()
|
||||
engine := &Engine{}
|
||||
config := Config{ListenPort: port, Feature: "combined", Mode: "global", MeshSOCKS: "127.0.0.1:9", DNS: dnsSock.LocalAddr().String(), ProtectedCIDRs: []string{"10.77.0.0/24"}, Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}, FakeIP: true, MeshDNS: []MeshDNS{{Suffix: "mesh.test", Server: "10.77.0.2"}}}
|
||||
if e := engine.Start(context.Background(), config); e != nil {
|
||||
t.Fatalf("%v: %v", e, engine.startupCause)
|
||||
}
|
||||
defer engine.Close()
|
||||
query := func(domain string) *D.Msg {
|
||||
t.Helper()
|
||||
c, err := net.Dial("tcp4", net.JoinHostPort("127.0.0.1", jsonNumber(int(port))))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
c.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
_, err = socks.ClientHandshake5(c, socks5.CommandConnect, M.ParseSocksaddr("1.1.1.1:53"), "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conn := &D.Conn{Conn: c}
|
||||
msg := new(D.Msg)
|
||||
msg.SetQuestion(D.Fqdn(domain), D.TypeA)
|
||||
if e := conn.WriteMsg(msg); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
reply, e := conn.ReadMsg()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return reply
|
||||
}
|
||||
reply := query("public.test")
|
||||
if len(reply.Answer) != 1 {
|
||||
t.Fatalf("missing FakeIP answer: %v", reply)
|
||||
}
|
||||
address, ok := reply.Answer[0].(*D.A)
|
||||
if !ok || !netip.MustParsePrefix("198.18.0.0/15").Contains(netip.MustParseAddr(address.A.String())) {
|
||||
t.Fatal("not a FakeIP answer")
|
||||
}
|
||||
echoThrough(t, port, M.ParseSocksaddr(net.JoinHostPort(address.A.String(), "443")), true)
|
||||
if count.Load() != 1 {
|
||||
t.Fatal("FakeIP connection did not use selected proxy")
|
||||
}
|
||||
if err := engine.Stop(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := engine.Start(context.Background(), config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
echoThrough(t, port, M.ParseSocksaddr(net.JoinHostPort(address.A.String(), "443")), true)
|
||||
if count.Load() != 2 {
|
||||
t.Fatal("FakeIP mapping lost across managed rebuild")
|
||||
}
|
||||
// Known withdrawn mesh domains must reject before the generic FakeIP rule.
|
||||
reply = query("host.mesh.test")
|
||||
if len(reply.Answer) != 0 || reply.Rcode == D.RcodeSuccess {
|
||||
t.Fatal("withdrawn mesh domain leaked to FakeIP")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
"github.com/sagernet/sing/protocol/socks"
|
||||
"github.com/sagernet/sing/protocol/socks/socks5"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ProbeResult struct {
|
||||
Method string `json:"method"`
|
||||
ElapsedMS float64 `json:"elapsed_ms"`
|
||||
StatusCode int `json:"status_code"`
|
||||
}
|
||||
|
||||
// A draft probe owns an isolated loopback engine and never installs a TUN or
|
||||
// changes the running instance. The public ABI fixes its HTTPS test destination.
|
||||
func ProbeNode(parent context.Context, node map[string]any, dnsServer string, target string) (ProbeResult, error) {
|
||||
ctx, cancel := context.WithTimeout(parent, 10*time.Second)
|
||||
defer cancel()
|
||||
listener, err := net.Listen("tcp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return ProbeResult{}, errors.New("cannot reserve probe port")
|
||||
}
|
||||
port := uint16(listener.Addr().(*net.TCPAddr).Port)
|
||||
listener.Close()
|
||||
var engine Engine
|
||||
defer engine.Close()
|
||||
if err := engine.Start(ctx, Config{ListenPort: port, Feature: "proxy", Mode: "global", Proxy: node, DNS: dnsServer}); err != nil {
|
||||
return ProbeResult{}, errors.New("invalid draft proxy configuration")
|
||||
}
|
||||
transport := &http.Transport{DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
c, err := (&net.Dialer{}).DialContext(ctx, "tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(int(port))))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.SetDeadline(time.Now().Add(8 * time.Second))
|
||||
_, err = socks.ClientHandshake5(c, socks5.CommandConnect, M.ParseSocksaddr(address), "", "")
|
||||
if err != nil {
|
||||
c.Close()
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}, TLSHandshakeTimeout: 8 * time.Second, DisableKeepAlives: true}
|
||||
defer transport.CloseIdleConnections()
|
||||
client := http.Client{Transport: transport, Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
|
||||
if err != nil {
|
||||
return ProbeResult{}, errors.New("invalid probe target")
|
||||
}
|
||||
started := time.Now()
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return ProbeResult{}, errors.New("HTTPS connectivity check failed")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
_, err = io.Copy(io.Discard, io.LimitReader(response.Body, 4096))
|
||||
if err != nil {
|
||||
return ProbeResult{}, errors.New("connectivity response failed")
|
||||
}
|
||||
result := ProbeResult{Method: "HTTP connectivity", ElapsedMS: float64(time.Since(started).Microseconds()) / 1000, StatusCode: response.StatusCode}
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return result, errors.New("connectivity target returned a non-success status")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDraftHTTPProbeIsIsolated(t *testing.T) {
|
||||
proxy, count := socksFixture(t, func(c net.Conn) {
|
||||
request, err := http.ReadRequest(bufio.NewReader(c))
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
if request.Host != "203.0.113.7" || request.Method != "GET" {
|
||||
t.Error("unexpected draft request")
|
||||
}
|
||||
fmt.Fprint(c, "HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n")
|
||||
})
|
||||
defer proxy.Close()
|
||||
l, port := reservePort(t)
|
||||
l.Close()
|
||||
var running Engine
|
||||
if err := running.Start(context.Background(), Config{ListenPort: port, MeshSOCKS: "127.0.0.1:9", MeshCIDRs: []string{"10.77.0.0/24"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer running.Close()
|
||||
node := map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}
|
||||
result, err := ProbeNode(context.Background(), node, "", "http://203.0.113.7/probe")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.StatusCode != 204 || result.ElapsedMS <= 0 || count.Load() != 1 {
|
||||
t.Fatal("probe did not use selected draft node")
|
||||
}
|
||||
if running.Snapshot().State != "Running" {
|
||||
t.Fatal("probe changed running engine")
|
||||
}
|
||||
canceled, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := ProbeNode(canceled, node, "", "http://203.0.113.7/probe"); err == nil {
|
||||
t.Fatal("canceled probe accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDesktopTunCaptureRoutesDoNotDuplicateProtection(t *testing.T) {
|
||||
data, err := (Config{ListenPort: 10818, Feature: "mesh", MeshSOCKS: "127.0.0.1:19001", MeshCIDRs: []string{"10.253.88.0/25"}, ProtectedCIDRs: []string{"10.253.88.0/25", "10.253.88.128/25"}, DesktopTun: true, PhysicalInterface: "en0"}).managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var config map[string]any
|
||||
if err := json.Unmarshal(data, &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inbounds := config["inbounds"].([]any)
|
||||
addresses := inbounds[1].(map[string]any)["address"].([]any)
|
||||
if len(addresses) != 1 || addresses[0] != "172.19.0.1/30" {
|
||||
t.Fatalf("mesh-only TUN must not create implicit IPv6 default routes: %v", addresses)
|
||||
}
|
||||
routes := inbounds[1].(map[string]any)["route_address"].([]any)
|
||||
if len(routes) != 2 || routes[0] != "10.253.88.0/25" || routes[1] != "10.253.88.128/25" {
|
||||
t.Fatalf("unsafe capture routes: %v", routes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTraceCannotLogOrdinaryNetworkProfiles(t *testing.T) {
|
||||
t.Setenv("MESHPORT_SELF_TEST_TRACE", "1")
|
||||
fixture := Config{Feature: "mesh", DesktopTun: true, MeshCIDRs: []string{"10.253.88.0/25"}}
|
||||
for _, change := range []func(*Config){
|
||||
func(c *Config) { c.MeshCIDRs = []string{"192.168.20.0/24"} },
|
||||
func(c *Config) { c.ProtectedCIDRs = []string{"192.168.21.0/24"} },
|
||||
func(c *Config) { c.MeshCIDRs = []string{"10.253.0.0/16"} },
|
||||
func(c *Config) { c.Feature = "combined" },
|
||||
func(c *Config) { c.DesktopTun = false },
|
||||
func(c *Config) { c.Proxy = map[string]any{"type": "socks"} },
|
||||
func(c *Config) { c.MeshCIDRs = nil },
|
||||
} {
|
||||
config := fixture
|
||||
change(&config)
|
||||
if config.selfTestTrace() {
|
||||
t.Fatal("self-test tracing accepted an ordinary network profile")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
// C ABI owns numeric contexts and malloc-allocated UTF-8 JSON responses.
|
||||
package main
|
||||
|
||||
/*
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
#include "protector.h"
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"unsafe"
|
||||
|
||||
"meshport.local/singbox/bridge"
|
||||
)
|
||||
|
||||
type engineContext struct {
|
||||
mu sync.Mutex
|
||||
engine bridge.Engine
|
||||
closed bool
|
||||
}
|
||||
|
||||
var registry = struct {
|
||||
sync.Mutex
|
||||
contexts map[uint64]*engineContext
|
||||
}{contexts: make(map[uint64]*engineContext)}
|
||||
var next atomic.Uint64
|
||||
|
||||
type request struct {
|
||||
Directory string `json:"directory,omitempty"`
|
||||
Op string `json:"op"`
|
||||
Config *bridge.Config `json:"config,omitempty"`
|
||||
}
|
||||
|
||||
func dispatch(id uint64, data []byte) (any, error) {
|
||||
if len(data) > 65536 {
|
||||
return nil, errors.New("request too large")
|
||||
}
|
||||
var input request
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&input); err != nil {
|
||||
return nil, errors.New("invalid engine request")
|
||||
}
|
||||
if err := decoder.Decode(new(any)); err != io.EOF {
|
||||
return nil, errors.New("trailing request data")
|
||||
}
|
||||
registry.Lock()
|
||||
slot := registry.contexts[id]
|
||||
registry.Unlock()
|
||||
if slot == nil {
|
||||
return nil, errors.New("engine context is closed")
|
||||
}
|
||||
slot.mu.Lock()
|
||||
defer slot.mu.Unlock()
|
||||
if slot.closed {
|
||||
return nil, errors.New("engine context is closed")
|
||||
}
|
||||
switch input.Op {
|
||||
case "configure_cache":
|
||||
if slot.engine.Snapshot().State != "Stopped" || input.Directory == "" || !filepath.IsAbs(input.Directory) {
|
||||
return nil, errors.New("valid stopped-engine cache directory required")
|
||||
}
|
||||
info, err := os.Lstat(input.Directory)
|
||||
if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
|
||||
return nil, errors.New("invalid cache directory")
|
||||
}
|
||||
slot.engine.CacheRoot = input.Directory
|
||||
case "probe_node":
|
||||
if input.Config == nil || input.Config.Proxy == nil {
|
||||
return nil, errors.New("draft node required")
|
||||
}
|
||||
return bridge.ProbeNode(context.Background(), input.Config.Proxy, input.Config.DNS, "https://www.gstatic.com/generate_204")
|
||||
case "start":
|
||||
if input.Config == nil {
|
||||
return nil, errors.New("managed configuration required")
|
||||
}
|
||||
if err := slot.engine.Start(context.Background(), *input.Config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "stop":
|
||||
if err := slot.engine.Stop(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "status":
|
||||
default:
|
||||
return nil, errors.New("unknown engine operation")
|
||||
}
|
||||
return slot.engine.Snapshot(), nil
|
||||
}
|
||||
func freeContext(id uint64) {
|
||||
registry.Lock()
|
||||
slot := registry.contexts[id]
|
||||
delete(registry.contexts, id)
|
||||
registry.Unlock()
|
||||
if slot != nil {
|
||||
slot.mu.Lock()
|
||||
defer slot.mu.Unlock()
|
||||
slot.closed = true
|
||||
_ = slot.engine.Close()
|
||||
}
|
||||
}
|
||||
|
||||
//export meshport_proxy_set_socket_protector
|
||||
func meshport_proxy_set_socket_protector(pointer C.uintptr_t) { C.proxy_set_protector(pointer) }
|
||||
|
||||
//export meshport_proxy_abi_version
|
||||
func meshport_proxy_abi_version() C.uint32_t { return 1 }
|
||||
|
||||
//export meshport_proxy_context_new
|
||||
func meshport_proxy_context_new() C.uint64_t {
|
||||
id := next.Add(1)
|
||||
registry.Lock()
|
||||
slot := &engineContext{}
|
||||
slot.engine.Protect = func(fd int) error {
|
||||
if C.proxy_protect(C.int(fd)) == 0 {
|
||||
return errors.New("platform socket protection failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
registry.contexts[id] = slot
|
||||
registry.Unlock()
|
||||
return C.uint64_t(id)
|
||||
}
|
||||
|
||||
//export meshport_proxy_context_free
|
||||
func meshport_proxy_context_free(id C.uint64_t) { freeContext(uint64(id)) }
|
||||
|
||||
//export meshport_proxy_call
|
||||
func meshport_proxy_call(id C.uint64_t, input *C.char) (output *C.char) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
output = C.CString(`{"ok":false,"error":"native engine failure"}`)
|
||||
}
|
||||
}()
|
||||
if input == nil {
|
||||
return C.CString(`{"ok":false,"error":"null request"}`)
|
||||
}
|
||||
result, err := dispatch(uint64(id), []byte(C.GoString(input)))
|
||||
envelope := map[string]any{"ok": err == nil}
|
||||
if err != nil {
|
||||
envelope["error"] = err.Error()
|
||||
} else {
|
||||
envelope["data"] = result
|
||||
}
|
||||
encoded, _ := json.Marshal(envelope)
|
||||
return C.CString(string(encoded))
|
||||
}
|
||||
|
||||
//export meshport_proxy_string_free
|
||||
func meshport_proxy_string_free(input *C.char) { C.free(unsafe.Pointer(input)) }
|
||||
func main() {}
|
||||
@@ -0,0 +1,54 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func newTestContext() uint64 {
|
||||
id := next.Add(1)
|
||||
registry.Lock()
|
||||
registry.contexts[id] = &engineContext{}
|
||||
registry.Unlock()
|
||||
return id
|
||||
}
|
||||
func TestABIRequestLifecycle(t *testing.T) {
|
||||
id := newTestContext()
|
||||
defer freeContext(id)
|
||||
listener, err := net.Listen("tcp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
port := listener.Addr().(*net.TCPAddr).Port
|
||||
listener.Close()
|
||||
input, _ := json.Marshal(map[string]any{"op": "start", "config": map[string]any{"listen_port": port, "mesh_socks": "127.0.0.1:9", "mesh_cidrs": []string{"10.77.0.0/24"}}})
|
||||
if _, err := dispatch(id, input); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := dispatch(id, input); err == nil {
|
||||
t.Fatal("duplicate start accepted")
|
||||
}
|
||||
for _, bad := range []string{`{"op":"status","extra":true}`, `{"op":"status"} {}`, `{"op":"start"}`, `{"op":"wrong"}`} {
|
||||
if _, err := dispatch(id, []byte(bad)); err == nil {
|
||||
t.Fatal("bad request accepted", bad)
|
||||
}
|
||||
}
|
||||
var wait sync.WaitGroup
|
||||
for i := 0; i < 8; i++ {
|
||||
wait.Add(1)
|
||||
go func() { defer wait.Done(); _, _ = dispatch(id, []byte(`{"op":"status"}`)) }()
|
||||
}
|
||||
freeContext(id)
|
||||
wait.Wait()
|
||||
if _, err := dispatch(id, []byte(`{"op":"status"}`)); err == nil {
|
||||
t.Fatal("freed context accepted")
|
||||
}
|
||||
probe, err := net.Listen("tcp4", net.JoinHostPort("127.0.0.1", jsonNumber(port)))
|
||||
if err != nil {
|
||||
t.Fatal("listener leaked", err)
|
||||
}
|
||||
probe.Close()
|
||||
}
|
||||
func jsonNumber(port int) string { data, _ := json.Marshal(port); return string(data) }
|
||||
@@ -0,0 +1,9 @@
|
||||
#include "protector.h"
|
||||
#include <stdatomic.h>
|
||||
static _Atomic(uintptr_t) protector;
|
||||
void proxy_set_protector(uintptr_t value) { atomic_store(&protector, value); }
|
||||
int proxy_protect(int fd) {
|
||||
uintptr_t value = atomic_load(&protector);
|
||||
if (!value) return 0;
|
||||
return ((int (*)(int))value)(fd);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
#include <stdint.h>
|
||||
void proxy_set_protector(uintptr_t pointer);
|
||||
int proxy_protect(int fd);
|
||||
@@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"meshport.local/singbox/bridge"
|
||||
)
|
||||
|
||||
func run() error {
|
||||
if len(os.Args) != 2 {
|
||||
return fmt.Errorf("usage: meshport-singbox MANAGED-CONFIG.json")
|
||||
}
|
||||
file, err := os.Open(os.Args[1])
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot read managed configuration")
|
||||
}
|
||||
defer file.Close()
|
||||
info, err := file.Stat()
|
||||
if err != nil || info.Size() > 65536 {
|
||||
return fmt.Errorf("managed configuration exceeds size limit or cannot be read")
|
||||
}
|
||||
decoder := json.NewDecoder(io.LimitReader(file, 65537))
|
||||
decoder.DisallowUnknownFields()
|
||||
var config bridge.Config
|
||||
if err = decoder.Decode(&config); err != nil {
|
||||
return fmt.Errorf("invalid managed configuration")
|
||||
}
|
||||
var extra any
|
||||
if decoder.Decode(&extra) != io.EOF {
|
||||
return fmt.Errorf("invalid trailing configuration")
|
||||
}
|
||||
var engine bridge.Engine
|
||||
if err = engine.Start(context.Background(), config); err != nil {
|
||||
return err
|
||||
}
|
||||
defer engine.Stop()
|
||||
// One machine-readable readiness line, no configuration/credentials/log dump.
|
||||
if err = json.NewEncoder(os.Stdout).Encode(engine.Snapshot()); err != nil {
|
||||
return err
|
||||
}
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
|
||||
defer signal.Stop(stop)
|
||||
<-stop
|
||||
return engine.Stop()
|
||||
}
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
module meshport.local/singbox
|
||||
|
||||
go 1.25.5
|
||||
|
||||
require (
|
||||
github.com/sagernet/sing v0.9.7-0.20260929150544-0ad23b637bd4
|
||||
github.com/sagernet/sing-box v1.14.3
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/andybalholm/brotli v1.1.0 // indirect
|
||||
github.com/caddyserver/certmagic v0.25.3-0.20260421143802-60d9d8b415d6 // indirect
|
||||
github.com/caddyserver/zerossl v0.1.5 // indirect
|
||||
github.com/database64128/netx-go v0.1.1 // indirect
|
||||
github.com/database64128/tfo-go/v2 v2.3.2 // indirect
|
||||
github.com/florianl/go-nfqueue/v2 v2.1.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/go-chi/chi/v5 v5.2.5 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/gobwas/httphead v0.1.0 // indirect
|
||||
github.com/gobwas/pool v0.2.1 // indirect
|
||||
github.com/godbus/dbus/v5 v5.2.2 // indirect
|
||||
github.com/gofrs/uuid/v5 v5.5.1 // indirect
|
||||
github.com/google/btree v1.1.3 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/hashicorp/yamux v0.1.2 // indirect
|
||||
github.com/jsimonetti/rtnetlink v1.4.1 // indirect
|
||||
github.com/klauspost/compress v1.19.1 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/libdns/acmedns v0.5.0 // indirect
|
||||
github.com/libdns/alidns v1.0.6 // indirect
|
||||
github.com/libdns/cloudflare v0.2.2 // indirect
|
||||
github.com/libdns/libdns v1.1.1 // indirect
|
||||
github.com/logrusorgru/aurora v2.0.3+incompatible // indirect
|
||||
github.com/mdlayher/netlink v1.11.2 // indirect
|
||||
github.com/mdlayher/socket v0.6.0 // indirect
|
||||
github.com/metacubex/utls v1.8.7 // indirect
|
||||
github.com/mholt/acmez/v3 v3.1.6 // indirect
|
||||
github.com/miekg/dns v1.1.72 // indirect
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/sagernet/bbolt v0.0.0-20260915102804-500ee1e84832 // indirect
|
||||
github.com/sagernet/fswatch v0.1.2 // indirect
|
||||
github.com/sagernet/gvisor v0.0.0-20260727.0-sing-box-mod.1 // indirect
|
||||
github.com/sagernet/netlink v0.0.0-20260814022025-64455d367bbf // indirect
|
||||
github.com/sagernet/nftables v0.3.0-mod.4 // indirect
|
||||
github.com/sagernet/quic-go v0.61.0-sing-box-mod.9 // indirect
|
||||
github.com/sagernet/sing-mux v0.3.10-0.20260929204512-caf09fe32475 // indirect
|
||||
github.com/sagernet/sing-quic v0.7.2-0.20261002084117-75c3ac4fa12b // indirect
|
||||
github.com/sagernet/sing-shadowsocks v0.2.9-0.20260929204512-65740e0f0e3e // indirect
|
||||
github.com/sagernet/sing-shadowsocks2 v0.2.2-0.20260929152114-a69d1086332b // indirect
|
||||
github.com/sagernet/sing-snell v0.0.0-20260904135315-bc5a12ac736f // indirect
|
||||
github.com/sagernet/sing-tun v0.9.7-0.20261009020158-bca4bf029237 // indirect
|
||||
github.com/sagernet/sing-usbip v0.0.0-20260817040617-28bd42667eca // indirect
|
||||
github.com/sagernet/sing-vmess v0.2.9-0.20260929152519-9b95ab8c9478 // indirect
|
||||
github.com/sagernet/smux v1.5.50-sing-box-mod.1 // indirect
|
||||
github.com/sagernet/ws v0.0.0-20231204124109-acfe8907c854 // indirect
|
||||
github.com/vishvananda/netns v0.0.5 // indirect
|
||||
github.com/zeebo/blake3 v0.2.4 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.27.1 // indirect
|
||||
go.uber.org/zap/exp v0.3.0 // indirect
|
||||
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba // indirect
|
||||
golang.org/x/crypto v0.54.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect
|
||||
golang.org/x/mod v0.37.0 // indirect
|
||||
golang.org/x/net v0.57.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
golang.org/x/tools v0.47.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect
|
||||
google.golang.org/grpc v1.79.1 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
lukechampine.com/blake3 v1.3.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,184 @@
|
||||
code.pfad.fr/check v1.1.0 h1:GWvjdzhSEgHvEHe2uJujDcpmZoySKuHQNrZMfzfO0bE=
|
||||
code.pfad.fr/check v1.1.0/go.mod h1:NiUH13DtYsb7xp5wll0U4SXx7KhXQVCtRgdC96IPfoM=
|
||||
github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=
|
||||
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
|
||||
github.com/caddyserver/certmagic v0.25.3-0.20260421143802-60d9d8b415d6 h1:LYSB6VgWzKtNrcxElw3c97BP40Oc7bizKxA9K1Vi/5k=
|
||||
github.com/caddyserver/certmagic v0.25.3-0.20260421143802-60d9d8b415d6/go.mod h1:llW/CvsNmza8S6hmsuggsZeiX+uS27dkqY27wDIuBWg=
|
||||
github.com/caddyserver/zerossl v0.1.5 h1:dkvOjBAEEtY6LIGAHei7sw2UgqSD6TrWweXpV7lvEvE=
|
||||
github.com/caddyserver/zerossl v0.1.5/go.mod h1:CxA0acn7oEGO6//4rtrRjYgEoa4MFw/XofZnrYwGqG4=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cilium/ebpf v0.12.3 h1:8ht6F9MquybnY97at+VDZb3eQQr8ev79RueWeVaEcG4=
|
||||
github.com/cilium/ebpf v0.12.3/go.mod h1:TctK1ivibvI3znr66ljgi4hqOT8EYQjz1KWBfb1UVgM=
|
||||
github.com/database64128/netx-go v0.1.1 h1:dT5LG7Gs7zFZBthFBbzWE6K8wAHjSNAaK7wCYZT7NzM=
|
||||
github.com/database64128/netx-go v0.1.1/go.mod h1:LNlYVipaYkQArRFDNNJ02VkNV+My9A5XR/IGS7sIBQc=
|
||||
github.com/database64128/tfo-go/v2 v2.3.2 h1:UhZMKiMq3swZGUiETkLBDzQnZBPSAeBMClpJGlnJ5Fw=
|
||||
github.com/database64128/tfo-go/v2 v2.3.2/go.mod h1:GC3uB5oa4beGpCUbRb2ZOWP73bJJFmMyAVgQSO7r724=
|
||||
github.com/florianl/go-nfqueue/v2 v2.1.0 h1:Fywt30TY/evxyDySpXjxQ1jsRW7nQbLpOhELqpr4068=
|
||||
github.com/florianl/go-nfqueue/v2 v2.1.0/go.mod h1:8PKUM5rYoVFO5IZV1bifx4/b0jHAglKkHXr9PRwzi4Y=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug=
|
||||
github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0=
|
||||
github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs=
|
||||
github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
||||
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
|
||||
github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
|
||||
github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
|
||||
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
|
||||
github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
|
||||
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
|
||||
github.com/gofrs/uuid/v5 v5.5.1 h1:z1Ce19/JwNidXpy3tOQc3241lnJLKdKyq/xlNvlD4Ng=
|
||||
github.com/gofrs/uuid/v5 v5.5.1/go.mod h1:bbAA98EoIlxyRHIVg6ektCSsZ5n8mSbwgEhvhMYlZgg=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg=
|
||||
github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/yamux v0.1.2 h1:XtB8kyFOyHXYVFnwT5C3+Bdo8gArse7j2AQ0DA0Uey8=
|
||||
github.com/hashicorp/yamux v0.1.2/go.mod h1:C+zze2n6e/7wshOZep2A70/aQU6QBRWJO/G6FT1wIns=
|
||||
github.com/jsimonetti/rtnetlink v1.4.1 h1:JfD4jthWBqZMEffc5RjgmlzpYttAVw1sdnmiNaPO3hE=
|
||||
github.com/jsimonetti/rtnetlink v1.4.1/go.mod h1:xJjT7t59UIZ62GLZbv6PLLo8VFrostJMPBAheR6OM8w=
|
||||
github.com/jsimonetti/rtnetlink/v2 v2.2.0 h1:/KfZ310gOAFrXXol5VwnFEt+ucldD/0dsSRZwpHCP9w=
|
||||
github.com/jsimonetti/rtnetlink/v2 v2.2.0/go.mod h1:lbjDHxC+5RJ08lzPeA90Ls2pEoId3F08MoEMlhfHxeI=
|
||||
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
|
||||
github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/letsencrypt/challtestsrv v1.4.2 h1:0ON3ldMhZyWlfVNYYpFuWRTmZNnyfiL9Hh5YzC3JVwU=
|
||||
github.com/letsencrypt/challtestsrv v1.4.2/go.mod h1:GhqMqcSoeGpYd5zX5TgwA6er/1MbWzx/o7yuuVya+Wk=
|
||||
github.com/letsencrypt/pebble/v2 v2.10.0 h1:Wq6gYXlsY6ubqI3hhxsTzdyotvfdjFBxuwYqCLCnj/U=
|
||||
github.com/letsencrypt/pebble/v2 v2.10.0/go.mod h1:Sk8cmUIPcIdv2nINo+9PB4L+ZBhzY+F9A1a/h/xmWiQ=
|
||||
github.com/libdns/acmedns v0.5.0 h1:5pRtmUj4Lb/QkNJSl1xgOGBUJTWW7RjpNaIhjpDXjPE=
|
||||
github.com/libdns/acmedns v0.5.0/go.mod h1:X7UAFP1Ep9NpTwWpVlrZzJLR7epynAy0wrIxSPFgKjQ=
|
||||
github.com/libdns/alidns v1.0.6 h1:/Ii428ty6WHFJmE24rZxq2taq++gh7rf9jhgLfp8PmM=
|
||||
github.com/libdns/alidns v1.0.6/go.mod h1:RECwyQ88e9VqQVtSrvX76o1ux3gQUKGzMgxICi+u7Ec=
|
||||
github.com/libdns/cloudflare v0.2.2 h1:XWHv+C1dDcApqazlh08Q6pjytYLgR2a+Y3xrXFu0vsI=
|
||||
github.com/libdns/cloudflare v0.2.2/go.mod h1:w9uTmRCDlAoafAsTPnn2nJ0XHK/eaUMh86DUk8BWi60=
|
||||
github.com/libdns/libdns v1.1.1 h1:wPrHrXILoSHKWJKGd0EiAVmiJbFShguILTg9leS/P/U=
|
||||
github.com/libdns/libdns v1.1.1/go.mod h1:4Bj9+5CQiNMVGf87wjX4CY3HQJypUHRuLvlsfsZqLWQ=
|
||||
github.com/logrusorgru/aurora v2.0.3+incompatible h1:tOpm7WcpBTn4fjmVfgpQq0EfczGlG91VSDkswnjF5A8=
|
||||
github.com/logrusorgru/aurora v2.0.3+incompatible/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4=
|
||||
github.com/mdlayher/netlink v1.11.2 h1:HKh2jqe+omdSWcQ88nrT7INE61B0NXfiSPFdgL4YbNI=
|
||||
github.com/mdlayher/netlink v1.11.2/go.mod h1:uT2Yc/QLaZubzDpZIBi9d4GoeLwtp3x1AMeqSRrK2sA=
|
||||
github.com/mdlayher/socket v0.6.0 h1:ScZPaAGyO1icQnbFrhPM8mnXyMu9qukC1K4ZoM2IQKU=
|
||||
github.com/mdlayher/socket v0.6.0/go.mod h1:q7vozUAnxSqnjHc12Fik5yUKIzfZ8ITCfMkhOtE9z18=
|
||||
github.com/metacubex/utls v1.8.7 h1:Cp+yWkNTFkSihETgGWq34hlVFds5HpYWVOR1xovUVTs=
|
||||
github.com/metacubex/utls v1.8.7/go.mod h1:kncGGVhFaoGn5M3pFe3SXhZCzsbCJayNOH4UEqTKTko=
|
||||
github.com/mholt/acmez/v3 v3.1.6 h1:eGVQNObP0pBN4sxqrXeg7MYqTOWyoiYpQqITVWlrevk=
|
||||
github.com/mholt/acmez/v3 v3.1.6/go.mod h1:5nTPosTGosLxF3+LU4ygbgMRFDhbAVpqMI4+a4aHLBY=
|
||||
github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=
|
||||
github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||
github.com/sagernet/bbolt v0.0.0-20260915102804-500ee1e84832 h1:KDXMGbzqLmDdKcld0T3wuMuqf1iezZq+DemgtZ/vhtQ=
|
||||
github.com/sagernet/bbolt v0.0.0-20260915102804-500ee1e84832/go.mod h1:7/qFPFH5fqK5XQeY8EA1Qpaly08Av77p38Zt50ieQww=
|
||||
github.com/sagernet/fswatch v0.1.2 h1:/TT7k4mkce1qFPxamLO842WjqBgbTBiXP2mlUjp9PFk=
|
||||
github.com/sagernet/fswatch v0.1.2/go.mod h1:5BpGmpUQVd3Mc5r313HRpvADHRg3/rKn5QbwFteB880=
|
||||
github.com/sagernet/gvisor v0.0.0-20260727.0-sing-box-mod.1 h1:IdQ7yTKkB2wv8txwshxUroPlO4npOYAV71xb7xQ7Lys=
|
||||
github.com/sagernet/gvisor v0.0.0-20260727.0-sing-box-mod.1/go.mod h1:9O3SQskYuCfdHNvHEsWuEAgoyKEF74PiWp4NsNUia8g=
|
||||
github.com/sagernet/netlink v0.0.0-20260814022025-64455d367bbf h1:b/3rm+KvxzuYRcnMdLq/hmcqX6/2B8k24l6SDHL2Piw=
|
||||
github.com/sagernet/netlink v0.0.0-20260814022025-64455d367bbf/go.mod h1:xLnfdiJbSp8rNqYEdIW/6eDO4mVoogml14Bh2hSiFpM=
|
||||
github.com/sagernet/nftables v0.3.0-mod.4 h1:vnOtcDYeSXv2e5RoRuGH0lrpttQFJ8iC4ICS2nhlDSo=
|
||||
github.com/sagernet/nftables v0.3.0-mod.4/go.mod h1:8kslHG4VvYNihcco+i6uxIX7qbT8A56T0y5q7U44ZaQ=
|
||||
github.com/sagernet/quic-go v0.61.0-sing-box-mod.9 h1:Lojx77uC63TxZO38Z1OSo6aOoBSXY+ueH0/IKKeTZuI=
|
||||
github.com/sagernet/quic-go v0.61.0-sing-box-mod.9/go.mod h1:hmLC8GJPp+BrpBgrgJnacvI4fZGIhasuy1ROJJ8GR4E=
|
||||
github.com/sagernet/sing v0.9.7-0.20260929150544-0ad23b637bd4 h1:d4WT3KO4zhp9qzPHUZCKqCP+ZmP1GXBsAmReqlnE4zA=
|
||||
github.com/sagernet/sing v0.9.7-0.20260929150544-0ad23b637bd4/go.mod h1:K3Owt3xPhHugvlnlPPxZJ/exXdaJfEPOTNorGk4AXjo=
|
||||
github.com/sagernet/sing-box v1.14.3 h1:cBg8TP5SPWoMAlWqTqbSNdHGKPUciZisjQbLtqFlMZA=
|
||||
github.com/sagernet/sing-box v1.14.3/go.mod h1:Yei01EtPLnLTpLho05THCbqUwfidsaE/0vm1oSu+XQA=
|
||||
github.com/sagernet/sing-mux v0.3.10-0.20260929204512-caf09fe32475 h1:aG0DqHEOjax7DyfE1GTAXZotOg3QGVCz3/8rCSua2kg=
|
||||
github.com/sagernet/sing-mux v0.3.10-0.20260929204512-caf09fe32475/go.mod h1:jricpwCOndDsTEM1TM3piJvhL/2Mm7OhLkm+JadJJ1Q=
|
||||
github.com/sagernet/sing-quic v0.7.2-0.20261002084117-75c3ac4fa12b h1:2Jx/URJAPt32MEbLmAR5nzH87tO6NQZLRfRFvFqBWuk=
|
||||
github.com/sagernet/sing-quic v0.7.2-0.20261002084117-75c3ac4fa12b/go.mod h1:rJFeVxbEej2iuyeCJ3drKW+p5rOgtLIW3XhZ6ty7Fig=
|
||||
github.com/sagernet/sing-shadowsocks v0.2.9-0.20260929204512-65740e0f0e3e h1:LKgE/uuqp/D2kgxYViOz8vf4slaCUfpFywXjtuwD5gU=
|
||||
github.com/sagernet/sing-shadowsocks v0.2.9-0.20260929204512-65740e0f0e3e/go.mod h1:lo7TWEMDcN5/h5B8S0ew+r78ZODn6SwVaFhvB6H+PTI=
|
||||
github.com/sagernet/sing-shadowsocks2 v0.2.2-0.20260929152114-a69d1086332b h1:VH65QNqSHat2b+N3Rlzo5Qe44gRmQGwzY5atuy3D0A8=
|
||||
github.com/sagernet/sing-shadowsocks2 v0.2.2-0.20260929152114-a69d1086332b/go.mod h1:RnXS0lExcDAovvDeniJ4IKa2IuChrdipolPYWBv9hWQ=
|
||||
github.com/sagernet/sing-snell v0.0.0-20260904135315-bc5a12ac736f h1:tbTCI+iis5sTmua7a6Q7vebcSRURok/LGgnEafnQAsc=
|
||||
github.com/sagernet/sing-snell v0.0.0-20260904135315-bc5a12ac736f/go.mod h1:et8Lws4f5QbOrY65DmjevHGup3mijJkhswkto6cwciM=
|
||||
github.com/sagernet/sing-tun v0.9.7-0.20261009020158-bca4bf029237 h1:B9tUcRf1FAatPyzN8sKEvIHMvKNkFMBZikeIOL4gqtQ=
|
||||
github.com/sagernet/sing-tun v0.9.7-0.20261009020158-bca4bf029237/go.mod h1:3EgPst7agntRO7D6GOsiZ1l9FoqdLeuWmKT5TnWkmf0=
|
||||
github.com/sagernet/sing-usbip v0.0.0-20260817040617-28bd42667eca h1:5wA+IE0Fq1CGVLOgSpm0gKKZ03HzugcJ2JyhmDqeX6A=
|
||||
github.com/sagernet/sing-usbip v0.0.0-20260817040617-28bd42667eca/go.mod h1:ADAZZU85MnM91XNhd2TdZRTaIbA7RjTZuQ1KCHcUbNg=
|
||||
github.com/sagernet/sing-vmess v0.2.9-0.20260929152519-9b95ab8c9478 h1:q2eQn4nq8oWGxRm9zXesXSlPr9GEgPrOGzf4iPtzG9A=
|
||||
github.com/sagernet/sing-vmess v0.2.9-0.20260929152519-9b95ab8c9478/go.mod h1:P11scgTxMxVVQ8dlM27yNm3Cro40mD0+gHbnqrNGDuY=
|
||||
github.com/sagernet/smux v1.5.50-sing-box-mod.1 h1:XkJcivBC9V4wBjiGXIXZ229aZCU1hzcbp6kSkkyQ478=
|
||||
github.com/sagernet/smux v1.5.50-sing-box-mod.1/go.mod h1:NjhsCEWedJm7eFLyhuBgIEzwfhRmytrUoiLluxs5Sk8=
|
||||
github.com/sagernet/ws v0.0.0-20231204124109-acfe8907c854 h1:6uUiZcDRnZSAegryaUGwPC/Fj13JSHwiTftrXhMmYOc=
|
||||
github.com/sagernet/ws v0.0.0-20231204124109-acfe8907c854/go.mod h1:LtfoSK3+NG57tvnVEHgcuBW9ujgE8enPSgzgwStwCAA=
|
||||
github.com/stretchr/testify v1.12.0 h1:K6Mr6jO9JICuend/5xzTM03ydSV3vdNRYAdPSukj8uI=
|
||||
github.com/stretchr/testify v1.12.0/go.mod h1:bOYBZb5qJ00vPzWfIqBUZPaxK8jWiXc6d3ErP4Ca9Gw=
|
||||
github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=
|
||||
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
|
||||
github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY=
|
||||
github.com/zeebo/assert v1.1.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
|
||||
github.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI=
|
||||
github.com/zeebo/blake3 v0.2.4/go.mod h1:7eeQ6d2iXWRGF6npfaxl2CU+xy2Fjo2gxeyZGCRUjcE=
|
||||
github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo=
|
||||
github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48=
|
||||
go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8=
|
||||
go.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0=
|
||||
go.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs=
|
||||
go.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18=
|
||||
go.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew=
|
||||
go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI=
|
||||
go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
|
||||
go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
go.uber.org/zap/exp v0.3.0 h1:6JYzdifzYkGmTdRR59oYH+Ng7k49H9qVpWwNSsGJj3U=
|
||||
go.uber.org/zap/exp v0.3.0/go.mod h1:5I384qq7XGxYyByIhHm6jg5CHkGY0nsTfbDLgDDlgJQ=
|
||||
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba h1:0b9z3AuHCjxk0x/opv64kcgZLBseWJUpBw5I82+2U4M=
|
||||
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM=
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80=
|
||||
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
|
||||
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
|
||||
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
|
||||
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk=
|
||||
google.golang.org/grpc v1.79.1 h1:zGhSi45ODB9/p3VAawt9a+O/MULLl9dpizzNNpq7flY=
|
||||
google.golang.org/grpc v1.79.1/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
lukechampine.com/blake3 v1.3.0 h1:sJ3XhFINmHSrYCgl958hscfIa3bw8x4DqMP3u1YvoYE=
|
||||
lukechampine.com/blake3 v1.3.0/go.mod h1:0OFRp7fBtAylGVCO40o87sbupkyIGgbpv1+M1k1LM6k=
|
||||
@@ -0,0 +1,13 @@
|
||||
# Pinned sing-box rule-set patch
|
||||
|
||||
Upstream: sing-box **v1.14.3**, GPL-3.0-or-later; license copy in `docs/upstream/sing-box-LICENSE`.
|
||||
|
||||
`rule_set_remote.go.txt` is the pinned source with MeshPort's small changes:
|
||||
|
||||
- Match, merge, string rendering, cleanup and close synchronize rule-list access with the existing RWMutex. Upstream already locked replacement and metadata, but did not lock all readers/clear operations. The remote refresh integration test reproduced this with `go test -race`.
|
||||
- Remote downloads have a 30-second deadline, a 32 MiB response limit and at most five HTTPS redirects. HTTP downgrade and URL authentication are rejected.
|
||||
- Failed fetch or parsing leaves the last good rules intact.
|
||||
|
||||
`sh scripts/go-local.sh ...` prepares an 11 MiB private module copy under ignored `work/singbox-patched`, verifies the original rule source hash, and uses an alternate modfile. The shared download cache, tracked `go.mod` and dependency checksums are unchanged. All project Go build/test scripts use this wrapper. Invoke it for development builds too; raw `go build` uses the unpatched upstream module.
|
||||
|
||||
The `.txt` suffix prevents Go from treating the patch directory as a standalone package. Review and rebase this patch explicitly when updating the pinned version.
|
||||
@@ -0,0 +1,360 @@
|
||||
// MeshPort patch of sing-box v1.14.3: synchronized rule snapshots and bounded HTTPS fetch.
|
||||
// Copyright (C) 2022 nekohasekai; licensed under GPL-3.0-or-later.
|
||||
// Upstream license: docs/upstream/sing-box-LICENSE.
|
||||
package rule
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/common/srs"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/experimental/deprecated"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
F "github.com/sagernet/sing/common/format"
|
||||
"github.com/sagernet/sing/common/json"
|
||||
"github.com/sagernet/sing/common/logger"
|
||||
"github.com/sagernet/sing/common/x/list"
|
||||
"github.com/sagernet/sing/service"
|
||||
"github.com/sagernet/sing/service/filemanager"
|
||||
"github.com/sagernet/sing/service/pause"
|
||||
|
||||
"go4.org/netipx"
|
||||
)
|
||||
|
||||
var _ adapter.RuleSet = (*RemoteRuleSet)(nil)
|
||||
|
||||
type RemoteRuleSet struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
logger logger.ContextLogger
|
||||
outbound adapter.OutboundManager
|
||||
tag string
|
||||
url string
|
||||
urlHash [32]byte
|
||||
initialPath string
|
||||
options option.RuleSet
|
||||
updateInterval time.Duration
|
||||
httpClient *http.Client
|
||||
access sync.RWMutex
|
||||
rules []adapter.HeadlessRule
|
||||
metadata adapter.RuleSetMetadata
|
||||
lastUpdated time.Time
|
||||
lastEtag string
|
||||
cacheFile adapter.CacheFile
|
||||
pauseManager pause.Manager
|
||||
callbacks list.List[adapter.RuleSetUpdateCallback]
|
||||
refs atomic.Int32
|
||||
}
|
||||
|
||||
func NewRemoteRuleSet(ctx context.Context, logger logger.ContextLogger, tag string, options option.RuleSet) (*RemoteRuleSet, error) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
var updateInterval time.Duration
|
||||
if options.RemoteOptions.UpdateInterval > 0 {
|
||||
updateInterval = time.Duration(options.RemoteOptions.UpdateInterval)
|
||||
} else {
|
||||
updateInterval = 24 * time.Hour
|
||||
}
|
||||
var initialPath string
|
||||
if options.RemoteOptions.InitialPath != "" {
|
||||
initialPath = filemanager.BasePath(ctx, strings.ReplaceAll(options.RemoteOptions.InitialPath, C.RuleSetTagPlaceholder, tag))
|
||||
initialPath, _ = filepath.Abs(initialPath)
|
||||
}
|
||||
url := strings.ReplaceAll(options.RemoteOptions.URL, C.RuleSetTagPlaceholder, tag)
|
||||
return &RemoteRuleSet{
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
outbound: service.FromContext[adapter.OutboundManager](ctx),
|
||||
logger: logger,
|
||||
tag: tag,
|
||||
url: url,
|
||||
urlHash: sha256.Sum256([]byte(url)),
|
||||
initialPath: initialPath,
|
||||
options: options,
|
||||
updateInterval: updateInterval,
|
||||
pauseManager: service.FromContext[pause.Manager](ctx),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) Name() string {
|
||||
return s.tag
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) String() string {
|
||||
s.access.RLock()
|
||||
defer s.access.RUnlock()
|
||||
return strings.Join(F.MapToString(s.rules), " ")
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) StartContext(ctx context.Context, startContext *adapter.HTTPStartContext) error {
|
||||
s.cacheFile = service.FromContext[adapter.CacheFile](s.ctx)
|
||||
transport, err := s.resolveTransport()
|
||||
if err != nil {
|
||||
return E.Cause(err, "create rule-set http client")
|
||||
}
|
||||
startContext.Register(transport)
|
||||
s.httpClient = &http.Client{Transport: transport, Timeout: 30 * time.Second, CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if req.URL.Scheme != "https" || req.URL.User != nil || len(via) >= 5 {
|
||||
return E.New("rule-set redirect must remain HTTPS and within five hops")
|
||||
}
|
||||
return nil
|
||||
}}
|
||||
if s.cacheFile != nil {
|
||||
savedSet := s.cacheFile.LoadRuleSet(s.tag)
|
||||
if savedSet != nil {
|
||||
if len(savedSet.URLHash) > 0 && !bytes.Equal(savedSet.URLHash, s.urlHash[:]) {
|
||||
s.logger.Info("cached rule-set was downloaded from another URL, will refetch")
|
||||
} else {
|
||||
err = s.loadBytes(savedSet.Content)
|
||||
if err != nil {
|
||||
s.logger.Warn(E.Cause(err, "restore cached rule-set, will refetch"))
|
||||
} else {
|
||||
s.lastUpdated = savedSet.LastUpdated
|
||||
s.lastEtag = savedSet.LastEtag
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var loadedFromInitialPath bool
|
||||
if s.lastUpdated.IsZero() && s.initialPath != "" {
|
||||
var content []byte
|
||||
content, err = filemanager.ReadFile(s.ctx, s.initialPath)
|
||||
if err == nil {
|
||||
err = s.loadBytes(content)
|
||||
}
|
||||
if err != nil {
|
||||
s.logger.Warn(E.Cause(err, "load initial rule-set from ", s.initialPath))
|
||||
} else {
|
||||
loadedFromInitialPath = true
|
||||
}
|
||||
}
|
||||
if s.lastUpdated.IsZero() && !loadedFromInitialPath {
|
||||
err = s.fetch(ctx, true)
|
||||
if err != nil {
|
||||
return E.Cause(err, "initial rule-set: ", s.tag)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) Metadata() adapter.RuleSetMetadata {
|
||||
s.access.RLock()
|
||||
defer s.access.RUnlock()
|
||||
return s.metadata
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) ExtractIPSet() []*netipx.IPSet {
|
||||
s.access.RLock()
|
||||
defer s.access.RUnlock()
|
||||
return common.FlatMap(s.rules, extractIPSetFromRule)
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) IncRef() {
|
||||
s.refs.Add(1)
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) DecRef() {
|
||||
if s.refs.Add(-1) < 0 {
|
||||
panic("rule-set: negative refs")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) Cleanup() {
|
||||
s.access.Lock()
|
||||
defer s.access.Unlock()
|
||||
if s.refs.Load() == 0 {
|
||||
s.rules = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) RegisterCallback(callback adapter.RuleSetUpdateCallback) *list.Element[adapter.RuleSetUpdateCallback] {
|
||||
s.access.Lock()
|
||||
defer s.access.Unlock()
|
||||
return s.callbacks.PushBack(callback)
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) UnregisterCallback(element *list.Element[adapter.RuleSetUpdateCallback]) {
|
||||
s.access.Lock()
|
||||
defer s.access.Unlock()
|
||||
s.callbacks.Remove(element)
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) loadBytes(content []byte) error {
|
||||
var (
|
||||
ruleSet option.PlainRuleSetCompat
|
||||
err error
|
||||
)
|
||||
switch s.options.Format {
|
||||
case C.RuleSetFormatSource:
|
||||
ruleSet, err = json.UnmarshalExtended[option.PlainRuleSetCompat](content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case C.RuleSetFormatBinary:
|
||||
ruleSet, err = srs.Read(bytes.NewReader(content), false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
return E.New("unknown rule-set format: ", s.options.Format)
|
||||
}
|
||||
plainRuleSet, err := ruleSet.Upgrade()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rules := make([]adapter.HeadlessRule, len(plainRuleSet.Rules))
|
||||
for i, ruleOptions := range plainRuleSet.Rules {
|
||||
rules[i], err = NewHeadlessRule(s.ctx, ruleOptions)
|
||||
if err != nil {
|
||||
return E.Cause(err, "parse rule_set.rules.[", i, "]")
|
||||
}
|
||||
}
|
||||
metadata := buildRuleSetMetadata(plainRuleSet.Rules)
|
||||
err = validateRuleSetMetadataUpdate(s.ctx, s.tag, metadata)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.access.Lock()
|
||||
s.metadata = metadata
|
||||
s.rules = rules
|
||||
callbacks := s.callbacks.Array()
|
||||
s.access.Unlock()
|
||||
for _, callback := range callbacks {
|
||||
callback(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) updateOnce() {
|
||||
err := s.fetch(s.ctx, false)
|
||||
if err != nil {
|
||||
s.logger.Error("fetch rule-set ", s.tag, ": ", err)
|
||||
} else {
|
||||
s.Cleanup()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) fetch(ctx context.Context, isStart bool) error {
|
||||
s.logger.Debug("updating rule-set ", s.tag, " from URL: ", s.url)
|
||||
request, err := http.NewRequest("GET", s.url, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s.lastEtag != "" {
|
||||
request.Header.Set("If-None-Match", s.lastEtag)
|
||||
}
|
||||
if !isStart {
|
||||
defer s.httpClient.CloseIdleConnections()
|
||||
}
|
||||
response, err := s.httpClient.Do(request.WithContext(ctx))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
switch response.StatusCode {
|
||||
case http.StatusOK:
|
||||
case http.StatusNotModified:
|
||||
s.lastUpdated = time.Now()
|
||||
if s.cacheFile != nil {
|
||||
savedRuleSet := s.cacheFile.LoadRuleSet(s.tag)
|
||||
if savedRuleSet != nil {
|
||||
savedRuleSet.LastUpdated = s.lastUpdated
|
||||
savedRuleSet.URLHash = s.urlHash[:]
|
||||
err = s.cacheFile.SaveRuleSet(s.tag, savedRuleSet)
|
||||
if err != nil {
|
||||
s.logger.Error("save rule-set updated time: ", err)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
s.logger.Info("update rule-set ", s.tag, ": not modified")
|
||||
return nil
|
||||
default:
|
||||
return E.New("unexpected status: ", response.Status)
|
||||
}
|
||||
const maxRuleSetBytes = 32 * 1024 * 1024
|
||||
content, err := io.ReadAll(io.LimitReader(response.Body, maxRuleSetBytes+1))
|
||||
if len(content) > maxRuleSetBytes {
|
||||
return E.New("rule-set exceeds 32 MiB")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = s.loadBytes(content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
eTagHeader := response.Header.Get("Etag")
|
||||
if eTagHeader != "" {
|
||||
s.lastEtag = eTagHeader
|
||||
}
|
||||
s.lastUpdated = time.Now()
|
||||
if s.cacheFile != nil {
|
||||
err = s.cacheFile.SaveRuleSet(s.tag, &adapter.SavedBinary{
|
||||
LastUpdated: s.lastUpdated,
|
||||
Content: content,
|
||||
LastEtag: s.lastEtag,
|
||||
URLHash: s.urlHash[:],
|
||||
})
|
||||
if err != nil {
|
||||
s.logger.Error("save rule-set cache: ", err)
|
||||
}
|
||||
}
|
||||
s.logger.Info("updated rule-set ", s.tag)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) resolveTransport() (adapter.HTTPTransport, error) {
|
||||
httpClientManager := service.FromContext[adapter.HTTPClientManager](s.ctx)
|
||||
if s.options.RemoteOptions.HTTPClient != nil && !s.options.RemoteOptions.HTTPClient.IsEmpty() {
|
||||
if s.options.RemoteOptions.DownloadDetour != "" { //nolint:staticcheck
|
||||
return nil, E.New("http_client is conflict with deprecated download_detour field")
|
||||
}
|
||||
return httpClientManager.ResolveTransport(s.ctx, s.logger, *s.options.RemoteOptions.HTTPClient)
|
||||
}
|
||||
if s.options.RemoteOptions.DownloadDetour != "" { //nolint:staticcheck
|
||||
deprecated.Report(s.ctx, deprecated.OptionLegacyRuleSetDownloadDetour)
|
||||
return httpClientManager.ResolveTransport(s.ctx, s.logger, option.HTTPClientOptions{
|
||||
DialerOptions: option.DialerOptions{
|
||||
Detour: s.options.RemoteOptions.DownloadDetour, //nolint:staticcheck
|
||||
},
|
||||
DisableEmptyDirectCheck: true,
|
||||
})
|
||||
}
|
||||
defaultTransport := httpClientManager.DefaultTransport()
|
||||
if defaultTransport == nil {
|
||||
return nil, E.New("default http client transport is not initialized")
|
||||
}
|
||||
return defaultTransport, nil
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) Close() error {
|
||||
s.cancel()
|
||||
s.access.Lock()
|
||||
s.rules = nil
|
||||
s.access.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) Match(metadata *adapter.InboundContext) bool {
|
||||
s.access.RLock()
|
||||
defer s.access.RUnlock()
|
||||
return matchAnyHeadlessRule(s.rules, metadata)
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) mergeableRule() *DefaultHeadlessRule {
|
||||
s.access.RLock()
|
||||
defer s.access.RUnlock()
|
||||
return mergeableRuleIn(s.rules)
|
||||
}
|
||||
Reference in New Issue
Block a user