Compare commits

...
23 Commits
Author SHA1 Message Date
semanym faf5a5e0a2 fix: do not cache zero-byte closed connections in sniffer skipList (#3550)
In Dispatcher.TCPSniff, any error returned by sniffDomain incremented
skipList[dstIP:port], including connections that closed or were canceled
before sending a single application byte (such as speculative browser
pre-connects or Happy Eyeballs races). Six such zero-byte closures
disabled SNI sniffing for all domains sharing that IP:port for the full
600 s TTL.

Skip caching the failure when conn.Buffered() == 0 and the error is a
connection-closed or cancellation error (io.EOF, io.ErrUnexpectedEOF,
net.ErrClosed, syscall.ECONNRESET, context.Canceled, etc.), while still
counting server-first read timeouts (os.ErrDeadlineExceeded) and
unrecognized or truncated payloads.

Fixes #3527
2026-11-30 18:42:08 +08:00
Abhijeet Chugh 5807ee08fd fix: forget in-flight dns lookups on ResetConnection (#3533)
A lookup that starts while the old network is going away (for example
Wi-Fi dropping on Android) can be sent to servers that will never
answer. It runs on its own DefaultDNSTimeout inside the singleflight
group, and every later request for the same name joins it, even after
the platform has signalled the network change (Clash Meta for Android
calls ClearCache and ResetConnection on every DNS change). So all
requests for that name fail together when the stale lookup times out.

Reset the singleflight group both before and after resetting the
clients. Before, so requests made while a client reset is blocked
(DoH's ResetConnection waits for clientMu) start a fresh lookup instead
of joining one stuck on the old network. After, so requests made once
ResetConnection returns do not join a lookup that started during the
reset on a connection from before the change.
2026-11-29 08:52:49 +08:00
Iaroslav 4ffa6eea4b fix: validate websocket upgrade and Hijacker before writing 101 (#3538) 2026-11-29 08:21:52 +08:00
塵 72214858cf feat: allow configuring XHTTP HTTP/2 stream receive window (#3331) 2026-11-29 08:20:49 +08:00
Iaroslav ba0cfd094e fix: reset hysteria defragger when FragCount does not match (#3537) 2026-11-29 08:18:19 +08:00
Chenx Dust 87e08489b7 fix: pass valid rAddrPort in Tailscale SystemPacketListener (#3535) 2026-11-27 23:14:54 +08:00
Bukely_ 53f61d4291 fix: avoid xhttp init panic when the system clock is wrong (#3521)
ChromeVersion() had no lower bound. A clock before ~2012 gave a negative
version, and the GREASE helpers indexed with a negative modulo during
package init, crashing the core even for `mihomo -v`. Clamp the version
to startVersion.
2026-11-25 13:25:12 +08:00
lovitus dd74780d4e fix: close the outbound when smux options are invalid (#3517)
ParseProxy built the outbound and then returned early if the smux options
failed to decode or NewSingMux failed, without closing it. Outbounds that
acquire process-wide state in their constructor kept it: EasyTier and
Tailscale register a DNS client by name and only remove it in Close, so a
failed parse left a client behind that a later outbound of the same name
would replace and then delete.

Close the outbound on both error paths and keep the wrapped value in a
separate variable so a failed NewSingMux cannot shadow the proxy that needs
closing.
2026-11-25 09:04:24 +08:00
ztywyjandZou c7af25cee0 feat: add WebSocket support to GOST relay (#3507)
Co-authored-by: Zou <zou@outlook.com>
2026-11-24 21:03:19 +08:00
wwqgtxx fc3bd70369 fix: always convert domain to lowercase for rule matching 2026-11-24 10:56:58 +08:00
enfein e13f0f187e chore: update mieru version (#3514)
See https://github.com/enfein/mieru/releases/tag/v3.40.0 for the summary of changes.
2026-11-24 08:33:16 +08:00
Livy Yao 100ff73ae7 fix: correct msftncsi hostname typo in default fake-ip-filter (#3481)
dns.msftnsci.com / www.msftnsci.com are transposed; NCSI probes dns.msftncsi.com and www.msftncsi.com. Under fake-ip, the unfiltered real probe host resolves to 198.18.x.x and Windows 10 reports "no internet".
2026-11-20 08:18:09 +08:00
i40e 024152115c feat: allow disable redir-host mapping in fake-ip mode (#3496)
When a real IP is returned from fake-ip-filter, subsequent connection
toward the real IP will be mapped back to domain (redir-host behavior).
For configurations with a small number of filtered real IP, the real IP
returned is functionally equivalent to a fake IP.

Add a configuration option to disable the redir-host behavior in fake
IP mode.
2026-11-20 07:44:34 +08:00
Esko Mobius 2be2f08909 fix: skip expired entries when picking reusable connections for xhttp (#3479) 2026-11-18 09:37:53 +08:00
SoulOriginal 0976eb6ac1 fix: PROCESS-NAME/PROCESS-PATH rules miss when any process exits during the /proc search on Linux
https://github.com/MetaCubeX/mihomo/issues/3469
2026-11-18 08:18:10 +08:00
wwqgtxx 7907040f27 chore: ignored invalid dns-mode for tun 2026-11-18 08:06:41 +08:00
wwqgtxx 3c0d10a503 chore: adjust internal function 2026-11-15 17:48:09 +08:00
wwqgtxx 184857ce21 fix: ss none packet write 2026-11-14 23:28:18 +08:00
wwqgtxx 7e73a9448b fix: ShadowTLS v2 not work with X25519MLKEM768
The v2 server authenticates the client only if its HMAC covers all the
data relayed from the handshake server, or all but the last write. The
client hashed only the bytes the TLS stack asked for, which end at the
server Finished record, so session tickets sent in the same flight were
left out whenever the stack's last read did not happen to pick them up.
With an X25519MLKEM768 ServerHello this happened on every connection to
a Go crypto/tls handshake server, and the chrome fingerprint always fell
back. Read the socket through a 16 KiB buffer and hash everything each
read returns, as the original implementation does.
2026-11-14 23:09:45 +08:00
wwqgtxx a9e5c456e3 chore: adjust randomization weights 2026-11-14 23:09:19 +08:00
wwqgtxx 4c57a4a600 chore: remove unnecessary forwarding code 2026-11-14 16:05:41 +08:00
CatMsg d569d9eba7 feat: support optional userkey for Snell v6 outbound (#3460) 2026-11-14 15:57:54 +08:00
AaronChen0 12b81d465a fix: use correct format verb for subscription-userinfo parse errors (#3455) 2026-11-12 09:13:57 +08:00
48 changed files with 866 additions and 206 deletions

No files matched your search

+26 -16
View File
@@ -18,22 +18,29 @@ type GostRelay struct {
type GostRelayOption struct { type GostRelayOption struct {
BasicOption BasicOption
Name string `proxy:"name"` Name string `proxy:"name"`
Server string `proxy:"server"` Server string `proxy:"server"`
Port int `proxy:"port"` Port int `proxy:"port"`
Forward bool `proxy:"forward,omitempty"` Forward bool `proxy:"forward,omitempty"`
UDP bool `proxy:"udp,omitempty"` UDP bool `proxy:"udp,omitempty"`
TLS bool `proxy:"tls,omitempty"` WS bool `proxy:"ws,omitempty"`
Mux bool `proxy:"mux,omitempty"` WSOpts GostRelayWSOptions `proxy:"ws-opts,omitempty"`
SNI string `proxy:"sni,omitempty"` TLS bool `proxy:"tls,omitempty"`
Username string `proxy:"username,omitempty"` Mux bool `proxy:"mux,omitempty"`
Password string `proxy:"password,omitempty"` SNI string `proxy:"sni,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"` Username string `proxy:"username,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"` Password string `proxy:"password,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"` SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
Certificate string `proxy:"certificate,omitempty"` NameCertVerify string `proxy:"name-cert-verify,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"` Fingerprint string `proxy:"fingerprint,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"` Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
}
type GostRelayWSOptions struct {
Path string `proxy:"path,omitempty"`
Headers map[string]string `proxy:"headers,omitempty"`
} }
func (g *GostRelay) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) { func (g *GostRelay) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
@@ -95,6 +102,9 @@ func NewGostRelay(option GostRelayOption) (*GostRelay, error) {
Server: option.Server, Server: option.Server,
Port: option.Port, Port: option.Port,
Forward: option.Forward, Forward: option.Forward,
WS: option.WS,
WSPath: option.WSOpts.Path,
WSHeaders: option.WSOpts.Headers,
TLS: option.TLS, TLS: option.TLS,
Mux: option.Mux, Mux: option.Mux,
SNI: option.SNI, SNI: option.SNI,
+5 -4
View File
@@ -373,10 +373,11 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
} }
obfsMode = opts.Mode obfsMode = opts.Mode
gostOption = &gost.Option{ gostOption = &gost.Option{
Host: opts.Host, Host: opts.Host,
Path: opts.Path, Path: opts.Path,
Headers: opts.Headers, Headers: opts.Headers,
Mux: opts.Mux, Mux: opts.Mux,
MuxKeepAliveDisabled: true,
} }
if opts.TLS { if opts.TLS {
+12 -2
View File
@@ -20,6 +20,7 @@ type Snell struct {
*Base *Base
option *SnellOption option *SnellOption
psk []byte psk []byte
userKey []byte
pool *snell.Pool pool *snell.Pool
obfsOption *simpleObfsOption obfsOption *simpleObfsOption
shadowTLSOption *shadowtls.ShadowTLSOption shadowTLSOption *shadowtls.ShadowTLSOption
@@ -36,6 +37,7 @@ type SnellOption struct {
Server string `proxy:"server"` Server string `proxy:"server"`
Port int `proxy:"port"` Port int `proxy:"port"`
Psk string `proxy:"psk"` Psk string `proxy:"psk"`
UserKey string `proxy:"userkey,omitempty"`
UDP bool `proxy:"udp,omitempty"` UDP bool `proxy:"udp,omitempty"`
Version int `proxy:"version,omitempty"` Version int `proxy:"version,omitempty"`
Reuse bool `proxy:"reuse,omitempty"` Reuse bool `proxy:"reuse,omitempty"`
@@ -91,7 +93,7 @@ func (s *Snell) writeHeaderContext(ctx context.Context, c net.Conn, metadata *C.
} }
if metadata.NetWork == C.UDP { if metadata.NetWork == C.UDP {
err = snell.WriteUDPHeader(c, s.version) err = snell.WriteUDPHeader(c, s.version, s.userKey)
if err == nil && s.version >= snell.Version4 { if err == nil && s.version >= snell.Version4 {
if sc, ok := c.(*snell.Snell); ok { if sc, ok := c.(*snell.Snell); ok {
err = sc.ReadReply() err = sc.ReadReply()
@@ -99,7 +101,7 @@ func (s *Snell) writeHeaderContext(ctx context.Context, c net.Conn, metadata *C.
} }
return return
} }
err = snell.WriteHeaderWithReuse(c, metadata.String(), uint(metadata.DstPort), s.version, s.reuse) err = snell.WriteHeader(c, metadata.String(), metadata.DstPort, s.version, s.reuse, s.userKey)
return return
} }
@@ -254,6 +256,13 @@ func NewSnell(option SnellOption) (*Snell, error) {
// Snell v5 servers are backward-compatible with v4 clients. // Snell v5 servers are backward-compatible with v4 clients.
option.Version = snell.Version4 option.Version = snell.Version4
} }
userKey := []byte(option.UserKey)
if len(userKey) > snell.MaxClientIDLength {
return nil, fmt.Errorf("snell %s userkey must be at most 255 bytes", addr)
}
if len(userKey) > 0 && option.Version != snell.Version6 {
return nil, fmt.Errorf("snell %s userkey is only supported on version 6", addr)
}
reuse := option.Version == snell.Version2 || reuse := option.Version == snell.Version2 ||
((option.Version == snell.Version4 || option.Version == snell.Version6) && option.Reuse) ((option.Version == snell.Version4 || option.Version == snell.Version6) && option.Reuse)
var v6Mode snell.V6Mode var v6Mode snell.V6Mode
@@ -299,6 +308,7 @@ func NewSnell(option SnellOption) (*Snell, error) {
}), }),
option: &option, option: &option,
psk: psk, psk: psk,
userKey: userKey,
obfsOption: obfsOption, obfsOption: obfsOption,
shadowTLSOption: shadowTLSOpt, shadowTLSOption: shadowTLSOpt,
restlsConfig: restlsConfig, restlsConfig: restlsConfig,
+7 -1
View File
@@ -159,7 +159,13 @@ func NewTailscale(option TailscaleOption) (*Tailscale, error) {
}, },
SystemPacketListener: func(ctx context.Context, network, address string) (net.PacketConn, error) { SystemPacketListener: func(ctx context.Context, network, address string) (net.PacketConn, error) {
log.Debugln("[Tailscale](%s) SystemPacketListener: start listen %s %s", option.Name, network, address) log.Debugln("[Tailscale](%s) SystemPacketListener: start listen %s %s", option.Name, network, address)
pc, err := outbound.dialer.ListenPacket(ctx, network, address, netip.AddrPort{}) var rAddrPort netip.AddrPort
if strings.HasSuffix(network, "6") {
rAddrPort = netip.AddrPortFrom(netip.IPv6Unspecified(), 0)
} else {
rAddrPort = netip.AddrPortFrom(netip.IPv4Unspecified(), 0)
}
pc, err := outbound.dialer.ListenPacket(ctx, network, address, rAddrPort)
log.Debugln("[Tailscale](%s) SystemPacketListener: finish listen %s %s, err: %v", option.Name, network, address, err) log.Debugln("[Tailscale](%s) SystemPacketListener: finish listen %s %s, err: %v", option.Name, network, address, err)
return pc, err return pc, err
}, },
+41 -29
View File
@@ -91,31 +91,32 @@ type VlessOption struct {
} }
type XHTTPOptions struct { type XHTTPOptions struct {
Path string `proxy:"path,omitempty"` Path string `proxy:"path,omitempty"`
Host string `proxy:"host,omitempty"` Host string `proxy:"host,omitempty"`
Mode string `proxy:"mode,omitempty"` Mode string `proxy:"mode,omitempty"`
Headers map[string]string `proxy:"headers,omitempty"` Headers map[string]string `proxy:"headers,omitempty"`
NoGRPCHeader bool `proxy:"no-grpc-header,omitempty"` NoGRPCHeader bool `proxy:"no-grpc-header,omitempty"`
XPaddingBytes string `proxy:"x-padding-bytes,omitempty"` XPaddingBytes string `proxy:"x-padding-bytes,omitempty"`
XPaddingObfsMode bool `proxy:"x-padding-obfs-mode,omitempty"` XPaddingObfsMode bool `proxy:"x-padding-obfs-mode,omitempty"`
XPaddingKey string `proxy:"x-padding-key,omitempty"` XPaddingKey string `proxy:"x-padding-key,omitempty"`
XPaddingHeader string `proxy:"x-padding-header,omitempty"` XPaddingHeader string `proxy:"x-padding-header,omitempty"`
XPaddingPlacement string `proxy:"x-padding-placement,omitempty"` XPaddingPlacement string `proxy:"x-padding-placement,omitempty"`
XPaddingMethod string `proxy:"x-padding-method,omitempty"` XPaddingMethod string `proxy:"x-padding-method,omitempty"`
UplinkHTTPMethod string `proxy:"uplink-http-method,omitempty"` UplinkHTTPMethod string `proxy:"uplink-http-method,omitempty"`
SessionPlacement string `proxy:"session-placement,omitempty"` SessionPlacement string `proxy:"session-placement,omitempty"`
SessionKey string `proxy:"session-key,omitempty"` SessionKey string `proxy:"session-key,omitempty"`
SessionTable string `proxy:"session-table,omitempty"` SessionTable string `proxy:"session-table,omitempty"`
SessionLength string `proxy:"session-length,omitempty"` SessionLength string `proxy:"session-length,omitempty"`
SeqPlacement string `proxy:"seq-placement,omitempty"` SeqPlacement string `proxy:"seq-placement,omitempty"`
SeqKey string `proxy:"seq-key,omitempty"` SeqKey string `proxy:"seq-key,omitempty"`
UplinkDataPlacement string `proxy:"uplink-data-placement,omitempty"` UplinkDataPlacement string `proxy:"uplink-data-placement,omitempty"`
UplinkDataKey string `proxy:"uplink-data-key,omitempty"` UplinkDataKey string `proxy:"uplink-data-key,omitempty"`
UplinkChunkSize string `proxy:"uplink-chunk-size,omitempty"` UplinkChunkSize string `proxy:"uplink-chunk-size,omitempty"`
ScMaxEachPostBytes string `proxy:"sc-max-each-post-bytes,omitempty"` ScMaxEachPostBytes string `proxy:"sc-max-each-post-bytes,omitempty"`
ScMinPostsIntervalMs string `proxy:"sc-min-posts-interval-ms,omitempty"` ScMinPostsIntervalMs string `proxy:"sc-min-posts-interval-ms,omitempty"`
ReuseSettings *XHTTPReuseSettings `proxy:"reuse-settings,omitempty"` // aka XMUX MaxReceiveBufferPerStream int `proxy:"max-receive-buffer-per-stream,omitempty"`
DownloadSettings *XHTTPDownloadSettings `proxy:"download-settings,omitempty"` ReuseSettings *XHTTPReuseSettings `proxy:"reuse-settings,omitempty"` // aka XMUX
DownloadSettings *XHTTPDownloadSettings `proxy:"download-settings,omitempty"`
} }
type XHTTPReuseSettings struct { type XHTTPReuseSettings struct {
@@ -129,10 +130,11 @@ type XHTTPReuseSettings struct {
type XHTTPDownloadSettings struct { type XHTTPDownloadSettings struct {
// xhttp part // xhttp part
Path *string `proxy:"path,omitempty"` Path *string `proxy:"path,omitempty"`
Host *string `proxy:"host,omitempty"` Host *string `proxy:"host,omitempty"`
Headers *map[string]string `proxy:"headers,omitempty"` Headers *map[string]string `proxy:"headers,omitempty"`
ReuseSettings *XHTTPReuseSettings `proxy:"reuse-settings,omitempty"` // aka XMUX ReuseSettings *XHTTPReuseSettings `proxy:"reuse-settings,omitempty"` // aka XMUX
MaxReceiveBufferPerStream *int `proxy:"max-receive-buffer-per-stream,omitempty"`
// proxy part // proxy part
Server *string `proxy:"server,omitempty"` Server *string `proxy:"server,omitempty"`
Port *int `proxy:"port,omitempty"` Port *int `proxy:"port,omitempty"`
@@ -624,6 +626,10 @@ func NewVless(option VlessOption) (*Vless, error) {
} }
} }
h2ReceiveWindow := option.XHTTPOpts.MaxReceiveBufferPerStream
if h2ReceiveWindow < 0 || int64(h2ReceiveWindow) > 1<<31-1 {
return nil, fmt.Errorf("xhttp max-receive-buffer-per-stream must be between 0 and 2147483647 bytes")
}
var hKeepAlivePeriod time.Duration var hKeepAlivePeriod time.Duration
var reuseCfg *xhttp.ReuseConfig var reuseCfg *xhttp.ReuseConfig
@@ -713,6 +719,7 @@ func NewVless(option VlessOption) (*Vless, error) {
}, },
v.option.ALPN, v.option.ALPN,
hKeepAlivePeriod, hKeepAlivePeriod,
h2ReceiveWindow,
) )
} }
var makeDownloadTransport func() http.RoundTripper var makeDownloadTransport func() http.RoundTripper
@@ -807,6 +814,10 @@ func NewVless(option VlessOption) (*Vless, error) {
} }
downloadHKeepAlivePeriod := hKeepAlivePeriod downloadHKeepAlivePeriod := hKeepAlivePeriod
downloadH2ReceiveWindow := lo.FromPtrOr(ds.MaxReceiveBufferPerStream, h2ReceiveWindow)
if downloadH2ReceiveWindow < 0 || int64(downloadH2ReceiveWindow) > 1<<31-1 {
return nil, fmt.Errorf("xhttp download-settings.max-receive-buffer-per-stream must be between 0 and 2147483647 bytes")
}
downloadCfg := *cfg // make a copy downloadCfg := *cfg // make a copy
downloadCfg.Host = downloadHost downloadCfg.Host = downloadHost
@@ -904,6 +915,7 @@ func NewVless(option VlessOption) (*Vless, error) {
}, },
downloadALPN, downloadALPN,
downloadHKeepAlivePeriod, downloadHKeepAlivePeriod,
downloadH2ReceiveWindow,
) )
} }
} }
@@ -0,0 +1,73 @@
package outbound
import (
"strings"
"testing"
"github.com/metacubex/mihomo/common/structure"
)
func TestXHTTPReceiveWindowValidation(t *testing.T) {
for _, tc := range []struct {
name string
up int
down *int
wantError string
}{
{name: "defaults"},
{name: "inherited", up: 8 << 20},
{name: "download override", up: 4 << 20, down: windowInt(16 << 20)},
{name: "explicit default", up: 8 << 20, down: windowInt(0)},
{name: "negative", up: -1, wantError: "xhttp max-receive-buffer-per-stream"},
{name: "negative download", down: windowInt(-1), wantError: "download-settings.max-receive-buffer-per-stream"},
} {
t.Run(tc.name, func(t *testing.T) {
_, err := NewVless(VlessOption{
Name: "window-test", Server: "192.0.2.1", Port: 443,
UUID: "00000000-0000-4000-8000-000000000001", Network: "xhttp",
XHTTPOpts: XHTTPOptions{Mode: "stream-up", MaxReceiveBufferPerStream: tc.up,
DownloadSettings: &XHTTPDownloadSettings{MaxReceiveBufferPerStream: tc.down}},
})
if tc.wantError == "" {
if err != nil {
t.Fatal(err)
}
} else if err == nil || !strings.Contains(err.Error(), tc.wantError) {
t.Fatalf("error = %v, want %q", err, tc.wantError)
}
})
}
}
func windowInt(value int) *int { return &value }
func TestXHTTPReceiveWindowDecode(t *testing.T) {
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
for _, tc := range []struct {
name string
down map[string]any
want *int
}{
{"inherit", map[string]any{}, nil},
{"override", map[string]any{"max-receive-buffer-per-stream": 16 << 20}, windowInt(16 << 20)},
{"reset", map[string]any{"max-receive-buffer-per-stream": 0}, windowInt(0)},
} {
t.Run(tc.name, func(t *testing.T) {
var option VlessOption
err := decoder.Decode(map[string]any{"name": "window-test", "server": "192.0.2.1", "port": 443,
"uuid": "00000000-0000-4000-8000-000000000001", "xhttp-opts": map[string]any{
"max-receive-buffer-per-stream": 8 << 20, "download-settings": tc.down,
}}, &option)
if err != nil {
t.Fatal(err)
}
if option.XHTTPOpts.MaxReceiveBufferPerStream != 8<<20 {
t.Fatal("main window not decoded")
}
got := option.XHTTPOpts.DownloadSettings.MaxReceiveBufferPerStream
if (got == nil) != (tc.want == nil) || got != nil && *got != *tc.want {
t.Fatalf("download window = %v, want %v", got, tc.want)
}
})
}
}
+5 -3
View File
@@ -233,15 +233,17 @@ func ParseProxy(mapping map[string]any, options ...ProxyOption) (C.Proxy, error)
if muxMapping, muxExist := mapping["smux"].(map[string]any); muxExist { if muxMapping, muxExist := mapping["smux"].(map[string]any); muxExist {
muxOption := &outbound.SingMuxOption{} muxOption := &outbound.SingMuxOption{}
err = decoder.Decode(muxMapping, muxOption) if err := decoder.Decode(muxMapping, muxOption); err != nil {
if err != nil { _ = proxy.Close()
return nil, err return nil, err
} }
if muxOption.Enabled { if muxOption.Enabled {
proxy, err = outbound.NewSingMux(*muxOption, proxy) wrapped, err := outbound.NewSingMux(*muxOption, proxy)
if err != nil { if err != nil {
_ = proxy.Close()
return nil, err return nil, err
} }
proxy = wrapped
} }
} }
+1 -1
View File
@@ -27,7 +27,7 @@ func NewSubscriptionInfo(userinfo string) (si *SubscriptionInfo) {
intValue, err := parseValue(value) intValue, err := parseValue(value)
if err != nil { if err != nil {
log.Warnln("[Provider] get subscription-userinfo: %e", err) log.Warnln("[Provider] get subscription-userinfo: %s", err)
continue continue
} }
+1 -1
View File
@@ -190,7 +190,7 @@ func resolveProcessNameByProcSearch(inode, uid uint32) (string, error) {
info, err := f.Info() info, err := f.Info()
if err != nil { if err != nil {
return "", err continue
} }
if info.Sys().(*syscall.Stat_t).Uid != uid { if info.Sys().(*syscall.Stat_t).Uid != uid {
continue continue
+18 -3
View File
@@ -2,17 +2,20 @@ package sniffer
import ( import (
"bufio" "bufio"
"context"
"errors" "errors"
"io"
"net/netip" "net/netip"
"time" "time"
"github.com/metacubex/sing/common/metadata"
"github.com/metacubex/mihomo/common/lru" "github.com/metacubex/mihomo/common/lru"
N "github.com/metacubex/mihomo/common/net" N "github.com/metacubex/mihomo/common/net"
C "github.com/metacubex/mihomo/constant" C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/constant/sniffer" "github.com/metacubex/mihomo/constant/sniffer"
"github.com/metacubex/mihomo/log" "github.com/metacubex/mihomo/log"
E "github.com/metacubex/sing/common/exceptions"
"github.com/metacubex/sing/common/metadata"
) )
var ( var (
@@ -146,7 +149,7 @@ func (sd *Dispatcher) TCPSniff(conn *N.BufferedConn, metadata *C.Metadata) bool
host, config, err := sd.sniffDomain(conn, metadata) host, config, err := sd.sniffDomain(conn, metadata)
if err != nil { if err != nil {
if !forceSniffer { if !forceSniffer && shouldCacheSniffFailure(conn, err) {
sd.cacheSniffFailed(metadata) sd.cacheSniffFailed(metadata)
} }
log.Debugln("[Sniffer] All sniffing sniff failed with from [%s:%d] to [%s:%d]", metadata.SrcIP, metadata.SrcPort, metadata.String(), metadata.DstPort) log.Debugln("[Sniffer] All sniffing sniff failed with from [%s:%d] to [%s:%d]", metadata.SrcIP, metadata.SrcPort, metadata.String(), metadata.DstPort)
@@ -298,6 +301,18 @@ func (sd *Dispatcher) sniffDomain(conn *N.BufferedConn, metadata *C.Metadata) (s
return "", SnifferConfig{}, ErrorSniffFailed return "", SnifferConfig{}, ErrorSniffFailed
} }
// shouldCacheSniffFailure reports whether a sniffing failure provides evidence
// that the destination is unsniffable (such as a server-first timeout or an
// unrecognized payload). Connections that close or are canceled before sending
// any bytes (e.g., speculative pre-connects) carry no protocol evidence and
// must not poison skipList for a shared destination IP:port.
func shouldCacheSniffFailure(conn *N.BufferedConn, err error) bool {
if conn.Buffered() == 0 && (E.IsClosed(err) || errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, context.Canceled)) {
return false
}
return true
}
func (sd *Dispatcher) cacheSniffFailed(metadata *C.Metadata) { func (sd *Dispatcher) cacheSniffFailed(metadata *C.Metadata) {
dst := metadata.AddrPort() dst := metadata.AddrPort()
sd.skipList.Compute(dst, func(oldValue uint8, loaded bool) (newValue uint8, delete bool) { sd.skipList.Compute(dst, func(oldValue uint8, loaded bool) (newValue uint8, delete bool) {
+148
View File
@@ -7,9 +7,12 @@ package sniffer
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"context"
"io" "io"
"net" "net"
"net/netip" "net/netip"
"os"
"syscall"
"testing" "testing"
"time" "time"
@@ -18,6 +21,7 @@ import (
"github.com/metacubex/mihomo/constant/sniffer" "github.com/metacubex/mihomo/constant/sniffer"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
// chunkedConn hands out one chunk per Read, so a sniffer only ever sees the // chunkedConn hands out one chunk per Read, so a sniffer only ever sees the
@@ -458,3 +462,147 @@ func TestDispatcherMultipleSniffers(t *testing.T) {
assert.Equal(t, []string{"tls", "http", "quic"}, protocols) assert.Equal(t, []string{"tls", "http", "quic"}, protocols)
}) })
} }
func TestDispatcherSkipList(t *testing.T) {
clientHello := makeTestTLSRecords(makeTestClientHello("cdn-a.example.net", 0))
newTLSDispatcher := func(t *testing.T) *Dispatcher {
t.Helper()
sd, err := NewDispatcher(&Config{
Enable: true,
ParsePureIp: true,
Sniffers: map[sniffer.Type]SnifferConfig{
sniffer.TLS: {OverrideDest: true},
},
})
require.NoError(t, err)
return sd
}
newMetadata := func(ip string) *C.Metadata {
return &C.Metadata{
NetWork: C.TCP,
DstIP: netip.MustParseAddr(ip),
DstPort: 443,
}
}
t.Run("does not poison skipList on zero-byte closed or canceled connections", func(t *testing.T) {
cases := []struct {
name string
readErr error
}{
{name: "EOF", readErr: io.EOF},
{name: "unexpected EOF", readErr: io.ErrUnexpectedEOF},
{name: "net.ErrClosed", readErr: &net.OpError{Op: "read", Net: "tcp", Err: net.ErrClosed}},
{name: "ECONNRESET", readErr: &net.OpError{Op: "read", Net: "tcp", Err: syscall.ECONNRESET}},
{name: "context.Canceled", readErr: context.Canceled},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
sd := newTLSDispatcher(t)
for i := 0; i < 8; i++ {
raw := &chunkedConn{t: t, readErr: tc.readErr}
t.Cleanup(raw.stopTimer)
md := newMetadata("192.0.2.1")
assert.False(t, sd.TCPSniff(N.NewBufferedConn(raw), md))
_, cached := sd.skipList.Get(md.AddrPort())
assert.False(t, cached, "zero-byte %s should not be cached in skipList", tc.name)
}
raw := &chunkedConn{t: t, chunks: [][]byte{clientHello}}
t.Cleanup(raw.stopTimer)
md := newMetadata("192.0.2.1")
assert.True(t, sd.TCPSniff(N.NewBufferedConn(raw), md))
assert.Equal(t, "cdn-a.example.net", md.SniffHost)
assert.Equal(t, "cdn-a.example.net", md.Host)
})
}
})
t.Run("caches unrecognized protocol payloads until skip threshold", func(t *testing.T) {
sd := newTLSDispatcher(t)
nonTLS := []byte("SSH-2.0-OpenSSH_9.0\r\n")
for i := 0; i < 6; i++ {
raw := &chunkedConn{t: t, chunks: [][]byte{nonTLS}}
t.Cleanup(raw.stopTimer)
md := newMetadata("192.0.2.2")
assert.False(t, sd.TCPSniff(N.NewBufferedConn(raw), md))
failures, cached := sd.skipList.Get(md.AddrPort())
assert.True(t, cached)
assert.Equal(t, uint8(i+1), failures)
}
// Once threshold (> 5) is reached, sniffing is skipped without reading.
raw := &chunkedConn{t: t, chunks: [][]byte{clientHello}}
t.Cleanup(raw.stopTimer)
md := newMetadata("192.0.2.2")
assert.False(t, sd.TCPSniff(N.NewBufferedConn(raw), md))
assert.Empty(t, raw.deadlines)
assert.Empty(t, md.SniffHost)
})
t.Run("caches server-first read timeouts until skip threshold", func(t *testing.T) {
sd := newTLSDispatcher(t)
timeoutErr := &net.OpError{Op: "read", Net: "tcp", Err: os.ErrDeadlineExceeded}
for i := 0; i < 6; i++ {
raw := &chunkedConn{t: t, readErr: timeoutErr}
t.Cleanup(raw.stopTimer)
md := newMetadata("192.0.2.3")
assert.False(t, sd.TCPSniff(N.NewBufferedConn(raw), md))
failures, cached := sd.skipList.Get(md.AddrPort())
assert.True(t, cached)
assert.Equal(t, uint8(i+1), failures)
}
raw := &chunkedConn{t: t, chunks: [][]byte{clientHello}}
t.Cleanup(raw.stopTimer)
md := newMetadata("192.0.2.3")
assert.False(t, sd.TCPSniff(N.NewBufferedConn(raw), md))
assert.Empty(t, raw.deadlines)
})
t.Run("caches truncated payload followed by EOF", func(t *testing.T) {
sd := newTLSDispatcher(t)
partialTLSHeader := []byte{tlsRecordTypeHandshake, 0x03, 0x01}
raw := &chunkedConn{t: t, chunks: [][]byte{partialTLSHeader}}
t.Cleanup(raw.stopTimer)
md := newMetadata("192.0.2.4")
assert.False(t, sd.TCPSniff(N.NewBufferedConn(raw), md))
failures, cached := sd.skipList.Get(md.AddrPort())
assert.True(t, cached)
assert.Equal(t, uint8(1), failures)
})
t.Run("zero-byte EOF does not push partial failure count over threshold", func(t *testing.T) {
sd := newTLSDispatcher(t)
nonTLS := []byte("SSH-2.0-OpenSSH_9.0\r\n")
for i := 0; i < 5; i++ {
raw := &chunkedConn{t: t, chunks: [][]byte{nonTLS}}
t.Cleanup(raw.stopTimer)
assert.False(t, sd.TCPSniff(N.NewBufferedConn(raw), newMetadata("192.0.2.5")))
}
eofRaw := &chunkedConn{t: t, readErr: io.EOF}
t.Cleanup(eofRaw.stopTimer)
mdEOF := newMetadata("192.0.2.5")
assert.False(t, sd.TCPSniff(N.NewBufferedConn(eofRaw), mdEOF))
failures, cached := sd.skipList.Get(mdEOF.AddrPort())
assert.True(t, cached)
assert.Equal(t, uint8(5), failures)
helloRaw := &chunkedConn{t: t, chunks: [][]byte{clientHello}}
t.Cleanup(helloRaw.stopTimer)
mdHello := newMetadata("192.0.2.5")
assert.True(t, sd.TCPSniff(N.NewBufferedConn(helloRaw), mdHello))
assert.Equal(t, "cdn-a.example.net", mdHello.SniffHost)
_, cached = sd.skipList.Get(mdEOF.AddrPort())
assert.False(t, cached)
})
}
+2 -1
View File
@@ -63,7 +63,6 @@ var randomFingerprint = once.OnceValue(func() UClientHelloID {
chooser, _ := weightedrand.NewChooser( chooser, _ := weightedrand.NewChooser(
weightedrand.NewChoice("chrome", 6), weightedrand.NewChoice("chrome", 6),
weightedrand.NewChoice("safari", 3), weightedrand.NewChoice("safari", 3),
weightedrand.NewChoice("ios", 2),
weightedrand.NewChoice("firefox", 1), weightedrand.NewChoice("firefox", 1),
) )
initClient := chooser.Pick() initClient := chooser.Pick()
@@ -104,6 +103,8 @@ func init() {
weights := utls.DefaultWeights weights := utls.DefaultWeights
weights.TLSVersMax_Set_VersionTLS13 = 1 weights.TLSVersMax_Set_VersionTLS13 = 1
weights.FirstKeyShare_Set_CurveP256 = 0 weights.FirstKeyShare_Set_CurveP256 = 0
weights.CurveIDs_Append_X25519 = 1
weights.KeyShare_Append_RandomGroups = 1
randomized := utls.HelloRandomized randomized := utls.HelloRandomized
randomized.Seed, _ = utls.NewPRNGSeed() randomized.Seed, _ = utls.NewPRNGSeed()
randomized.Weights = &weights randomized.Weights = &weights
+5 -2
View File
@@ -168,6 +168,7 @@ type DNS struct {
FakeIPPool6 *fakeip.Pool FakeIPPool6 *fakeip.Pool
FakeIPSkipper *fakeip.Skipper FakeIPSkipper *fakeip.Skipper
FakeIPTTL int FakeIPTTL int
FakeIPDisableMapping bool
NameServerPolicy []dns.Policy NameServerPolicy []dns.Policy
ProxyServerNameserver []dns.NameServer ProxyServerNameserver []dns.NameServer
ProxyServerPolicy []dns.Policy ProxyServerPolicy []dns.Policy
@@ -237,6 +238,7 @@ type RawDNS struct {
FakeIPRange6 string `yaml:"fake-ip-range6" json:"fake-ip-range6"` FakeIPRange6 string `yaml:"fake-ip-range6" json:"fake-ip-range6"`
FakeIPFilter []string `yaml:"fake-ip-filter" json:"fake-ip-filter"` FakeIPFilter []string `yaml:"fake-ip-filter" json:"fake-ip-filter"`
FakeIPFilterMode C.FilterMode `yaml:"fake-ip-filter-mode" json:"fake-ip-filter-mode"` FakeIPFilterMode C.FilterMode `yaml:"fake-ip-filter-mode" json:"fake-ip-filter-mode"`
FakeIPDisableMapping bool `yaml:"fake-ip-disable-mapping" json:"fake-ip-disable-mapping"`
FakeIPTTL int `yaml:"fake-ip-ttl" json:"fake-ip-ttl"` FakeIPTTL int `yaml:"fake-ip-ttl" json:"fake-ip-ttl"`
DefaultNameserver []string `yaml:"default-nameserver" json:"default-nameserver"` DefaultNameserver []string `yaml:"default-nameserver" json:"default-nameserver"`
CacheAlgorithm string `yaml:"cache-algorithm" json:"cache-algorithm"` CacheAlgorithm string `yaml:"cache-algorithm" json:"cache-algorithm"`
@@ -529,8 +531,8 @@ func DefaultRawConfig() *RawConfig {
"tls://223.5.5.5:853", "tls://223.5.5.5:853",
}, },
FakeIPFilter: []string{ FakeIPFilter: []string{
"dns.msftnsci.com", "dns.msftncsi.com",
"www.msftnsci.com", "www.msftncsi.com",
"www.msftconnecttest.com", "www.msftconnecttest.com",
}, },
FakeIPFilterMode: C.FilterBlackList, FakeIPFilterMode: C.FilterBlackList,
@@ -1538,6 +1540,7 @@ func parseDNS(rawCfg *RawConfig, ruleProviders map[string]P.RuleProvider) (*DNS,
dnsCfg.FakeIPSkipper = skipper dnsCfg.FakeIPSkipper = skipper
dnsCfg.FakeIPTTL = cfg.FakeIPTTL dnsCfg.FakeIPTTL = cfg.FakeIPTTL
dnsCfg.FakeIPDisableMapping = cfg.FakeIPDisableMapping
if dnsCfg.FakeIPRange.IsValid() { if dnsCfg.FakeIPRange.IsValid() {
pool, err := fakeip.New(fakeip.Options{ pool, err := fakeip.New(fakeip.Options{
+18 -15
View File
@@ -10,14 +10,15 @@ import (
) )
type ResolverEnhancer struct { type ResolverEnhancer struct {
ipv6 bool ipv6 bool
mode C.DNSMode mode C.DNSMode
fakeIPPool *fakeip.Pool fakeIPPool *fakeip.Pool
fakeIPPool6 *fakeip.Pool fakeIPPool6 *fakeip.Pool
fakeIPSkipper *fakeip.Skipper fakeIPSkipper *fakeip.Skipper
fakeIPTTL int fakeIPTTL int
mapping *lru.LruCache[netip.Addr, string] fakeIPDisableMapping bool
useHosts bool mapping *lru.LruCache[netip.Addr, string]
useHosts bool
} }
func (h *ResolverEnhancer) FakeIPEnabled() bool { func (h *ResolverEnhancer) FakeIPEnabled() bool {
@@ -159,13 +160,14 @@ func (h *ResolverEnhancer) StoreFakePoolState() {
} }
type EnhancerConfig struct { type EnhancerConfig struct {
IPv6 bool IPv6 bool
EnhancedMode C.DNSMode EnhancedMode C.DNSMode
FakeIPPool *fakeip.Pool FakeIPPool *fakeip.Pool
FakeIPPool6 *fakeip.Pool FakeIPPool6 *fakeip.Pool
FakeIPSkipper *fakeip.Skipper FakeIPSkipper *fakeip.Skipper
FakeIPTTL int FakeIPTTL int
UseHosts bool FakeIPDisableMapping bool
UseHosts bool
} }
func NewEnhancer(cfg EnhancerConfig) *ResolverEnhancer { func NewEnhancer(cfg EnhancerConfig) *ResolverEnhancer {
@@ -182,6 +184,7 @@ func NewEnhancer(cfg EnhancerConfig) *ResolverEnhancer {
} }
e.fakeIPSkipper = cfg.FakeIPSkipper e.fakeIPSkipper = cfg.FakeIPSkipper
e.fakeIPTTL = cfg.FakeIPTTL e.fakeIPTTL = cfg.FakeIPTTL
e.fakeIPDisableMapping = cfg.FakeIPDisableMapping
if e.fakeIPTTL < 1 { if e.fakeIPTTL < 1 {
e.fakeIPTTL = 1 e.fakeIPTTL = 1
} }
+3 -1
View File
@@ -237,11 +237,13 @@ func newHandler(resolver resolver.Resolver, mapper *ResolverEnhancer) handler {
middlewares = append(middlewares, withHosts(mapper.mapping)) middlewares = append(middlewares, withHosts(mapper.mapping))
} }
disableMapping := false
if mapper.mode == C.DNSFakeIP { if mapper.mode == C.DNSFakeIP {
middlewares = append(middlewares, withFakeIP(mapper.fakeIPSkipper, mapper.fakeIPPool, mapper.fakeIPPool6, mapper.fakeIPTTL)) middlewares = append(middlewares, withFakeIP(mapper.fakeIPSkipper, mapper.fakeIPPool, mapper.fakeIPPool6, mapper.fakeIPTTL))
disableMapping = mapper.fakeIPDisableMapping
} }
if mapper.mode != C.DNSNormal { if mapper.mode != C.DNSNormal && !disableMapping {
middlewares = append(middlewares, withMapping(mapper.mapping)) middlewares = append(middlewares, withMapping(mapper.mapping))
} }
+7
View File
@@ -398,6 +398,10 @@ func (r *Resolver) ClearCache() {
func (r *Resolver) ResetConnection() { func (r *Resolver) ResetConnection() {
if r != nil { if r != nil {
// The network changed: lookups still in flight went out on the old network and may never be
// answered. Forget them before resetting the clients, which can block (DoH waits for clientMu),
// so new requests start a fresh lookup right away instead of joining the old ones.
r.group.Reset()
for _, c := range r.main { for _, c := range r.main {
c.ResetConnection() c.ResetConnection()
} }
@@ -407,6 +411,9 @@ func (r *Resolver) ResetConnection() {
if dr := r.defaultResolver; dr != nil { if dr := r.defaultResolver; dr != nil {
dr.ResetConnection() dr.ResetConnection()
} }
// Forget them again after: a lookup that started while the clients were being reset may be using
// a connection from before the change, and requests made after ResetConnection must not join it.
r.group.Reset()
} }
} }
+11 -2
View File
@@ -414,6 +414,7 @@ proxies: # socks5
server: server server: server
port: 44046 port: 44046
psk: yourpsk psk: yourpsk
# userkey: per-user-client-id # v6 only; sent as the Snell ClientID
# version: 4 # support 1/2/3/4/5/6 # version: 4 # support 1/2/3/4/5/6
# udp: true # support UDP on version 3/4/5/6 # udp: true # support UDP on version 3/4/5/6
# reuse: false # v4/5/6 only # reuse: false # v4/5/6 only
@@ -593,8 +594,13 @@ proxies: # socks5
port: 443 port: 443
udp: true udp: true
tls: true tls: true
# mux: true # relay+mtls when tls is also true # mux: true # with tls enabled and ws disabled, this selects relay+mtls
# sni: relay.example.com # ws: true # enables WebSocket; combine with tls/mux for relay+wss/mws/mwss
# ws-opts:
# path: /ws # GOST default; set to match the listener's ws.path
# headers:
# Host: relay.example.com
# sni: relay.example.com # optional; defaults to ws-opts.headers.Host, or server if absent
# username: user # username: user
# password: pass # password: pass
# client-fingerprint: chrome # client-fingerprint: chrome
@@ -1049,6 +1055,8 @@ proxies: # socks5
xhttp-opts: xhttp-opts:
path: "/" path: "/"
host: xxx.com host: xxx.com
# max-receive-buffer-per-stream: 0 # Bytes; 0 keeps the HTTP/2 library default. HTTP/2 only.
# Larger windows may improve high-bandwidth/high-latency downloads but increase memory use and loaded latency.
# mode: "stream-one" # Available: "stream-one", "stream-up" or "packet-up" # mode: "stream-one" # Available: "stream-one", "stream-up" or "packet-up"
# headers: # headers:
# X-Forwarded-For: "" # X-Forwarded-For: ""
@@ -1078,6 +1086,7 @@ proxies: # socks5
# h-keep-alive-period: 0 # h-keep-alive-period: 0
# download-settings: # download-settings:
# ## xhttp part # ## xhttp part
# max-receive-buffer-per-stream: 8388608 # 8 MiB; omitted inherits above, explicit 0 restores the library default.
# path: "/" # path: "/"
# host: xxx.com # host: xxx.com
# headers: # headers:
+2 -2
View File
@@ -7,7 +7,7 @@ require (
github.com/coreos/go-iptables v0.8.0 github.com/coreos/go-iptables v0.8.0
github.com/dlclark/regexp2 v1.12.0 github.com/dlclark/regexp2 v1.12.0
github.com/easytier/easytier/easytier-go v0.0.0-20261111015056-2abb1676b475 github.com/easytier/easytier/easytier-go v0.0.0-20261111015056-2abb1676b475
github.com/enfein/mieru/v3 v3.39.0 github.com/enfein/mieru/v3 v3.40.0
github.com/gobwas/ws v1.4.0 github.com/gobwas/ws v1.4.0
github.com/gofrs/uuid/v5 v5.4.0 github.com/gofrs/uuid/v5 v5.4.0
github.com/golang/snappy v1.0.0 github.com/golang/snappy v1.0.0
@@ -37,7 +37,7 @@ require (
github.com/metacubex/sing v0.5.9 github.com/metacubex/sing v0.5.9
github.com/metacubex/sing-mux v0.3.12 github.com/metacubex/sing-mux v0.3.12
github.com/metacubex/sing-quic v0.0.0-20260904234848-1c242664697a github.com/metacubex/sing-quic v0.0.0-20260904234848-1c242664697a
github.com/metacubex/sing-shadowsocks v0.2.13 github.com/metacubex/sing-shadowsocks v0.2.14
github.com/metacubex/sing-shadowsocks2 v0.2.8 github.com/metacubex/sing-shadowsocks2 v0.2.8
github.com/metacubex/sing-tun v0.4.29 github.com/metacubex/sing-tun v0.4.29
github.com/metacubex/sing-vmess v0.2.5 github.com/metacubex/sing-vmess v0.2.5
+4 -4
View File
@@ -29,8 +29,8 @@ github.com/dunglas/httpsfv v1.0.2 h1:iERDp/YAfnojSDJ7PW3dj1AReJz4MrwbECSSE59JWL0
github.com/dunglas/httpsfv v1.0.2/go.mod h1:zID2mqw9mFsnt7YC3vYQ9/cjq30q41W+1AnDwH8TiMg= github.com/dunglas/httpsfv v1.0.2/go.mod h1:zID2mqw9mFsnt7YC3vYQ9/cjq30q41W+1AnDwH8TiMg=
github.com/easytier/easytier/easytier-go v0.0.0-20261111015056-2abb1676b475 h1:L5C1yfYJyzcX7lCWi6aEX8H/0gBKqnlGcVxaBfQVTY8= github.com/easytier/easytier/easytier-go v0.0.0-20261111015056-2abb1676b475 h1:L5C1yfYJyzcX7lCWi6aEX8H/0gBKqnlGcVxaBfQVTY8=
github.com/easytier/easytier/easytier-go v0.0.0-20261111015056-2abb1676b475/go.mod h1:fCEi5+K2yt+sPDONSWO1uNpOifrwPgFGvm3J0YrFRvk= github.com/easytier/easytier/easytier-go v0.0.0-20261111015056-2abb1676b475/go.mod h1:fCEi5+K2yt+sPDONSWO1uNpOifrwPgFGvm3J0YrFRvk=
github.com/enfein/mieru/v3 v3.39.0 h1:22WJN9i7I4FrY1cTAVp5KfKOFm4sWrXVOXhqf5fkdr8= github.com/enfein/mieru/v3 v3.40.0 h1:J4M+g7YWi4eU2rYKPvEE3IdY8VB8Kw4xuybLCf+h6PU=
github.com/enfein/mieru/v3 v3.39.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM= github.com/enfein/mieru/v3 v3.40.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358 h1:kXYqH/sL8dS/FdoFjr12ePjnLPorPo2FsnrHNuXSDyo= github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358 h1:kXYqH/sL8dS/FdoFjr12ePjnLPorPo2FsnrHNuXSDyo=
github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358/go.mod h1:hkIFzoiIPZYxdFOOLyDho59b7SrDfo+w3h+yWdlg45I= github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358/go.mod h1:hkIFzoiIPZYxdFOOLyDho59b7SrDfo+w3h+yWdlg45I=
github.com/ericlagergren/polyval v0.0.0-20220411101811-e25bc10ba391 h1:8j2RH289RJplhA6WfdaPqzg1MjH2K8wX5e0uhAxrw2g= github.com/ericlagergren/polyval v0.0.0-20220411101811-e25bc10ba391 h1:8j2RH289RJplhA6WfdaPqzg1MjH2K8wX5e0uhAxrw2g=
@@ -159,8 +159,8 @@ github.com/metacubex/sing-mux v0.3.12 h1:80jrJsGgRW7ZHpJCRpwJhG3yzT5muEHIWjaOsDJ
github.com/metacubex/sing-mux v0.3.12/go.mod h1:8bT7ZKT3clRrJjYc/x5CRYibC1TX/bK73a3r3+2E+Fc= github.com/metacubex/sing-mux v0.3.12/go.mod h1:8bT7ZKT3clRrJjYc/x5CRYibC1TX/bK73a3r3+2E+Fc=
github.com/metacubex/sing-quic v0.0.0-20260904234848-1c242664697a h1:qZzQwtWDrPU1LXoMow0/iLHY3mb7uauS/mho8hYcenE= github.com/metacubex/sing-quic v0.0.0-20260904234848-1c242664697a h1:qZzQwtWDrPU1LXoMow0/iLHY3mb7uauS/mho8hYcenE=
github.com/metacubex/sing-quic v0.0.0-20260904234848-1c242664697a/go.mod h1:6ayFGfzzBE85csgQkM3gf4neFq6s0losHlPRSxY+nuk= github.com/metacubex/sing-quic v0.0.0-20260904234848-1c242664697a/go.mod h1:6ayFGfzzBE85csgQkM3gf4neFq6s0losHlPRSxY+nuk=
github.com/metacubex/sing-shadowsocks v0.2.13 h1:PKmInHy9+4nY3FLhmKcWdASUBo9WZ/KrSPWjNpGaUTQ= github.com/metacubex/sing-shadowsocks v0.2.14 h1:P9HUtAPRVa24sB0dHwwTUkaEu5V0A8FGXJ35zdNAbN4=
github.com/metacubex/sing-shadowsocks v0.2.13/go.mod h1:2e5EIaw0rxKrm1YTRmiMnDulwbGxH9hAFlrwQLQMQkU= github.com/metacubex/sing-shadowsocks v0.2.14/go.mod h1:kUDOwF06u5/zSkwPQa0BSdYLa1a7XtGVFik1/VSTkN0=
github.com/metacubex/sing-shadowsocks2 v0.2.8 h1:6MoODu7BAcnwIC0w9muq+2LZVz01wWD07L5IRhOty9Q= github.com/metacubex/sing-shadowsocks2 v0.2.8 h1:6MoODu7BAcnwIC0w9muq+2LZVz01wWD07L5IRhOty9Q=
github.com/metacubex/sing-shadowsocks2 v0.2.8/go.mod h1:vOEbfKC60txi0ca+yUlqEwOGc3Obl6cnSgx9Gf45KjE= github.com/metacubex/sing-shadowsocks2 v0.2.8/go.mod h1:vOEbfKC60txi0ca+yUlqEwOGc3Obl6cnSgx9Gf45KjE=
github.com/metacubex/sing-tun v0.4.29 h1:KIULEuW0iFXxLegOgrW8orq5Sx4TCBBhwo6j8+CIFBs= github.com/metacubex/sing-tun v0.4.29 h1:KIULEuW0iFXxLegOgrW8orq5Sx4TCBBhwo6j8+CIFBs=
+8 -7
View File
@@ -265,13 +265,14 @@ func updateDNS(c *config.DNS, generalIPv6 bool) {
CacheMaxSize: c.CacheMaxSize, CacheMaxSize: c.CacheMaxSize,
}) })
m := dns.NewEnhancer(dns.EnhancerConfig{ m := dns.NewEnhancer(dns.EnhancerConfig{
IPv6: ipv6, IPv6: ipv6,
EnhancedMode: c.EnhancedMode, EnhancedMode: c.EnhancedMode,
FakeIPPool: c.FakeIPPool, FakeIPPool: c.FakeIPPool,
FakeIPPool6: c.FakeIPPool6, FakeIPPool6: c.FakeIPPool6,
FakeIPSkipper: c.FakeIPSkipper, FakeIPSkipper: c.FakeIPSkipper,
FakeIPTTL: c.FakeIPTTL, FakeIPTTL: c.FakeIPTTL,
UseHosts: c.UseHosts, UseHosts: c.UseHosts,
FakeIPDisableMapping: c.FakeIPDisableMapping,
}) })
// reuse cache of old host mapper // reuse cache of old host mapper
+2 -1
View File
@@ -277,7 +277,8 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis
switch options.DNSMode { switch options.DNSMode {
case "", tun.DNSModeDisabled, tun.DNSModeNative, tun.DNSModeHijack: case "", tun.DNSModeDisabled, tun.DNSModeNative, tun.DNSModeHijack:
default: default:
return nil, fmt.Errorf("invalid dns-mode: %s", options.DNSMode) log.Warnln("[TUN] ignored invalid dns-mode: %s", options.DNSMode)
options.DNSMode = ""
} }
var dnsAdds []netip.AddrPort var dnsAdds []netip.AddrPort
+5 -1
View File
@@ -169,7 +169,11 @@ func New(config LC.VlessServer, lc C.InboundListenConfig, tunnel C.Tunnel, addit
httpMux.HandleFunc(config.WsPath, func(w http.ResponseWriter, r *http.Request) { httpMux.HandleFunc(config.WsPath, func(w http.ResponseWriter, r *http.Request) {
conn, err := mihomoVMess.StreamUpgradedWebsocketConn(w, r) conn, err := mihomoVMess.StreamUpgradedWebsocketConn(w, r)
if err != nil { if err != nil {
http.Error(w, err.Error(), 500) if errors.Is(err, mihomoVMess.ErrNotWebSocketUpgrade) {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
sl.HandleConn(conn, tunnel, additions...) sl.HandleConn(conn, tunnel, additions...)
+5 -1
View File
@@ -203,7 +203,11 @@ func New(config LC.VmessServer, lc C.InboundListenConfig, tunnel C.Tunnel, addit
httpMux.HandleFunc(config.WsPath, func(w http.ResponseWriter, r *http.Request) { httpMux.HandleFunc(config.WsPath, func(w http.ResponseWriter, r *http.Request) {
conn, err := mihomoVMess.StreamUpgradedWebsocketConn(w, r) conn, err := mihomoVMess.StreamUpgradedWebsocketConn(w, r)
if err != nil { if err != nil {
http.Error(w, err.Error(), 500) if errors.Is(err, mihomoVMess.ErrNotWebSocketUpgrade) {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
sl.HandleConn(conn, tunnel, additions...) sl.HandleConn(conn, tunnel, additions...)
+5 -1
View File
@@ -165,7 +165,11 @@ func New(config LC.TrojanServer, lc C.InboundListenConfig, tunnel C.Tunnel, addi
httpMux.HandleFunc(config.WsPath, func(w http.ResponseWriter, r *http.Request) { httpMux.HandleFunc(config.WsPath, func(w http.ResponseWriter, r *http.Request) {
conn, err := mihomoVMess.StreamUpgradedWebsocketConn(w, r) conn, err := mihomoVMess.StreamUpgradedWebsocketConn(w, r)
if err != nil { if err != nil {
http.Error(w, err.Error(), 500) if errors.Is(err, mihomoVMess.ErrNotWebSocketUpgrade) {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
sl.HandleConn(conn, tunnel, additions...) sl.HandleConn(conn, tunnel, additions...)
+2 -1
View File
@@ -17,7 +17,8 @@ func (d *Domain) RuleType() C.RuleType {
} }
func (d *Domain) Match(metadata *C.Metadata, helper C.RuleMatchHelper) (bool, string) { func (d *Domain) Match(metadata *C.Metadata, helper C.RuleMatchHelper) (bool, string) {
return metadata.RuleHost() == d.domain, d.adapter domain := strings.ToLower(metadata.RuleHost())
return domain == d.domain, d.adapter
} }
func (d *Domain) Adapter() string { func (d *Domain) Adapter() string {
+1 -1
View File
@@ -17,7 +17,7 @@ func (dk *DomainKeyword) RuleType() C.RuleType {
} }
func (dk *DomainKeyword) Match(metadata *C.Metadata, helper C.RuleMatchHelper) (bool, string) { func (dk *DomainKeyword) Match(metadata *C.Metadata, helper C.RuleMatchHelper) (bool, string) {
domain := metadata.RuleHost() domain := strings.ToLower(metadata.RuleHost())
return strings.Contains(domain, dk.keyword), dk.adapter return strings.Contains(domain, dk.keyword), dk.adapter
} }
+2 -1
View File
@@ -2,6 +2,7 @@ package common
import ( import (
C "github.com/metacubex/mihomo/constant" C "github.com/metacubex/mihomo/constant"
"strings"
"github.com/dlclark/regexp2" "github.com/dlclark/regexp2"
) )
@@ -17,7 +18,7 @@ func (dr *DomainRegex) RuleType() C.RuleType {
} }
func (dr *DomainRegex) Match(metadata *C.Metadata, helper C.RuleMatchHelper) (bool, string) { func (dr *DomainRegex) Match(metadata *C.Metadata, helper C.RuleMatchHelper) (bool, string) {
domain := metadata.RuleHost() domain := strings.ToLower(metadata.RuleHost())
match, _ := dr.regex.MatchString(domain) match, _ := dr.regex.MatchString(domain)
return match, dr.adapter return match, dr.adapter
} }
+1 -1
View File
@@ -17,7 +17,7 @@ func (ds *DomainSuffix) RuleType() C.RuleType {
} }
func (ds *DomainSuffix) Match(metadata *C.Metadata, helper C.RuleMatchHelper) (bool, string) { func (ds *DomainSuffix) Match(metadata *C.Metadata, helper C.RuleMatchHelper) (bool, string) {
domain := metadata.RuleHost() domain := strings.ToLower(metadata.RuleHost())
return strings.HasSuffix(domain, "."+ds.suffix) || domain == ds.suffix, ds.adapter return strings.HasSuffix(domain, "."+ds.suffix) || domain == ds.suffix, ds.adapter
} }
+2 -1
View File
@@ -18,7 +18,8 @@ func (dw *DomainWildcard) RuleType() C.RuleType {
} }
func (dw *DomainWildcard) Match(metadata *C.Metadata, _ C.RuleMatchHelper) (bool, string) { func (dw *DomainWildcard) Match(metadata *C.Metadata, _ C.RuleMatchHelper) (bool, string) {
return wildcard.Match(dw.pattern, metadata.RuleHost()), dw.adapter domain := strings.ToLower(metadata.RuleHost())
return wildcard.Match(dw.pattern, domain), dw.adapter
} }
func (dw *DomainWildcard) Adapter() string { func (dw *DomainWildcard) Adapter() string {
+3 -1
View File
@@ -2,6 +2,7 @@ package common
import ( import (
"fmt" "fmt"
"strings"
"github.com/metacubex/mihomo/component/geodata" "github.com/metacubex/mihomo/component/geodata"
_ "github.com/metacubex/mihomo/component/geodata/memconservative" _ "github.com/metacubex/mihomo/component/geodata/memconservative"
@@ -23,7 +24,8 @@ func (gs *GEOSITE) RuleType() C.RuleType {
} }
func (gs *GEOSITE) Match(metadata *C.Metadata, helper C.RuleMatchHelper) (bool, string) { func (gs *GEOSITE) Match(metadata *C.Metadata, helper C.RuleMatchHelper) (bool, string) {
return gs.MatchDomain(metadata.RuleHost()), gs.adapter domain := strings.ToLower(metadata.RuleHost())
return gs.MatchDomain(domain), gs.adapter
} }
// MatchDomain implements C.DomainMatcher // MatchDomain implements C.DomainMatcher
+2 -1
View File
@@ -24,7 +24,8 @@ func (d *domainStrategy) Behavior() P.RuleBehavior {
} }
func (d *domainStrategy) Match(metadata *C.Metadata, helper C.RuleMatchHelper) bool { func (d *domainStrategy) Match(metadata *C.Metadata, helper C.RuleMatchHelper) bool {
return d.domainSet != nil && d.domainSet.Has(metadata.RuleHost()) domain := strings.ToLower(metadata.RuleHost())
return d.domainSet != nil && d.domainSet.Has(domain)
} }
func (d *domainStrategy) Count() int { func (d *domainStrategy) Count() int {
+136 -47
View File
@@ -49,20 +49,23 @@ const (
// RelayOption is the common gost relay transport configuration that can wrap any TCP outbound dial. // RelayOption is the common gost relay transport configuration that can wrap any TCP outbound dial.
type RelayOption struct { type RelayOption struct {
Server string `proxy:"server,omitempty"` Server string `proxy:"server,omitempty"`
Port int `proxy:"port,omitempty"` Port int `proxy:"port,omitempty"`
Forward bool `proxy:"forward,omitempty"` Forward bool `proxy:"forward,omitempty"`
TLS bool `proxy:"tls,omitempty"` WS bool `proxy:"ws,omitempty"`
Mux bool `proxy:"mux,omitempty"` WSPath string `proxy:"ws-path,omitempty"`
SNI string `proxy:"sni,omitempty"` WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
Username string `proxy:"username,omitempty"` TLS bool `proxy:"tls,omitempty"`
Password string `proxy:"password,omitempty"` Mux bool `proxy:"mux,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"` SNI string `proxy:"sni,omitempty"`
NameCertVerify string `proxy:"name-cert-verify,omitempty"` Username string `proxy:"username,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"` Password string `proxy:"password,omitempty"`
Certificate string `proxy:"certificate,omitempty"` SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"` NameCertVerify string `proxy:"name-cert-verify,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"` Fingerprint string `proxy:"fingerprint,omitempty"`
Certificate string `proxy:"certificate,omitempty"`
PrivateKey string `proxy:"private-key,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
} }
type relayDialer struct { type relayDialer struct {
@@ -106,12 +109,9 @@ func (d *relayDialer) DialContext(ctx context.Context, network, address string)
if err := writeRelayRequest(conn, relayCmdConnect, targetAddress, relayNetworkTCP, d.option.Username, d.option.Password); err != nil { if err := writeRelayRequest(conn, relayCmdConnect, targetAddress, relayNetworkTCP, d.option.Username, d.option.Password); err != nil {
return nil, err return nil, err
} }
if err := readRelayConnectResponse(conn); err != nil {
return nil, err
}
success = true success = true
return conn, nil return newRelayConn(conn), nil
} }
func (d *relayDialer) ListenPacket(ctx context.Context, network, _ string, rAddrPort netip.AddrPort) (net.PacketConn, error) { func (d *relayDialer) ListenPacket(ctx context.Context, network, _ string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
@@ -142,9 +142,6 @@ func (d *relayDialer) ListenPacket(ctx context.Context, network, _ string, rAddr
if err := writeRelayRequest(conn, relayCmdConnect|relayFlagUDP, targetAddress, relayNetworkUDP, d.option.Username, d.option.Password); err != nil { if err := writeRelayRequest(conn, relayCmdConnect|relayFlagUDP, targetAddress, relayNetworkUDP, d.option.Username, d.option.Password); err != nil {
return nil, err return nil, err
} }
if err := readRelayConnectResponse(conn); err != nil {
return nil, err
}
success = true success = true
return &relayPacketConn{ return &relayPacketConn{
@@ -172,42 +169,76 @@ func (d *relayDialer) dialRelayServer(ctx context.Context, fallbackAddress strin
return nil, err return nil, err
} }
if d.option.TLS { if d.option.WS {
tlsConn, err := mihomoVMess.StreamTLSConn(ctx, conn, &mihomoVMess.TLSConfig{ host, port, err := net.SplitHostPort(relayAddress)
Host: d.serverName(relayAddress), if err != nil {
_ = conn.Close()
return nil, fmt.Errorf("invalid gost relay websocket address %q: %w", relayAddress, err)
}
wsPath := d.option.WSPath
if wsPath == "" {
// Match the default path of GOST's ws/wss/mws/mwss listeners.
wsPath = "/ws"
}
wsConn, err := NewGostWebsocket(ctx, conn, &Option{
Host: host,
Port: port,
Path: wsPath,
Headers: d.option.WSHeaders,
TLS: d.option.TLS,
SNI: d.option.SNI,
SkipCertVerify: d.option.SkipCertVerify, SkipCertVerify: d.option.SkipCertVerify,
NameCertVerify: d.option.NameCertVerify, NameCertVerify: d.option.NameCertVerify,
FingerPrint: d.option.Fingerprint, Fingerprint: d.option.Fingerprint,
Certificate: d.option.Certificate, Certificate: d.option.Certificate,
PrivateKey: d.option.PrivateKey, PrivateKey: d.option.PrivateKey,
ClientFingerprint: d.option.ClientFingerprint, ClientFingerprint: d.option.ClientFingerprint,
Mux: d.option.Mux,
}) })
if err != nil { if err != nil {
_ = conn.Close() _ = conn.Close()
return nil, err return nil, err
} }
conn = tlsConn conn = wsConn
} } else {
if d.option.TLS {
if d.option.Mux { tlsConn, err := mihomoVMess.StreamTLSConn(ctx, conn, &mihomoVMess.TLSConfig{
config := smux.DefaultConfig() Host: d.serverName(relayAddress),
config.KeepAliveDisabled = true SkipCertVerify: d.option.SkipCertVerify,
NameCertVerify: d.option.NameCertVerify,
session, err := smux.Client(conn, config) FingerPrint: d.option.Fingerprint,
if err != nil { Certificate: d.option.Certificate,
_ = conn.Close() PrivateKey: d.option.PrivateKey,
return nil, err ClientFingerprint: d.option.ClientFingerprint,
})
if err != nil {
_ = conn.Close()
return nil, err
}
conn = tlsConn
} }
stream, err := session.OpenStream() if d.option.Mux {
if err != nil { // Keep the default smux v1 and keepalive settings aligned with GOST.
_ = session.Close() config := smux.DefaultConfig()
return nil, err
}
conn = &muxConn{ session, err := smux.Client(conn, config)
Conn: stream, if err != nil {
session: session, _ = conn.Close()
return nil, err
}
stream, err := session.OpenStream()
if err != nil {
_ = session.Close()
return nil, err
}
conn = &muxConn{
Conn: stream,
session: session,
}
} }
} }
@@ -284,13 +315,71 @@ func writeRelayRequest(w io.Writer, command byte, address string, network uint16
return nil return nil
} }
// relayConn strips GOST's CONNECT response on the first read. With the
// default nodelay=false, GOST sends that response together with the first
// bytes received from the target, so waiting inside DialContext would stall.
type relayConn struct {
net.Conn
responseOnce sync.Once
responseErr error
}
func newRelayConn(conn net.Conn) net.Conn {
wrapped := &relayConn{Conn: conn}
if closeWriter, ok := conn.(interface{ CloseWrite() error }); ok {
return &relayConnWithCloseWrite{
relayConn: wrapped,
closeWriter: closeWriter,
}
}
return wrapped
}
func (c *relayConn) Read(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
c.responseOnce.Do(func() {
c.responseErr = readRelayConnectResponse(c.Conn)
})
if c.responseErr != nil {
return 0, c.responseErr
}
return c.Conn.Read(p)
}
// Keep TCP half-close available where the wrapped transport supports it.
type relayConnWithCloseWrite struct {
*relayConn
closeWriter interface{ CloseWrite() error }
}
func (c *relayConnWithCloseWrite) CloseWrite() error {
return c.closeWriter.CloseWrite()
}
type relayPacketConn struct { type relayPacketConn struct {
conn net.Conn conn net.Conn
raddr net.Addr raddr net.Addr
wmu sync.Mutex rmu sync.Mutex
wmu sync.Mutex
responseOnce sync.Once
responseErr error
} }
func (c *relayPacketConn) ReadFrom(p []byte) (int, net.Addr, error) { func (c *relayPacketConn) ReadFrom(p []byte) (int, net.Addr, error) {
c.rmu.Lock()
defer c.rmu.Unlock()
c.responseOnce.Do(func() {
c.responseErr = readRelayConnectResponse(c.conn)
})
if c.responseErr != nil {
return 0, nil, c.responseErr
}
var header [2]byte var header [2]byte
if _, err := io.ReadFull(c.conn, header[:]); err != nil { if _, err := io.ReadFull(c.conn, header[:]); err != nil {
return 0, nil, err return 0, nil, err
+26 -18
View File
@@ -15,18 +15,21 @@ import (
// Option is options of gost websocket // Option is options of gost websocket
type Option struct { type Option struct {
Host string Host string
Port string Port string
Path string Path string
Headers map[string]string Headers map[string]string
TLS bool TLS bool
ECHConfig *ech.Config ECHConfig *ech.Config
SkipCertVerify bool SkipCertVerify bool
NameCertVerify string NameCertVerify string
Fingerprint string Fingerprint string
Certificate string Certificate string
PrivateKey string PrivateKey string
Mux bool SNI string
ClientFingerprint string
Mux bool
MuxKeepAliveDisabled bool
} }
// muxConn is a wrapper around smux.Stream that also closes the session when closed // muxConn is a wrapper around smux.Stream that also closes the session when closed
@@ -54,11 +57,12 @@ func NewGostWebsocket(ctx context.Context, conn net.Conn, option *Option) (net.C
} }
config := &vmess.WebsocketConfig{ config := &vmess.WebsocketConfig{
Host: option.Host, Host: option.Host,
Port: option.Port, Port: option.Port,
Path: option.Path, Path: option.Path,
ECHConfig: option.ECHConfig, ECHConfig: option.ECHConfig,
Headers: header, Headers: header,
ClientFingerprint: option.ClientFingerprint,
} }
var err error var err error
@@ -82,6 +86,9 @@ func NewGostWebsocket(ctx context.Context, conn net.Conn, option *Option) (net.C
if host := config.Headers.Get("Host"); host != "" { if host := config.Headers.Get("Host"); host != "" {
config.TLSConfig.ServerName = host config.TLSConfig.ServerName = host
} }
if option.SNI != "" {
config.TLSConfig.ServerName = option.SNI
}
} }
conn, err = vmess.StreamWebsocketConn(ctx, conn, config) conn, err = vmess.StreamWebsocketConn(ctx, conn, config)
@@ -90,8 +97,9 @@ func NewGostWebsocket(ctx context.Context, conn net.Conn, option *Option) (net.C
} }
if option.Mux { if option.Mux {
// Keep the default smux v1 and keepalive settings aligned with GOST MWS.
config := smux.DefaultConfig() config := smux.DefaultConfig()
config.KeepAliveDisabled = true config.KeepAliveDisabled = option.MuxKeepAliveDisabled
session, err := smux.Client(conn, config) session, err := smux.Client(conn, config)
if err != nil { if err != nil {
+1 -1
View File
@@ -40,7 +40,7 @@ func (d *defragger) Feed(m udpMessage) *udpMessage {
// wtf is this? // wtf is this?
return nil return nil
} }
if m.MsgID != d.msgID { if m.MsgID != d.msgID || int(m.FragCount) != len(d.frags) {
// new message, clear previous state // new message, clear previous state
d.msgID = m.MsgID d.msgID = m.MsgID
d.frags = make([]*udpMessage, m.FragCount) d.frags = make([]*udpMessage, m.FragCount)
+15
View File
@@ -302,3 +302,18 @@ func Test_defragger_Feed(t *testing.T) {
}) })
} }
} }
func Test_defragger_FeedFragCountChange(t *testing.T) {
var d defragger
if got := d.Feed(udpMessage{MsgID: 0, FragID: 0, FragCount: 2, Data: []byte("ab")}); got != nil {
t.Fatalf("unexpected early reassembly: %v", got)
}
got := d.Feed(udpMessage{MsgID: 0, FragID: 1, FragCount: 2, Data: []byte("cd")})
if got == nil || string(got.Data) != "abcd" {
t.Fatalf("got %v, want abcd", got)
}
d.Feed(udpMessage{MsgID: 7, FragID: 0, FragCount: 2, Data: []byte("1")})
if got := d.Feed(udpMessage{MsgID: 7, FragID: 3, FragCount: 4, Data: []byte("4")}); got != nil {
t.Fatalf("expected nil on mismatched FragCount reset, got %v", got)
}
}
-5
View File
@@ -190,11 +190,6 @@ func uTLSHandshakeFunc(config *tls.Config, clientFingerprint string, version int
return err return err
} }
} }
if version == 2 { // ShadowTLS v2 not work with X25519MLKEM768
if err := tlsC.BuildRemovedX25519MLKEM768HandshakeState(tlsConn); err != nil {
return err
}
}
return tlsConn.HandshakeContext(ctx) return tlsConn.HandshakeContext(ctx)
} }
return tlsC.Client(conn, tlsConfig).HandshakeContext(ctx) return tlsC.Client(conn, tlsConfig).HandshakeContext(ctx)
+1
View File
@@ -32,6 +32,7 @@ func TestServer(t *testing.T) {
}{ }{
{name: "v1", version: 1}, {name: "v1", version: 1},
{name: "v2", version: 2}, {name: "v2", version: 2},
{name: "v2-utls", version: 2, fingerprint: "chrome"},
{name: "v2-utls-websocket", version: 2, fingerprint: "chrome", alpn: WsALPN}, {name: "v2-utls-websocket", version: 2, fingerprint: "chrome", alpn: WsALPN},
{name: "v3", version: 3}, {name: "v3", version: 3},
{name: "v3-utls", version: 3, fingerprint: "chrome"}, {name: "v3-utls", version: 3, fingerprint: "chrome"},
+7 -7
View File
@@ -1,6 +1,7 @@
package shadowtls package shadowtls
import ( import (
"bufio"
"bytes" "bytes"
"crypto/hmac" "crypto/hmac"
"crypto/sha1" "crypto/sha1"
@@ -17,19 +18,18 @@ import (
type hashReadConn struct { type hashReadConn struct {
net.Conn net.Conn
hmac hash.Hash reader *bufio.Reader
hmac hash.Hash
} }
func newHashReadConn(conn net.Conn, password string) *hashReadConn { func newHashReadConn(conn net.Conn, password string) *hashReadConn {
return &hashReadConn{Conn: conn, hmac: hmac.New(sha1.New, []byte(password))} readHMAC := hmac.New(sha1.New, []byte(password))
reader := bufio.NewReaderSize(io.TeeReader(conn, readHMAC), 16*1024)
return &hashReadConn{Conn: conn, reader: reader, hmac: readHMAC}
} }
func (c *hashReadConn) Read(p []byte) (int, error) { func (c *hashReadConn) Read(p []byte) (int, error) {
n, err := c.Conn.Read(p) return c.reader.Read(p)
if n > 0 {
_, _ = c.hmac.Write(p[:n])
}
return n, err
} }
func (c *hashReadConn) Sum() []byte { func (c *hashReadConn) Sum() []byte {
+23 -9
View File
@@ -39,6 +39,9 @@ const (
CommandError byte = 2 CommandError byte = 2
Version byte = 1 Version byte = 1
// MaxClientIDLength is the maximum ClientID length encoded in a Snell request header.
MaxClientIDLength = 255
) )
var endSignal = []byte{} var endSignal = []byte{}
@@ -97,11 +100,13 @@ func (s *Snell) ReadReply() error {
return fmt.Errorf("server reported code: %d, message: %s", errcode, string(msg)) return fmt.Errorf("server reported code: %d, message: %s", errcode, string(msg))
} }
func WriteHeader(conn net.Conn, host string, port uint, version int) error { func WriteHeader(conn net.Conn, host string, port uint16, version int, reuse bool, clientID []byte) error {
return WriteHeaderWithReuse(conn, host, port, version, false) if len(clientID) > MaxClientIDLength {
} return errors.New("snell client ID too long")
}
func WriteHeaderWithReuse(conn net.Conn, host string, port uint, version int, reuse bool) error { if len(clientID) > 0 && version != Version6 {
return errors.New("snell client ID is only supported on version 6")
}
buf := pool.GetBuffer() buf := pool.GetBuffer()
defer pool.PutBuffer(buf) defer pool.PutBuffer(buf)
buf.WriteByte(Version) buf.WriteByte(Version)
@@ -112,7 +117,8 @@ func WriteHeaderWithReuse(conn net.Conn, host string, port uint, version int, re
} }
// clientID length & id // clientID length & id
buf.WriteByte(0) buf.WriteByte(uint8(len(clientID)))
buf.Write(clientID)
// host & port // host & port
buf.WriteByte(uint8(len(host))) buf.WriteByte(uint8(len(host)))
@@ -126,13 +132,21 @@ func WriteHeaderWithReuse(conn net.Conn, host string, port uint, version int, re
return nil return nil
} }
func WriteUDPHeader(conn net.Conn, version int) error { func WriteUDPHeader(conn net.Conn, version int, clientID []byte) error {
if version < Version3 { if version < Version3 {
return errors.New("unsupport UDP version") return errors.New("unsupport UDP version")
} }
if len(clientID) > MaxClientIDLength {
return errors.New("snell client ID too long")
}
if len(clientID) > 0 && version != Version6 {
return errors.New("snell client ID is only supported on version 6")
}
// version, command, clientID length // version, command, client ID length, and optional per-user identity
_, err := conn.Write([]byte{Version, CommandUDP, 0x00}) header := []byte{Version, CommandUDP, uint8(len(clientID))}
header = append(header, clientID...)
_, err := conn.Write(header)
return err return err
} }
+53 -1
View File
@@ -301,7 +301,7 @@ func TestSnellWriteHeaderConnectCommand(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
conn := &bufferConn{} conn := &bufferConn{}
if err := WriteHeaderWithReuse(conn, "example.com", 443, tt.version, tt.reuse); err != nil { if err := WriteHeader(conn, "example.com", 443, tt.version, tt.reuse, nil); err != nil {
t.Fatal(err) t.Fatal(err)
} }
data := conn.Bytes() data := conn.Bytes()
@@ -315,6 +315,58 @@ func TestSnellWriteHeaderConnectCommand(t *testing.T) {
} }
} }
func TestSnellClientIDValidation(t *testing.T) {
maxID := bytes.Repeat([]byte{'k'}, MaxClientIDLength)
tcpConn := &bufferConn{}
if err := WriteHeader(tcpConn, "example.com", 443, Version6, false, maxID); err != nil {
t.Fatalf("TCP header rejected a %d-byte client ID: %v", MaxClientIDLength, err)
}
if got := tcpConn.Bytes()[2]; got != 0xff {
t.Fatalf("TCP client ID length = %d, want 255", got)
}
udpConn := &bufferConn{}
if err := WriteUDPHeader(udpConn, Version6, maxID); err != nil {
t.Fatalf("UDP header rejected a %d-byte client ID: %v", MaxClientIDLength, err)
}
if got := udpConn.Bytes()[2]; got != 0xff {
t.Fatalf("UDP client ID length = %d, want 255", got)
}
oversizedID := make([]byte, 256)
if err := WriteHeader(&bufferConn{}, "example.com", 443, Version6, false, oversizedID); err == nil {
t.Fatal("TCP header accepted a client ID longer than 255 bytes")
}
if err := WriteUDPHeader(&bufferConn{}, Version6, oversizedID); err == nil {
t.Fatal("UDP header accepted a client ID longer than 255 bytes")
}
clientID := []byte("alice-key")
if err := WriteHeader(&bufferConn{}, "example.com", 443, Version4, false, clientID); err == nil {
t.Fatal("TCP header accepted a client ID for Snell v4")
}
if err := WriteUDPHeader(&bufferConn{}, Version4, clientID); err == nil {
t.Fatal("UDP header accepted a client ID for Snell v4")
}
}
func TestSnellEmptyClientIDRemainsCompatible(t *testing.T) {
tcpConn := &bufferConn{}
if err := WriteHeader(tcpConn, "example.com", 443, Version6, true, nil); err != nil {
t.Fatal(err)
}
if got := tcpConn.Bytes()[2]; got != 0 {
t.Fatalf("legacy TCP client ID length = %d, want 0", got)
}
udpConn := &bufferConn{}
if err := WriteUDPHeader(udpConn, Version6, nil); err != nil {
t.Fatal(err)
}
if want := []byte{Version, CommandUDP, 0}; !bytes.Equal(udpConn.Bytes(), want) {
t.Fatalf("legacy UDP header = %x, want %x", udpConn.Bytes(), want)
}
}
func TestSnellReadReplyPreservesBufferedPayload(t *testing.T) { func TestSnellReadReplyPreservesBufferedPayload(t *testing.T) {
conn := &Snell{Conn: &bufferConn{}} conn := &Snell{Conn: &bufferConn{}}
conn.Conn.(*bufferConn).Write([]byte{CommandTunnel, 'o', 'k'}) conn.Conn.(*bufferConn).Write([]byte{CommandTunnel, 'o', 'k'})
+38
View File
@@ -202,3 +202,41 @@ func TestValidateV6PSK(t *testing.T) {
require.Error(t, ValidateV6PSK(make([]byte, 256))) require.Error(t, ValidateV6PSK(make([]byte, 256)))
require.NoError(t, ValidateV6PSK([]byte(v6TestPSK))) require.NoError(t, ValidateV6PSK([]byte(v6TestPSK)))
} }
func TestSnellV6ClientIDHeaders(t *testing.T) {
clientID := []byte("alice-key")
for _, tt := range []struct {
name string
reuse bool
cmd byte
}{
{name: "connect", cmd: CommandConnect},
{name: "reuse", reuse: true, cmd: CommandConnectV2},
} {
t.Run(tt.name, func(t *testing.T) {
conn := &bufferConn{}
if err := WriteHeader(conn, "example.com", 443, Version6, tt.reuse, clientID); err != nil {
t.Fatal(err)
}
want := []byte{Version, tt.cmd, byte(len(clientID))}
want = append(want, clientID...)
want = append(want, byte(len("example.com")))
want = append(want, "example.com"...)
want = append(want, 0x01, 0xbb)
if !bytes.Equal(conn.Bytes(), want) {
t.Fatalf("TCP header = %x, want %x", conn.Bytes(), want)
}
})
}
udpConn := &bufferConn{}
if err := WriteUDPHeader(udpConn, Version6, clientID); err != nil {
t.Fatal(err)
}
wantUDP := append([]byte{Version, CommandUDP, byte(len(clientID))}, clientID...)
if !bytes.Equal(udpConn.Bytes(), wantUDP) {
t.Fatalf("UDP header = %x, want %x", udpConn.Bytes(), wantUDP)
}
}
+10 -5
View File
@@ -542,8 +542,10 @@ func decodeXray0rtt(requestHeader http.Header) []byte {
return nil return nil
} }
var ErrNotWebSocketUpgrade = errors.New("not a websocket upgrade request")
func IsWebSocketUpgrade(r *http.Request) bool { func IsWebSocketUpgrade(r *http.Request) bool {
return r.Header.Get("Upgrade") == "websocket" return strings.EqualFold(r.Header.Get("Upgrade"), "websocket")
} }
func IsV2rayHttpUpdate(r *http.Request) bool { func IsV2rayHttpUpdate(r *http.Request) bool {
@@ -554,6 +556,13 @@ func StreamUpgradedWebsocketConn(w http.ResponseWriter, r *http.Request) (net.Co
var conn net.Conn var conn net.Conn
var rw *bufio.ReadWriter var rw *bufio.ReadWriter
var err error var err error
if !IsWebSocketUpgrade(r) {
return nil, ErrNotWebSocketUpgrade
}
hijacker, canHijack := w.(http.Hijacker)
if !canHijack {
return nil, errors.New("invalid connection, maybe HTTP/2")
}
isRaw := IsV2rayHttpUpdate(r) isRaw := IsV2rayHttpUpdate(r)
w.Header().Set("Connection", "upgrade") w.Header().Set("Connection", "upgrade")
w.Header().Set("Upgrade", "websocket") w.Header().Set("Upgrade", "websocket")
@@ -567,10 +576,6 @@ func StreamUpgradedWebsocketConn(w http.ResponseWriter, r *http.Request) (net.Co
return nil, fmt.Errorf("flush response: %w", err) return nil, fmt.Errorf("flush response: %w", err)
} }
} }
hijacker, canHijack := w.(http.Hijacker)
if !canHijack {
return nil, errors.New("invalid connection, maybe HTTP/2")
}
conn, rw, err = hijacker.Hijack() conn, rw, err = hijacker.Hijack()
if err != nil { if err != nil {
return nil, fmt.Errorf("hijack failed: %w", err) return nil, fmt.Errorf("hijack failed: %w", err)
+5 -1
View File
@@ -18,7 +18,11 @@ func ChromeVersion() int {
var timeStart int64 = time.Date(2026, 1, 13, 0, 0, 0, 0, time.UTC).Unix() / 86400 var timeStart int64 = time.Date(2026, 1, 13, 0, 0, 0, 0, time.UTC).Unix() / 86400
var timeCurrent int64 = time.Now().Unix() / 86400 var timeCurrent int64 = time.Now().Unix() / 86400
var timeDiff int = int((timeCurrent - timeStart - 35)) - int(math.Floor(math.Pow(randv2.Float64(), 2)*105)) var timeDiff int = int((timeCurrent - timeStart - 35)) - int(math.Floor(math.Pow(randv2.Float64(), 2)*105))
return startVersion + (timeDiff / 35) // It's 31.15 currently. var version int = startVersion + (timeDiff / 35) // It's 31.15 currently.
if version < startVersion {
return startVersion
}
return version
} }
var safariMinorMap [25]int = [25]int{0, 0, 0, 1, 1, var safariMinorMap [25]int = [25]int{0, 0, 0, 1, 1,
+3 -2
View File
@@ -155,7 +155,7 @@ func (c *PacketUpWriter) Close() error {
return nil return nil
} }
func NewTransport(dialRaw DialRawFunc, wrapTLS WrapTLSFunc, dialQUIC DialQUICFunc, alpn []string, keepAlivePeriod time.Duration) http.RoundTripper { func NewTransport(dialRaw DialRawFunc, wrapTLS WrapTLSFunc, dialQUIC DialQUICFunc, alpn []string, keepAlivePeriod time.Duration, h2MaxReceiveBufferPerStream int) http.RoundTripper {
if len(alpn) == 1 && alpn[0] == "h3" { // `alpn: [h3]` means using h3 mode if len(alpn) == 1 && alpn[0] == "h3" { // `alpn: [h3]` means using h3 mode
if keepAlivePeriod == 0 { if keepAlivePeriod == 0 {
keepAlivePeriod = QuicgoH3KeepAlivePeriod keepAlivePeriod = QuicgoH3KeepAlivePeriod
@@ -223,7 +223,8 @@ func NewTransport(dialRaw DialRawFunc, wrapTLS WrapTLSFunc, dialQUIC DialQUICFun
IdleConnTimeout: ConnIdleTimeout, IdleConnTimeout: ConnIdleTimeout,
Protocols: protocols, Protocols: protocols,
HTTP2: &http.HTTP2Config{ HTTP2: &http.HTTP2Config{
SendPingTimeout: keepAlivePeriod, MaxReceiveBufferPerStream: h2MaxReceiveBufferPerStream,
SendPingTimeout: keepAlivePeriod,
}, },
} }
} }
+5 -2
View File
@@ -139,7 +139,7 @@ func (entry *reuseEntry) release() {
} }
} }
func (m *ReuseManager) pickLocked() *reuseEntry { func (m *ReuseManager) pickLocked(now time.Time) *reuseEntry {
var best *reuseEntry var best *reuseEntry
for _, entry := range m.entries { for _, entry := range m.entries {
if entry.isClosed() { if entry.isClosed() {
@@ -151,6 +151,9 @@ func (m *ReuseManager) pickLocked() *reuseEntry {
if entry.maxReuseTimes > 0 && entry.reuseCount.Load() >= entry.maxReuseTimes { if entry.maxReuseTimes > 0 && entry.reuseCount.Load() >= entry.maxReuseTimes {
continue continue
} }
if !entry.unreusableAt.IsZero() && now.After(entry.unreusableAt) {
continue
}
if m.maxConcurrency > 0 && int(entry.openUsage.Load()) >= m.maxConcurrency { if m.maxConcurrency > 0 && int(entry.openUsage.Load()) >= m.maxConcurrency {
continue continue
} }
@@ -200,7 +203,7 @@ func (m *ReuseManager) GetTransport() http.RoundTripper {
var entry *reuseEntry var entry *reuseEntry
if !m.shouldCreateLocked() { if !m.shouldCreateLocked() {
entry = m.pickLocked() entry = m.pickLocked(now)
} }
reused := entry != nil reused := entry != nil
+32
View File
@@ -160,6 +160,38 @@ func TestManagerRotateOnReusableSecs(t *testing.T) {
manager.Close() manager.Close()
} }
func TestManagerSkipExpiredBusyEntry(t *testing.T) {
for name, cfg := range map[string]*ReuseConfig{
"max-concurrency": {MaxConcurrency: "16", HMaxReusableSecs: "1"},
"max-connections": {MaxConnections: "1", HMaxReusableSecs: "1"},
} {
t.Run(name, func(t *testing.T) {
var created atomic.Int64
manager, err := NewReuseManager(cfg, makeTestTransportFactory(&created))
if err != nil {
t.Fatal(err)
}
transport1 := manager.GetTransport().(*ReuseTransport)
id1 := transportID(transport1)
time.Sleep(1100 * time.Millisecond)
transport2 := manager.GetTransport().(*ReuseTransport)
id2 := transportID(transport2)
if id1 == id2 {
t.Fatalf("expected new transport after reusable timeout while busy, got same id %d", id1)
}
transport1.Close()
transport2.Close()
manager.Close()
})
}
}
func TestManagerRotateOnConnReuseLimit(t *testing.T) { func TestManagerRotateOnConnReuseLimit(t *testing.T) {
var created atomic.Int64 var created atomic.Int64
+74
View File
@@ -0,0 +1,74 @@
package xhttp
import (
"context"
"io"
"net"
"testing"
"time"
"github.com/metacubex/http"
"github.com/metacubex/http/http2"
)
// Read the actual client SETTINGS, rather than just inspecting the Go field:
// a value silently rejected by the HTTP/2 implementation would fail this test.
func TestH2ReceiveWindowSettings(t *testing.T) {
for _, tc := range []struct {
name string
configured int
want uint32
}{
{"default", 0, 4 << 20},
{"8MiB", 8 << 20, 8 << 20},
{"16MiB", 16 << 20, 16 << 20},
} {
t.Run(tc.name, func(t *testing.T) {
client, server := net.Pipe()
defer client.Close()
defer server.Close()
server.SetDeadline(time.Now().Add(5 * time.Second))
rt := NewTransport(func(context.Context) (net.Conn, error) { return client, nil },
func(_ context.Context, c net.Conn, _ bool) (net.Conn, error) { return c, nil },
nil, []string{"h2"}, -1, tc.configured).(*http.Transport)
defer rt.CloseIdleConnections()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
done := make(chan struct{})
go func() {
defer close(done)
req, _ := http.NewRequestWithContext(ctx, "GET", "https://example.test/", nil)
resp, _ := rt.RoundTrip(req)
if resp != nil {
resp.Body.Close()
}
}()
preface := make([]byte, len(http2.ClientPreface))
if _, err := io.ReadFull(server, preface); err != nil {
t.Fatal(err)
}
if string(preface) != http2.ClientPreface {
t.Fatal("missing HTTP/2 client preface")
}
frame, err := http2.NewFramer(server, server).ReadFrame()
if err != nil {
t.Fatal(err)
}
settings, ok := frame.(*http2.SettingsFrame)
if !ok {
t.Fatalf("first frame is %T", frame)
}
got, ok := settings.Value(http2.SettingInitialWindowSize)
if !ok || got != tc.want {
t.Fatalf("INITIAL_WINDOW_SIZE = %d (present %v), want %d", got, ok, tc.want)
}
cancel()
client.Close()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("request did not stop")
}
})
}
}
+10 -3
View File
@@ -203,12 +203,16 @@ func Listeners() map[string]C.InboundListener {
} }
// UpdateRules handle update rules // UpdateRules handle update rules
func UpdateRules(newRules []C.Rule, newSubRule map[string][]C.Rule, rp map[string]P.RuleProvider) { func UpdateRules(newRules []C.Rule, newSubRule map[string][]C.Rule, newRuleProviders map[string]P.RuleProvider) (oldRules []C.Rule, oldSubRule map[string][]C.Rule, oldRuleProviders map[string]P.RuleProvider) {
configMux.Lock() configMux.Lock()
oldRules = rules
oldSubRule = subRules
oldRuleProviders = ruleProviders
rules = newRules rules = newRules
ruleProviders = rp ruleProviders = newRuleProviders
subRules = newSubRule subRules = newSubRule
configMux.Unlock() configMux.Unlock()
return
} }
// Proxies return all proxies // Proxies return all proxies
@@ -227,11 +231,14 @@ func RuleProviders() map[string]P.RuleProvider {
} }
// UpdateProxies handle update proxies // UpdateProxies handle update proxies
func UpdateProxies(newProxies map[string]C.Proxy, newProviders map[string]P.ProxyProvider) { func UpdateProxies(newProxies map[string]C.Proxy, newProviders map[string]P.ProxyProvider) (oldProxies map[string]C.Proxy, oldProviders map[string]P.ProxyProvider) {
configMux.Lock() configMux.Lock()
oldProxies = proxies
oldProviders = providers
proxies = newProxies proxies = newProxies
providers = newProviders providers = newProviders
configMux.Unlock() configMux.Unlock()
return
} }
func UpdateListeners(newListeners map[string]C.InboundListener) { func UpdateListeners(newListeners map[string]C.InboundListener) {