mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-11-24 19:28:32 +00:00
Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c7af25cee0 | ||
|
|
fc3bd70369 | ||
|
|
e13f0f187e | ||
|
|
100ff73ae7 | ||
|
|
024152115c | ||
|
|
2be2f08909 | ||
|
|
0976eb6ac1 | ||
|
|
7907040f27 | ||
|
|
3c0d10a503 | ||
|
|
184857ce21 | ||
|
|
7e73a9448b | ||
|
|
a9e5c456e3 | ||
|
|
4c57a4a600 | ||
|
|
d569d9eba7 | ||
|
|
12b81d465a |
No files matched your search
@@ -18,22 +18,29 @@ type GostRelay struct {
|
||||
|
||||
type GostRelayOption struct {
|
||||
BasicOption
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
Forward bool `proxy:"forward,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
TLS bool `proxy:"tls,omitempty"`
|
||||
Mux bool `proxy:"mux,omitempty"`
|
||||
SNI string `proxy:"sni,omitempty"`
|
||||
Username string `proxy:"username,omitempty"`
|
||||
Password string `proxy:"password,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
|
||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||
Certificate string `proxy:"certificate,omitempty"`
|
||||
PrivateKey string `proxy:"private-key,omitempty"`
|
||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
Forward bool `proxy:"forward,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
WS bool `proxy:"ws,omitempty"`
|
||||
WSOpts GostRelayWSOptions `proxy:"ws-opts,omitempty"`
|
||||
TLS bool `proxy:"tls,omitempty"`
|
||||
Mux bool `proxy:"mux,omitempty"`
|
||||
SNI string `proxy:"sni,omitempty"`
|
||||
Username string `proxy:"username,omitempty"`
|
||||
Password string `proxy:"password,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
|
||||
Fingerprint string `proxy:"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) {
|
||||
@@ -95,6 +102,9 @@ func NewGostRelay(option GostRelayOption) (*GostRelay, error) {
|
||||
Server: option.Server,
|
||||
Port: option.Port,
|
||||
Forward: option.Forward,
|
||||
WS: option.WS,
|
||||
WSPath: option.WSOpts.Path,
|
||||
WSHeaders: option.WSOpts.Headers,
|
||||
TLS: option.TLS,
|
||||
Mux: option.Mux,
|
||||
SNI: option.SNI,
|
||||
|
||||
@@ -373,10 +373,11 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
}
|
||||
obfsMode = opts.Mode
|
||||
gostOption = &gost.Option{
|
||||
Host: opts.Host,
|
||||
Path: opts.Path,
|
||||
Headers: opts.Headers,
|
||||
Mux: opts.Mux,
|
||||
Host: opts.Host,
|
||||
Path: opts.Path,
|
||||
Headers: opts.Headers,
|
||||
Mux: opts.Mux,
|
||||
MuxKeepAliveDisabled: true,
|
||||
}
|
||||
|
||||
if opts.TLS {
|
||||
|
||||
@@ -20,6 +20,7 @@ type Snell struct {
|
||||
*Base
|
||||
option *SnellOption
|
||||
psk []byte
|
||||
userKey []byte
|
||||
pool *snell.Pool
|
||||
obfsOption *simpleObfsOption
|
||||
shadowTLSOption *shadowtls.ShadowTLSOption
|
||||
@@ -36,6 +37,7 @@ type SnellOption struct {
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
Psk string `proxy:"psk"`
|
||||
UserKey string `proxy:"userkey,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
Version int `proxy:"version,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 {
|
||||
err = snell.WriteUDPHeader(c, s.version)
|
||||
err = snell.WriteUDPHeader(c, s.version, s.userKey)
|
||||
if err == nil && s.version >= snell.Version4 {
|
||||
if sc, ok := c.(*snell.Snell); ok {
|
||||
err = sc.ReadReply()
|
||||
@@ -99,7 +101,7 @@ func (s *Snell) writeHeaderContext(ctx context.Context, c net.Conn, metadata *C.
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -254,6 +256,13 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
||||
// Snell v5 servers are backward-compatible with v4 clients.
|
||||
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 ||
|
||||
((option.Version == snell.Version4 || option.Version == snell.Version6) && option.Reuse)
|
||||
var v6Mode snell.V6Mode
|
||||
@@ -299,6 +308,7 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
||||
}),
|
||||
option: &option,
|
||||
psk: psk,
|
||||
userKey: userKey,
|
||||
obfsOption: obfsOption,
|
||||
shadowTLSOption: shadowTLSOpt,
|
||||
restlsConfig: restlsConfig,
|
||||
|
||||
@@ -27,7 +27,7 @@ func NewSubscriptionInfo(userinfo string) (si *SubscriptionInfo) {
|
||||
|
||||
intValue, err := parseValue(value)
|
||||
if err != nil {
|
||||
log.Warnln("[Provider] get subscription-userinfo: %e", err)
|
||||
log.Warnln("[Provider] get subscription-userinfo: %s", err)
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
@@ -190,7 +190,7 @@ func resolveProcessNameByProcSearch(inode, uid uint32) (string, error) {
|
||||
|
||||
info, err := f.Info()
|
||||
if err != nil {
|
||||
return "", err
|
||||
continue
|
||||
}
|
||||
if info.Sys().(*syscall.Stat_t).Uid != uid {
|
||||
continue
|
||||
|
||||
@@ -63,7 +63,6 @@ var randomFingerprint = once.OnceValue(func() UClientHelloID {
|
||||
chooser, _ := weightedrand.NewChooser(
|
||||
weightedrand.NewChoice("chrome", 6),
|
||||
weightedrand.NewChoice("safari", 3),
|
||||
weightedrand.NewChoice("ios", 2),
|
||||
weightedrand.NewChoice("firefox", 1),
|
||||
)
|
||||
initClient := chooser.Pick()
|
||||
@@ -104,6 +103,8 @@ func init() {
|
||||
weights := utls.DefaultWeights
|
||||
weights.TLSVersMax_Set_VersionTLS13 = 1
|
||||
weights.FirstKeyShare_Set_CurveP256 = 0
|
||||
weights.CurveIDs_Append_X25519 = 1
|
||||
weights.KeyShare_Append_RandomGroups = 1
|
||||
randomized := utls.HelloRandomized
|
||||
randomized.Seed, _ = utls.NewPRNGSeed()
|
||||
randomized.Weights = &weights
|
||||
|
||||
+5
-2
@@ -168,6 +168,7 @@ type DNS struct {
|
||||
FakeIPPool6 *fakeip.Pool
|
||||
FakeIPSkipper *fakeip.Skipper
|
||||
FakeIPTTL int
|
||||
FakeIPDisableMapping bool
|
||||
NameServerPolicy []dns.Policy
|
||||
ProxyServerNameserver []dns.NameServer
|
||||
ProxyServerPolicy []dns.Policy
|
||||
@@ -237,6 +238,7 @@ type RawDNS struct {
|
||||
FakeIPRange6 string `yaml:"fake-ip-range6" json:"fake-ip-range6"`
|
||||
FakeIPFilter []string `yaml:"fake-ip-filter" json:"fake-ip-filter"`
|
||||
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"`
|
||||
DefaultNameserver []string `yaml:"default-nameserver" json:"default-nameserver"`
|
||||
CacheAlgorithm string `yaml:"cache-algorithm" json:"cache-algorithm"`
|
||||
@@ -529,8 +531,8 @@ func DefaultRawConfig() *RawConfig {
|
||||
"tls://223.5.5.5:853",
|
||||
},
|
||||
FakeIPFilter: []string{
|
||||
"dns.msftnsci.com",
|
||||
"www.msftnsci.com",
|
||||
"dns.msftncsi.com",
|
||||
"www.msftncsi.com",
|
||||
"www.msftconnecttest.com",
|
||||
},
|
||||
FakeIPFilterMode: C.FilterBlackList,
|
||||
@@ -1538,6 +1540,7 @@ func parseDNS(rawCfg *RawConfig, ruleProviders map[string]P.RuleProvider) (*DNS,
|
||||
|
||||
dnsCfg.FakeIPSkipper = skipper
|
||||
dnsCfg.FakeIPTTL = cfg.FakeIPTTL
|
||||
dnsCfg.FakeIPDisableMapping = cfg.FakeIPDisableMapping
|
||||
|
||||
if dnsCfg.FakeIPRange.IsValid() {
|
||||
pool, err := fakeip.New(fakeip.Options{
|
||||
|
||||
+18
-15
@@ -10,14 +10,15 @@ import (
|
||||
)
|
||||
|
||||
type ResolverEnhancer struct {
|
||||
ipv6 bool
|
||||
mode C.DNSMode
|
||||
fakeIPPool *fakeip.Pool
|
||||
fakeIPPool6 *fakeip.Pool
|
||||
fakeIPSkipper *fakeip.Skipper
|
||||
fakeIPTTL int
|
||||
mapping *lru.LruCache[netip.Addr, string]
|
||||
useHosts bool
|
||||
ipv6 bool
|
||||
mode C.DNSMode
|
||||
fakeIPPool *fakeip.Pool
|
||||
fakeIPPool6 *fakeip.Pool
|
||||
fakeIPSkipper *fakeip.Skipper
|
||||
fakeIPTTL int
|
||||
fakeIPDisableMapping bool
|
||||
mapping *lru.LruCache[netip.Addr, string]
|
||||
useHosts bool
|
||||
}
|
||||
|
||||
func (h *ResolverEnhancer) FakeIPEnabled() bool {
|
||||
@@ -159,13 +160,14 @@ func (h *ResolverEnhancer) StoreFakePoolState() {
|
||||
}
|
||||
|
||||
type EnhancerConfig struct {
|
||||
IPv6 bool
|
||||
EnhancedMode C.DNSMode
|
||||
FakeIPPool *fakeip.Pool
|
||||
FakeIPPool6 *fakeip.Pool
|
||||
FakeIPSkipper *fakeip.Skipper
|
||||
FakeIPTTL int
|
||||
UseHosts bool
|
||||
IPv6 bool
|
||||
EnhancedMode C.DNSMode
|
||||
FakeIPPool *fakeip.Pool
|
||||
FakeIPPool6 *fakeip.Pool
|
||||
FakeIPSkipper *fakeip.Skipper
|
||||
FakeIPTTL int
|
||||
FakeIPDisableMapping bool
|
||||
UseHosts bool
|
||||
}
|
||||
|
||||
func NewEnhancer(cfg EnhancerConfig) *ResolverEnhancer {
|
||||
@@ -182,6 +184,7 @@ func NewEnhancer(cfg EnhancerConfig) *ResolverEnhancer {
|
||||
}
|
||||
e.fakeIPSkipper = cfg.FakeIPSkipper
|
||||
e.fakeIPTTL = cfg.FakeIPTTL
|
||||
e.fakeIPDisableMapping = cfg.FakeIPDisableMapping
|
||||
if e.fakeIPTTL < 1 {
|
||||
e.fakeIPTTL = 1
|
||||
}
|
||||
|
||||
+3
-1
@@ -237,11 +237,13 @@ func newHandler(resolver resolver.Resolver, mapper *ResolverEnhancer) handler {
|
||||
middlewares = append(middlewares, withHosts(mapper.mapping))
|
||||
}
|
||||
|
||||
disableMapping := false
|
||||
if mapper.mode == C.DNSFakeIP {
|
||||
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))
|
||||
}
|
||||
|
||||
|
||||
+8
-2
@@ -414,6 +414,7 @@ proxies: # socks5
|
||||
server: server
|
||||
port: 44046
|
||||
psk: yourpsk
|
||||
# userkey: per-user-client-id # v6 only; sent as the Snell ClientID
|
||||
# version: 4 # support 1/2/3/4/5/6
|
||||
# udp: true # support UDP on version 3/4/5/6
|
||||
# reuse: false # v4/5/6 only
|
||||
@@ -593,8 +594,13 @@ proxies: # socks5
|
||||
port: 443
|
||||
udp: true
|
||||
tls: true
|
||||
# mux: true # relay+mtls when tls is also true
|
||||
# sni: relay.example.com
|
||||
# mux: true # with tls enabled and ws disabled, this selects relay+mtls
|
||||
# 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
|
||||
# password: pass
|
||||
# client-fingerprint: chrome
|
||||
|
||||
@@ -7,7 +7,7 @@ require (
|
||||
github.com/coreos/go-iptables v0.8.0
|
||||
github.com/dlclark/regexp2 v1.12.0
|
||||
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/gofrs/uuid/v5 v5.4.0
|
||||
github.com/golang/snappy v1.0.0
|
||||
@@ -37,7 +37,7 @@ require (
|
||||
github.com/metacubex/sing v0.5.9
|
||||
github.com/metacubex/sing-mux v0.3.12
|
||||
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-tun v0.4.29
|
||||
github.com/metacubex/sing-vmess v0.2.5
|
||||
|
||||
@@ -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/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/enfein/mieru/v3 v3.39.0 h1:22WJN9i7I4FrY1cTAVp5KfKOFm4sWrXVOXhqf5fkdr8=
|
||||
github.com/enfein/mieru/v3 v3.39.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
|
||||
github.com/enfein/mieru/v3 v3.40.0 h1:J4M+g7YWi4eU2rYKPvEE3IdY8VB8Kw4xuybLCf+h6PU=
|
||||
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/go.mod h1:hkIFzoiIPZYxdFOOLyDho59b7SrDfo+w3h+yWdlg45I=
|
||||
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-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-shadowsocks v0.2.13 h1:PKmInHy9+4nY3FLhmKcWdASUBo9WZ/KrSPWjNpGaUTQ=
|
||||
github.com/metacubex/sing-shadowsocks v0.2.13/go.mod h1:2e5EIaw0rxKrm1YTRmiMnDulwbGxH9hAFlrwQLQMQkU=
|
||||
github.com/metacubex/sing-shadowsocks v0.2.14 h1:P9HUtAPRVa24sB0dHwwTUkaEu5V0A8FGXJ35zdNAbN4=
|
||||
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/go.mod h1:vOEbfKC60txi0ca+yUlqEwOGc3Obl6cnSgx9Gf45KjE=
|
||||
github.com/metacubex/sing-tun v0.4.29 h1:KIULEuW0iFXxLegOgrW8orq5Sx4TCBBhwo6j8+CIFBs=
|
||||
|
||||
@@ -265,13 +265,14 @@ func updateDNS(c *config.DNS, generalIPv6 bool) {
|
||||
CacheMaxSize: c.CacheMaxSize,
|
||||
})
|
||||
m := dns.NewEnhancer(dns.EnhancerConfig{
|
||||
IPv6: ipv6,
|
||||
EnhancedMode: c.EnhancedMode,
|
||||
FakeIPPool: c.FakeIPPool,
|
||||
FakeIPPool6: c.FakeIPPool6,
|
||||
FakeIPSkipper: c.FakeIPSkipper,
|
||||
FakeIPTTL: c.FakeIPTTL,
|
||||
UseHosts: c.UseHosts,
|
||||
IPv6: ipv6,
|
||||
EnhancedMode: c.EnhancedMode,
|
||||
FakeIPPool: c.FakeIPPool,
|
||||
FakeIPPool6: c.FakeIPPool6,
|
||||
FakeIPSkipper: c.FakeIPSkipper,
|
||||
FakeIPTTL: c.FakeIPTTL,
|
||||
UseHosts: c.UseHosts,
|
||||
FakeIPDisableMapping: c.FakeIPDisableMapping,
|
||||
})
|
||||
|
||||
// reuse cache of old host mapper
|
||||
|
||||
@@ -277,7 +277,8 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis
|
||||
switch options.DNSMode {
|
||||
case "", tun.DNSModeDisabled, tun.DNSModeNative, tun.DNSModeHijack:
|
||||
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
|
||||
|
||||
@@ -17,7 +17,8 @@ func (d *Domain) RuleType() C.RuleType {
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
@@ -17,7 +17,7 @@ func (dk *DomainKeyword) RuleType() C.RuleType {
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package common
|
||||
|
||||
import (
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"strings"
|
||||
|
||||
"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) {
|
||||
domain := metadata.RuleHost()
|
||||
domain := strings.ToLower(metadata.RuleHost())
|
||||
match, _ := dr.regex.MatchString(domain)
|
||||
return match, dr.adapter
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ func (ds *DomainSuffix) RuleType() C.RuleType {
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,8 @@ func (dw *DomainWildcard) RuleType() C.RuleType {
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
@@ -2,6 +2,7 @@ package common
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/metacubex/mihomo/component/geodata"
|
||||
_ "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) {
|
||||
return gs.MatchDomain(metadata.RuleHost()), gs.adapter
|
||||
domain := strings.ToLower(metadata.RuleHost())
|
||||
return gs.MatchDomain(domain), gs.adapter
|
||||
}
|
||||
|
||||
// MatchDomain implements C.DomainMatcher
|
||||
|
||||
@@ -24,7 +24,8 @@ func (d *domainStrategy) Behavior() P.RuleBehavior {
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
+136
-47
@@ -49,20 +49,23 @@ const (
|
||||
|
||||
// RelayOption is the common gost relay transport configuration that can wrap any TCP outbound dial.
|
||||
type RelayOption struct {
|
||||
Server string `proxy:"server,omitempty"`
|
||||
Port int `proxy:"port,omitempty"`
|
||||
Forward bool `proxy:"forward,omitempty"`
|
||||
TLS bool `proxy:"tls,omitempty"`
|
||||
Mux bool `proxy:"mux,omitempty"`
|
||||
SNI string `proxy:"sni,omitempty"`
|
||||
Username string `proxy:"username,omitempty"`
|
||||
Password string `proxy:"password,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
NameCertVerify string `proxy:"name-cert-verify,omitempty"`
|
||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||
Certificate string `proxy:"certificate,omitempty"`
|
||||
PrivateKey string `proxy:"private-key,omitempty"`
|
||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||
Server string `proxy:"server,omitempty"`
|
||||
Port int `proxy:"port,omitempty"`
|
||||
Forward bool `proxy:"forward,omitempty"`
|
||||
WS bool `proxy:"ws,omitempty"`
|
||||
WSPath string `proxy:"ws-path,omitempty"`
|
||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
||||
TLS bool `proxy:"tls,omitempty"`
|
||||
Mux bool `proxy:"mux,omitempty"`
|
||||
SNI string `proxy:"sni,omitempty"`
|
||||
Username string `proxy:"username,omitempty"`
|
||||
Password string `proxy:"password,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
NameCertVerify string `proxy:"name-cert-verify,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 {
|
||||
@@ -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 {
|
||||
return nil, err
|
||||
}
|
||||
if err := readRelayConnectResponse(conn); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
success = true
|
||||
return conn, nil
|
||||
return newRelayConn(conn), nil
|
||||
}
|
||||
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
if err := readRelayConnectResponse(conn); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
success = true
|
||||
return &relayPacketConn{
|
||||
@@ -172,42 +169,76 @@ func (d *relayDialer) dialRelayServer(ctx context.Context, fallbackAddress strin
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if d.option.TLS {
|
||||
tlsConn, err := mihomoVMess.StreamTLSConn(ctx, conn, &mihomoVMess.TLSConfig{
|
||||
Host: d.serverName(relayAddress),
|
||||
if d.option.WS {
|
||||
host, port, err := net.SplitHostPort(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,
|
||||
NameCertVerify: d.option.NameCertVerify,
|
||||
FingerPrint: d.option.Fingerprint,
|
||||
Fingerprint: d.option.Fingerprint,
|
||||
Certificate: d.option.Certificate,
|
||||
PrivateKey: d.option.PrivateKey,
|
||||
ClientFingerprint: d.option.ClientFingerprint,
|
||||
Mux: d.option.Mux,
|
||||
})
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
conn = tlsConn
|
||||
}
|
||||
|
||||
if d.option.Mux {
|
||||
config := smux.DefaultConfig()
|
||||
config.KeepAliveDisabled = true
|
||||
|
||||
session, err := smux.Client(conn, config)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, err
|
||||
conn = wsConn
|
||||
} else {
|
||||
if d.option.TLS {
|
||||
tlsConn, err := mihomoVMess.StreamTLSConn(ctx, conn, &mihomoVMess.TLSConfig{
|
||||
Host: d.serverName(relayAddress),
|
||||
SkipCertVerify: d.option.SkipCertVerify,
|
||||
NameCertVerify: d.option.NameCertVerify,
|
||||
FingerPrint: d.option.Fingerprint,
|
||||
Certificate: d.option.Certificate,
|
||||
PrivateKey: d.option.PrivateKey,
|
||||
ClientFingerprint: d.option.ClientFingerprint,
|
||||
})
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
conn = tlsConn
|
||||
}
|
||||
|
||||
stream, err := session.OpenStream()
|
||||
if err != nil {
|
||||
_ = session.Close()
|
||||
return nil, err
|
||||
}
|
||||
if d.option.Mux {
|
||||
// Keep the default smux v1 and keepalive settings aligned with GOST.
|
||||
config := smux.DefaultConfig()
|
||||
|
||||
conn = &muxConn{
|
||||
Conn: stream,
|
||||
session: session,
|
||||
session, err := smux.Client(conn, config)
|
||||
if err != nil {
|
||||
_ = 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
|
||||
}
|
||||
|
||||
// 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 {
|
||||
conn net.Conn
|
||||
raddr net.Addr
|
||||
wmu sync.Mutex
|
||||
conn net.Conn
|
||||
raddr net.Addr
|
||||
rmu sync.Mutex
|
||||
wmu sync.Mutex
|
||||
responseOnce sync.Once
|
||||
responseErr 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
|
||||
if _, err := io.ReadFull(c.conn, header[:]); err != nil {
|
||||
return 0, nil, err
|
||||
|
||||
+26
-18
@@ -15,18 +15,21 @@ import (
|
||||
|
||||
// Option is options of gost websocket
|
||||
type Option struct {
|
||||
Host string
|
||||
Port string
|
||||
Path string
|
||||
Headers map[string]string
|
||||
TLS bool
|
||||
ECHConfig *ech.Config
|
||||
SkipCertVerify bool
|
||||
NameCertVerify string
|
||||
Fingerprint string
|
||||
Certificate string
|
||||
PrivateKey string
|
||||
Mux bool
|
||||
Host string
|
||||
Port string
|
||||
Path string
|
||||
Headers map[string]string
|
||||
TLS bool
|
||||
ECHConfig *ech.Config
|
||||
SkipCertVerify bool
|
||||
NameCertVerify string
|
||||
Fingerprint string
|
||||
Certificate string
|
||||
PrivateKey string
|
||||
SNI string
|
||||
ClientFingerprint string
|
||||
Mux bool
|
||||
MuxKeepAliveDisabled bool
|
||||
}
|
||||
|
||||
// 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{
|
||||
Host: option.Host,
|
||||
Port: option.Port,
|
||||
Path: option.Path,
|
||||
ECHConfig: option.ECHConfig,
|
||||
Headers: header,
|
||||
Host: option.Host,
|
||||
Port: option.Port,
|
||||
Path: option.Path,
|
||||
ECHConfig: option.ECHConfig,
|
||||
Headers: header,
|
||||
ClientFingerprint: option.ClientFingerprint,
|
||||
}
|
||||
|
||||
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 != "" {
|
||||
config.TLSConfig.ServerName = host
|
||||
}
|
||||
if option.SNI != "" {
|
||||
config.TLSConfig.ServerName = option.SNI
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
// Keep the default smux v1 and keepalive settings aligned with GOST MWS.
|
||||
config := smux.DefaultConfig()
|
||||
config.KeepAliveDisabled = true
|
||||
config.KeepAliveDisabled = option.MuxKeepAliveDisabled
|
||||
|
||||
session, err := smux.Client(conn, config)
|
||||
if err != nil {
|
||||
|
||||
@@ -190,11 +190,6 @@ func uTLSHandshakeFunc(config *tls.Config, clientFingerprint string, version int
|
||||
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 tlsC.Client(conn, tlsConfig).HandshakeContext(ctx)
|
||||
|
||||
@@ -32,6 +32,7 @@ func TestServer(t *testing.T) {
|
||||
}{
|
||||
{name: "v1", version: 1},
|
||||
{name: "v2", version: 2},
|
||||
{name: "v2-utls", version: 2, fingerprint: "chrome"},
|
||||
{name: "v2-utls-websocket", version: 2, fingerprint: "chrome", alpn: WsALPN},
|
||||
{name: "v3", version: 3},
|
||||
{name: "v3-utls", version: 3, fingerprint: "chrome"},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package shadowtls
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
@@ -17,19 +18,18 @@ import (
|
||||
|
||||
type hashReadConn struct {
|
||||
net.Conn
|
||||
hmac hash.Hash
|
||||
reader *bufio.Reader
|
||||
hmac hash.Hash
|
||||
}
|
||||
|
||||
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) {
|
||||
n, err := c.Conn.Read(p)
|
||||
if n > 0 {
|
||||
_, _ = c.hmac.Write(p[:n])
|
||||
}
|
||||
return n, err
|
||||
return c.reader.Read(p)
|
||||
}
|
||||
|
||||
func (c *hashReadConn) Sum() []byte {
|
||||
|
||||
@@ -39,6 +39,9 @@ const (
|
||||
CommandError byte = 2
|
||||
|
||||
Version byte = 1
|
||||
|
||||
// MaxClientIDLength is the maximum ClientID length encoded in a Snell request header.
|
||||
MaxClientIDLength = 255
|
||||
)
|
||||
|
||||
var endSignal = []byte{}
|
||||
@@ -97,11 +100,13 @@ func (s *Snell) ReadReply() error {
|
||||
return fmt.Errorf("server reported code: %d, message: %s", errcode, string(msg))
|
||||
}
|
||||
|
||||
func WriteHeader(conn net.Conn, host string, port uint, version int) error {
|
||||
return WriteHeaderWithReuse(conn, host, port, version, false)
|
||||
}
|
||||
|
||||
func WriteHeaderWithReuse(conn net.Conn, host string, port uint, version int, reuse bool) error {
|
||||
func WriteHeader(conn net.Conn, host string, port uint16, version int, reuse bool, clientID []byte) error {
|
||||
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")
|
||||
}
|
||||
buf := pool.GetBuffer()
|
||||
defer pool.PutBuffer(buf)
|
||||
buf.WriteByte(Version)
|
||||
@@ -112,7 +117,8 @@ func WriteHeaderWithReuse(conn net.Conn, host string, port uint, version int, re
|
||||
}
|
||||
|
||||
// clientID length & id
|
||||
buf.WriteByte(0)
|
||||
buf.WriteByte(uint8(len(clientID)))
|
||||
buf.Write(clientID)
|
||||
|
||||
// host & port
|
||||
buf.WriteByte(uint8(len(host)))
|
||||
@@ -126,13 +132,21 @@ func WriteHeaderWithReuse(conn net.Conn, host string, port uint, version int, re
|
||||
return nil
|
||||
}
|
||||
|
||||
func WriteUDPHeader(conn net.Conn, version int) error {
|
||||
func WriteUDPHeader(conn net.Conn, version int, clientID []byte) error {
|
||||
if version < Version3 {
|
||||
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
|
||||
_, err := conn.Write([]byte{Version, CommandUDP, 0x00})
|
||||
// version, command, client ID length, and optional per-user identity
|
||||
header := []byte{Version, CommandUDP, uint8(len(clientID))}
|
||||
header = append(header, clientID...)
|
||||
_, err := conn.Write(header)
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -301,7 +301,7 @@ func TestSnellWriteHeaderConnectCommand(t *testing.T) {
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
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) {
|
||||
conn := &Snell{Conn: &bufferConn{}}
|
||||
conn.Conn.(*bufferConn).Write([]byte{CommandTunnel, 'o', 'k'})
|
||||
|
||||
@@ -202,3 +202,41 @@ func TestValidateV6PSK(t *testing.T) {
|
||||
require.Error(t, ValidateV6PSK(make([]byte, 256)))
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -139,7 +139,7 @@ func (entry *reuseEntry) release() {
|
||||
}
|
||||
}
|
||||
|
||||
func (m *ReuseManager) pickLocked() *reuseEntry {
|
||||
func (m *ReuseManager) pickLocked(now time.Time) *reuseEntry {
|
||||
var best *reuseEntry
|
||||
for _, entry := range m.entries {
|
||||
if entry.isClosed() {
|
||||
@@ -151,6 +151,9 @@ func (m *ReuseManager) pickLocked() *reuseEntry {
|
||||
if entry.maxReuseTimes > 0 && entry.reuseCount.Load() >= entry.maxReuseTimes {
|
||||
continue
|
||||
}
|
||||
if !entry.unreusableAt.IsZero() && now.After(entry.unreusableAt) {
|
||||
continue
|
||||
}
|
||||
if m.maxConcurrency > 0 && int(entry.openUsage.Load()) >= m.maxConcurrency {
|
||||
continue
|
||||
}
|
||||
@@ -200,7 +203,7 @@ func (m *ReuseManager) GetTransport() http.RoundTripper {
|
||||
|
||||
var entry *reuseEntry
|
||||
if !m.shouldCreateLocked() {
|
||||
entry = m.pickLocked()
|
||||
entry = m.pickLocked(now)
|
||||
}
|
||||
reused := entry != nil
|
||||
|
||||
|
||||
@@ -160,6 +160,38 @@ func TestManagerRotateOnReusableSecs(t *testing.T) {
|
||||
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) {
|
||||
var created atomic.Int64
|
||||
|
||||
|
||||
+10
-3
@@ -203,12 +203,16 @@ func Listeners() map[string]C.InboundListener {
|
||||
}
|
||||
|
||||
// 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()
|
||||
oldRules = rules
|
||||
oldSubRule = subRules
|
||||
oldRuleProviders = ruleProviders
|
||||
rules = newRules
|
||||
ruleProviders = rp
|
||||
ruleProviders = newRuleProviders
|
||||
subRules = newSubRule
|
||||
configMux.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
// Proxies return all proxies
|
||||
@@ -227,11 +231,14 @@ func RuleProviders() map[string]P.RuleProvider {
|
||||
}
|
||||
|
||||
// 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()
|
||||
oldProxies = proxies
|
||||
oldProviders = providers
|
||||
proxies = newProxies
|
||||
providers = newProviders
|
||||
configMux.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
func UpdateListeners(newListeners map[string]C.InboundListener) {
|
||||
|
||||
Reference in new issue
Block a user