Compare commits

...
12 Commits
Author SHA1 Message Date
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
21 changed files with 225 additions and 61 deletions

No files matched your search

+12 -2
View File
@@ -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,
+1 -1
View File
@@ -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
}
+1 -1
View File
@@ -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
+2 -1
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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))
}
+1
View File
@@ -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
+1 -1
View File
@@ -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
+2 -2
View File
@@ -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=
+8 -7
View File
@@ -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
+2 -1
View File
@@ -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
-5
View File
@@ -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)
+1
View File
@@ -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"},
+7 -7
View File
@@ -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 {
+23 -9
View File
@@ -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
}
+53 -1
View File
@@ -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'})
+38
View File
@@ -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)
}
}
+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
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
+32
View File
@@ -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
View File
@@ -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) {