Compare commits

...
18 Commits
Author SHA1 Message Date
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
35 changed files with 458 additions and 163 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
}, },
+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
+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))
} }
+8 -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
+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
+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 {
-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)
}
}
+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,
+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
+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) {