Compare commits

..

49 Commits

Author SHA1 Message Date
enfein
a001b1b110 chore: update mieru version (#2403) 2025-12-01 08:42:28 +08:00
wwqgtxx
d1f89fa05e chore: update tfo-go ready for go1.26 2025-12-01 01:12:31 +08:00
wwqgtxx
e2796e2d5c chore: apply ping destination filter for windows 2025-11-30 17:00:04 +08:00
futai
93de49d20c chore: sync sudoku with mihomo log (#2402) 2025-11-29 15:21:29 +08:00
wwqgtxx
4d3167ff2f chore: completely remove relay group type using dialer-proxy instead
which was marked as deprecated in v1.18.6
2025-11-29 09:39:28 +08:00
enfein
5998956a72 fix: a nil pointer error when closing mieru underlay (#2401) 2025-11-29 08:39:45 +08:00
futai
6cf1743961 feat: add Sudoku protocol inbound & outbound support (#2397) 2025-11-28 23:40:00 +08:00
Sinspired
8b6ba22b90 fix: replace wrong SetString() with SetBool() for uint weak-typed input (#2394)
The uint branch in decodeBool() incorrectly used SetString(). Use SetBool(dataVal.Uint() != 0) to match expected behavior.
2025-11-26 10:35:26 +08:00
wwqgtxx
7571c87afb chore: add fake-ip-ttl to dns section 2025-11-23 21:34:30 +08:00
wwqgtxx
d4d2c062a3 test: skip inbound test on darwin 2025-11-23 21:34:30 +08:00
TargetLocked
438d4138d6 fix: compare authentication scheme case-insensitively (#2386) 2025-11-23 19:34:02 +08:00
wwqgtxx
140d892ccf chore: better log 2025-11-22 20:59:53 +08:00
enfein
5aa140c493 feat: support mieru UDP outbound (#2384) 2025-11-22 08:54:14 +08:00
enfein
c107c6a824 fix: crash due to nil net.Conn from mieru inbound (#2361) 2025-11-15 07:42:29 +08:00
wwqgtxx
f6e494e73f chore: upgrade the embedded xsync.Map to v4.2.0 2025-11-14 00:23:01 +08:00
hi
0b3159bf9b chore: remove redundant code (#2355) 2025-11-11 17:06:49 +08:00
wwqgtxx
45fd628788 fix: bugs in kcp-go and smux 2025-11-11 09:33:41 +08:00
wwqgtxx
2f545ef634 fix: hosts not working
https://github.com/MetaCubeX/mihomo/issues/2351
2025-11-10 10:55:02 +08:00
wwqgtxx
054e63cb3f chore: remove depend of purego 2025-11-10 00:46:09 +08:00
wwqgtxx
d48bcf1e1e fix: fakeip6 logic not work correctly 2025-11-09 19:19:20 +08:00
wwqgtxx
0df2f79ece fix: missing metadata in mieru inbound 2025-11-09 11:41:37 +08:00
wwqgtxx
644c04fdc9 chore: update sing-tun 2025-11-09 10:09:01 +08:00
wwqgtxx
926aaec717 chore: update purego 2025-11-09 10:08:51 +08:00
enfein
a4b76809ac feat: support mieru inbound (#2347) 2025-11-09 09:29:47 +08:00
wwqgtxx
ff76576cbe chore: cleanup import path for listener 2025-11-06 19:39:03 +08:00
wwqgtxx
1d5890abc1 chore: cleanup import path for constant/provider 2025-11-06 19:32:12 +08:00
wwqgtxx
a3c023ae3e chore: cleanup import path for component/process 2025-11-06 19:27:40 +08:00
wwqgtxx
8b32c4371e fix: race in kcp-go 2025-11-05 16:50:22 +08:00
wwqgtxx
5a285acd32 chore: reduce the global variables that should not be used in amneziawg-go 2025-11-05 01:44:18 +08:00
wwqgtxx
c2209d68f7 fix: vision panic with dialer-proxy
https://github.com/MetaCubeX/mihomo/issues/2334
2025-11-04 18:54:33 +08:00
wwqgtxx
fd39c2a7fc chore: better maphash test 2025-11-03 15:34:46 +08:00
wwqgtxx
421dc79aea chore: cleanup default value in parseProxy 2025-11-03 15:29:14 +08:00
wwqgtxx
27b47f976c chore: structure support ignore tag 2025-11-03 15:01:07 +08:00
wwqgtxx
c25a38898f chore: share append chains logic 2025-11-03 10:12:24 +08:00
wwqgtxx
f3edbc2b45 chore: remove unused code 2025-11-03 09:56:19 +08:00
Restia-Ashbell
6fb1f796a5 fix: handle nil pointer stored in non-nil interface (#2337) 2025-11-02 20:02:16 +08:00
wwqgtxx
99e68e9983 chore: update dependencies 2025-10-31 17:18:22 +08:00
wwqgtxx
6bffbdd9d3 chore: ignore ipv6 check when get interface addrs failed 2025-10-28 18:30:57 +08:00
wwqgtxx
cfdaebe952 chore: check fake-ip-range and fake-ip-range6 are indeed ipv4 and ipv6 prefixes 2025-10-28 16:23:01 +08:00
wwqgtxx
c8af92a01f feat: support fake-ip-range6 in dns module 2025-10-28 11:40:00 +08:00
wwqgtxx
ff62386f6b chore: reduce internal dependencies of the ntp package 2025-10-27 17:29:57 +08:00
wwqgtxx
85c56e7446 chore: revert ade42346 for convert speed 2025-10-27 11:37:49 +08:00
wwqgtxx
9ed9c3d1c3 fix: docker build 2025-10-26 11:10:40 +08:00
vernesong
dcfe664a7d fix: strategyFn index out of range if proxies changed (#2330) 2025-10-26 10:10:36 +08:00
wwqgtxx
fb1ae21fb7 chore: remove unused code 2025-10-26 09:42:36 +08:00
wwqgtxx
90f47a6d0c fix: openbsd build 2025-10-24 18:20:05 +08:00
wwqgtxx
f2bf4a077e fix: memory leak in h3 stream hijack 2025-10-24 14:03:53 +08:00
wwqgtxx
8701639347 chore: update bart 2025-10-20 12:19:36 +08:00
wwqgtxx
5bc0ac7281 fix: openbsd build 2025-10-18 19:56:39 +08:00
80 changed files with 2600 additions and 718 deletions

View File

@@ -54,6 +54,11 @@ jobs:
cd $(go env GOROOT)
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go${{matrix.go-version}}.patch
- name: Remove inbound test for macOS
if: ${{ runner.os == 'macOS' }}
run: |
rm -rf listener/inbound/*_test.go
- name: Test
run: go test ./... -v -count=1

View File

@@ -4,9 +4,9 @@ RUN echo "I'm building for $TARGETPLATFORM"
RUN apk add --no-cache gzip && \
mkdir /mihomo-config && \
wget -O /mihomo-config/geoip.metadb https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.metadb && \
wget -O /mihomo-config/geosite.dat https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geosite.dat && \
wget -O /mihomo-config/geoip.dat https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.dat
wget -O /mihomo-config/geoip.metadb https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geoip.metadb && \
wget -O /mihomo-config/geosite.dat https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geosite.dat && \
wget -O /mihomo-config/geoip.dat https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geoip.dat
COPY docker/file-name.sh /mihomo/file-name.sh
WORKDIR /mihomo

View File

@@ -51,26 +51,12 @@ func (p *Proxy) AliveForTestUrl(url string) bool {
return p.alive.Load()
}
// Dial implements C.Proxy
func (p *Proxy) Dial(metadata *C.Metadata) (C.Conn, error) {
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTCPTimeout)
defer cancel()
return p.DialContext(ctx, metadata)
}
// DialContext implements C.ProxyAdapter
func (p *Proxy) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
conn, err := p.ProxyAdapter.DialContext(ctx, metadata)
return conn, err
}
// DialUDP implements C.ProxyAdapter
func (p *Proxy) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultUDPTimeout)
defer cancel()
return p.ListenPacketContext(ctx, metadata)
}
// ListenPacketContext implements C.ProxyAdapter
func (p *Proxy) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
pc, err := p.ProxyAdapter.ListenPacketContext(ctx, metadata)

View File

@@ -263,7 +263,9 @@ func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
if _, ok := c.(syscall.Conn); !ok { // exclusion system conn like *net.TCPConn
c = N.NewDeadlineConn(c) // most conn from outbound can't handle readDeadline correctly
}
return &conn{N.NewExtendedConn(c), []string{a.Name()}, a.Addr()}
cc := &conn{N.NewExtendedConn(c), nil, a.Addr()}
cc.AppendToChains(a)
return cc
}
type packetConn struct {
@@ -320,7 +322,9 @@ func newPacketConn(pc net.PacketConn, a ProxyAdapter) C.PacketConn {
if _, ok := pc.(syscall.Conn); !ok { // exclusion system conn like *net.UDPConn
epc = N.NewDeadlineEnhancePacketConn(epc) // most conn from outbound can't handle readDeadline correctly
}
return &packetConn{epc, []string{a.Name()}, a.Name(), utils.NewUUIDV4().String(), a.Addr(), a.ResolveUDP}
cpc := &packetConn{epc, nil, a.Name(), utils.NewUUIDV4().String(), a.Addr(), a.ResolveUDP}
cpc.AppendToChains(a)
return cpc
}
type AddRef interface {

View File

@@ -4,12 +4,14 @@ import (
"context"
"fmt"
"net"
"net/netip"
"strconv"
"sync"
CN "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/component/dialer"
"github.com/metacubex/mihomo/component/proxydialer"
"github.com/metacubex/mihomo/component/resolver"
C "github.com/metacubex/mihomo/constant"
mieruclient "github.com/enfein/mieru/v3/apis/client"
@@ -40,6 +42,45 @@ type MieruOption struct {
HandshakeMode string `proxy:"handshake-mode,omitempty"`
}
type mieruPacketDialer struct {
C.Dialer
}
var _ mierucommon.PacketDialer = (*mieruPacketDialer)(nil)
func (pd mieruPacketDialer) ListenPacket(ctx context.Context, network, laddr, raddr string) (net.PacketConn, error) {
rAddrPort, err := netip.ParseAddrPort(raddr)
if err != nil {
return nil, fmt.Errorf("invalid address %s: %w", raddr, err)
}
return pd.Dialer.ListenPacket(ctx, network, laddr, rAddrPort)
}
type mieruDNSResolver struct {
prefer C.DNSPrefer
}
var _ mierucommon.DNSResolver = (*mieruDNSResolver)(nil)
func (dr mieruDNSResolver) LookupIP(ctx context.Context, network, host string) (_ []net.IP, err error) {
var ip netip.Addr
switch dr.prefer {
case C.IPv4Only:
ip, err = resolver.ResolveIPv4WithResolver(ctx, host, resolver.ProxyServerHostResolver)
case C.IPv6Only:
ip, err = resolver.ResolveIPv6WithResolver(ctx, host, resolver.ProxyServerHostResolver)
case C.IPv6Prefer:
ip, err = resolver.ResolveIPPrefer6WithResolver(ctx, host, resolver.ProxyServerHostResolver)
default:
ip, err = resolver.ResolveIPWithResolver(ctx, host, resolver.ProxyServerHostResolver)
}
if err != nil {
return nil, fmt.Errorf("can't resolve ip: %w", err)
}
// TODO: handle IP4P (due to interface limitations, it's currently impossible to modify the port here)
return []net.IP{ip.AsSlice()}, nil
}
// DialContext implements C.ProxyAdapter
func (m *Mieru) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
if err := m.ensureClientIsRunning(); err != nil {
@@ -102,6 +143,8 @@ func (m *Mieru) ensureClientIsRunning() error {
return err
}
config.Dialer = dialer
config.PacketDialer = mieruPacketDialer{Dialer: dialer}
config.Resolver = mieruDNSResolver{prefer: m.prefer}
if err := m.client.Store(config); err != nil {
return err
}
@@ -158,23 +201,21 @@ func (m *Mieru) Close() error {
}
func metadataToMieruNetAddrSpec(metadata *C.Metadata) mierumodel.NetAddrSpec {
spec := mierumodel.NetAddrSpec{
Net: metadata.NetWork.String(),
}
if metadata.Host != "" {
return mierumodel.NetAddrSpec{
AddrSpec: mierumodel.AddrSpec{
FQDN: metadata.Host,
Port: int(metadata.DstPort),
},
Net: "tcp",
spec.AddrSpec = mierumodel.AddrSpec{
FQDN: metadata.Host,
Port: int(metadata.DstPort),
}
} else {
return mierumodel.NetAddrSpec{
AddrSpec: mierumodel.AddrSpec{
IP: metadata.DstIP.AsSlice(),
Port: int(metadata.DstPort),
},
Net: "tcp",
spec.AddrSpec = mierumodel.AddrSpec{
IP: metadata.DstIP.AsSlice(),
Port: int(metadata.DstPort),
}
}
return spec
}
func buildMieruClientConfig(option MieruOption) (*mieruclient.ClientConfig, error) {
@@ -182,7 +223,13 @@ func buildMieruClientConfig(option MieruOption) (*mieruclient.ClientConfig, erro
return nil, fmt.Errorf("failed to validate mieru option: %w", err)
}
transportProtocol := mierupb.TransportProtocol_TCP.Enum()
var transportProtocol = mierupb.TransportProtocol_UNKNOWN_TRANSPORT_PROTOCOL.Enum()
switch option.Transport {
case "TCP":
transportProtocol = mierupb.TransportProtocol_TCP.Enum()
case "UDP":
transportProtocol = mierupb.TransportProtocol_UDP.Enum()
}
var server *mierupb.ServerEndpoint
if net.ParseIP(option.Server) != nil {
// server is an IP address
@@ -240,6 +287,9 @@ func buildMieruClientConfig(option MieruOption) (*mieruclient.ClientConfig, erro
},
Servers: []*mierupb.ServerEndpoint{server},
},
DNSConfig: &mierucommon.ClientDNSConfig{
BypassDialerDNS: true,
},
}
if multiplexing, ok := mierupb.MultiplexingLevel_value[option.Multiplexing]; ok {
config.Profile.Multiplexing = &mierupb.MultiplexingConfig{
@@ -284,8 +334,8 @@ func validateMieruOption(option MieruOption) error {
}
}
if option.Transport != "TCP" {
return fmt.Errorf("transport must be TCP")
if option.Transport != "TCP" && option.Transport != "UDP" {
return fmt.Errorf("transport must be TCP or UDP")
}
if option.UserName == "" {
return fmt.Errorf("username is empty")

View File

@@ -34,7 +34,7 @@ func TestNewMieru(t *testing.T) {
Name: "test",
Server: "example.com",
Port: 10003,
Transport: "TCP",
Transport: "UDP",
UserName: "test",
Password: "test",
},

View File

@@ -252,13 +252,14 @@ func (spc *ssrPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr
return nil, nil, nil, errors.New("parse addr error")
}
addr = _addr.UDPAddr()
if addr == nil {
udpAddr := _addr.UDPAddr()
if udpAddr == nil {
if put != nil {
put()
}
return nil, nil, nil, errors.New("parse addr error")
}
addr = udpAddr
data = data[len(_addr):]
return

270
adapter/outbound/sudoku.go Normal file
View File

@@ -0,0 +1,270 @@
package outbound
import (
"context"
"crypto/sha256"
"encoding/binary"
"fmt"
"io"
"net"
"strconv"
"strings"
"time"
"github.com/metacubex/mihomo/log"
"github.com/saba-futai/sudoku/apis"
"github.com/saba-futai/sudoku/pkg/crypto"
"github.com/saba-futai/sudoku/pkg/obfs/httpmask"
"github.com/saba-futai/sudoku/pkg/obfs/sudoku"
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/component/dialer"
"github.com/metacubex/mihomo/component/proxydialer"
C "github.com/metacubex/mihomo/constant"
)
type Sudoku struct {
*Base
option *SudokuOption
table *sudoku.Table
baseConf apis.ProtocolConfig
}
type SudokuOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Key string `proxy:"key"`
AEADMethod string `proxy:"aead-method,omitempty"`
PaddingMin *int `proxy:"padding-min,omitempty"`
PaddingMax *int `proxy:"padding-max,omitempty"`
TableType string `proxy:"table-type,omitempty"` // "prefer_ascii" or "prefer_entropy"
HTTPMask bool `proxy:"http-mask,omitempty"`
}
// DialContext implements C.ProxyAdapter
func (s *Sudoku) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
return s.DialContextWithDialer(ctx, dialer.NewDialer(s.DialOptions()...), metadata)
}
// DialContextWithDialer implements C.ProxyAdapter
func (s *Sudoku) DialContextWithDialer(ctx context.Context, d C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
if len(s.option.DialerProxy) > 0 {
d, err = proxydialer.NewByName(s.option.DialerProxy, d)
if err != nil {
return nil, err
}
}
cfg, err := s.buildConfig(metadata)
if err != nil {
return nil, err
}
c, err := d.DialContext(ctx, "tcp", s.addr)
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
}
defer func() {
safeConnClose(c, err)
}()
if ctx.Done() != nil {
done := N.SetupContextForConn(ctx, c)
defer done(&err)
}
c, err = s.streamConn(c, cfg)
if err != nil {
return nil, err
}
return NewConn(c, s), nil
}
// ListenPacketContext implements C.ProxyAdapter
func (s *Sudoku) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
return nil, C.ErrNotSupport
}
// SupportUOT implements C.ProxyAdapter
func (s *Sudoku) SupportUOT() bool {
return false // Sudoku protocol only supports TCP
}
// SupportWithDialer implements C.ProxyAdapter
func (s *Sudoku) SupportWithDialer() C.NetWork {
return C.TCP
}
// ProxyInfo implements C.ProxyAdapter
func (s *Sudoku) ProxyInfo() C.ProxyInfo {
info := s.Base.ProxyInfo()
info.DialerProxy = s.option.DialerProxy
return info
}
func (s *Sudoku) buildConfig(metadata *C.Metadata) (*apis.ProtocolConfig, error) {
if metadata == nil || metadata.DstPort == 0 || !metadata.Valid() {
return nil, fmt.Errorf("invalid metadata for sudoku outbound")
}
cfg := s.baseConf
cfg.TargetAddress = metadata.RemoteAddress()
if err := cfg.ValidateClient(); err != nil {
return nil, err
}
return &cfg, nil
}
func (s *Sudoku) streamConn(rawConn net.Conn, cfg *apis.ProtocolConfig) (_ net.Conn, err error) {
if !cfg.DisableHTTPMask {
if err = httpmask.WriteRandomRequestHeader(rawConn, cfg.ServerAddress); err != nil {
return nil, fmt.Errorf("write http mask failed: %w", err)
}
}
obfsConn := sudoku.NewConn(rawConn, cfg.Table, cfg.PaddingMin, cfg.PaddingMax, false)
cConn, err := crypto.NewAEADConn(obfsConn, cfg.Key, cfg.AEADMethod)
if err != nil {
return nil, fmt.Errorf("setup crypto failed: %w", err)
}
handshake := buildSudokuHandshakePayload(cfg.Key)
if _, err = cConn.Write(handshake[:]); err != nil {
cConn.Close()
return nil, fmt.Errorf("send handshake failed: %w", err)
}
if err = writeTargetAddress(cConn, cfg.TargetAddress); err != nil {
cConn.Close()
return nil, fmt.Errorf("send target address failed: %w", err)
}
return cConn, nil
}
func NewSudoku(option SudokuOption) (*Sudoku, error) {
if option.Server == "" {
return nil, fmt.Errorf("server is required")
}
if option.Port <= 0 || option.Port > 65535 {
return nil, fmt.Errorf("invalid port: %d", option.Port)
}
if option.Key == "" {
return nil, fmt.Errorf("key is required")
}
tableType := strings.ToLower(option.TableType)
if tableType == "" {
tableType = "prefer_ascii"
}
if tableType != "prefer_ascii" && tableType != "prefer_entropy" {
return nil, fmt.Errorf("table-type must be prefer_ascii or prefer_entropy")
}
seed := option.Key
if recoveredFromKey, err := crypto.RecoverPublicKey(option.Key); err == nil {
seed = crypto.EncodePoint(recoveredFromKey)
}
start := time.Now()
table := sudoku.NewTable(seed, tableType)
log.Infoln("[Sudoku] Tables initialized (%s) in %v", tableType, time.Since(start))
defaultConf := apis.DefaultConfig()
paddingMin := defaultConf.PaddingMin
paddingMax := defaultConf.PaddingMax
if option.PaddingMin != nil {
paddingMin = *option.PaddingMin
}
if option.PaddingMax != nil {
paddingMax = *option.PaddingMax
}
if option.PaddingMin == nil && option.PaddingMax != nil && paddingMax < paddingMin {
paddingMin = paddingMax
}
if option.PaddingMax == nil && option.PaddingMin != nil && paddingMax < paddingMin {
paddingMax = paddingMin
}
baseConf := apis.ProtocolConfig{
ServerAddress: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
Key: option.Key,
AEADMethod: defaultConf.AEADMethod,
Table: table,
PaddingMin: paddingMin,
PaddingMax: paddingMax,
HandshakeTimeoutSeconds: defaultConf.HandshakeTimeoutSeconds,
DisableHTTPMask: !option.HTTPMask,
}
if option.AEADMethod != "" {
baseConf.AEADMethod = option.AEADMethod
}
return &Sudoku{
Base: &Base{
name: option.Name,
addr: baseConf.ServerAddress,
tp: C.Sudoku,
udp: false,
tfo: option.TFO,
mpTcp: option.MPTCP,
iface: option.Interface,
rmark: option.RoutingMark,
prefer: C.NewDNSPrefer(option.IPVersion),
},
option: &option,
table: table,
baseConf: baseConf,
}, nil
}
func buildSudokuHandshakePayload(key string) [16]byte {
var payload [16]byte
binary.BigEndian.PutUint64(payload[:8], uint64(time.Now().Unix()))
hash := sha256.Sum256([]byte(key))
copy(payload[8:], hash[:8])
return payload
}
func writeTargetAddress(w io.Writer, rawAddr string) error {
host, portStr, err := net.SplitHostPort(rawAddr)
if err != nil {
return err
}
portInt, err := net.LookupPort("tcp", portStr)
if err != nil {
return err
}
var buf []byte
if ip := net.ParseIP(host); ip != nil {
if ip4 := ip.To4(); ip4 != nil {
buf = append(buf, 0x01) // IPv4
buf = append(buf, ip4...)
} else {
buf = append(buf, 0x04) // IPv6
buf = append(buf, ip...)
}
} else {
if len(host) > 255 {
return fmt.Errorf("domain too long")
}
buf = append(buf, 0x03) // domain
buf = append(buf, byte(len(host)))
buf = append(buf, host...)
}
var portBytes [2]byte
binary.BigEndian.PutUint16(portBytes[:], uint16(portInt))
buf = append(buf, portBytes[:]...)
_, err = w.Write(buf)
return err
}

View File

@@ -10,7 +10,7 @@ import (
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/common/utils"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/constant/provider"
P "github.com/metacubex/mihomo/constant/provider"
)
type Fallback struct {
@@ -150,7 +150,7 @@ func (f *Fallback) ForceSet(name string) {
f.selected = name
}
func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
func NewFallback(option *GroupCommonOption, providers []P.ProxyProvider) *Fallback {
return &Fallback{
GroupBase: NewGroupBase(GroupBaseOption{
Name: option.Name,

View File

@@ -12,8 +12,7 @@ import (
"github.com/metacubex/mihomo/common/atomic"
"github.com/metacubex/mihomo/common/utils"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/constant/provider"
types "github.com/metacubex/mihomo/constant/provider"
P "github.com/metacubex/mihomo/constant/provider"
"github.com/metacubex/mihomo/log"
"github.com/metacubex/mihomo/tunnel"
@@ -26,7 +25,7 @@ type GroupBase struct {
filterRegs []*regexp2.Regexp
excludeFilterRegs []*regexp2.Regexp
excludeTypeArray []string
providers []provider.ProxyProvider
providers []P.ProxyProvider
failedTestMux sync.Mutex
failedTimes int
failedTime time.Time
@@ -48,7 +47,7 @@ type GroupBaseOption struct {
ExcludeType string
TestTimeout int
MaxFailedTimes int
Providers []provider.ProxyProvider
Providers []P.ProxyProvider
}
func NewGroupBase(opt GroupBaseOption) *GroupBase {
@@ -125,7 +124,7 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
}
} else {
for _, pd := range gb.providers {
if pd.VehicleType() == types.Compatible { // compatible provider unneeded filter
if pd.VehicleType() == P.Compatible { // compatible provider unneeded filter
proxies = append(proxies, pd.Proxies()...)
continue
}

View File

@@ -14,7 +14,7 @@ import (
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/common/utils"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/constant/provider"
P "github.com/metacubex/mihomo/constant/provider"
"golang.org/x/net/publicsuffix"
)
@@ -194,7 +194,7 @@ func strategyStickySessions(url string) strategyFn {
key := utils.MapHash(getKeyWithSrcAndDst(metadata))
length := len(proxies)
idx, has := lruCache.Get(key)
if !has {
if !has || idx >= length {
idx = int(jumpHash(key+uint64(time.Now().UnixNano()), int32(length)))
}
@@ -239,7 +239,7 @@ func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
})
}
func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvider, strategy string) (lb *LoadBalance, err error) {
func NewLoadBalance(option *GroupCommonOption, providers []P.ProxyProvider, strategy string) (lb *LoadBalance, err error) {
var strategyFn strategyFn
switch strategy {
case "consistent-hashing":

View File

@@ -11,7 +11,7 @@ import (
"github.com/metacubex/mihomo/common/structure"
"github.com/metacubex/mihomo/common/utils"
C "github.com/metacubex/mihomo/constant"
types "github.com/metacubex/mihomo/constant/provider"
P "github.com/metacubex/mihomo/constant/provider"
"github.com/metacubex/mihomo/log"
)
@@ -48,7 +48,7 @@ type GroupCommonOption struct {
RoutingMark int `group:"routing-mark,omitempty"`
}
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider, AllProxies []string, AllProviders []string) (C.ProxyAdapter, error) {
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]P.ProxyProvider, AllProxies []string, AllProviders []string) (C.ProxyAdapter, error) {
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
groupOption := &GroupCommonOption{
@@ -71,7 +71,7 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
groupName := groupOption.Name
providers := []types.ProxyProvider{}
providers := []P.ProxyProvider{}
if groupOption.IncludeAll {
groupOption.IncludeAllProviders = true
@@ -169,7 +169,7 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
return nil, fmt.Errorf("%s: %w", groupName, err)
}
providers = append([]types.ProxyProvider{pd}, providers...)
providers = append([]P.ProxyProvider{pd}, providers...)
providersMap[groupName] = pd
}
@@ -186,7 +186,7 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
strategy := parseStrategy(config)
return NewLoadBalance(groupOption, providers, strategy)
case "relay":
group = NewRelay(groupOption, providers)
return nil, fmt.Errorf("%w: The group [%s] with relay type was removed, please using dialer-proxy instead", errType, groupName)
default:
return nil, fmt.Errorf("%w: %s", errType, groupOption.Type)
}
@@ -206,15 +206,15 @@ func getProxies(mapping map[string]C.Proxy, list []string) ([]C.Proxy, error) {
return ps, nil
}
func getProviders(mapping map[string]types.ProxyProvider, list []string) ([]types.ProxyProvider, error) {
var ps []types.ProxyProvider
func getProviders(mapping map[string]P.ProxyProvider, list []string) ([]P.ProxyProvider, error) {
var ps []P.ProxyProvider
for _, name := range list {
p, ok := mapping[name]
if !ok {
return nil, fmt.Errorf("'%s' not found", name)
}
if p.VehicleType() == types.Compatible {
if p.VehicleType() == P.Compatible {
return nil, fmt.Errorf("proxy group %s can't contains in `use`", name)
}
ps = append(ps, p)
@@ -222,7 +222,7 @@ func getProviders(mapping map[string]types.ProxyProvider, list []string) ([]type
return ps, nil
}
func addTestUrlToProviders(providers []types.ProxyProvider, url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
func addTestUrlToProviders(providers []P.ProxyProvider, url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
if len(providers) == 0 || len(url) == 0 {
return
}

View File

@@ -4,22 +4,22 @@ package outboundgroup
import (
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/constant/provider"
P "github.com/metacubex/mihomo/constant/provider"
)
type ProxyGroup interface {
C.ProxyAdapter
Providers() []provider.ProxyProvider
Providers() []P.ProxyProvider
Proxies() []C.Proxy
Now() string
}
func (f *Fallback) Providers() []provider.ProxyProvider {
func (f *Fallback) Providers() []P.ProxyProvider {
return f.providers
}
func (lb *LoadBalance) Providers() []provider.ProxyProvider {
func (lb *LoadBalance) Providers() []P.ProxyProvider {
return lb.providers
}
@@ -35,7 +35,7 @@ func (lb *LoadBalance) Now() string {
return ""
}
func (r *Relay) Providers() []provider.ProxyProvider {
func (r *Relay) Providers() []P.ProxyProvider {
return r.providers
}
@@ -47,7 +47,7 @@ func (r *Relay) Now() string {
return ""
}
func (s *Selector) Providers() []provider.ProxyProvider {
func (s *Selector) Providers() []P.ProxyProvider {
return s.providers
}
@@ -55,7 +55,7 @@ func (s *Selector) Proxies() []C.Proxy {
return s.GetProxies(false)
}
func (u *URLTest) Providers() []provider.ProxyProvider {
func (u *URLTest) Providers() []P.ProxyProvider {
return u.providers
}

View File

@@ -8,7 +8,7 @@ import (
"github.com/metacubex/mihomo/component/dialer"
"github.com/metacubex/mihomo/component/proxydialer"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/constant/provider"
P "github.com/metacubex/mihomo/constant/provider"
"github.com/metacubex/mihomo/log"
)
@@ -149,7 +149,7 @@ func (r *Relay) Addr() string {
return proxies[len(proxies)-1].Addr()
}
func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Relay {
func NewRelay(option *GroupCommonOption, providers []P.ProxyProvider) *Relay {
log.Warnln("The group [%s] with relay type is deprecated, please using dialer-proxy instead", option.Name)
return &Relay{
GroupBase: NewGroupBase(GroupBaseOption{

View File

@@ -6,7 +6,7 @@ import (
"errors"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/constant/provider"
P "github.com/metacubex/mihomo/constant/provider"
)
type Selector struct {
@@ -108,7 +108,7 @@ func (s *Selector) selectedProxy(touch bool) C.Proxy {
return proxies[0]
}
func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider) *Selector {
func NewSelector(option *GroupCommonOption, providers []P.ProxyProvider) *Selector {
return &Selector{
GroupBase: NewGroupBase(GroupBaseOption{
Name: option.Name,

View File

@@ -11,7 +11,7 @@ import (
"github.com/metacubex/mihomo/common/singledo"
"github.com/metacubex/mihomo/common/utils"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/constant/provider"
P "github.com/metacubex/mihomo/constant/provider"
)
type urlTestOption func(*URLTest)
@@ -202,7 +202,7 @@ func parseURLTestOption(config map[string]any) []urlTestOption {
return opts
}
func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, options ...urlTestOption) *URLTest {
func NewURLTest(option *GroupCommonOption, providers []P.ProxyProvider, options ...urlTestOption) *URLTest {
urlTest := &URLTest{
GroupBase: NewGroupBase(GroupBaseOption{
Name: option.Name,

View File

@@ -49,13 +49,7 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
}
proxy, err = outbound.NewHttp(*httpOption)
case "vmess":
vmessOption := &outbound.VmessOption{
HTTPOpts: outbound.HTTPOptions{
Method: "GET",
Path: []string{"/"},
},
}
vmessOption := &outbound.VmessOption{}
err = decoder.Decode(mapping, vmessOption)
if err != nil {
break
@@ -152,6 +146,13 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
break
}
proxy, err = outbound.NewAnyTLS(*anytlsOption)
case "sudoku":
sudokuOption := &outbound.SudokuOption{}
err = decoder.Decode(mapping, sudokuOption)
if err != nil {
break
}
proxy, err = outbound.NewSudoku(*sudokuOption)
default:
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
}

View File

@@ -10,7 +10,7 @@ import (
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/component/resource"
C "github.com/metacubex/mihomo/constant"
types "github.com/metacubex/mihomo/constant/provider"
P "github.com/metacubex/mihomo/constant/provider"
"github.com/dlclark/regexp2"
)
@@ -73,7 +73,7 @@ type proxyProviderSchema struct {
Header map[string][]string `provider:"header,omitempty"`
}
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
func ParseProxyProvider(name string, mapping map[string]any) (P.ProxyProvider, error) {
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
schema := &proxyProviderSchema{
@@ -104,7 +104,7 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
return nil, err
}
var vehicle types.Vehicle
var vehicle P.Vehicle
switch schema.Type {
case "file":
path := C.Path.Resolve(schema.Path)

View File

@@ -16,7 +16,7 @@ import (
"github.com/metacubex/mihomo/component/profile/cachefile"
"github.com/metacubex/mihomo/component/resource"
C "github.com/metacubex/mihomo/constant"
types "github.com/metacubex/mihomo/constant/provider"
P "github.com/metacubex/mihomo/constant/provider"
"github.com/metacubex/mihomo/tunnel/statistic"
"github.com/dlclark/regexp2"
@@ -68,8 +68,8 @@ func (bp *baseProvider) HealthCheck() {
bp.healthCheck.check()
}
func (bp *baseProvider) Type() types.ProviderType {
return types.Proxy
func (bp *baseProvider) Type() P.ProviderType {
return P.Proxy
}
func (bp *baseProvider) Proxies() []C.Proxy {
@@ -171,7 +171,7 @@ func (pp *proxySetProvider) Close() error {
return pp.Fetcher.Close()
}
func NewProxySetProvider(name string, interval time.Duration, payload []map[string]any, parser resource.Parser[[]C.Proxy], vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
func NewProxySetProvider(name string, interval time.Duration, payload []map[string]any, parser resource.Parser[[]C.Proxy], vehicle P.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
pd := &proxySetProvider{
baseProvider: baseProvider{
name: name,
@@ -238,8 +238,8 @@ func (ip *inlineProvider) MarshalJSON() ([]byte, error) {
})
}
func (ip *inlineProvider) VehicleType() types.VehicleType {
return types.Inline
func (ip *inlineProvider) VehicleType() P.VehicleType {
return P.Inline
}
func (ip *inlineProvider) Update() error {
@@ -303,8 +303,8 @@ func (cp *compatibleProvider) Update() error {
return nil
}
func (cp *compatibleProvider) VehicleType() types.VehicleType {
return types.Compatible
func (cp *compatibleProvider) VehicleType() P.VehicleType {
return P.Compatible
}
func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*CompatibleProvider, error) {

View File

@@ -138,3 +138,5 @@ func escape[T any](x T) T {
// ptrSize is the size of a pointer in bytes - unsafe.Sizeof(uintptr(0)) but as an ideal constant.
// It is also the size of the machine's native word size (that is, 4 on 32-bit systems, 8 on 64-bit).
const ptrSize = 4 << (^uintptr(0) >> 63)
const testComparableAllocations = false

View File

@@ -11,3 +11,5 @@ func Comparable[T comparable](seed Seed, v T) uint64 {
func WriteComparable[T comparable](h *Hash, x T) {
maphash.WriteComparable(h, x)
}
const testComparableAllocations = true

View File

@@ -423,7 +423,9 @@ func TestWriteComparableNoncommute(t *testing.T) {
}
func TestComparableAllocations(t *testing.T) {
t.Skip("test broken in old golang version")
if !testComparableAllocations {
t.Skip("test broken in old golang version")
}
seed := MakeSeed()
x := heapStr(t)
allocs := testing.AllocsPerRun(10, func() {

View File

@@ -24,6 +24,8 @@ var WriteBuffer = bufio.WriteBuffer
type ReadWaitOptions = network.ReadWaitOptions
var NewReadWaitOptions = network.NewReadWaitOptions
var CalculateFrontHeadroom = network.CalculateFrontHeadroom
var CalculateRearHeadroom = network.CalculateRearHeadroom
type ReaderWithUpstream = network.ReaderWithUpstream
type WithUpstreamReader = network.WithUpstreamReader

View File

@@ -53,6 +53,12 @@ func (d *Decoder) Decode(src map[string]any, dst any) error {
key, omitKey, found := strings.Cut(tag, ",")
omitempty := found && omitKey == "omitempty"
// As a special case, if the field tag is "-", the field is always omitted.
// Note that a field with name "-" can still be generated using the tag "-,".
if key == "-" {
continue
}
value, ok := src[key]
if !ok {
if d.option.KeyReplacer != nil {
@@ -283,7 +289,7 @@ func (d *Decoder) decodeBool(name string, data any, val reflect.Value) (err erro
case isInt(kind) && d.option.WeaklyTypedInput:
val.SetBool(dataVal.Int() != 0)
case isUint(kind) && d.option.WeaklyTypedInput:
val.SetString(strconv.FormatUint(dataVal.Uint(), 10))
val.SetBool(dataVal.Uint() != 0)
default:
err = fmt.Errorf(
"'%s' expected type '%s', got unconvertible type '%s'",

View File

@@ -288,3 +288,23 @@ func TestStructure_Null(t *testing.T) {
assert.Nil(t, err)
assert.Equal(t, s.Opt.Bar, "")
}
func TestStructure_Ignore(t *testing.T) {
rawMap := map[string]any{
"-": "newData",
}
s := struct {
MustIgnore string `test:"-"`
}{MustIgnore: "oldData"}
err := decoder.Decode(rawMap, &s)
assert.Nil(t, err)
assert.Equal(t, s.MustIgnore, "oldData")
// test omitempty
delete(rawMap, "-")
err = decoder.Decode(rawMap, &s)
assert.Nil(t, err)
assert.Equal(t, s.MustIgnore, "oldData")
}

View File

@@ -1,16 +1,17 @@
package xsync
// copy and modified from https://github.com/puzpuzpuz/xsync/blob/v4.1.0/map.go
// copy and modified from https://github.com/puzpuzpuz/xsync/blob/v4.2.0/map.go
// which is licensed under Apache v2.
//
// mihomo modified:
// 1. parallel Map resize has been removed to decrease the memory using.
// 1. restore xsync/v3's LoadOrCompute api and rename to LoadOrStoreFn.
// 2. the zero Map is ready for use.
import (
"fmt"
"math"
"math/bits"
"runtime"
"strings"
"sync"
"sync/atomic"
@@ -41,8 +42,28 @@ const (
metaMask uint64 = 0xffffffffff
defaultMetaMasked uint64 = defaultMeta & metaMask
emptyMetaSlot uint8 = 0x80
// minimal number of buckets to transfer when participating in cooperative
// resize; should be at least defaultMinMapTableLen
minResizeTransferStride = 64
// upper limit for max number of additional goroutines that participate
// in cooperative resize; must be changed simultaneously with resizeCtl
// and the related code
maxResizeHelpersLimit = (1 << 5) - 1
)
// max number of additional goroutines that participate in cooperative resize;
// "resize owner" goroutine isn't counted
var maxResizeHelpers = func() int32 {
v := int32(parallelism() - 1)
if v < 1 {
v = 1
}
if v > maxResizeHelpersLimit {
v = maxResizeHelpersLimit
}
return v
}()
type mapResizeHint int
const (
@@ -100,16 +121,25 @@ type Map[K comparable, V any] struct {
initOnce sync.Once
totalGrowths atomic.Int64
totalShrinks atomic.Int64
resizing atomic.Bool // resize in progress flag
resizeMu sync.Mutex // only used along with resizeCond
resizeCond sync.Cond // used to wake up resize waiters (concurrent modifications)
table atomic.Pointer[mapTable[K, V]]
minTableLen int
growOnly bool
// table being transferred to
nextTable atomic.Pointer[mapTable[K, V]]
// resize control state: combines resize sequence number (upper 59 bits) and
// the current number of resize helpers (lower 5 bits);
// odd values of resize sequence mean in-progress resize
resizeCtl atomic.Uint64
// only used along with resizeCond
resizeMu sync.Mutex
// used to wake up resize waiters (concurrent writes)
resizeCond sync.Cond
// transfer progress index for resize
resizeIdx atomic.Int64
minTableLen int
growOnly bool
}
type mapTable[K comparable, V any] struct {
buckets []bucketPadded[K, V]
buckets []bucketPadded
// striped counter for number of table entries;
// used to determine if a table shrinking is needed
// occupies min(buckets_memory/1024, 64KB) of memory
@@ -125,16 +155,16 @@ type counterStripe struct {
// bucketPadded is a CL-sized map bucket holding up to
// entriesPerMapBucket entries.
type bucketPadded[K comparable, V any] struct {
type bucketPadded struct {
//lint:ignore U1000 ensure each bucket takes two cache lines on both 32 and 64-bit archs
pad [cacheLineSize - unsafe.Sizeof(bucket[K, V]{})]byte
bucket[K, V]
pad [cacheLineSize - unsafe.Sizeof(bucket{})]byte
bucket
}
type bucket[K comparable, V any] struct {
meta atomic.Uint64
entries [entriesPerMapBucket]atomic.Pointer[entry[K, V]] // *entry
next atomic.Pointer[bucketPadded[K, V]] // *bucketPadded
type bucket struct {
meta uint64
entries [entriesPerMapBucket]unsafe.Pointer // *entry
next unsafe.Pointer // *bucketPadded
mu sync.Mutex
}
@@ -194,15 +224,15 @@ func (m *Map[K, V]) init() {
m.minTableLen = defaultMinMapTableLen
}
m.resizeCond = *sync.NewCond(&m.resizeMu)
table := newMapTable[K, V](m.minTableLen)
table := newMapTable[K, V](m.minTableLen, maphash.MakeSeed())
m.minTableLen = len(table.buckets)
m.table.Store(table)
}
func newMapTable[K comparable, V any](minTableLen int) *mapTable[K, V] {
buckets := make([]bucketPadded[K, V], minTableLen)
func newMapTable[K comparable, V any](minTableLen int, seed maphash.Seed) *mapTable[K, V] {
buckets := make([]bucketPadded, minTableLen)
for i := range buckets {
buckets[i].meta.Store(defaultMeta)
buckets[i].meta = defaultMeta
}
counterLen := minTableLen >> 10
if counterLen < minMapCounterLen {
@@ -214,7 +244,7 @@ func newMapTable[K comparable, V any](minTableLen int) *mapTable[K, V] {
t := &mapTable[K, V]{
buckets: buckets,
size: counter,
seed: maphash.MakeSeed(),
seed: seed,
}
return t
}
@@ -246,22 +276,24 @@ func (m *Map[K, V]) Load(key K) (value V, ok bool) {
bidx := uint64(len(table.buckets)-1) & h1
b := &table.buckets[bidx]
for {
metaw := b.meta.Load()
metaw := atomic.LoadUint64(&b.meta)
markedw := markZeroBytes(metaw^h2w) & metaMask
for markedw != 0 {
idx := firstMarkedByteIndex(markedw)
e := b.entries[idx].Load()
if e != nil {
eptr := atomic.LoadPointer(&b.entries[idx])
if eptr != nil {
e := (*entry[K, V])(eptr)
if e.key == key {
return e.value, true
}
}
markedw &= markedw - 1
}
b = b.next.Load()
if b == nil {
bptr := atomic.LoadPointer(&b.next)
if bptr == nil {
return
}
b = (*bucketPadded)(bptr)
}
}
@@ -399,7 +431,7 @@ func (m *Map[K, V]) doCompute(
for {
compute_attempt:
var (
emptyb *bucketPadded[K, V]
emptyb *bucketPadded
emptyidx int
)
table := m.table.Load()
@@ -415,12 +447,13 @@ func (m *Map[K, V]) doCompute(
b := rootb
load:
for {
metaw := b.meta.Load()
metaw := atomic.LoadUint64(&b.meta)
markedw := markZeroBytes(metaw^h2w) & metaMask
for markedw != 0 {
idx := firstMarkedByteIndex(markedw)
e := b.entries[idx].Load()
if e != nil {
eptr := atomic.LoadPointer(&b.entries[idx])
if eptr != nil {
e := (*entry[K, V])(eptr)
if e.key == key {
if loadOp == loadOrComputeOp {
return e.value, true
@@ -430,23 +463,24 @@ func (m *Map[K, V]) doCompute(
}
markedw &= markedw - 1
}
b = b.next.Load()
if b == nil {
bptr := atomic.LoadPointer(&b.next)
if bptr == nil {
if loadOp == loadAndDeleteOp {
return *new(V), false
}
break load
}
b = (*bucketPadded)(bptr)
}
}
rootb.mu.Lock()
// The following two checks must go in reverse to what's
// in the resize method.
if m.resizeInProgress() {
// Resize is in progress. Wait, then go for another attempt.
if seq := resizeSeq(m.resizeCtl.Load()); seq&1 == 1 {
// Resize is in progress. Help with the transfer, then go for another attempt.
rootb.mu.Unlock()
m.waitForResize()
m.helpResize(seq)
goto compute_attempt
}
if m.newerTableExists(table) {
@@ -456,12 +490,13 @@ func (m *Map[K, V]) doCompute(
}
b := rootb
for {
metaw := b.meta.Load()
metaw := b.meta
markedw := markZeroBytes(metaw^h2w) & metaMask
for markedw != 0 {
idx := firstMarkedByteIndex(markedw)
e := b.entries[idx].Load()
if e != nil {
eptr := b.entries[idx]
if eptr != nil {
e := (*entry[K, V])(eptr)
if e.key == key {
// In-place update/delete.
// We get a copy of the value via an interface{} on each call,
@@ -475,8 +510,8 @@ func (m *Map[K, V]) doCompute(
// Deletion.
// First we update the hash, then the entry.
newmetaw := setByte(metaw, emptyMetaSlot, idx)
b.meta.Store(newmetaw)
b.entries[idx].Store(nil)
atomic.StoreUint64(&b.meta, newmetaw)
atomic.StorePointer(&b.entries[idx], nil)
rootb.mu.Unlock()
table.addSize(bidx, -1)
// Might need to shrink the table if we left bucket empty.
@@ -488,7 +523,7 @@ func (m *Map[K, V]) doCompute(
newe := new(entry[K, V])
newe.key = key
newe.value = newv
b.entries[idx].Store(newe)
atomic.StorePointer(&b.entries[idx], unsafe.Pointer(newe))
case CancelOp:
newv = oldv
}
@@ -512,7 +547,7 @@ func (m *Map[K, V]) doCompute(
emptyidx = idx
}
}
if b.next.Load() == nil {
if b.next == nil {
if emptyb != nil {
// Insertion into an existing bucket.
var zeroV V
@@ -526,8 +561,8 @@ func (m *Map[K, V]) doCompute(
newe.key = key
newe.value = newValue
// First we update meta, then the entry.
emptyb.meta.Store(setByte(emptyb.meta.Load(), h2, emptyidx))
emptyb.entries[emptyidx].Store(newe)
atomic.StoreUint64(&emptyb.meta, setByte(emptyb.meta, h2, emptyidx))
atomic.StorePointer(&emptyb.entries[emptyidx], unsafe.Pointer(newe))
rootb.mu.Unlock()
table.addSize(bidx, 1)
return newValue, computeOnly
@@ -549,19 +584,19 @@ func (m *Map[K, V]) doCompute(
return newValue, false
default:
// Create and append a bucket.
newb := new(bucketPadded[K, V])
newb.meta.Store(setByte(defaultMeta, h2, 0))
newb := new(bucketPadded)
newb.meta = setByte(defaultMeta, h2, 0)
newe := new(entry[K, V])
newe.key = key
newe.value = newValue
newb.entries[0].Store(newe)
b.next.Store(newb)
newb.entries[0] = unsafe.Pointer(newe)
atomic.StorePointer(&b.next, unsafe.Pointer(newb))
rootb.mu.Unlock()
table.addSize(bidx, 1)
return newValue, computeOnly
}
}
b = b.next.Load()
b = (*bucketPadded)(b.next)
}
}
}
@@ -570,13 +605,21 @@ func (m *Map[K, V]) newerTableExists(table *mapTable[K, V]) bool {
return table != m.table.Load()
}
func (m *Map[K, V]) resizeInProgress() bool {
return m.resizing.Load()
func resizeSeq(ctl uint64) uint64 {
return ctl >> 5
}
func resizeHelpers(ctl uint64) uint64 {
return ctl & maxResizeHelpersLimit
}
func resizeCtl(seq uint64, helpers uint64) uint64 {
return (seq << 5) | (helpers & maxResizeHelpersLimit)
}
func (m *Map[K, V]) waitForResize() {
m.resizeMu.Lock()
for m.resizeInProgress() {
for resizeSeq(m.resizeCtl.Load())&1 == 1 {
m.resizeCond.Wait()
}
m.resizeMu.Unlock()
@@ -593,9 +636,9 @@ func (m *Map[K, V]) resize(knownTable *mapTable[K, V], hint mapResizeHint) {
}
}
// Slow path.
if !m.resizing.CompareAndSwap(false, true) {
// Someone else started resize. Wait for it to finish.
m.waitForResize()
seq := resizeSeq(m.resizeCtl.Load())
if seq&1 == 1 || !m.resizeCtl.CompareAndSwap(resizeCtl(seq, 0), resizeCtl(seq+1, 0)) {
m.helpResize(seq)
return
}
var newTable *mapTable[K, V]
@@ -604,64 +647,189 @@ func (m *Map[K, V]) resize(knownTable *mapTable[K, V], hint mapResizeHint) {
switch hint {
case mapGrowHint:
// Grow the table with factor of 2.
// We must keep the same table seed here to keep the same hash codes
// allowing us to avoid locking destination buckets when resizing.
m.totalGrowths.Add(1)
newTable = newMapTable[K, V](tableLen << 1)
newTable = newMapTable[K, V](tableLen<<1, table.seed)
case mapShrinkHint:
shrinkThreshold := int64((tableLen * entriesPerMapBucket) / mapShrinkFraction)
if tableLen > m.minTableLen && table.sumSize() <= shrinkThreshold {
// Shrink the table with factor of 2.
// It's fine to generate a new seed since full locking
// is required anyway.
m.totalShrinks.Add(1)
newTable = newMapTable[K, V](tableLen >> 1)
newTable = newMapTable[K, V](tableLen>>1, maphash.MakeSeed())
} else {
// No need to shrink. Wake up all waiters and give up.
m.resizeMu.Lock()
m.resizing.Store(false)
m.resizeCtl.Store(resizeCtl(seq+2, 0))
m.resizeCond.Broadcast()
m.resizeMu.Unlock()
return
}
case mapClearHint:
newTable = newMapTable[K, V](m.minTableLen)
newTable = newMapTable[K, V](m.minTableLen, maphash.MakeSeed())
default:
panic(fmt.Sprintf("unexpected resize hint: %d", hint))
}
// Copy the data only if we're not clearing the map.
if hint != mapClearHint {
for i := 0; i < tableLen; i++ {
copied := copyBucket(&table.buckets[i], newTable)
newTable.addSizePlain(uint64(i), copied)
}
// Set up cooperative transfer state.
// Next table must be published as the last step.
m.resizeIdx.Store(0)
m.nextTable.Store(newTable)
// Copy the buckets.
m.transfer(table, newTable)
}
// We're about to publish the new table, but before that
// we must wait for all helpers to finish.
for resizeHelpers(m.resizeCtl.Load()) != 0 {
runtime.Gosched()
}
// Publish the new table and wake up all waiters.
m.table.Store(newTable)
m.nextTable.Store(nil)
ctl := resizeCtl(seq+1, 0)
newCtl := resizeCtl(seq+2, 0)
// Increment the sequence number and wake up all waiters.
m.resizeMu.Lock()
m.resizing.Store(false)
// There may be slowpoke helpers who have just incremented
// the helper counter. This CAS loop makes sure to wait
// for them to back off.
for !m.resizeCtl.CompareAndSwap(ctl, newCtl) {
runtime.Gosched()
}
m.resizeCond.Broadcast()
m.resizeMu.Unlock()
}
func copyBucket[K comparable, V any](
b *bucketPadded[K, V],
func (m *Map[K, V]) helpResize(seq uint64) {
for {
table := m.table.Load()
nextTable := m.nextTable.Load()
if resizeSeq(m.resizeCtl.Load()) == seq {
if nextTable == nil || nextTable == table {
// Carry on until the next table is set by the main
// resize goroutine or until the resize finishes.
runtime.Gosched()
continue
}
// The resize is still in-progress, so let's try registering
// as a helper.
for {
ctl := m.resizeCtl.Load()
if resizeSeq(ctl) != seq || resizeHelpers(ctl) >= uint64(maxResizeHelpers) {
// The resize has ended or there are too many helpers.
break
}
if m.resizeCtl.CompareAndSwap(ctl, ctl+1) {
// Yay, we're a resize helper!
m.transfer(table, nextTable)
// Don't forget to unregister as a helper.
m.resizeCtl.Add(^uint64(0))
break
}
}
m.waitForResize()
}
break
}
}
func (m *Map[K, V]) transfer(table, newTable *mapTable[K, V]) {
tableLen := len(table.buckets)
newTableLen := len(newTable.buckets)
stride := (tableLen >> 3) / int(maxResizeHelpers)
if stride < minResizeTransferStride {
stride = minResizeTransferStride
}
for {
// Claim work by incrementing resizeIdx.
nextIdx := m.resizeIdx.Add(int64(stride))
start := int(nextIdx) - stride
if start < 0 {
start = 0
}
if start > tableLen {
break
}
end := int(nextIdx)
if end > tableLen {
end = tableLen
}
// Transfer buckets in this range.
total := 0
if newTableLen > tableLen {
// We're growing the table with 2x multiplier, so entries from a N bucket can
// only be transferred to N and 2*N buckets in the new table. Thus, destination
// buckets written by the resize helpers don't intersect, so we don't need to
// acquire locks in the destination buckets.
for i := start; i < end; i++ {
total += transferBucketUnsafe(&table.buckets[i], newTable)
}
} else {
// We're shrinking the table, so all locks must be acquired.
for i := start; i < end; i++ {
total += transferBucket(&table.buckets[i], newTable)
}
}
// The exact counter stripe doesn't matter here, so pick up the one
// that corresponds to the start value to avoid contention.
newTable.addSize(uint64(start), total)
}
}
// Doesn't acquire dest bucket lock.
func transferBucketUnsafe[K comparable, V any](
b *bucketPadded,
destTable *mapTable[K, V],
) (copied int) {
rootb := b
rootb.mu.Lock()
for {
for i := 0; i < entriesPerMapBucket; i++ {
if e := b.entries[i].Load(); e != nil {
if eptr := b.entries[i]; eptr != nil {
e := (*entry[K, V])(eptr)
hash := maphash.Comparable(destTable.seed, e.key)
bidx := uint64(len(destTable.buckets)-1) & h1(hash)
destb := &destTable.buckets[bidx]
appendToBucket(h2(hash), b.entries[i].Load(), destb)
appendToBucket(h2(hash), e, destb)
copied++
}
}
if next := b.next.Load(); next == nil {
if b.next == nil {
rootb.mu.Unlock()
return
} else {
b = next
}
b = (*bucketPadded)(b.next)
}
}
func transferBucket[K comparable, V any](
b *bucketPadded,
destTable *mapTable[K, V],
) (copied int) {
rootb := b
rootb.mu.Lock()
for {
for i := 0; i < entriesPerMapBucket; i++ {
if eptr := b.entries[i]; eptr != nil {
e := (*entry[K, V])(eptr)
hash := maphash.Comparable(destTable.seed, e.key)
bidx := uint64(len(destTable.buckets)-1) & h1(hash)
destb := &destTable.buckets[bidx]
destb.mu.Lock()
appendToBucket(h2(hash), e, destb)
destb.mu.Unlock()
copied++
}
}
if b.next == nil {
rootb.mu.Unlock()
return
}
b = (*bucketPadded)(b.next)
}
}
@@ -691,16 +859,15 @@ func (m *Map[K, V]) Range(f func(key K, value V) bool) {
rootb.mu.Lock()
for {
for i := 0; i < entriesPerMapBucket; i++ {
if entry := b.entries[i].Load(); entry != nil {
bentries = append(bentries, entry)
if b.entries[i] != nil {
bentries = append(bentries, (*entry[K, V])(b.entries[i]))
}
}
if next := b.next.Load(); next == nil {
if b.next == nil {
rootb.mu.Unlock()
break
} else {
b = next
}
b = (*bucketPadded)(b.next)
}
// Call the function for all copied entries.
for j, e := range bentries {
@@ -727,24 +894,25 @@ func (m *Map[K, V]) Size() int {
return int(m.table.Load().sumSize())
}
func appendToBucket[K comparable, V any](h2 uint8, e *entry[K, V], b *bucketPadded[K, V]) {
// It is safe to use plain stores here because the destination bucket must be
// either locked or exclusively written to by the helper during resize.
func appendToBucket[K comparable, V any](h2 uint8, e *entry[K, V], b *bucketPadded) {
for {
for i := 0; i < entriesPerMapBucket; i++ {
if b.entries[i].Load() == nil {
b.meta.Store(setByte(b.meta.Load(), h2, i))
b.entries[i].Store(e)
if b.entries[i] == nil {
b.meta = setByte(b.meta, h2, i)
b.entries[i] = unsafe.Pointer(e)
return
}
}
if next := b.next.Load(); next == nil {
newb := new(bucketPadded[K, V])
newb.meta.Store(setByte(defaultMeta, h2, 0))
newb.entries[0].Store(e)
b.next.Store(newb)
if b.next == nil {
newb := new(bucketPadded)
newb.meta = setByte(defaultMeta, h2, 0)
newb.entries[0] = unsafe.Pointer(e)
b.next = unsafe.Pointer(newb)
return
} else {
b = next
}
b = (*bucketPadded)(b.next)
}
}
@@ -753,11 +921,6 @@ func (table *mapTable[K, V]) addSize(bucketIdx uint64, delta int) {
atomic.AddInt64(&table.size[cidx].c, int64(delta))
}
func (table *mapTable[K, V]) addSizePlain(bucketIdx uint64, delta int) {
cidx := uint64(len(table.size)-1) & bucketIdx
table.size[cidx].c += int64(delta)
}
func (table *mapTable[K, V]) sumSize() int64 {
sum := int64(0)
for i := range table.size {
@@ -856,7 +1019,7 @@ func (m *Map[K, V]) Stats() MapStats {
nentriesLocal := 0
stats.Capacity += entriesPerMapBucket
for i := 0; i < entriesPerMapBucket; i++ {
if b.entries[i].Load() != nil {
if atomic.LoadPointer(&b.entries[i]) != nil {
stats.Size++
nentriesLocal++
}
@@ -865,11 +1028,10 @@ func (m *Map[K, V]) Stats() MapStats {
if nentriesLocal == 0 {
stats.EmptyBuckets++
}
if next := b.next.Load(); next == nil {
if b.next == nil {
break
} else {
b = next
}
b = (*bucketPadded)(atomic.LoadPointer(&b.next))
stats.TotalBuckets++
}
if nentries < stats.MinEntries {
@@ -906,6 +1068,15 @@ func nextPowOf2(v uint32) uint32 {
return v
}
func parallelism() uint32 {
maxProcs := uint32(runtime.GOMAXPROCS(0))
numCores := uint32(runtime.NumCPU())
if maxProcs < numCores {
return maxProcs
}
return numCores
}
func broadcast(b uint8) uint64 {
return 0x101010101010101 * uint64(b)
}
@@ -920,6 +1091,7 @@ func markZeroBytes(w uint64) uint64 {
return ((w - 0x0101010101010101) & (^w) & 0x8080808080808080)
}
// Sets byte of the input word at the specified index to the given value.
func setByte(w uint64, b uint8, idx int) uint64 {
shift := idx << 3
return (w &^ (0xff << shift)) | (uint64(b) << shift)

View File

@@ -3,6 +3,7 @@ package xsync
import (
"math"
"math/rand"
"runtime"
"strconv"
"sync"
"sync/atomic"
@@ -53,11 +54,11 @@ func runParallel(b *testing.B, benchFn func(pb *testing.PB)) {
}
func TestMap_BucketStructSize(t *testing.T) {
size := unsafe.Sizeof(bucketPadded[string, int64]{})
size := unsafe.Sizeof(bucketPadded{})
if size != 64 {
t.Fatalf("size of 64B (one cache line) is expected, got: %d", size)
}
size = unsafe.Sizeof(bucketPadded[struct{}, int32]{})
size = unsafe.Sizeof(bucketPadded{})
if size != 64 {
t.Fatalf("size of 64B (one cache line) is expected, got: %d", size)
}
@@ -743,10 +744,7 @@ func TestNewMapGrowOnly_OnlyShrinksOnClear(t *testing.T) {
}
func TestMapResize(t *testing.T) {
testMapResize(t, NewMap[string, int]())
}
func testMapResize(t *testing.T, m *Map[string, int]) {
m := NewMap[string, int]()
const numEntries = 100_000
for i := 0; i < numEntries; i++ {
@@ -810,6 +808,147 @@ func TestMapResize_CounterLenLimit(t *testing.T) {
}
}
func testParallelResize(t *testing.T, numGoroutines int) {
m := NewMap[int, int]()
// Fill the map to trigger resizing
const initialEntries = 10000
const newEntries = 5000
for i := 0; i < initialEntries; i++ {
m.Store(i, i*2)
}
// Start concurrent operations that should trigger helping behavior
var wg sync.WaitGroup
// Launch goroutines that will encounter resize operations
for g := 0; g < numGoroutines; g++ {
wg.Add(1)
go func(goroutineID int) {
defer wg.Done()
// Perform many operations to trigger resize and helping
for i := 0; i < newEntries; i++ {
key := goroutineID*newEntries + i + initialEntries
m.Store(key, key*2)
// Verify the value
if val, ok := m.Load(key); !ok || val != key*2 {
t.Errorf("Failed to load key %d: got %v, %v", key, val, ok)
return
}
}
}(g)
}
wg.Wait()
// Verify all entries are present
finalSize := m.Size()
expectedSize := initialEntries + numGoroutines*newEntries
if finalSize != expectedSize {
t.Errorf("Expected size %d, got %d", expectedSize, finalSize)
}
stats := m.Stats()
if stats.TotalGrowths == 0 {
t.Error("Expected at least one table growth due to concurrent operations")
}
}
func TestMapParallelResize(t *testing.T) {
testParallelResize(t, 1)
testParallelResize(t, runtime.GOMAXPROCS(0))
testParallelResize(t, 100)
}
func testParallelResizeWithSameKeys(t *testing.T, numGoroutines int) {
m := NewMap[int, int]()
// Fill the map to trigger resizing
const entries = 1000
for i := 0; i < entries; i++ {
m.Store(2*i, 2*i)
}
// Start concurrent operations that should trigger helping behavior
var wg sync.WaitGroup
// Launch goroutines that will encounter resize operations
for g := 0; g < numGoroutines; g++ {
wg.Add(1)
go func(goroutineID int) {
defer wg.Done()
for i := 0; i < 10*entries; i++ {
m.Store(i, i)
}
}(g)
}
wg.Wait()
// Verify all entries are present
finalSize := m.Size()
expectedSize := 10 * entries
if finalSize != expectedSize {
t.Errorf("Expected size %d, got %d", expectedSize, finalSize)
}
stats := m.Stats()
if stats.TotalGrowths == 0 {
t.Error("Expected at least one table growth due to concurrent operations")
}
}
func TestMapParallelResize_IntersectingKeys(t *testing.T) {
testParallelResizeWithSameKeys(t, 1)
testParallelResizeWithSameKeys(t, runtime.GOMAXPROCS(0))
testParallelResizeWithSameKeys(t, 100)
}
func testParallelShrinking(t *testing.T, numGoroutines int) {
m := NewMap[int, int]()
// Fill the map to trigger resizing
const entries = 100000
for i := 0; i < entries; i++ {
m.Store(i, i)
}
// Start concurrent operations that should trigger helping behavior
var wg sync.WaitGroup
// Launch goroutines that will encounter resize operations
for g := 0; g < numGoroutines; g++ {
wg.Add(1)
go func(goroutineID int) {
defer wg.Done()
for i := 0; i < entries; i++ {
m.Delete(i)
}
}(g)
}
wg.Wait()
// Verify all entries are present
finalSize := m.Size()
if finalSize != 0 {
t.Errorf("Expected size 0, got %d", finalSize)
}
stats := m.Stats()
if stats.TotalShrinks == 0 {
t.Error("Expected at least one table shrinking due to concurrent operations")
}
}
func TestMapParallelShrinking(t *testing.T) {
testParallelShrinking(t, 1)
testParallelShrinking(t, runtime.GOMAXPROCS(0))
testParallelShrinking(t, 100)
}
func parallelSeqMapGrower(m *Map[int, int], numEntries int, positive bool, cdone chan bool) {
for i := 0; i < numEntries; i++ {
if positive {
@@ -1459,7 +1598,7 @@ func BenchmarkMapRange(b *testing.B) {
}
// Benchmarks noop performance of Compute
func BenchmarkCompute(b *testing.B) {
func BenchmarkMapCompute(b *testing.B) {
tests := []struct {
Name string
Op ComputeOp
@@ -1487,6 +1626,57 @@ func BenchmarkCompute(b *testing.B) {
}
}
func BenchmarkMapParallelRehashing(b *testing.B) {
tests := []struct {
name string
goroutines int
numEntries int
}{
{"1goroutine_10M", 1, 10_000_000},
{"4goroutines_10M", 4, 10_000_000},
{"8goroutines_10M", 8, 10_000_000},
}
for _, test := range tests {
b.Run(test.name, func(b *testing.B) {
for i := 0; i < b.N; i++ {
m := NewMap[int, int]()
var wg sync.WaitGroup
entriesPerGoroutine := test.numEntries / test.goroutines
start := time.Now()
for g := 0; g < test.goroutines; g++ {
wg.Add(1)
go func(goroutineID int) {
defer wg.Done()
base := goroutineID * entriesPerGoroutine
for j := 0; j < entriesPerGoroutine; j++ {
key := base + j
m.Store(key, key)
}
}(g)
}
wg.Wait()
duration := time.Since(start)
b.ReportMetric(float64(test.numEntries)/duration.Seconds(), "entries/s")
finalSize := m.Size()
if finalSize != test.numEntries {
b.Fatalf("Expected size %d, got %d", test.numEntries, finalSize)
}
stats := m.Stats()
if stats.TotalGrowths == 0 {
b.Error("Expected at least one table growth during rehashing")
}
}
})
}
}
func TestNextPowOf2(t *testing.T) {
if nextPowOf2(0) != 1 {
t.Error("nextPowOf2 failed")

View File

@@ -50,6 +50,10 @@ func (c *cachefileStore) FlushFakeIP() error {
return c.cache.FlushFakeIP()
}
func newCachefileStore(cache *cachefile.CacheFile) *cachefileStore {
return &cachefileStore{cache.FakeIpStore()}
func newCachefileStore(cache *cachefile.CacheFile, prefix netip.Prefix) *cachefileStore {
if prefix.Addr().Is6() {
return &cachefileStore{cache.FakeIpStore6()}
} else {
return &cachefileStore{cache.FakeIpStore()}
}
}

View File

@@ -7,7 +7,6 @@ import (
"sync"
"github.com/metacubex/mihomo/component/profile/cachefile"
C "github.com/metacubex/mihomo/constant"
"go4.org/netipx"
)
@@ -36,8 +35,6 @@ type Pool struct {
offset netip.Addr
cycle bool
mux sync.Mutex
host []C.DomainMatcher
mode C.FilterMode
ipnet netip.Prefix
store store
}
@@ -66,24 +63,6 @@ func (p *Pool) LookBack(ip netip.Addr) (string, bool) {
return p.store.GetByIP(ip)
}
// ShouldSkipped return if domain should be skipped
func (p *Pool) ShouldSkipped(domain string) bool {
should := p.shouldSkipped(domain)
if p.mode == C.FilterWhiteList {
return !should
}
return should
}
func (p *Pool) shouldSkipped(domain string) bool {
for _, matcher := range p.host {
if matcher.MatchDomain(domain) {
return true
}
}
return false
}
// Exist returns if given ip exists in fake-ip pool
func (p *Pool) Exist(ip netip.Addr) bool {
p.mux.Lock()
@@ -166,8 +145,6 @@ func (p *Pool) restoreState() {
type Options struct {
IPNet netip.Prefix
Host []C.DomainMatcher
Mode C.FilterMode
// Size sets the maximum number of entries in memory
// and does not work if Persistence is true
@@ -197,12 +174,10 @@ func New(options Options) (*Pool, error) {
last: last,
offset: first.Prev(),
cycle: false,
host: options.Host,
mode: options.Mode,
ipnet: options.IPNet,
}
if options.Persistence {
pool.store = newCachefileStore(cachefile.Cache())
pool.store = newCachefileStore(cachefile.Cache(), options.IPNet)
} else {
pool.store = newMemoryStore(options.Size)
}

View File

@@ -8,8 +8,6 @@ import (
"time"
"github.com/metacubex/mihomo/component/profile/cachefile"
"github.com/metacubex/mihomo/component/trie"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/bbolt"
"github.com/stretchr/testify/assert"
@@ -43,7 +41,7 @@ func createCachefileStore(options Options) (*Pool, string, error) {
return nil, "", err
}
pool.store = newCachefileStore(&cachefile.CacheFile{DB: db})
pool.store = newCachefileStore(&cachefile.CacheFile{DB: db}, options.IPNet)
return pool, f.Name(), nil
}
@@ -146,47 +144,6 @@ func TestPool_CycleUsed(t *testing.T) {
}
}
func TestPool_Skip(t *testing.T) {
ipnet := netip.MustParsePrefix("192.168.0.1/29")
tree := trie.New[struct{}]()
assert.NoError(t, tree.Insert("example.com", struct{}{}))
assert.False(t, tree.IsEmpty())
pools, tempfile, err := createPools(Options{
IPNet: ipnet,
Size: 10,
Host: []C.DomainMatcher{tree.NewDomainSet()},
})
assert.Nil(t, err)
defer os.Remove(tempfile)
for _, pool := range pools {
assert.True(t, pool.ShouldSkipped("example.com"))
assert.False(t, pool.ShouldSkipped("foo.com"))
assert.False(t, pool.shouldSkipped("baz.com"))
}
}
func TestPool_SkipWhiteList(t *testing.T) {
ipnet := netip.MustParsePrefix("192.168.0.1/29")
tree := trie.New[struct{}]()
assert.NoError(t, tree.Insert("example.com", struct{}{}))
assert.False(t, tree.IsEmpty())
pools, tempfile, err := createPools(Options{
IPNet: ipnet,
Size: 10,
Host: []C.DomainMatcher{tree.NewDomainSet()},
Mode: C.FilterWhiteList,
})
assert.Nil(t, err)
defer os.Remove(tempfile)
for _, pool := range pools {
assert.False(t, pool.ShouldSkipped("example.com"))
assert.True(t, pool.ShouldSkipped("foo.com"))
assert.True(t, pool.ShouldSkipped("baz.com"))
}
}
func TestPool_MaxCacheSize(t *testing.T) {
ipnet := netip.MustParsePrefix("192.168.0.1/24")
pool, _ := New(Options{

View File

@@ -0,0 +1,28 @@
package fakeip
import (
C "github.com/metacubex/mihomo/constant"
)
type Skipper struct {
Host []C.DomainMatcher
Mode C.FilterMode
}
// ShouldSkipped return if domain should be skipped
func (p *Skipper) ShouldSkipped(domain string) bool {
should := p.shouldSkipped(domain)
if p.Mode == C.FilterWhiteList {
return !should
}
return should
}
func (p *Skipper) shouldSkipped(domain string) bool {
for _, matcher := range p.Host {
if matcher.MatchDomain(domain) {
return true
}
}
return false
}

View File

@@ -0,0 +1,35 @@
package fakeip
import (
"testing"
"github.com/metacubex/mihomo/component/trie"
C "github.com/metacubex/mihomo/constant"
"github.com/stretchr/testify/assert"
)
func TestSkipper_BlackList(t *testing.T) {
tree := trie.New[struct{}]()
assert.NoError(t, tree.Insert("example.com", struct{}{}))
assert.False(t, tree.IsEmpty())
skipper := &Skipper{
Host: []C.DomainMatcher{tree.NewDomainSet()},
}
assert.True(t, skipper.ShouldSkipped("example.com"))
assert.False(t, skipper.ShouldSkipped("foo.com"))
assert.False(t, skipper.shouldSkipped("baz.com"))
}
func TestSkipper_WhiteList(t *testing.T) {
tree := trie.New[struct{}]()
assert.NoError(t, tree.Insert("example.com", struct{}{}))
assert.False(t, tree.IsEmpty())
skipper := &Skipper{
Host: []C.DomainMatcher{tree.NewDomainSet()},
Mode: C.FilterWhiteList,
}
assert.False(t, skipper.ShouldSkipped("example.com"))
assert.True(t, skipper.ShouldSkipped("foo.com"))
assert.True(t, skipper.ShouldSkipped("baz.com"))
}

View File

@@ -1,9 +1,9 @@
package memory
import (
"syscall"
"unsafe"
"github.com/ebitengine/purego"
_ "unsafe"
)
const PROC_PIDTASKINFO = 4
@@ -29,24 +29,12 @@ type ProcTaskInfo struct {
Priority int32
}
const System = "/usr/lib/libSystem.B.dylib"
type ProcPidInfoFunc func(pid, flavor int32, arg uint64, buffer uintptr, bufferSize int32) int32
const ProcPidInfoSym = "proc_pidinfo"
func GetMemoryInfo(pid int32) (*MemoryInfoStat, error) {
lib, err := purego.Dlopen(System, purego.RTLD_LAZY|purego.RTLD_GLOBAL)
if err != nil {
return nil, err
}
defer purego.Dlclose(lib)
var procPidInfo ProcPidInfoFunc
purego.RegisterLibFunc(&procPidInfo, lib, ProcPidInfoSym)
var ti ProcTaskInfo
procPidInfo(pid, PROC_PIDTASKINFO, 0, uintptr(unsafe.Pointer(&ti)), int32(unsafe.Sizeof(ti)))
_, _, errno := syscall_syscall6(proc_pidinfo_trampoline_addr, uintptr(pid), PROC_PIDTASKINFO, 0, uintptr(unsafe.Pointer(&ti)), unsafe.Sizeof(ti), 0)
if errno != 0 {
return nil, errno
}
ret := &MemoryInfoStat{
RSS: uint64(ti.Resident_size),
@@ -54,3 +42,26 @@ func GetMemoryInfo(pid int32) (*MemoryInfoStat, error) {
}
return ret, nil
}
var proc_pidinfo_trampoline_addr uintptr
//go:cgo_import_dynamic proc_pidinfo proc_pidinfo "/usr/lib/libSystem.B.dylib"
// from golang.org/x/sys@v0.30.0/unix/syscall_darwin_libSystem.go
// Implemented in the runtime package (runtime/sys_darwin.go)
func syscall_syscall(fn, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno)
func syscall_syscall6(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno)
func syscall_syscall6X(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno)
func syscall_syscall9(fn, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) // 32-bit only
func syscall_rawSyscall(fn, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno)
func syscall_rawSyscall6(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno)
func syscall_syscallPtr(fn, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno)
//go:linkname syscall_syscall syscall.syscall
//go:linkname syscall_syscall6 syscall.syscall6
//go:linkname syscall_syscall6X syscall.syscall6X
//go:linkname syscall_syscall9 syscall.syscall9
//go:linkname syscall_rawSyscall syscall.rawSyscall
//go:linkname syscall_rawSyscall6 syscall.rawSyscall6
//go:linkname syscall_syscallPtr syscall.syscallPtr

View File

@@ -0,0 +1,9 @@
// go run mkasm.go darwin amd64
// Code generated by the command above; DO NOT EDIT.
#include "textflag.h"
TEXT proc_pidinfo_trampoline<>(SB),NOSPLIT,$0-0
JMP proc_pidinfo(SB)
GLOBL ·proc_pidinfo_trampoline_addr(SB), RODATA, $8
DATA ·proc_pidinfo_trampoline_addr(SB)/8, $proc_pidinfo_trampoline<>(SB)

View File

@@ -0,0 +1,9 @@
// go run mkasm.go darwin arm64
// Code generated by the command above; DO NOT EDIT.
#include "textflag.h"
TEXT proc_pidinfo_trampoline<>(SB),NOSPLIT,$0-0
JMP proc_pidinfo(SB)
GLOBL ·proc_pidinfo_trampoline_addr(SB), RODATA, $8
DATA ·proc_pidinfo_trampoline_addr(SB)/8, $proc_pidinfo_trampoline<>(SB)

View File

@@ -19,6 +19,7 @@ var (
bucketSelected = []byte("selected")
bucketFakeip = []byte("fakeip")
bucketFakeip6 = []byte("fakeip6")
bucketETag = []byte("etag")
bucketSubscriptionInfo = []byte("subscriptioninfo")
)

View File

@@ -10,10 +10,15 @@ import (
type FakeIpStore struct {
*CacheFile
bucketName []byte
}
func (c *CacheFile) FakeIpStore() *FakeIpStore {
return &FakeIpStore{c}
return &FakeIpStore{c, bucketFakeip}
}
func (c *CacheFile) FakeIpStore6() *FakeIpStore {
return &FakeIpStore{c, bucketFakeip6}
}
func (c *FakeIpStore) GetByHost(host string) (ip netip.Addr, exist bool) {
@@ -21,7 +26,7 @@ func (c *FakeIpStore) GetByHost(host string) (ip netip.Addr, exist bool) {
return
}
c.DB.View(func(t *bbolt.Tx) error {
if bucket := t.Bucket(bucketFakeip); bucket != nil {
if bucket := t.Bucket(c.bucketName); bucket != nil {
if v := bucket.Get([]byte(host)); v != nil {
ip, exist = netip.AddrFromSlice(v)
}
@@ -36,7 +41,7 @@ func (c *FakeIpStore) PutByHost(host string, ip netip.Addr) {
return
}
err := c.DB.Batch(func(t *bbolt.Tx) error {
bucket, err := t.CreateBucketIfNotExists(bucketFakeip)
bucket, err := t.CreateBucketIfNotExists(c.bucketName)
if err != nil {
return err
}
@@ -52,7 +57,7 @@ func (c *FakeIpStore) GetByIP(ip netip.Addr) (host string, exist bool) {
return
}
c.DB.View(func(t *bbolt.Tx) error {
if bucket := t.Bucket(bucketFakeip); bucket != nil {
if bucket := t.Bucket(c.bucketName); bucket != nil {
if v := bucket.Get(ip.AsSlice()); v != nil {
host, exist = string(v), true
}
@@ -67,7 +72,7 @@ func (c *FakeIpStore) PutByIP(ip netip.Addr, host string) {
return
}
err := c.DB.Batch(func(t *bbolt.Tx) error {
bucket, err := t.CreateBucketIfNotExists(bucketFakeip)
bucket, err := t.CreateBucketIfNotExists(c.bucketName)
if err != nil {
return err
}
@@ -85,7 +90,7 @@ func (c *FakeIpStore) DelByIP(ip netip.Addr) {
addr := ip.AsSlice()
err := c.DB.Batch(func(t *bbolt.Tx) error {
bucket, err := t.CreateBucketIfNotExists(bucketFakeip)
bucket, err := t.CreateBucketIfNotExists(c.bucketName)
if err != nil {
return err
}
@@ -105,11 +110,11 @@ func (c *FakeIpStore) DelByIP(ip netip.Addr) {
func (c *FakeIpStore) FlushFakeIP() error {
err := c.DB.Batch(func(t *bbolt.Tx) error {
bucket := t.Bucket(bucketFakeip)
bucket := t.Bucket(c.bucketName)
if bucket == nil {
return nil
}
return t.DeleteBucket(bucketFakeip)
return t.DeleteBucket(c.bucketName)
})
return err
}

View File

@@ -8,7 +8,7 @@ import (
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/component/slowdown"
types "github.com/metacubex/mihomo/constant/provider"
P "github.com/metacubex/mihomo/constant/provider"
"github.com/metacubex/mihomo/log"
"github.com/metacubex/fswatch"
@@ -22,7 +22,7 @@ type Fetcher[V any] struct {
ctxCancel context.CancelFunc
resourceType string
name string
vehicle types.Vehicle
vehicle P.Vehicle
updatedAt time.Time
hash utils.HashType
parser Parser[V]
@@ -37,11 +37,11 @@ func (f *Fetcher[V]) Name() string {
return f.name
}
func (f *Fetcher[V]) Vehicle() types.Vehicle {
func (f *Fetcher[V]) Vehicle() P.Vehicle {
return f.vehicle
}
func (f *Fetcher[V]) VehicleType() types.VehicleType {
func (f *Fetcher[V]) VehicleType() P.VehicleType {
return f.vehicle.Type()
}
@@ -88,7 +88,7 @@ func (f *Fetcher[V]) Update() (V, bool, error) {
f.backoff.AddAttempt() // add a failed attempt to backoff
return lo.Empty[V](), false, err
}
return f.loadBuf(buf, hash, f.vehicle.Type() != types.File)
return f.loadBuf(buf, hash, f.vehicle.Type() != P.File)
}
func (f *Fetcher[V]) SideUpdate(buf []byte) (V, bool, error) {
@@ -180,7 +180,7 @@ func (f *Fetcher[V]) pullLoop(forceUpdate bool) {
func (f *Fetcher[V]) startPullLoop(forceUpdate bool) (err error) {
// pull contents automatically
if f.vehicle.Type() == types.File {
if f.vehicle.Type() == P.File {
f.watcher, err = fswatch.NewWatcher(fswatch.Options{
Path: []string{f.vehicle.Path()},
Callback: f.updateCallback,
@@ -218,7 +218,7 @@ func (f *Fetcher[V]) updateWithLog() {
return
}
func NewFetcher[V any](name string, interval time.Duration, vehicle types.Vehicle, parser Parser[V], onUpdate func(V)) *Fetcher[V] {
func NewFetcher[V any](name string, interval time.Duration, vehicle P.Vehicle, parser Parser[V], onUpdate func(V)) *Fetcher[V] {
ctx, cancel := context.WithCancel(context.Background())
minBackoff := 10 * time.Second
if interval < minBackoff {

View File

@@ -12,7 +12,7 @@ import (
"github.com/metacubex/mihomo/common/utils"
mihomoHttp "github.com/metacubex/mihomo/component/http"
"github.com/metacubex/mihomo/component/profile/cachefile"
types "github.com/metacubex/mihomo/constant/provider"
P "github.com/metacubex/mihomo/constant/provider"
)
const (
@@ -50,8 +50,8 @@ type FileVehicle struct {
path string
}
func (f *FileVehicle) Type() types.VehicleType {
return types.File
func (f *FileVehicle) Type() P.VehicleType {
return P.File
}
func (f *FileVehicle) Path() string {
@@ -91,15 +91,15 @@ type HTTPVehicle struct {
timeout time.Duration
sizeLimit int64
inRead func(response *http.Response)
provider types.ProxyProvider
provider P.ProxyProvider
}
func (h *HTTPVehicle) Url() string {
return h.url
}
func (h *HTTPVehicle) Type() types.VehicleType {
return types.HTTP
func (h *HTTPVehicle) Type() P.VehicleType {
return P.HTTP
}
func (h *HTTPVehicle) Path() string {

View File

@@ -20,15 +20,15 @@ import (
"github.com/metacubex/mihomo/component/cidr"
"github.com/metacubex/mihomo/component/fakeip"
"github.com/metacubex/mihomo/component/geodata"
P "github.com/metacubex/mihomo/component/process"
"github.com/metacubex/mihomo/component/process"
"github.com/metacubex/mihomo/component/resolver"
"github.com/metacubex/mihomo/component/sniffer"
"github.com/metacubex/mihomo/component/trie"
C "github.com/metacubex/mihomo/constant"
providerTypes "github.com/metacubex/mihomo/constant/provider"
P "github.com/metacubex/mihomo/constant/provider"
snifferTypes "github.com/metacubex/mihomo/constant/sniffer"
"github.com/metacubex/mihomo/dns"
L "github.com/metacubex/mihomo/listener"
"github.com/metacubex/mihomo/listener"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/log"
R "github.com/metacubex/mihomo/rules"
@@ -44,27 +44,27 @@ import (
// General config
type General struct {
Inbound
Mode T.TunnelMode `json:"mode"`
UnifiedDelay bool `json:"unified-delay"`
LogLevel log.LogLevel `json:"log-level"`
IPv6 bool `json:"ipv6"`
Interface string `json:"interface-name"`
RoutingMark int `json:"routing-mark"`
GeoXUrl GeoXUrl `json:"geox-url"`
GeoAutoUpdate bool `json:"geo-auto-update"`
GeoUpdateInterval int `json:"geo-update-interval"`
GeodataMode bool `json:"geodata-mode"`
GeodataLoader string `json:"geodata-loader"`
GeositeMatcher string `json:"geosite-matcher"`
TCPConcurrent bool `json:"tcp-concurrent"`
FindProcessMode P.FindProcessMode `json:"find-process-mode"`
Sniffing bool `json:"sniffing"`
GlobalClientFingerprint string `json:"global-client-fingerprint"`
GlobalUA string `json:"global-ua"`
ETagSupport bool `json:"etag-support"`
KeepAliveIdle int `json:"keep-alive-idle"`
KeepAliveInterval int `json:"keep-alive-interval"`
DisableKeepAlive bool `json:"disable-keep-alive"`
Mode T.TunnelMode `json:"mode"`
UnifiedDelay bool `json:"unified-delay"`
LogLevel log.LogLevel `json:"log-level"`
IPv6 bool `json:"ipv6"`
Interface string `json:"interface-name"`
RoutingMark int `json:"routing-mark"`
GeoXUrl GeoXUrl `json:"geox-url"`
GeoAutoUpdate bool `json:"geo-auto-update"`
GeoUpdateInterval int `json:"geo-update-interval"`
GeodataMode bool `json:"geodata-mode"`
GeodataLoader string `json:"geodata-loader"`
GeositeMatcher string `json:"geosite-matcher"`
TCPConcurrent bool `json:"tcp-concurrent"`
FindProcessMode process.FindProcessMode `json:"find-process-mode"`
Sniffing bool `json:"sniffing"`
GlobalClientFingerprint string `json:"global-client-fingerprint"`
GlobalUA string `json:"global-ua"`
ETagSupport bool `json:"etag-support"`
KeepAliveIdle int `json:"keep-alive-idle"`
KeepAliveInterval int `json:"keep-alive-interval"`
DisableKeepAlive bool `json:"disable-keep-alive"`
}
// Inbound config
@@ -157,7 +157,12 @@ type DNS struct {
DefaultNameserver []dns.NameServer
CacheAlgorithm string
CacheMaxSize int
FakeIPRange *fakeip.Pool
FakeIPRange netip.Prefix
FakeIPPool *fakeip.Pool
FakeIPRange6 netip.Prefix
FakeIPPool6 *fakeip.Pool
FakeIPSkipper *fakeip.Skipper
FakeIPTTL int
NameServerPolicy []dns.Policy
ProxyServerNameserver []dns.NameServer
DirectNameServer []dns.NameServer
@@ -195,8 +200,8 @@ type Config struct {
Users []auth.AuthUser
Proxies map[string]C.Proxy
Listeners map[string]C.InboundListener
Providers map[string]providerTypes.ProxyProvider
RuleProviders map[string]providerTypes.RuleProvider
Providers map[string]P.ProxyProvider
RuleProviders map[string]P.RuleProvider
Tunnels []LC.Tunnel
Sniffer *sniffer.Config
TLS *TLS
@@ -221,8 +226,10 @@ type RawDNS struct {
Listen string `yaml:"listen" json:"listen"`
EnhancedMode C.DNSMode `yaml:"enhanced-mode" json:"enhanced-mode"`
FakeIPRange string `yaml:"fake-ip-range" json:"fake-ip-range"`
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"`
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"`
CacheMaxSize int `yaml:"cache-max-size" json:"cache-max-size"`
@@ -377,51 +384,51 @@ type RawTLS struct {
}
type RawConfig struct {
Port int `yaml:"port" json:"port"`
SocksPort int `yaml:"socks-port" json:"socks-port"`
RedirPort int `yaml:"redir-port" json:"redir-port"`
TProxyPort int `yaml:"tproxy-port" json:"tproxy-port"`
MixedPort int `yaml:"mixed-port" json:"mixed-port"`
ShadowSocksConfig string `yaml:"ss-config" json:"ss-config"`
VmessConfig string `yaml:"vmess-config" json:"vmess-config"`
InboundTfo bool `yaml:"inbound-tfo" json:"inbound-tfo"`
InboundMPTCP bool `yaml:"inbound-mptcp" json:"inbound-mptcp"`
Authentication []string `yaml:"authentication" json:"authentication"`
SkipAuthPrefixes []netip.Prefix `yaml:"skip-auth-prefixes" json:"skip-auth-prefixes"`
LanAllowedIPs []netip.Prefix `yaml:"lan-allowed-ips" json:"lan-allowed-ips"`
LanDisAllowedIPs []netip.Prefix `yaml:"lan-disallowed-ips" json:"lan-disallowed-ips"`
AllowLan bool `yaml:"allow-lan" json:"allow-lan"`
BindAddress string `yaml:"bind-address" json:"bind-address"`
Mode T.TunnelMode `yaml:"mode" json:"mode"`
UnifiedDelay bool `yaml:"unified-delay" json:"unified-delay"`
LogLevel log.LogLevel `yaml:"log-level" json:"log-level"`
IPv6 bool `yaml:"ipv6" json:"ipv6"`
ExternalController string `yaml:"external-controller" json:"external-controller"`
ExternalControllerPipe string `yaml:"external-controller-pipe" json:"external-controller-pipe"`
ExternalControllerUnix string `yaml:"external-controller-unix" json:"external-controller-unix"`
ExternalControllerTLS string `yaml:"external-controller-tls" json:"external-controller-tls"`
ExternalControllerCors RawCors `yaml:"external-controller-cors" json:"external-controller-cors"`
ExternalUI string `yaml:"external-ui" json:"external-ui"`
ExternalUIURL string `yaml:"external-ui-url" json:"external-ui-url"`
ExternalUIName string `yaml:"external-ui-name" json:"external-ui-name"`
ExternalDohServer string `yaml:"external-doh-server" json:"external-doh-server"`
Secret string `yaml:"secret" json:"secret"`
Interface string `yaml:"interface-name" json:"interface-name"`
RoutingMark int `yaml:"routing-mark" json:"routing-mark"`
Tunnels []LC.Tunnel `yaml:"tunnels" json:"tunnels"`
GeoAutoUpdate bool `yaml:"geo-auto-update" json:"geo-auto-update"`
GeoUpdateInterval int `yaml:"geo-update-interval" json:"geo-update-interval"`
GeodataMode bool `yaml:"geodata-mode" json:"geodata-mode"`
GeodataLoader string `yaml:"geodata-loader" json:"geodata-loader"`
GeositeMatcher string `yaml:"geosite-matcher" json:"geosite-matcher"`
TCPConcurrent bool `yaml:"tcp-concurrent" json:"tcp-concurrent"`
FindProcessMode P.FindProcessMode `yaml:"find-process-mode" json:"find-process-mode"`
GlobalClientFingerprint string `yaml:"global-client-fingerprint" json:"global-client-fingerprint"`
GlobalUA string `yaml:"global-ua" json:"global-ua"`
ETagSupport bool `yaml:"etag-support" json:"etag-support"`
KeepAliveIdle int `yaml:"keep-alive-idle" json:"keep-alive-idle"`
KeepAliveInterval int `yaml:"keep-alive-interval" json:"keep-alive-interval"`
DisableKeepAlive bool `yaml:"disable-keep-alive" json:"disable-keep-alive"`
Port int `yaml:"port" json:"port"`
SocksPort int `yaml:"socks-port" json:"socks-port"`
RedirPort int `yaml:"redir-port" json:"redir-port"`
TProxyPort int `yaml:"tproxy-port" json:"tproxy-port"`
MixedPort int `yaml:"mixed-port" json:"mixed-port"`
ShadowSocksConfig string `yaml:"ss-config" json:"ss-config"`
VmessConfig string `yaml:"vmess-config" json:"vmess-config"`
InboundTfo bool `yaml:"inbound-tfo" json:"inbound-tfo"`
InboundMPTCP bool `yaml:"inbound-mptcp" json:"inbound-mptcp"`
Authentication []string `yaml:"authentication" json:"authentication"`
SkipAuthPrefixes []netip.Prefix `yaml:"skip-auth-prefixes" json:"skip-auth-prefixes"`
LanAllowedIPs []netip.Prefix `yaml:"lan-allowed-ips" json:"lan-allowed-ips"`
LanDisAllowedIPs []netip.Prefix `yaml:"lan-disallowed-ips" json:"lan-disallowed-ips"`
AllowLan bool `yaml:"allow-lan" json:"allow-lan"`
BindAddress string `yaml:"bind-address" json:"bind-address"`
Mode T.TunnelMode `yaml:"mode" json:"mode"`
UnifiedDelay bool `yaml:"unified-delay" json:"unified-delay"`
LogLevel log.LogLevel `yaml:"log-level" json:"log-level"`
IPv6 bool `yaml:"ipv6" json:"ipv6"`
ExternalController string `yaml:"external-controller" json:"external-controller"`
ExternalControllerPipe string `yaml:"external-controller-pipe" json:"external-controller-pipe"`
ExternalControllerUnix string `yaml:"external-controller-unix" json:"external-controller-unix"`
ExternalControllerTLS string `yaml:"external-controller-tls" json:"external-controller-tls"`
ExternalControllerCors RawCors `yaml:"external-controller-cors" json:"external-controller-cors"`
ExternalUI string `yaml:"external-ui" json:"external-ui"`
ExternalUIURL string `yaml:"external-ui-url" json:"external-ui-url"`
ExternalUIName string `yaml:"external-ui-name" json:"external-ui-name"`
ExternalDohServer string `yaml:"external-doh-server" json:"external-doh-server"`
Secret string `yaml:"secret" json:"secret"`
Interface string `yaml:"interface-name" json:"interface-name"`
RoutingMark int `yaml:"routing-mark" json:"routing-mark"`
Tunnels []LC.Tunnel `yaml:"tunnels" json:"tunnels"`
GeoAutoUpdate bool `yaml:"geo-auto-update" json:"geo-auto-update"`
GeoUpdateInterval int `yaml:"geo-update-interval" json:"geo-update-interval"`
GeodataMode bool `yaml:"geodata-mode" json:"geodata-mode"`
GeodataLoader string `yaml:"geodata-loader" json:"geodata-loader"`
GeositeMatcher string `yaml:"geosite-matcher" json:"geosite-matcher"`
TCPConcurrent bool `yaml:"tcp-concurrent" json:"tcp-concurrent"`
FindProcessMode process.FindProcessMode `yaml:"find-process-mode" json:"find-process-mode"`
GlobalClientFingerprint string `yaml:"global-client-fingerprint" json:"global-client-fingerprint"`
GlobalUA string `yaml:"global-ua" json:"global-ua"`
ETagSupport bool `yaml:"etag-support" json:"etag-support"`
KeepAliveIdle int `yaml:"keep-alive-idle" json:"keep-alive-idle"`
KeepAliveInterval int `yaml:"keep-alive-interval" json:"keep-alive-interval"`
DisableKeepAlive bool `yaml:"disable-keep-alive" json:"disable-keep-alive"`
ProxyProvider map[string]map[string]any `yaml:"proxy-providers" json:"proxy-providers"`
RuleProvider map[string]map[string]any `yaml:"rule-providers" json:"rule-providers"`
@@ -474,7 +481,7 @@ func DefaultRawConfig() *RawConfig {
Proxy: []map[string]any{},
ProxyGroup: []map[string]any{},
TCPConcurrent: false,
FindProcessMode: P.FindProcessStrict,
FindProcessMode: process.FindProcessStrict,
GlobalUA: "clash.meta/" + C.Version,
ETagSupport: true,
DNS: RawDNS{
@@ -485,6 +492,7 @@ func DefaultRawConfig() *RawConfig {
IPv6Timeout: 100,
EnhancedMode: C.DNSMapping,
FakeIPRange: "198.18.0.1/16",
FakeIPTTL: 1,
FallbackFilter: RawFallbackFilter{
GeoIP: true,
GeoIPCode: "CN",
@@ -648,11 +656,11 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
config.Proxies = proxies
config.Providers = providers
listener, err := parseListeners(rawCfg)
listeners, err := parseListeners(rawCfg)
if err != nil {
return nil, err
}
config.Listeners = listener
config.Listeners = listeners
log.Infoln("Geodata Loader mode: %s", geodata.LoaderName())
log.Infoln("Geosite Matcher implementation: %s", geodata.SiteMatcherName())
@@ -680,13 +688,15 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
}
config.Hosts = hosts
parseIPV6(rawCfg) // must before DNS and Tun
dnsCfg, err := parseDNS(rawCfg, ruleProviders)
if err != nil {
return nil, err
}
config.DNS = dnsCfg
err = parseTun(rawCfg.Tun, config.General)
err = parseTun(rawCfg.Tun, dnsCfg, config.General)
if err != nil {
return nil, err
}
@@ -838,9 +848,9 @@ func parseTLS(cfg *RawConfig) (*TLS, error) {
}, nil
}
func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[string]providerTypes.ProxyProvider, err error) {
func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[string]P.ProxyProvider, err error) {
proxies = make(map[string]C.Proxy)
providersMap = make(map[string]providerTypes.ProxyProvider)
providersMap = make(map[string]P.ProxyProvider)
proxiesConfig := cfg.Proxy
groupsConfig := cfg.ProxyGroup
providersConfig := cfg.ProxyProvider
@@ -940,7 +950,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
&outboundgroup.GroupCommonOption{
Name: "GLOBAL",
},
[]providerTypes.ProxyProvider{pd},
[]P.ProxyProvider{pd},
)
proxies["GLOBAL"] = adapter.NewProxy(global)
}
@@ -950,24 +960,25 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
func parseListeners(cfg *RawConfig) (listeners map[string]C.InboundListener, err error) {
listeners = make(map[string]C.InboundListener)
for index, mapping := range cfg.Listeners {
listener, err := L.ParseListener(mapping)
inboundListener, err := listener.ParseListener(mapping)
if err != nil {
return nil, fmt.Errorf("proxy %d: %w", index, err)
}
if _, exist := mapping[listener.Name()]; exist {
return nil, fmt.Errorf("listener %s is the duplicate name", listener.Name())
name := inboundListener.Name()
if _, exist := mapping[name]; exist {
return nil, fmt.Errorf("listener %s is the duplicate name", name)
}
listeners[listener.Name()] = listener
listeners[name] = inboundListener
}
return
}
func parseRuleProviders(cfg *RawConfig) (ruleProviders map[string]providerTypes.RuleProvider, err error) {
func parseRuleProviders(cfg *RawConfig) (ruleProviders map[string]P.RuleProvider, err error) {
RP.SetTunnel(T.Tunnel)
ruleProviders = map[string]providerTypes.RuleProvider{}
ruleProviders = map[string]P.RuleProvider{}
// parse rule provider
for name, mapping := range cfg.RuleProvider {
rp, err := RP.ParseRuleProvider(name, mapping, R.ParseRule)
@@ -980,7 +991,7 @@ func parseRuleProviders(cfg *RawConfig) (ruleProviders map[string]providerTypes.
return
}
func parseSubRules(cfg *RawConfig, proxies map[string]C.Proxy, ruleProviders map[string]providerTypes.RuleProvider) (subRules map[string][]C.Rule, err error) {
func parseSubRules(cfg *RawConfig, proxies map[string]C.Proxy, ruleProviders map[string]P.RuleProvider) (subRules map[string][]C.Rule, err error) {
subRules = map[string][]C.Rule{}
for name := range cfg.SubRules {
subRules[name] = make([]C.Rule, 0)
@@ -1043,7 +1054,7 @@ func verifySubRuleCircularReferences(n string, subRules map[string][]C.Rule, arr
return nil
}
func parseRules(rulesConfig []string, proxies map[string]C.Proxy, ruleProviders map[string]providerTypes.RuleProvider, subRules map[string][]C.Rule, format string) ([]C.Rule, error) {
func parseRules(rulesConfig []string, proxies map[string]C.Proxy, ruleProviders map[string]P.RuleProvider, subRules map[string][]C.Rule, format string) ([]C.Rule, error) {
var rules []C.Rule
// parse rules
@@ -1266,7 +1277,7 @@ func parsePureDNSServer(server string) string {
}
}
func parseNameServerPolicy(nsPolicy *orderedmap.OrderedMap[string, any], ruleProviders map[string]providerTypes.RuleProvider, respectRules bool, preferH3 bool) ([]dns.Policy, error) {
func parseNameServerPolicy(nsPolicy *orderedmap.OrderedMap[string, any], ruleProviders map[string]P.RuleProvider, respectRules bool, preferH3 bool) ([]dns.Policy, error) {
var policy []dns.Policy
for pair := nsPolicy.Oldest(); pair != nil; pair = pair.Next() {
@@ -1341,7 +1352,7 @@ func parseNameServerPolicy(nsPolicy *orderedmap.OrderedMap[string, any], rulePro
return policy, nil
}
func parseDNS(rawCfg *RawConfig, ruleProviders map[string]providerTypes.RuleProvider) (*DNS, error) {
func parseDNS(rawCfg *RawConfig, ruleProviders map[string]P.RuleProvider) (*DNS, error) {
cfg := rawCfg.DNS
if cfg.Enable && len(cfg.NameServer) == 0 {
return nil, fmt.Errorf("if DNS configuration is turned on, NameServer cannot be empty")
@@ -1407,13 +1418,27 @@ func parseDNS(rawCfg *RawConfig, ruleProviders map[string]providerTypes.RuleProv
}
}
fakeIPRange, err := netip.ParsePrefix(cfg.FakeIPRange)
T.SetFakeIPRange(fakeIPRange)
if cfg.EnhancedMode == C.DNSFakeIP {
if cfg.FakeIPRange != "" {
dnsCfg.FakeIPRange, err = netip.ParsePrefix(cfg.FakeIPRange)
if err != nil {
return nil, err
}
if !dnsCfg.FakeIPRange.Addr().Is4() {
return nil, errors.New("dns.fake-ip-range must be a IPv4 prefix")
}
}
if cfg.FakeIPRange6 != "" {
dnsCfg.FakeIPRange6, err = netip.ParsePrefix(cfg.FakeIPRange6)
if err != nil {
return nil, err
}
if !dnsCfg.FakeIPRange6.Addr().Is6() {
return nil, errors.New("dns.fake-ip-range6 must be a IPv6 prefix")
}
}
if cfg.EnhancedMode == C.DNSFakeIP {
var fakeIPTrie *trie.DomainTrie[struct{}]
if len(dnsCfg.Fallback) != 0 {
fakeIPTrie = trie.New[struct{}]()
@@ -1431,18 +1456,40 @@ func parseDNS(rawCfg *RawConfig, ruleProviders map[string]providerTypes.RuleProv
return nil, err
}
pool, err := fakeip.New(fakeip.Options{
IPNet: fakeIPRange,
Size: 1000,
Host: host,
Mode: cfg.FakeIPFilterMode,
Persistence: rawCfg.Profile.StoreFakeIP,
})
if err != nil {
return nil, err
skipper := &fakeip.Skipper{
Host: host,
Mode: cfg.FakeIPFilterMode,
}
dnsCfg.FakeIPSkipper = skipper
dnsCfg.FakeIPTTL = cfg.FakeIPTTL
if dnsCfg.FakeIPRange.IsValid() {
pool, err := fakeip.New(fakeip.Options{
IPNet: dnsCfg.FakeIPRange,
Size: 1000,
Persistence: rawCfg.Profile.StoreFakeIP,
})
if err != nil {
return nil, err
}
dnsCfg.FakeIPPool = pool
}
dnsCfg.FakeIPRange = pool
if dnsCfg.FakeIPRange6.IsValid() {
pool6, err := fakeip.New(fakeip.Options{
IPNet: dnsCfg.FakeIPRange6,
Size: 1000,
Persistence: rawCfg.Profile.StoreFakeIP,
})
if err != nil {
return nil, err
}
dnsCfg.FakeIPPool6 = pool6
}
if dnsCfg.FakeIPPool == nil && dnsCfg.FakeIPPool6 == nil {
return nil, errors.New("disallow `fake-ip-range` and `fake-ip-range6` both empty with fake-ip mode")
}
}
if len(cfg.Fallback) != 0 {
@@ -1504,17 +1551,20 @@ func parseAuthentication(rawRecords []string) []auth.AuthUser {
return users
}
func parseTun(rawTun RawTun, general *General) error {
tunAddressPrefix := T.FakeIPRange()
func parseIPV6(rawCfg *RawConfig) {
if !rawCfg.IPv6 || !verifyIP6() {
rawCfg.DNS.FakeIPRange6 = ""
rawCfg.Tun.Inet6Address = nil
}
}
func parseTun(rawTun RawTun, dns *DNS, general *General) error {
tunAddressPrefix := dns.FakeIPRange
if !tunAddressPrefix.IsValid() {
tunAddressPrefix = netip.MustParsePrefix("198.18.0.1/16")
}
tunAddressPrefix = netip.PrefixFrom(tunAddressPrefix.Addr(), 30)
if !general.IPv6 || !verifyIP6() {
rawTun.Inet6Address = nil
}
general.Tun = LC.Tun{
Enable: rawTun.Enable,
Device: rawTun.Device,
@@ -1587,7 +1637,7 @@ func parseTuicServer(rawTuic RawTuicServer, general *General) error {
return nil
}
func parseSniffer(snifferRaw RawSniffer, ruleProviders map[string]providerTypes.RuleProvider) (*sniffer.Config, error) {
func parseSniffer(snifferRaw RawSniffer, ruleProviders map[string]P.RuleProvider) (*sniffer.Config, error) {
snifferConfig := &sniffer.Config{
Enable: snifferRaw.Enable,
ForceDnsMapping: snifferRaw.ForceDnsMapping,
@@ -1677,7 +1727,7 @@ func parseSniffer(snifferRaw RawSniffer, ruleProviders map[string]providerTypes.
return snifferConfig, nil
}
func parseIPCIDR(addresses []string, cidrSet *cidr.IpCidrSet, adapterName string, ruleProviders map[string]providerTypes.RuleProvider) (matchers []C.IpMatcher, err error) {
func parseIPCIDR(addresses []string, cidrSet *cidr.IpCidrSet, adapterName string, ruleProviders map[string]P.RuleProvider) (matchers []C.IpMatcher, err error) {
var matcher C.IpMatcher
for _, ipcidr := range addresses {
ipcidrLower := strings.ToLower(ipcidr)
@@ -1724,7 +1774,7 @@ func parseIPCIDR(addresses []string, cidrSet *cidr.IpCidrSet, adapterName string
return
}
func parseDomain(domains []string, domainTrie *trie.DomainTrie[struct{}], adapterName string, ruleProviders map[string]providerTypes.RuleProvider) (matchers []C.DomainMatcher, err error) {
func parseDomain(domains []string, domainTrie *trie.DomainTrie[struct{}], adapterName string, ruleProviders map[string]P.RuleProvider) (matchers []C.DomainMatcher, err error) {
var matcher C.DomainMatcher
for _, domain := range domains {
domainLower := strings.ToLower(domain)
@@ -1767,14 +1817,14 @@ func parseDomain(domains []string, domainTrie *trie.DomainTrie[struct{}], adapte
return
}
func parseIPRuleSet(domainSetName string, adapterName string, ruleProviders map[string]providerTypes.RuleProvider) (C.IpMatcher, error) {
func parseIPRuleSet(domainSetName string, adapterName string, ruleProviders map[string]P.RuleProvider) (C.IpMatcher, error) {
if rp, ok := ruleProviders[domainSetName]; !ok {
return nil, fmt.Errorf("not found rule-set: %s", domainSetName)
} else {
switch rp.Behavior() {
case providerTypes.Domain:
case P.Domain:
return nil, fmt.Errorf("rule provider type error, except ipcidr,actual %s", rp.Behavior())
case providerTypes.Classical:
case P.Classical:
log.Warnln("%s provider is %s, only matching it contain ip rule", rp.Name(), rp.Behavior())
default:
}
@@ -1782,14 +1832,14 @@ func parseIPRuleSet(domainSetName string, adapterName string, ruleProviders map[
return RP.NewRuleSet(domainSetName, adapterName, false, true)
}
func parseDomainRuleSet(domainSetName string, adapterName string, ruleProviders map[string]providerTypes.RuleProvider) (C.DomainMatcher, error) {
func parseDomainRuleSet(domainSetName string, adapterName string, ruleProviders map[string]P.RuleProvider) (C.DomainMatcher, error) {
if rp, ok := ruleProviders[domainSetName]; !ok {
return nil, fmt.Errorf("not found rule-set: %s", domainSetName)
} else {
switch rp.Behavior() {
case providerTypes.IPCIDR:
case P.IPCIDR:
return nil, fmt.Errorf("rule provider type error, except domain,actual %s", rp.Behavior())
case providerTypes.Classical:
case P.Classical:
log.Warnln("%s provider is %s, only matching it contain domain rule", rp.Name(), rp.Behavior())
default:
}

View File

@@ -155,6 +155,10 @@ func verifyIP6() bool {
}
}
}
} else {
// eg: Calling net.InterfaceAddrs() fails on Android SDK 30
// https://github.com/golang/go/issues/40569
return true // just ignore
}
return false
}

View File

@@ -44,6 +44,7 @@ const (
Ssh
Mieru
AnyTLS
Sudoku
)
const (
@@ -139,8 +140,11 @@ type ProxyAdapter interface {
// SupportUOT return UDP over TCP support
SupportUOT() bool
// SupportWithDialer only for deprecated relay group, the new protocol does not need to be implemented.
SupportWithDialer() NetWork
// DialContextWithDialer only for deprecated relay group, the new protocol does not need to be implemented.
DialContextWithDialer(ctx context.Context, dialer Dialer, metadata *Metadata) (Conn, error)
// ListenPacketWithDialer only for deprecated relay group, the new protocol does not need to be implemented.
ListenPacketWithDialer(ctx context.Context, dialer Dialer, metadata *Metadata) (PacketConn, error)
// IsL3Protocol return ProxyAdapter working in L3 (tell dns module not pass the domain to avoid loopback)
@@ -178,12 +182,6 @@ type Proxy interface {
ExtraDelayHistories() map[string]ProxyState
LastDelayForTestUrl(url string) uint16
URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16]) (uint16, error)
// Deprecated: use DialContext instead.
Dial(metadata *Metadata) (Conn, error)
// Deprecated: use DialPacketConn instead.
DialUDP(metadata *Metadata) (PacketConn, error)
}
// AdapterType is enum of adapter type
@@ -233,6 +231,8 @@ func (at AdapterType) String() string {
return "Mieru"
case AnyTLS:
return "AnyTLS"
case Sudoku:
return "Sudoku"
case Relay:
return "Relay"
case Selector:

View File

@@ -38,6 +38,8 @@ const (
TUIC
HYSTERIA2
ANYTLS
MIERU
SUDOKU
INNER
)
@@ -109,6 +111,10 @@ func (t Type) String() string {
return "Hysteria2"
case ANYTLS:
return "AnyTLS"
case MIERU:
return "Mieru"
case SUDOKU:
return "Sudoku"
case INNER:
return "Inner"
default:
@@ -149,6 +155,10 @@ func ParseType(t string) (*Type, error) {
res = HYSTERIA2
case "ANYTLS":
res = ANYTLS
case "MIERU":
res = MIERU
case "SUDOKU":
res = SUDOKU
case "INNER":
res = INNER
default:

View File

@@ -1,6 +1,7 @@
package dns
import (
"errors"
"net/netip"
"github.com/metacubex/mihomo/common/lru"
@@ -9,10 +10,13 @@ import (
)
type ResolverEnhancer struct {
mode C.DNSMode
fakePool *fakeip.Pool
mapping *lru.LruCache[netip.Addr, string]
useHosts bool
mode C.DNSMode
fakeIPPool *fakeip.Pool
fakeIPPool6 *fakeip.Pool
fakeIPSkipper *fakeip.Skipper
fakeIPTTL int
mapping *lru.LruCache[netip.Addr, string]
useHosts bool
}
func (h *ResolverEnhancer) FakeIPEnabled() bool {
@@ -28,8 +32,16 @@ func (h *ResolverEnhancer) IsExistFakeIP(ip netip.Addr) bool {
return false
}
if pool := h.fakePool; pool != nil {
return pool.Exist(ip)
if pool := h.fakeIPPool; pool != nil {
if pool.Exist(ip) {
return true
}
}
if pool6 := h.fakeIPPool6; pool6 != nil {
if pool6.Exist(ip) {
return true
}
}
return false
@@ -40,8 +52,16 @@ func (h *ResolverEnhancer) IsFakeIP(ip netip.Addr) bool {
return false
}
if pool := h.fakePool; pool != nil {
return pool.IPNet().Contains(ip) && ip != pool.Gateway() && ip != pool.Broadcast()
if pool := h.fakeIPPool; pool != nil {
if pool.IPNet().Contains(ip) && ip != pool.Gateway() && ip != pool.Broadcast() {
return true
}
}
if pool6 := h.fakeIPPool6; pool6 != nil {
if pool6.IPNet().Contains(ip) && ip != pool6.Gateway() && ip != pool6.Broadcast() {
return true
}
}
return false
@@ -52,20 +72,34 @@ func (h *ResolverEnhancer) IsFakeBroadcastIP(ip netip.Addr) bool {
return false
}
if pool := h.fakePool; pool != nil {
return pool.Broadcast() == ip
if pool := h.fakeIPPool; pool != nil {
if pool.Broadcast() == ip {
return true
}
}
if pool6 := h.fakeIPPool6; pool6 != nil {
if pool6.Broadcast() == ip {
return true
}
}
return false
}
func (h *ResolverEnhancer) FindHostByIP(ip netip.Addr) (string, bool) {
if pool := h.fakePool; pool != nil {
if pool := h.fakeIPPool; pool != nil {
if host, existed := pool.LookBack(ip); existed {
return host, true
}
}
if pool6 := h.fakeIPPool6; pool6 != nil {
if host, existed := pool6.LookBack(ip); existed {
return host, true
}
}
if mapping := h.mapping; mapping != nil {
if host, existed := h.mapping.Get(ip); existed {
return host, true
@@ -82,8 +116,19 @@ func (h *ResolverEnhancer) InsertHostByIP(ip netip.Addr, host string) {
}
func (h *ResolverEnhancer) FlushFakeIP() error {
if pool := h.fakePool; pool != nil {
return pool.FlushFakeIP()
var errs []error
if pool := h.fakeIPPool; pool != nil {
if err := pool.FlushFakeIP(); err != nil {
errs = append(errs, err)
}
}
if pool6 := h.fakeIPPool6; pool6 != nil {
if err := pool6.FlushFakeIP(); err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return errors.Join(errs...)
}
return nil
}
@@ -93,36 +138,53 @@ func (h *ResolverEnhancer) PatchFrom(o *ResolverEnhancer) {
o.mapping.CloneTo(h.mapping)
}
if h.fakePool != nil && o.fakePool != nil {
h.fakePool.CloneFrom(o.fakePool)
if h.fakeIPPool != nil && o.fakeIPPool != nil {
h.fakeIPPool.CloneFrom(o.fakeIPPool)
}
if h.fakeIPPool6 != nil && o.fakeIPPool6 != nil {
h.fakeIPPool6.CloneFrom(o.fakeIPPool6)
}
}
func (h *ResolverEnhancer) StoreFakePoolState() {
if h.fakePool != nil {
h.fakePool.StoreState()
if h.fakeIPPool != nil {
h.fakeIPPool.StoreState()
}
if h.fakeIPPool6 != nil {
h.fakeIPPool6.StoreState()
}
}
type EnhancerConfig struct {
EnhancedMode C.DNSMode
Pool *fakeip.Pool
UseHosts bool
IPv6 bool
EnhancedMode C.DNSMode
FakeIPPool *fakeip.Pool
FakeIPPool6 *fakeip.Pool
FakeIPSkipper *fakeip.Skipper
FakeIPTTL int
UseHosts bool
}
func NewEnhancer(cfg EnhancerConfig) *ResolverEnhancer {
var fakePool *fakeip.Pool
var mapping *lru.LruCache[netip.Addr, string]
if cfg.EnhancedMode != C.DNSNormal {
fakePool = cfg.Pool
mapping = lru.New(lru.WithSize[netip.Addr, string](4096))
}
return &ResolverEnhancer{
e := &ResolverEnhancer{
mode: cfg.EnhancedMode,
fakePool: fakePool,
mapping: mapping,
useHosts: cfg.UseHosts,
}
if cfg.EnhancedMode != C.DNSNormal {
e.fakeIPPool = cfg.FakeIPPool
if cfg.IPv6 {
e.fakeIPPool6 = cfg.FakeIPPool6
}
e.fakeIPSkipper = cfg.FakeIPSkipper
e.fakeIPTTL = cfg.FakeIPTTL
if e.fakeIPTTL < 1 {
e.fakeIPTTL = 1
}
e.mapping = lru.New(lru.WithSize[netip.Addr, string](4096))
}
return e
}

View File

@@ -64,11 +64,10 @@ func withHosts(mapping *lru.LruCache[netip.Addr, string]) middleware {
if mapping != nil {
mapping.SetWithExpire(ipAddr, host, time.Now().Add(time.Second*10))
}
} else if q.Qtype == D.TypeAAAA {
} else if ipAddr.Is6() && q.Qtype == D.TypeAAAA {
rr := &D.AAAA{}
rr.Hdr = D.RR_Header{Name: q.Name, Rrtype: D.TypeAAAA, Class: D.ClassINET, Ttl: 10}
ip := ipAddr.As16()
rr.AAAA = ip[:]
rr.AAAA = ipAddr.AsSlice()
msg.Answer = append(msg.Answer, rr)
if mapping != nil {
mapping.SetWithExpire(ipAddr, host, time.Now().Add(time.Second*10))
@@ -147,34 +146,47 @@ func withMapping(mapping *lru.LruCache[netip.Addr, string]) middleware {
}
}
func withFakeIP(fakePool *fakeip.Pool) middleware {
func withFakeIP(skipper *fakeip.Skipper, fakePool *fakeip.Pool, fakePool6 *fakeip.Pool, fakeIPTTL int) middleware {
return func(next handler) handler {
return func(ctx *icontext.DNSContext, r *D.Msg) (*D.Msg, error) {
q := r.Question[0]
host := strings.TrimRight(q.Name, ".")
if fakePool.ShouldSkipped(host) {
if skipper.ShouldSkipped(host) {
return next(ctx, r)
}
var rr D.RR
switch q.Qtype {
case D.TypeAAAA, D.TypeSVCB, D.TypeHTTPS:
case D.TypeA:
if fakePool == nil {
return handleMsgWithEmptyAnswer(r), nil
}
ip := fakePool.Lookup(host)
rr = &D.A{
Hdr: D.RR_Header{Name: q.Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: dnsDefaultTTL},
A: ip.AsSlice(),
}
case D.TypeAAAA:
if fakePool6 == nil {
return handleMsgWithEmptyAnswer(r), nil
}
ip := fakePool6.Lookup(host)
rr = &D.AAAA{
Hdr: D.RR_Header{Name: q.Name, Rrtype: D.TypeAAAA, Class: D.ClassINET, Ttl: dnsDefaultTTL},
AAAA: ip.AsSlice(),
}
case D.TypeSVCB, D.TypeHTTPS:
return handleMsgWithEmptyAnswer(r), nil
}
if q.Qtype != D.TypeA {
default:
return next(ctx, r)
}
rr := &D.A{}
rr.Hdr = D.RR_Header{Name: q.Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: dnsDefaultTTL}
ip := fakePool.Lookup(host)
rr.A = ip.AsSlice()
msg := r.Copy()
msg.Answer = []D.RR{rr}
ctx.SetType(icontext.DNSTypeFakeIP)
setMsgTTL(msg, 1)
setMsgTTL(msg, uint32(fakeIPTTL))
msg.SetRcode(r, D.RcodeSuccess)
msg.Authoritative = true
msg.RecursionAvailable = true
@@ -226,7 +238,7 @@ func newHandler(resolver *Resolver, mapper *ResolverEnhancer) handler {
}
if mapper.mode == C.DNSFakeIP {
middlewares = append(middlewares, withFakeIP(mapper.fakePool))
middlewares = append(middlewares, withFakeIP(mapper.fakeIPSkipper, mapper.fakeIPPool, mapper.fakeIPPool6, mapper.fakeIPTTL))
}
if mapper.mode != C.DNSNormal {

View File

@@ -261,6 +261,7 @@ dns:
enhanced-mode: fake-ip # or redir-host
fake-ip-range: 198.18.0.1/16 # fake-ip 池设置
# fake-ip-range6: fdfe:dcba:9876::1/64 # fake-ip6 池设置
# 配置不使用 fake-ip 的域名
fake-ip-filter:
@@ -274,6 +275,8 @@ dns:
# 配置fake-ip-filter的匹配模式默认为blacklist即如果匹配成功不返回fake-ip
# 可设置为whitelist即只有匹配成功才返回fake-ip
fake-ip-filter-mode: blacklist
# 配置fakeip查询返回的TTL非必要情况下请勿修改
fake-ip-ttl: 1
# use-hosts: true # 查询 hosts
@@ -1026,7 +1029,7 @@ proxies: # socks5
server: 1.2.3.4
port: 2999
# port-range: 2090-2099 #(不可同时填写 port 和 port-range
transport: TCP # 支持 TCP
transport: TCP # 支持 TCP 或者 UDP
udp: true # 支持 UDP over TCP
username: user
password: password
@@ -1035,6 +1038,18 @@ proxies: # socks5
# 如果想开启 0-RTT 握手,请设置为 HANDSHAKE_NO_WAIT否则请设置为 HANDSHAKE_STANDARD。默认值为 HANDSHAKE_STANDARD
# handshake-mode: HANDSHAKE_STANDARD
# sudoku
- name: sudoku
type: sudoku
server: serverip # 1.2.3.4
port: 443
key: "<client_key>" # 如果你使用sudoku生成的ED25519密钥对请填写密钥对中的私钥否则填入和服务端相同的uuid
aead-method: chacha20-poly1305 # 可选值chacha20-poly1305、aes-128-gcm、none 我们保证在none的情况下sudoku混淆层仍然确保安全
padding-min: 2 # 最小填充字节数
padding-max: 7 # 最大填充字节数
table-type: prefer_ascii # 可选值prefer_ascii、prefer_entropy 前者全ascii映射后者保证熵值汉明1低于3
http-mask: true # 是否启用http掩码
# anytls
- name: anytls
type: anytls
@@ -1555,6 +1570,28 @@ listeners:
# -----END ECH KEYS-----
# padding-scheme: "" # https://github.com/anytls/anytls-go/blob/main/docs/protocol.md#cmdupdatepaddingscheme
- name: mieru-in-1
type: mieru
port: 10818 # 支持使用ports格式例如200,302 or 200,204,401-429,501-503
listen: 0.0.0.0
transport: TCP # 支持 TCP 或者 UDP
users:
username1: password1
username2: password2
- name: sudoku-in-1
type: sudoku
port: 8443 # 仅支持单端口
listen: 0.0.0.0
key: "<server_key>" # 如果你使用sudoku生成的ED25519密钥对此处是密钥对中的公钥当然你也可以仅仅使用任意uuid充当key
aead-method: chacha20-poly1305 # 支持chacha20-poly1305或者aes-128-gcm以及nonesudoku的混淆层可以确保none情况下数据安全
padding-min: 1 # 填充最小长度
padding-max: 15 # 填充最大长度,均不建议过大
seed: "<seed-or-key>" # 如果你不使用ED25519密钥对就请填入uuid否则仍然是公钥
table-type: prefer_ascii # 可选值prefer_ascii、prefer_entropy 前者全ascii映射后者保证熵值汉明1低于3
handshake-timeout: 5 # optional
- name: trojan-in-1
type: trojan
port: 10819 # 支持使用ports格式例如200,302 or 200,204,401-429,501-503
@@ -1703,3 +1740,4 @@ listeners:
# alpn:
# - h3
# max-udp-relay-packet-size: 1500

25
go.mod
View File

@@ -6,25 +6,24 @@ require (
github.com/bahlo/generic-list-go v0.2.0
github.com/coreos/go-iptables v0.8.0
github.com/dlclark/regexp2 v1.11.5
github.com/ebitengine/purego v0.9.0
github.com/enfein/mieru/v3 v3.20.0
github.com/enfein/mieru/v3 v3.26.0
github.com/go-chi/chi/v5 v5.2.3
github.com/go-chi/render v1.0.3
github.com/gobwas/ws v1.4.0
github.com/gofrs/uuid/v5 v5.3.2
github.com/gofrs/uuid/v5 v5.4.0
github.com/golang/snappy v1.0.0
github.com/insomniacslk/dhcp v0.0.0-20250109001534-8abf58130905
github.com/klauspost/compress v1.17.9 // lastest version compatible with golang1.20
github.com/mdlayher/netlink v1.7.2
github.com/metacubex/amneziawg-go v0.0.0-20250902133113-a7f637c14281
github.com/metacubex/bart v0.24.0
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d
github.com/metacubex/bart v0.26.0
github.com/metacubex/bbolt v0.0.0-20250725135710-010dbbbb7a5b
github.com/metacubex/blake3 v0.1.0
github.com/metacubex/chacha v0.1.5
github.com/metacubex/fswatch v0.1.1
github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759
github.com/metacubex/kcp-go v0.0.0-20251007183319-0df1aec1639a
github.com/metacubex/quic-go v0.55.1-0.20251004050223-450bd9e32033
github.com/metacubex/kcp-go v0.0.0-20251111012849-7455698490e9
github.com/metacubex/quic-go v0.55.1-0.20251024060151-bd465f127128
github.com/metacubex/randv2 v0.2.0
github.com/metacubex/restls-client-go v0.1.7
github.com/metacubex/sing v0.5.6
@@ -33,20 +32,21 @@ require (
github.com/metacubex/sing-shadowsocks v0.2.12
github.com/metacubex/sing-shadowsocks2 v0.2.7
github.com/metacubex/sing-shadowtls v0.0.0-20250503063515-5d9f966d17a2
github.com/metacubex/sing-tun v0.4.8
github.com/metacubex/sing-tun v0.4.10
github.com/metacubex/sing-vmess v0.2.4
github.com/metacubex/sing-wireguard v0.0.0-20250503063753-2dc62acc626f
github.com/metacubex/smux v0.0.0-20250922175018-15c9a6a78719
github.com/metacubex/tfo-go v0.0.0-20250921095601-b102db4216c0
github.com/metacubex/utls v1.8.2
github.com/metacubex/smux v0.0.0-20251111013112-03f8d12dafc1
github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443
github.com/metacubex/utls v1.8.3
github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f
github.com/miekg/dns v1.1.63 // lastest version compatible with golang1.20
github.com/mroth/weightedrand/v2 v2.1.0
github.com/openacid/low v0.1.21
github.com/oschwald/maxminddb-golang v1.12.0 // lastest version compatible with golang1.20
github.com/saba-futai/sudoku v0.0.1-g
github.com/sagernet/cors v1.2.1
github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a
github.com/samber/lo v1.51.0
github.com/samber/lo v1.52.0
github.com/sirupsen/logrus v1.9.3
github.com/stretchr/testify v1.11.1
github.com/vmihailenco/msgpack/v5 v5.4.1
@@ -64,6 +64,7 @@ require (
)
require (
filippo.io/edwards25519 v1.1.0 // indirect
github.com/RyuaNerin/go-krypto v1.3.0 // indirect
github.com/Yawning/aez v0.0.0-20211027044916-e49e68abd344 // indirect
github.com/ajg/form v1.5.1 // indirect

50
go.sum
View File

@@ -1,3 +1,5 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/RyuaNerin/go-krypto v1.3.0 h1:smavTzSMAx8iuVlGb4pEwl9MD2qicqMzuXR2QWp2/Pg=
github.com/RyuaNerin/go-krypto v1.3.0/go.mod h1:9R9TU936laAIqAmjcHo/LsaXYOZlymudOAxjaBf62UM=
github.com/RyuaNerin/testingutil v0.1.0 h1:IYT6JL57RV3U2ml3dLHZsVtPOP6yNK7WUVdzzlpNrss=
@@ -23,10 +25,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/ebitengine/purego v0.9.0 h1:mh0zpKBIXDceC63hpvPuGLiJ8ZAa3DfrFTudmfi8A4k=
github.com/ebitengine/purego v0.9.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
github.com/enfein/mieru/v3 v3.20.0 h1:1ob7pCIVSH5FYFAfYvim8isLW1vBOS4cFOUF9exJS38=
github.com/enfein/mieru/v3 v3.20.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
github.com/enfein/mieru/v3 v3.26.0 h1:ZsxCFkh3UfGSu9LL6EQ9+b97uxTJ7/AnJmLMyrbjSDI=
github.com/enfein/mieru/v3 v3.26.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=
@@ -55,8 +55,8 @@ github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
github.com/gofrs/uuid/v5 v5.3.2 h1:2jfO8j3XgSwlz/wHqemAEugfnTlikAYHhnqQ8Xh4fE0=
github.com/gofrs/uuid/v5 v5.3.2/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8=
github.com/gofrs/uuid/v5 v5.4.0 h1:EfbpCTjqMuGyq5ZJwxqzn3Cbr2d0rUZU7v5ycAk/e/0=
github.com/gofrs/uuid/v5 v5.4.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=
@@ -90,12 +90,12 @@ github.com/mdlayher/netlink v1.7.2 h1:/UtM3ofJap7Vl4QWCPDGXY8d3GIY2UGSDbK+QWmY8/
github.com/mdlayher/netlink v1.7.2/go.mod h1:xraEF7uJbxLhc5fpHL4cPe221LI2bdttWlU+ZGLfQSw=
github.com/mdlayher/socket v0.4.1 h1:eM9y2/jlbs1M615oshPQOHZzj6R6wMT7bX5NPiQvn2U=
github.com/mdlayher/socket v0.4.1/go.mod h1:cAqeGjoufqdxWkD7DkpyS+wcefOtmu5OQ8KuoJGIReA=
github.com/metacubex/amneziawg-go v0.0.0-20250902133113-a7f637c14281 h1:09EM0sOLb2kfL0KETGhHujsBLB5iy5U/2yHRHsxf/pI=
github.com/metacubex/amneziawg-go v0.0.0-20250902133113-a7f637c14281/go.mod h1:MsM/5czONyXMJ3PRr5DbQ4O/BxzAnJWOIcJdLzW6qHY=
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d h1:vAJ0ZT4aO803F1uw2roIA9yH7Sxzox34tVVyye1bz6c=
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d/go.mod h1:MsM/5czONyXMJ3PRr5DbQ4O/BxzAnJWOIcJdLzW6qHY=
github.com/metacubex/ascon v0.1.0 h1:6ZWxmXYszT1XXtwkf6nxfFhc/OTtQ9R3Vyj1jN32lGM=
github.com/metacubex/ascon v0.1.0/go.mod h1:eV5oim4cVPPdEL8/EYaTZ0iIKARH9pnhAK/fcT5Kacc=
github.com/metacubex/bart v0.24.0 h1:EyNiPeVOlg0joSHTzi5oentI0j5M89utUq/5dd76pWM=
github.com/metacubex/bart v0.24.0/go.mod h1:DCcyfP4MC+Zy7sLK7XeGuMw+P5K9mIRsYOBgiE8icsI=
github.com/metacubex/bart v0.26.0 h1:d/bBTvVatfVWGfQbiDpYKI1bXUJgjaabB2KpK1Tnk6w=
github.com/metacubex/bart v0.26.0/go.mod h1:DCcyfP4MC+Zy7sLK7XeGuMw+P5K9mIRsYOBgiE8icsI=
github.com/metacubex/bbolt v0.0.0-20250725135710-010dbbbb7a5b h1:j7dadXD8I2KTmMt8jg1JcaP1ANL3JEObJPdANKcSYPY=
github.com/metacubex/bbolt v0.0.0-20250725135710-010dbbbb7a5b/go.mod h1:+WmP0VJZDkDszvpa83HzfUp6QzARl/IKkMorH4+nODw=
github.com/metacubex/blake3 v0.1.0 h1:KGnjh/56REO7U+cgZA8dnBhxdP7jByrG7hTP+bu6cqY=
@@ -108,12 +108,12 @@ github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759 h1:cjd4biTvO
github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759/go.mod h1:UHOv2xu+RIgLwpXca7TLrXleEd4oR3sPatW6IF8wU88=
github.com/metacubex/gvisor v0.0.0-20250919004547-6122b699a301 h1:N5GExQJqYAH3gOCshpp2u/J3CtNYzMctmlb0xK9wtbQ=
github.com/metacubex/gvisor v0.0.0-20250919004547-6122b699a301/go.mod h1:8LpS0IJW1VmWzUm3ylb0e2SK5QDm5lO/2qwWLZgRpBU=
github.com/metacubex/kcp-go v0.0.0-20251007183319-0df1aec1639a h1:5vdk2pI71itLBT2mpyNExM1UKZ+2mG7MVC+ZARpRXmg=
github.com/metacubex/kcp-go v0.0.0-20251007183319-0df1aec1639a/go.mod h1:HIJZW4QMhbBqXuqC1ly6Hn0TEYT2SzRw58ns1yGhXTs=
github.com/metacubex/kcp-go v0.0.0-20251111012849-7455698490e9 h1:7m3tRPrLpKOLOvZ/Lp4XCxz0t7rg9t9K35x6TahjR8o=
github.com/metacubex/kcp-go v0.0.0-20251111012849-7455698490e9/go.mod h1:HIJZW4QMhbBqXuqC1ly6Hn0TEYT2SzRw58ns1yGhXTs=
github.com/metacubex/nftables v0.0.0-20250503052935-30a69ab87793 h1:1Qpuy+sU3DmyX9HwI+CrBT/oLNJngvBorR2RbajJcqo=
github.com/metacubex/nftables v0.0.0-20250503052935-30a69ab87793/go.mod h1:RjRNb4G52yAgfR+Oe/kp9G4PJJ97Fnj89eY1BFO3YyA=
github.com/metacubex/quic-go v0.55.1-0.20251004050223-450bd9e32033 h1:LEzvR5AmHEatqE6IWgMBUJHnaiz9VJfZeDGOiHFuWZU=
github.com/metacubex/quic-go v0.55.1-0.20251004050223-450bd9e32033/go.mod h1:1lktQFtCD17FZliVypbrDHwbsFSsmz2xz2TRXydvB5c=
github.com/metacubex/quic-go v0.55.1-0.20251024060151-bd465f127128 h1:I1uvJl206/HbkzEAZpLgGkZgUveOZb+P+6oTUj7dN+o=
github.com/metacubex/quic-go v0.55.1-0.20251024060151-bd465f127128/go.mod h1:1lktQFtCD17FZliVypbrDHwbsFSsmz2xz2TRXydvB5c=
github.com/metacubex/randv2 v0.2.0 h1:uP38uBvV2SxYfLj53kuvAjbND4RUDfFJjwr4UigMiLs=
github.com/metacubex/randv2 v0.2.0/go.mod h1:kFi2SzrQ5WuneuoLLCMkABtiBu6VRrMrWFqSPyj2cxY=
github.com/metacubex/restls-client-go v0.1.7 h1:eCwiXCTQb5WJu9IlgYvDBA1OgrINv58dEe7hcN5H15k=
@@ -131,18 +131,18 @@ github.com/metacubex/sing-shadowsocks2 v0.2.7 h1:hSuuc0YpsfiqYqt1o+fP4m34BQz4e6w
github.com/metacubex/sing-shadowsocks2 v0.2.7/go.mod h1:vOEbfKC60txi0ca+yUlqEwOGc3Obl6cnSgx9Gf45KjE=
github.com/metacubex/sing-shadowtls v0.0.0-20250503063515-5d9f966d17a2 h1:gXU+MYPm7Wme3/OAY2FFzVq9d9GxPHOqu5AQfg/ddhI=
github.com/metacubex/sing-shadowtls v0.0.0-20250503063515-5d9f966d17a2/go.mod h1:mbfboaXauKJNIHJYxQRa+NJs4JU9NZfkA+I33dS2+9E=
github.com/metacubex/sing-tun v0.4.8 h1:3PyiUKWXYi37yHptXskzL1723O3OUdyt0Aej4XHVikM=
github.com/metacubex/sing-tun v0.4.8/go.mod h1:L/TjQY5JEGy8nvsuYmy/XgMFMCPiF0+AWSFCYfS6r9w=
github.com/metacubex/sing-tun v0.4.10 h1:DllQTERAcqQyiEl4L/R7Ia0jCiSzZzikw2kL8N85p0E=
github.com/metacubex/sing-tun v0.4.10/go.mod h1:L/TjQY5JEGy8nvsuYmy/XgMFMCPiF0+AWSFCYfS6r9w=
github.com/metacubex/sing-vmess v0.2.4 h1:Tx6AGgCiEf400E/xyDuYyafsel6sGbR8oF7RkAaus6I=
github.com/metacubex/sing-vmess v0.2.4/go.mod h1:21R5R1u90uUvBQF0owoooEu96/SAYYD56nDrwm6nFaM=
github.com/metacubex/sing-wireguard v0.0.0-20250503063753-2dc62acc626f h1:Sr/DYKYofKHKc4GF3qkRGNuj6XA6c0eqPgEDN+VAsYU=
github.com/metacubex/sing-wireguard v0.0.0-20250503063753-2dc62acc626f/go.mod h1:jpAkVLPnCpGSfNyVmj6Cq4YbuZsFepm/Dc+9BAOcR80=
github.com/metacubex/smux v0.0.0-20250922175018-15c9a6a78719 h1:T6qCCfolRDAVJKeaPW/mXwNLjnlo65AYN7WS2jrBNaM=
github.com/metacubex/smux v0.0.0-20250922175018-15c9a6a78719/go.mod h1:4bPD8HWx9jPJ9aE4uadgyN7D1/Wz3KmPy+vale8sKLE=
github.com/metacubex/tfo-go v0.0.0-20250921095601-b102db4216c0 h1:Ui+/2s5Qz0lSnDUBmEL12M5Oi/PzvFxGTNohm8ZcsmE=
github.com/metacubex/tfo-go v0.0.0-20250921095601-b102db4216c0/go.mod h1:l9oLnLoEXyGZ5RVLsh7QCC5XsouTUyKk4F2nLm2DHLw=
github.com/metacubex/utls v1.8.2 h1:d7KalMZ5hnOJ6lThMz8Ykd+5dvmXH3Eoeyfv2jUuG3w=
github.com/metacubex/utls v1.8.2/go.mod h1:kncGGVhFaoGn5M3pFe3SXhZCzsbCJayNOH4UEqTKTko=
github.com/metacubex/smux v0.0.0-20251111013112-03f8d12dafc1 h1:a6DF0ze9miXes+rdwl8a4Wkvfpe0lXYU82sPJfDzz6s=
github.com/metacubex/smux v0.0.0-20251111013112-03f8d12dafc1/go.mod h1:4bPD8HWx9jPJ9aE4uadgyN7D1/Wz3KmPy+vale8sKLE=
github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443 h1:H6TnfM12tOoTizYE/qBHH3nEuibIelmHI+BVSxVJr8o=
github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443/go.mod h1:l9oLnLoEXyGZ5RVLsh7QCC5XsouTUyKk4F2nLm2DHLw=
github.com/metacubex/utls v1.8.3 h1:0m/yCxm3SK6kWve2lKiFb1pue1wHitJ8sQQD4Ikqde4=
github.com/metacubex/utls v1.8.3/go.mod h1:kncGGVhFaoGn5M3pFe3SXhZCzsbCJayNOH4UEqTKTko=
github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f h1:FGBPRb1zUabhPhDrlKEjQ9lgIwQ6cHL4x8M9lrERhbk=
github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f/go.mod h1:oPGcV994OGJedmmxrcK9+ni7jUEMGhR+uVQAdaduIP4=
github.com/metacubex/yamux v0.0.0-20250918083631-dd5f17c0be49 h1:lhlqpYHopuTLx9xQt22kSA9HtnyTDmk5XjjQVCGHe2E=
@@ -171,12 +171,14 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g=
github.com/quic-go/qpack v0.4.0 h1:Cr9BXA1sQS2SmDUWjSofMPNKmvF6IiIfDRmgU0w1ZCo=
github.com/quic-go/qpack v0.4.0/go.mod h1:UZVnYIfi5GRk+zI9UMaCPsmZ2xKJP7XBUvVyT1Knj9A=
github.com/saba-futai/sudoku v0.0.1-g h1:4q6OuAA6COaRW+CgoQtdim5AUPzzm0uOkvbYpJnOaBE=
github.com/saba-futai/sudoku v0.0.1-g/go.mod h1:2ZRzRwz93cS2K/o2yOG4CPJEltcvk5y6vbvUmjftGU0=
github.com/sagernet/cors v1.2.1 h1:Cv5Z8y9YSD6Gm+qSpNrL3LO4lD3eQVvbFYJSG7JCMHQ=
github.com/sagernet/cors v1.2.1/go.mod h1:O64VyOjjhrkLmQIjF4KGRrJO/5dVXFdpEmCW/eISRAI=
github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a h1:ObwtHN2VpqE0ZNjr6sGeT00J8uU7JF4cNUdb44/Duis=
github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a/go.mod h1:xLnfdiJbSp8rNqYEdIW/6eDO4mVoogml14Bh2hSiFpM=
github.com/samber/lo v1.51.0 h1:kysRYLbHy/MB7kQZf5DSN50JHmMsNEdeY24VzJFu7wI=
github.com/samber/lo v1.51.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
github.com/samber/lo v1.52.0 h1:Rvi+3BFHES3A8meP33VPAxiBZX/Aws5RxrschYGjomw=
github.com/samber/lo v1.52.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
github.com/sina-ghaderi/poly1305 v0.0.0-20220724002748-c5926b03988b h1:rXHg9GrUEtWZhEkrykicdND3VPjlVbYiLdX9J7gimS8=
github.com/sina-ghaderi/poly1305 v0.0.0-20220724002748-c5926b03988b/go.mod h1:X7qrxNQViEaAN9LNZOPl9PfvQtp3V3c7LTo0dvGi0fM=
github.com/sina-ghaderi/rabaead v0.0.0-20220730151906-ab6e06b96e8c h1:DjKMC30y6yjG3IxDaeAj3PCoRr+IsO+bzyT+Se2m2Hk=

View File

@@ -31,7 +31,7 @@ import (
"github.com/metacubex/mihomo/component/updater"
"github.com/metacubex/mihomo/config"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/constant/provider"
P "github.com/metacubex/mihomo/constant/provider"
"github.com/metacubex/mihomo/dns"
"github.com/metacubex/mihomo/listener"
authStore "github.com/metacubex/mihomo/listener/auth"
@@ -39,7 +39,7 @@ import (
"github.com/metacubex/mihomo/listener/inner"
"github.com/metacubex/mihomo/listener/tproxy"
"github.com/metacubex/mihomo/log"
"github.com/metacubex/mihomo/ntp"
"github.com/metacubex/mihomo/ntp/ntp"
"github.com/metacubex/mihomo/tunnel"
)
@@ -247,10 +247,11 @@ func updateDNS(c *config.DNS, generalIPv6 bool) {
return
}
ipv6 := c.IPv6 && generalIPv6
r := dns.NewResolver(dns.Config{
Main: c.NameServer,
Fallback: c.Fallback,
IPv6: c.IPv6 && generalIPv6,
IPv6: ipv6,
IPv6Timeout: c.IPv6Timeout,
FallbackIPFilter: c.FallbackIPFilter,
FallbackDomainFilter: c.FallbackDomainFilter,
@@ -263,9 +264,13 @@ func updateDNS(c *config.DNS, generalIPv6 bool) {
CacheMaxSize: c.CacheMaxSize,
})
m := dns.NewEnhancer(dns.EnhancerConfig{
EnhancedMode: c.EnhancedMode,
Pool: c.FakeIPRange,
UseHosts: c.UseHosts,
IPv6: ipv6,
EnhancedMode: c.EnhancedMode,
FakeIPPool: c.FakeIPPool,
FakeIPPool6: c.FakeIPPool6,
FakeIPSkipper: c.FakeIPSkipper,
FakeIPTTL: c.FakeIPTTL,
UseHosts: c.UseHosts,
})
// reuse cache of old host mapper
@@ -299,18 +304,18 @@ func updateHosts(tree *trie.DomainTrie[resolver.HostValue]) {
resolver.DefaultHosts = resolver.NewHosts(tree)
}
func updateProxies(proxies map[string]C.Proxy, providers map[string]provider.ProxyProvider) {
func updateProxies(proxies map[string]C.Proxy, providers map[string]P.ProxyProvider) {
tunnel.UpdateProxies(proxies, providers)
}
func updateRules(rules []C.Rule, subRules map[string][]C.Rule, ruleProviders map[string]provider.RuleProvider) {
func updateRules(rules []C.Rule, subRules map[string][]C.Rule, ruleProviders map[string]P.RuleProvider) {
tunnel.UpdateRules(rules, subRules, ruleProviders)
}
func loadProvider[P provider.Provider](providers map[string]P) {
load := func(pv P) {
func loadProvider[T P.Provider](providers map[string]T) {
load := func(pv T) {
name := pv.Name()
if pv.VehicleType() == provider.Compatible {
if pv.VehicleType() == P.Compatible {
log.Infoln("Start initial compatible provider %s", name)
} else {
log.Infoln("Start initial provider %s", name)
@@ -318,11 +323,11 @@ func loadProvider[P provider.Provider](providers map[string]P) {
if err := pv.Initial(); err != nil {
switch pv.Type() {
case provider.Proxy:
case P.Proxy:
{
log.Errorln("initial proxy provider %s error: %v", name, err)
}
case provider.Rule:
case P.Rule:
{
log.Errorln("initial rule provider %s error: %v", name, err)
}
@@ -445,12 +450,7 @@ func patchSelectGroup(proxies map[string]C.Proxy) {
return
}
for name, proxy := range proxies {
outbound, ok := proxy.(C.Proxy)
if !ok {
continue
}
for name, outbound := range proxies {
selector, ok := outbound.Adapter().(outboundgroup.SelectAble)
if !ok {
continue

View File

@@ -13,7 +13,7 @@ import (
"github.com/metacubex/mihomo/config"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/hub/executor"
P "github.com/metacubex/mihomo/listener"
"github.com/metacubex/mihomo/listener"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/log"
"github.com/metacubex/mihomo/tunnel"
@@ -306,7 +306,7 @@ func patchConfigs(w http.ResponseWriter, r *http.Request) {
}
if general.AllowLan != nil {
P.SetAllowLan(*general.AllowLan)
listener.SetAllowLan(*general.AllowLan)
}
if general.SkipAuthPrefixes != nil {
@@ -322,7 +322,7 @@ func patchConfigs(w http.ResponseWriter, r *http.Request) {
}
if general.BindAddress != nil {
P.SetBindAddress(*general.BindAddress)
listener.SetBindAddress(*general.BindAddress)
}
if general.Sniffing != nil {
@@ -337,17 +337,17 @@ func patchConfigs(w http.ResponseWriter, r *http.Request) {
dialer.DefaultInterface.Store(*general.InterfaceName)
}
ports := P.GetPorts()
ports := listener.GetPorts()
P.ReCreateHTTP(pointerOrDefault(general.Port, ports.Port), tunnel.Tunnel)
P.ReCreateSocks(pointerOrDefault(general.SocksPort, ports.SocksPort), tunnel.Tunnel)
P.ReCreateRedir(pointerOrDefault(general.RedirPort, ports.RedirPort), tunnel.Tunnel)
P.ReCreateTProxy(pointerOrDefault(general.TProxyPort, ports.TProxyPort), tunnel.Tunnel)
P.ReCreateMixed(pointerOrDefault(general.MixedPort, ports.MixedPort), tunnel.Tunnel)
P.ReCreateTun(pointerOrDefaultTun(general.Tun, P.LastTunConf), tunnel.Tunnel)
P.ReCreateShadowSocks(pointerOrDefault(general.ShadowSocksConfig, ports.ShadowSocksConfig), tunnel.Tunnel)
P.ReCreateVmess(pointerOrDefault(general.VmessConfig, ports.VmessConfig), tunnel.Tunnel)
P.ReCreateTuic(pointerOrDefaultTuicServer(general.TuicServer, P.LastTuicConf), tunnel.Tunnel)
listener.ReCreateHTTP(pointerOrDefault(general.Port, ports.Port), tunnel.Tunnel)
listener.ReCreateSocks(pointerOrDefault(general.SocksPort, ports.SocksPort), tunnel.Tunnel)
listener.ReCreateRedir(pointerOrDefault(general.RedirPort, ports.RedirPort), tunnel.Tunnel)
listener.ReCreateTProxy(pointerOrDefault(general.TProxyPort, ports.TProxyPort), tunnel.Tunnel)
listener.ReCreateMixed(pointerOrDefault(general.MixedPort, ports.MixedPort), tunnel.Tunnel)
listener.ReCreateTun(pointerOrDefaultTun(general.Tun, listener.LastTunConf), tunnel.Tunnel)
listener.ReCreateShadowSocks(pointerOrDefault(general.ShadowSocksConfig, ports.ShadowSocksConfig), tunnel.Tunnel)
listener.ReCreateVmess(pointerOrDefault(general.VmessConfig, ports.VmessConfig), tunnel.Tunnel)
listener.ReCreateTuic(pointerOrDefaultTuicServer(general.TuicServer, listener.LastTuicConf), tunnel.Tunnel)
if general.Mode != nil {
tunnel.SetMode(*general.Mode)

View File

@@ -5,7 +5,7 @@ import (
"net/http"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/constant/provider"
P "github.com/metacubex/mihomo/constant/provider"
"github.com/metacubex/mihomo/tunnel"
"github.com/go-chi/chi/v5"
@@ -45,12 +45,12 @@ func getProviders(w http.ResponseWriter, r *http.Request) {
}
func getProvider(w http.ResponseWriter, r *http.Request) {
provider := r.Context().Value(CtxKeyProvider).(provider.ProxyProvider)
provider := r.Context().Value(CtxKeyProvider).(P.ProxyProvider)
render.JSON(w, r, provider)
}
func updateProvider(w http.ResponseWriter, r *http.Request) {
provider := r.Context().Value(CtxKeyProvider).(provider.ProxyProvider)
provider := r.Context().Value(CtxKeyProvider).(P.ProxyProvider)
if err := provider.Update(); err != nil {
render.Status(r, http.StatusServiceUnavailable)
render.JSON(w, r, newError(err.Error()))
@@ -60,7 +60,7 @@ func updateProvider(w http.ResponseWriter, r *http.Request) {
}
func healthCheckProvider(w http.ResponseWriter, r *http.Request) {
provider := r.Context().Value(CtxKeyProvider).(provider.ProxyProvider)
provider := r.Context().Value(CtxKeyProvider).(P.ProxyProvider)
provider.HealthCheck()
render.NoContent(w, r)
}
@@ -93,7 +93,7 @@ func findProviderProxyByName(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var (
name = r.Context().Value(CtxKeyProxyName).(string)
pd = r.Context().Value(CtxKeyProvider).(provider.ProxyProvider)
pd = r.Context().Value(CtxKeyProvider).(P.ProxyProvider)
)
proxy, exist := lo.Find(pd.Proxies(), func(proxy C.Proxy) bool {
return proxy.Name() == name
@@ -128,7 +128,7 @@ func getRuleProviders(w http.ResponseWriter, r *http.Request) {
}
func updateRuleProvider(w http.ResponseWriter, r *http.Request) {
provider := r.Context().Value(CtxKeyProvider).(provider.RuleProvider)
provider := r.Context().Value(CtxKeyProvider).(P.RuleProvider)
if err := provider.Update(); err != nil {
render.Status(r, http.StatusServiceUnavailable)
render.JSON(w, r, newError(err.Error()))

22
listener/config/sudoku.go Normal file
View File

@@ -0,0 +1,22 @@
package config
import "encoding/json"
// SudokuServer describes a Sudoku inbound server configuration.
// It is internal to the listener layer and mainly used for logging and wiring.
type SudokuServer struct {
Enable bool `json:"enable"`
Listen string `json:"listen"`
Key string `json:"key"`
AEADMethod string `json:"aead-method,omitempty"`
PaddingMin *int `json:"padding-min,omitempty"`
PaddingMax *int `json:"padding-max,omitempty"`
Seed string `json:"seed,omitempty"`
TableType string `json:"table-type,omitempty"`
HandshakeTimeoutSecond *int `json:"handshake-timeout,omitempty"`
}
func (s SudokuServer) String() string {
b, _ := json.Marshal(s)
return string(b)
}

View File

@@ -63,7 +63,11 @@ func removeExtraHTTPHostPort(req *http.Request) {
// parseBasicProxyAuthorization parse header Proxy-Authorization and return base64-encoded credential
func parseBasicProxyAuthorization(request *http.Request) string {
value := request.Header.Get("Proxy-Authorization")
if !strings.HasPrefix(value, "Basic ") {
const prefix = "Basic "
// According to RFC7617, the scheme should be case-insensitive.
// In practice, some implementations do use different case styles, causing authentication to fail
// eg: https://github.com/algesten/ureq/blob/381fd42cfcb80a5eb709d64860aa0ae726f17b8e/src/unversioned/transport/connect.rs#L118
if len(value) < len(prefix) || !strings.EqualFold(value[:len(prefix)], prefix) {
return ""
}

View File

@@ -59,11 +59,13 @@ func init() {
}
type TestTunnel struct {
HandleTCPConnFn func(conn net.Conn, metadata *C.Metadata)
HandleUDPPacketFn func(packet C.UDPPacket, metadata *C.Metadata)
NatTableFn func() C.NatTable
CloseFn func() error
DoTestFn func(t *testing.T, proxy C.ProxyAdapter)
HandleTCPConnFn func(conn net.Conn, metadata *C.Metadata)
HandleUDPPacketFn func(packet C.UDPPacket, metadata *C.Metadata)
NatTableFn func() C.NatTable
CloseFn func() error
DoTestFn func(t *testing.T, proxy C.ProxyAdapter)
DoSequentialTestFn func(t *testing.T, proxy C.ProxyAdapter)
DoConcurrentTestFn func(t *testing.T, proxy C.ProxyAdapter)
}
func (tt *TestTunnel) HandleTCPConn(conn net.Conn, metadata *C.Metadata) {
@@ -86,6 +88,14 @@ func (tt *TestTunnel) DoTest(t *testing.T, proxy C.ProxyAdapter) {
tt.DoTestFn(t, proxy)
}
func (tt *TestTunnel) DoSequentialTest(t *testing.T, proxy C.ProxyAdapter) {
tt.DoSequentialTestFn(t, proxy)
}
func (tt *TestTunnel) DoConcurrentTest(t *testing.T, proxy C.ProxyAdapter) {
tt.DoConcurrentTestFn(t, proxy)
}
type TestTunnelListener struct {
ch chan net.Conn
ctx context.Context
@@ -213,6 +223,40 @@ func NewHttpTestTunnel() *TestTunnel {
}
assert.Equal(t, httpData[:size], data)
}
sequentialTestFn := func(t *testing.T, proxy C.ProxyAdapter) {
// Sequential testing for debugging
t.Run("Sequential", func(t *testing.T) {
testFn(t, proxy, "http", len(httpData))
testFn(t, proxy, "https", len(httpData))
})
}
concurrentTestFn := func(t *testing.T, proxy C.ProxyAdapter) {
// Concurrent testing to detect stress
t.Run("Concurrent", func(t *testing.T) {
wg := sync.WaitGroup{}
num := len(httpData) / 1024
for i := 1; i <= num; i++ {
i := i
wg.Add(1)
go func() {
testFn(t, proxy, "https", i*1024)
defer wg.Done()
}()
}
for i := 1; i <= num; i++ {
i := i
wg.Add(1)
go func() {
testFn(t, proxy, "http", i*1024)
defer wg.Done()
}()
}
wg.Wait()
})
}
tunnel := &TestTunnel{
HandleTCPConnFn: func(conn net.Conn, metadata *C.Metadata) {
defer conn.Close()
@@ -252,36 +296,11 @@ func NewHttpTestTunnel() *TestTunnel {
},
CloseFn: ln.Close,
DoTestFn: func(t *testing.T, proxy C.ProxyAdapter) {
// Sequential testing for debugging
t.Run("Sequential", func(t *testing.T) {
testFn(t, proxy, "http", len(httpData))
testFn(t, proxy, "https", len(httpData))
})
// Concurrent testing to detect stress
t.Run("Concurrent", func(t *testing.T) {
wg := sync.WaitGroup{}
num := len(httpData) / 1024
for i := 1; i <= num; i++ {
i := i
wg.Add(1)
go func() {
testFn(t, proxy, "https", i*1024)
defer wg.Done()
}()
}
for i := 1; i <= num; i++ {
i := i
wg.Add(1)
go func() {
testFn(t, proxy, "http", i*1024)
defer wg.Done()
}()
}
wg.Wait()
})
sequentialTestFn(t, proxy)
concurrentTestFn(t, proxy)
},
DoSequentialTestFn: sequentialTestFn,
DoConcurrentTestFn: concurrentTestFn,
}
return tunnel
}

183
listener/inbound/mieru.go Normal file
View File

@@ -0,0 +1,183 @@
package inbound
import (
"context"
"fmt"
"net"
"sync"
"github.com/metacubex/mihomo/adapter/inbound"
"github.com/metacubex/mihomo/common/utils"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/listener/mieru"
"github.com/metacubex/mihomo/log"
"google.golang.org/protobuf/proto"
mieruserver "github.com/enfein/mieru/v3/apis/server"
mierupb "github.com/enfein/mieru/v3/pkg/appctl/appctlpb"
)
type Mieru struct {
*Base
option *MieruOption
server mieruserver.Server
mu sync.Mutex
}
type MieruOption struct {
BaseOption
Transport string `inbound:"transport"`
Users map[string]string `inbound:"users"`
}
type mieruListenerFactory struct{}
func (mieruListenerFactory) Listen(ctx context.Context, network, address string) (net.Listener, error) {
return inbound.ListenContext(ctx, network, address)
}
func (mieruListenerFactory) ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error) {
return inbound.ListenPacketContext(ctx, network, address)
}
func NewMieru(option *MieruOption) (*Mieru, error) {
base, err := NewBase(&option.BaseOption)
if err != nil {
return nil, err
}
config, err := buildMieruServerConfig(option, base.ports)
if err != nil {
return nil, fmt.Errorf("failed to build mieru server config: %w", err)
}
s := mieruserver.NewServer()
if err := s.Store(config); err != nil {
return nil, fmt.Errorf("failed to store mieru server config: %w", err)
}
// Server is started lazily when Listen() is called for the first time.
return &Mieru{
Base: base,
option: option,
server: s,
}, nil
}
func (m *Mieru) Config() C.InboundConfig {
return m.option
}
func (m *Mieru) Listen(tunnel C.Tunnel) error {
m.mu.Lock()
defer m.mu.Unlock()
if !m.server.IsRunning() {
if err := m.server.Start(); err != nil {
return fmt.Errorf("failed to start mieru server: %w", err)
}
}
additions := m.config.Additions()
if len(additions) == 0 {
additions = []inbound.Addition{
inbound.WithInName("DEFAULT-MIERU"),
inbound.WithSpecialRules(""),
}
}
go func() {
for {
c, req, err := m.server.Accept()
if err != nil {
if !m.server.IsRunning() {
break
} else {
continue
}
}
go mieru.Handle(c, tunnel, req, additions...)
}
}()
log.Infoln("Mieru[%s] proxy listening at: %s", m.Name(), m.Address())
return nil
}
func (m *Mieru) Close() error {
m.mu.Lock()
defer m.mu.Unlock()
if m.server.IsRunning() {
return m.server.Stop()
}
return nil
}
var _ C.InboundListener = (*Mieru)(nil)
func (o MieruOption) Equal(config C.InboundConfig) bool {
return optionToString(o) == optionToString(config)
}
func buildMieruServerConfig(option *MieruOption, ports utils.IntRanges[uint16]) (*mieruserver.ServerConfig, error) {
if err := validateMieruOption(option); err != nil {
return nil, fmt.Errorf("failed to validate mieru option: %w", err)
}
if len(ports) == 0 {
return nil, fmt.Errorf("port is not set")
}
var transportProtocol *mierupb.TransportProtocol
switch option.Transport {
case "TCP":
transportProtocol = mierupb.TransportProtocol_TCP.Enum()
case "UDP":
transportProtocol = mierupb.TransportProtocol_UDP.Enum()
}
var portBindings []*mierupb.PortBinding
for _, portRange := range ports {
if portRange.Start() == portRange.End() {
portBindings = append(portBindings, &mierupb.PortBinding{
Port: proto.Int32(int32(portRange.Start())),
Protocol: transportProtocol,
})
} else {
portBindings = append(portBindings, &mierupb.PortBinding{
PortRange: proto.String(fmt.Sprintf("%d-%d", portRange.Start(), portRange.End())),
Protocol: transportProtocol,
})
}
}
var users []*mierupb.User
for username, password := range option.Users {
users = append(users, &mierupb.User{
Name: proto.String(username),
Password: proto.String(password),
})
}
return &mieruserver.ServerConfig{
Config: &mierupb.ServerConfig{
PortBindings: portBindings,
Users: users,
},
StreamListenerFactory: mieruListenerFactory{},
PacketListenerFactory: mieruListenerFactory{},
}, nil
}
func validateMieruOption(option *MieruOption) error {
if option.Transport != "TCP" && option.Transport != "UDP" {
return fmt.Errorf("transport must be TCP or UDP")
}
if len(option.Users) == 0 {
return fmt.Errorf("users is empty")
}
for username, password := range option.Users {
if username == "" {
return fmt.Errorf("username is empty")
}
if password == "" {
return fmt.Errorf("password is empty")
}
}
return nil
}

View File

@@ -0,0 +1,272 @@
package inbound_test
import (
"net"
"net/netip"
"strconv"
"testing"
"github.com/metacubex/mihomo/adapter/outbound"
"github.com/metacubex/mihomo/listener/inbound"
"github.com/stretchr/testify/assert"
)
func TestNewMieru(t *testing.T) {
type args struct {
option *inbound.MieruOption
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "valid with port",
args: args{
option: &inbound.MieruOption{
BaseOption: inbound.BaseOption{
Port: "8080",
},
Transport: "TCP",
Users: map[string]string{"user": "pass"},
},
},
wantErr: false,
},
{
name: "valid with port range",
args: args{
option: &inbound.MieruOption{
BaseOption: inbound.BaseOption{
Port: "8090-8099",
},
Transport: "UDP",
Users: map[string]string{"user": "pass"},
},
},
wantErr: false,
},
{
name: "valid mix of port and port-range",
args: args{
option: &inbound.MieruOption{
BaseOption: inbound.BaseOption{
Port: "8080,8090-8099",
},
Transport: "TCP",
Users: map[string]string{"user": "pass"},
},
},
wantErr: false,
},
{
name: "invalid - no port",
args: args{
option: &inbound.MieruOption{
Transport: "TCP",
Users: map[string]string{"user": "pass"},
},
},
wantErr: true,
},
{
name: "invalid - transport",
args: args{
option: &inbound.MieruOption{
BaseOption: inbound.BaseOption{
Port: "8080",
},
Transport: "INVALID",
Users: map[string]string{"user": "pass"},
},
},
wantErr: true,
},
{
name: "invalid - no transport",
args: args{
option: &inbound.MieruOption{
BaseOption: inbound.BaseOption{
Port: "8080",
},
Users: map[string]string{"user": "pass"},
},
},
wantErr: true,
},
{
name: "invalid - no users",
args: args{
option: &inbound.MieruOption{
BaseOption: inbound.BaseOption{
Port: "8080",
},
Transport: "TCP",
Users: map[string]string{},
},
},
wantErr: true,
},
{
name: "invalid - empty username",
args: args{
option: &inbound.MieruOption{
BaseOption: inbound.BaseOption{
Port: "8080",
},
Transport: "TCP",
Users: map[string]string{"": "pass"},
},
},
wantErr: true,
},
{
name: "invalid - empty password",
args: args{
option: &inbound.MieruOption{
BaseOption: inbound.BaseOption{
Port: "8080",
},
Transport: "TCP",
Users: map[string]string{"user": ""},
},
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := inbound.NewMieru(tt.args.option)
if (err != nil) != tt.wantErr {
t.Errorf("NewMieru() error = %v, wantErr %v", err, tt.wantErr)
return
}
if err == nil {
got.Close()
}
})
}
}
func TestInboundMieru(t *testing.T) {
t.Run("TCP_HANDSHAKE_STANDARD", func(t *testing.T) {
testInboundMieruTCP(t, "HANDSHAKE_STANDARD")
})
t.Run("TCP_HANDSHAKE_NO_WAIT", func(t *testing.T) {
testInboundMieruTCP(t, "HANDSHAKE_NO_WAIT")
})
t.Run("UDP_HANDSHAKE_STANDARD", func(t *testing.T) {
testInboundMieruUDP(t, "HANDSHAKE_STANDARD")
})
t.Run("UDP_HANDSHAKE_NO_WAIT", func(t *testing.T) {
testInboundMieruUDP(t, "HANDSHAKE_NO_WAIT")
})
}
func testInboundMieruTCP(t *testing.T, handshakeMode string) {
t.Parallel()
l, err := net.Listen("tcp", "127.0.0.1:0")
if !assert.NoError(t, err) {
return
}
port := l.Addr().(*net.TCPAddr).Port
l.Close()
inboundOptions := inbound.MieruOption{
BaseOption: inbound.BaseOption{
NameStr: "mieru_inbound_tcp",
Listen: "127.0.0.1",
Port: strconv.Itoa(port),
},
Transport: "TCP",
Users: map[string]string{"test": "password"},
}
in, err := inbound.NewMieru(&inboundOptions)
if !assert.NoError(t, err) {
return
}
tunnel := NewHttpTestTunnel()
defer tunnel.Close()
err = in.Listen(tunnel)
if !assert.NoError(t, err) {
return
}
defer in.Close()
addrPort, err := netip.ParseAddrPort(in.Address())
if !assert.NoError(t, err) {
return
}
outboundOptions := outbound.MieruOption{
Name: "mieru_outbound_tcp",
Server: addrPort.Addr().String(),
Port: int(addrPort.Port()),
Transport: "TCP",
UserName: "test",
Password: "password",
HandshakeMode: handshakeMode,
}
out, err := outbound.NewMieru(outboundOptions)
if !assert.NoError(t, err) {
return
}
defer out.Close()
tunnel.DoTest(t, out)
}
func testInboundMieruUDP(t *testing.T, handshakeMode string) {
t.Parallel()
l, err := net.ListenPacket("udp", "127.0.0.1:0")
if !assert.NoError(t, err) {
return
}
port := l.LocalAddr().(*net.UDPAddr).Port
l.Close()
inboundOptions := inbound.MieruOption{
BaseOption: inbound.BaseOption{
NameStr: "mieru_inbound_udp",
Listen: "127.0.0.1",
Port: strconv.Itoa(port),
},
Transport: "UDP",
Users: map[string]string{"test": "password"},
}
in, err := inbound.NewMieru(&inboundOptions)
if !assert.NoError(t, err) {
return
}
tunnel := NewHttpTestTunnel()
defer tunnel.Close()
err = in.Listen(tunnel)
if !assert.NoError(t, err) {
return
}
defer in.Close()
addrPort, err := netip.ParseAddrPort(in.Address())
if !assert.NoError(t, err) {
return
}
outboundOptions := outbound.MieruOption{
Name: "mieru_outbound_udp",
Server: addrPort.Addr().String(),
Port: int(addrPort.Port()),
Transport: "UDP",
UserName: "test",
Password: "password",
HandshakeMode: handshakeMode,
}
out, err := outbound.NewMieru(outboundOptions)
if !assert.NoError(t, err) {
return
}
defer out.Close()
tunnel.DoSequentialTest(t, out)
}

128
listener/inbound/sudoku.go Normal file
View File

@@ -0,0 +1,128 @@
package inbound
import (
"errors"
"fmt"
"strings"
"github.com/saba-futai/sudoku/apis"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
sudokuListener "github.com/metacubex/mihomo/listener/sudoku"
"github.com/metacubex/mihomo/log"
)
type SudokuOption struct {
BaseOption
Key string `inbound:"key"`
AEADMethod string `inbound:"aead-method,omitempty"`
PaddingMin *int `inbound:"padding-min,omitempty"`
PaddingMax *int `inbound:"padding-max,omitempty"`
Seed string `inbound:"seed,omitempty"`
TableType string `inbound:"table-type,omitempty"` // "prefer_ascii" or "prefer_entropy"
HandshakeTimeoutSecond *int `inbound:"handshake-timeout,omitempty"`
}
func (o SudokuOption) Equal(config C.InboundConfig) bool {
return optionToString(o) == optionToString(config)
}
type Sudoku struct {
*Base
config *SudokuOption
listeners []*sudokuListener.Listener
serverConf LC.SudokuServer
}
func NewSudoku(options *SudokuOption) (*Sudoku, error) {
if options.Key == "" {
return nil, fmt.Errorf("sudoku inbound requires key")
}
base, err := NewBase(&options.BaseOption)
if err != nil {
return nil, err
}
defaultConf := apis.DefaultConfig()
serverConf := LC.SudokuServer{
Enable: true,
Listen: base.RawAddress(),
Key: options.Key,
AEADMethod: options.AEADMethod,
PaddingMin: options.PaddingMin,
PaddingMax: options.PaddingMax,
Seed: options.Seed,
TableType: options.TableType,
}
if options.HandshakeTimeoutSecond != nil {
serverConf.HandshakeTimeoutSecond = options.HandshakeTimeoutSecond
} else {
// Use Sudoku default if not specified.
v := defaultConf.HandshakeTimeoutSeconds
serverConf.HandshakeTimeoutSecond = &v
}
return &Sudoku{
Base: base,
config: options,
serverConf: serverConf,
}, nil
}
// Config implements constant.InboundListener
func (s *Sudoku) Config() C.InboundConfig {
return s.config
}
// Address implements constant.InboundListener
func (s *Sudoku) Address() string {
var addrList []string
for _, l := range s.listeners {
addrList = append(addrList, l.Address())
}
return strings.Join(addrList, ",")
}
// Listen implements constant.InboundListener
func (s *Sudoku) Listen(tunnel C.Tunnel) error {
if s.serverConf.Key == "" {
return fmt.Errorf("sudoku inbound requires key")
}
var errs []error
for _, addr := range strings.Split(s.RawAddress(), ",") {
conf := s.serverConf
conf.Listen = addr
l, err := sudokuListener.New(conf, tunnel, s.Additions()...)
if err != nil {
errs = append(errs, err)
continue
}
s.listeners = append(s.listeners, l)
}
if len(errs) > 0 {
return errors.Join(errs...)
}
log.Infoln("Sudoku[%s] inbound listening at: %s", s.Name(), s.Address())
return nil
}
// Close implements constant.InboundListener
func (s *Sudoku) Close() error {
var errs []error
for _, l := range s.listeners {
if err := l.Close(); err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return errors.Join(errs...)
}
return nil
}
var _ C.InboundListener = (*Sudoku)(nil)

View File

@@ -0,0 +1,91 @@
package inbound_test
import (
"net/netip"
"testing"
"github.com/metacubex/mihomo/adapter/outbound"
"github.com/metacubex/mihomo/listener/inbound"
"github.com/stretchr/testify/assert"
)
func testInboundSudoku(t *testing.T, inboundOptions inbound.SudokuOption, outboundOptions outbound.SudokuOption) {
t.Parallel()
inboundOptions.BaseOption = inbound.BaseOption{
NameStr: "sudoku_inbound",
Listen: "127.0.0.1",
Port: "0",
}
in, err := inbound.NewSudoku(&inboundOptions)
if !assert.NoError(t, err) {
return
}
tunnel := NewHttpTestTunnel()
defer tunnel.Close()
err = in.Listen(tunnel)
if !assert.NoError(t, err) {
return
}
defer in.Close()
addrPort, err := netip.ParseAddrPort(in.Address())
if !assert.NoError(t, err) {
return
}
outboundOptions.Name = "sudoku_outbound"
outboundOptions.Server = addrPort.Addr().String()
outboundOptions.Port = int(addrPort.Port())
out, err := outbound.NewSudoku(outboundOptions)
if !assert.NoError(t, err) {
return
}
defer out.Close()
tunnel.DoTest(t, out)
}
func TestInboundSudoku_Basic(t *testing.T) {
key := "test_key"
inboundOptions := inbound.SudokuOption{
Key: key,
}
outboundOptions := outbound.SudokuOption{
Key: key,
}
testInboundSudoku(t, inboundOptions, outboundOptions)
}
func TestInboundSudoku_Entropy(t *testing.T) {
key := "test_key_entropy"
inboundOptions := inbound.SudokuOption{
Key: key,
TableType: "prefer_entropy",
}
outboundOptions := outbound.SudokuOption{
Key: key,
TableType: "prefer_entropy",
}
testInboundSudoku(t, inboundOptions, outboundOptions)
}
func TestInboundSudoku_Padding(t *testing.T) {
key := "test_key_padding"
min := 10
max := 100
inboundOptions := inbound.SudokuOption{
Key: key,
PaddingMin: &min,
PaddingMax: &max,
}
outboundOptions := outbound.SudokuOption{
Key: key,
PaddingMin: &min,
PaddingMax: &max,
}
testInboundSudoku(t, inboundOptions, outboundOptions)
}

122
listener/mieru/server.go Normal file
View File

@@ -0,0 +1,122 @@
package mieru
import (
"errors"
"io"
"net"
"net/netip"
"github.com/metacubex/mihomo/adapter/inbound"
N "github.com/metacubex/mihomo/common/net"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/transport/socks5"
mierucommon "github.com/enfein/mieru/v3/apis/common"
mieruconstant "github.com/enfein/mieru/v3/apis/constant"
mierumodel "github.com/enfein/mieru/v3/apis/model"
)
func Handle(conn net.Conn, tunnel C.Tunnel, request *mierumodel.Request, additions ...inbound.Addition) {
// Return a fake response to the client.
resp := &mierumodel.Response{
Reply: mieruconstant.Socks5ReplySuccess,
BindAddr: mierumodel.AddrSpec{
IP: net.IPv4zero,
Port: 0,
},
}
if err := resp.WriteToSocks5(conn); err != nil {
conn.Close()
return
}
// Handle the connection with tunnel.
switch request.Command {
case mieruconstant.Socks5ConnectCmd: // TCP
metadata := &C.Metadata{
NetWork: C.TCP,
Type: C.MIERU,
DstPort: uint16(request.DstAddr.Port),
}
if request.DstAddr.FQDN != "" {
metadata.Host = request.DstAddr.FQDN
} else if request.DstAddr.IP != nil {
metadata.DstIP, _ = netip.AddrFromSlice(request.DstAddr.IP)
metadata.DstIP = metadata.DstIP.Unmap()
}
inbound.ApplyAdditions(
metadata,
inbound.WithInName(conn.(mierucommon.UserContext).UserName()),
inbound.WithSrcAddr(conn.RemoteAddr()),
inbound.WithInAddr(conn.LocalAddr()),
)
inbound.ApplyAdditions(metadata, additions...)
tunnel.HandleTCPConn(conn, metadata)
case mieruconstant.Socks5UDPAssociateCmd: // UDP
pc := mierucommon.NewPacketOverStreamTunnel(conn)
ep := N.NewEnhancePacketConn(pc)
for {
data, put, addr, err := ep.WaitReadFrom()
if err != nil {
if put != nil {
// Unresolved UDP packet, return buffer to the pool.
put()
}
// mieru returns EOF or ErrUnexpectedEOF when a session is closed.
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, io.ErrClosedPipe) {
break
}
continue
}
target, payload, err := socks5.DecodeUDPPacket(data)
if err != nil {
return
}
packet := &packet{
pc: ep,
addr: addr,
payload: payload,
put: put,
}
tunnel.HandleUDPPacket(inbound.NewPacket(target, packet, C.MIERU, additions...))
}
}
}
type packet struct {
pc net.PacketConn
addr net.Addr // source (i.e. remote) IP & Port of the packet
payload []byte
put func()
}
var _ C.UDPPacket = (*packet)(nil)
var _ C.UDPPacketInAddr = (*packet)(nil)
func (c *packet) Data() []byte {
return c.payload
}
func (c *packet) WriteBack(b []byte, addr net.Addr) (n int, err error) {
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddrToSocksAddr(addr), b)
if err != nil {
return
}
return c.pc.WriteTo(packet, c.addr)
}
func (c *packet) Drop() {
if c.put != nil {
c.put()
c.put = nil
}
c.payload = nil
}
func (c *packet) LocalAddr() net.Addr {
return c.addr
}
func (c *packet) InAddr() net.Addr {
return c.pc.LocalAddr()
}

View File

@@ -127,6 +127,20 @@ func ParseListener(mapping map[string]any) (C.InboundListener, error) {
return nil, err
}
listener, err = IN.NewAnyTLS(anytlsOption)
case "mieru":
mieruOption := &IN.MieruOption{}
err = decoder.Decode(mapping, mieruOption)
if err != nil {
return nil, err
}
listener, err = IN.NewMieru(mieruOption)
case "sudoku":
sudokuOption := &IN.SudokuOption{}
err = decoder.Decode(mapping, sudokuOption)
if err != nil {
return nil, err
}
listener, err = IN.NewSudoku(sudokuOption)
default:
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
}

View File

@@ -18,7 +18,7 @@ import (
"github.com/metacubex/mihomo/component/iface"
"github.com/metacubex/mihomo/component/resolver"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/constant/provider"
P "github.com/metacubex/mihomo/constant/provider"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/sing"
"github.com/metacubex/mihomo/log"
@@ -133,7 +133,7 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis
}
}
ctx := context.TODO()
rpTunnel := tunnel.(provider.Tunnel)
rpTunnel := tunnel.(P.Tunnel)
if options.GSOMaxSize == 0 {
options.GSOMaxSize = 65536
}
@@ -504,7 +504,7 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis
return
}
func (l *Listener) ruleUpdateCallback(ruleProvider provider.RuleProvider) {
func (l *Listener) ruleUpdateCallback(ruleProvider P.RuleProvider) {
name := ruleProvider.Name()
if slices.Contains(l.options.RouteAddressSet, name) {
l.updateRule(ruleProvider, false, true)
@@ -520,7 +520,7 @@ type toIpCidr interface {
ToIpCidr() *netipx.IPSet
}
func (l *Listener) updateRule(ruleProvider provider.RuleProvider, exclude bool, update bool) {
func (l *Listener) updateRule(ruleProvider P.RuleProvider, exclude bool, update bool) {
l.ruleUpdateMutex.Lock()
defer l.ruleUpdateMutex.Unlock()
name := ruleProvider.Name()

139
listener/sudoku/server.go Normal file
View File

@@ -0,0 +1,139 @@
package sudoku
import (
"net"
"strings"
"github.com/saba-futai/sudoku/apis"
sudokuobfs "github.com/saba-futai/sudoku/pkg/obfs/sudoku"
"github.com/metacubex/mihomo/adapter/inbound"
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/transport/socks5"
)
type Listener struct {
listener net.Listener
addr string
closed bool
protoConf apis.ProtocolConfig
}
// RawAddress implements C.Listener
func (l *Listener) RawAddress() string {
return l.addr
}
// Address implements C.Listener
func (l *Listener) Address() string {
if l.listener == nil {
return ""
}
return l.listener.Addr().String()
}
// Close implements C.Listener
func (l *Listener) Close() error {
l.closed = true
if l.listener != nil {
return l.listener.Close()
}
return nil
}
func (l *Listener) handleConn(conn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) {
tunnelConn, target, err := apis.ServerHandshake(conn, &l.protoConf)
if err != nil {
_ = conn.Close()
return
}
targetAddr := socks5.ParseAddr(target)
if targetAddr == nil {
_ = tunnelConn.Close()
return
}
tunnel.HandleTCPConn(inbound.NewSocket(targetAddr, tunnelConn, C.SUDOKU, additions...))
}
func New(config LC.SudokuServer, tunnel C.Tunnel, additions ...inbound.Addition) (*Listener, error) {
if len(additions) == 0 {
additions = []inbound.Addition{
inbound.WithInName("DEFAULT-SUDOKU"),
inbound.WithSpecialRules(""),
}
}
l, err := inbound.Listen("tcp", config.Listen)
if err != nil {
return nil, err
}
seed := config.Seed
if seed == "" {
seed = config.Key
}
tableType := strings.ToLower(config.TableType)
if tableType == "" {
tableType = "prefer_ascii"
}
table := sudokuobfs.NewTable(seed, tableType)
defaultConf := apis.DefaultConfig()
paddingMin := defaultConf.PaddingMin
paddingMax := defaultConf.PaddingMax
if config.PaddingMin != nil {
paddingMin = *config.PaddingMin
}
if config.PaddingMax != nil {
paddingMax = *config.PaddingMax
}
if config.PaddingMin == nil && config.PaddingMax != nil && paddingMax < paddingMin {
paddingMin = paddingMax
}
if config.PaddingMax == nil && config.PaddingMin != nil && paddingMax < paddingMin {
paddingMax = paddingMin
}
handshakeTimeout := defaultConf.HandshakeTimeoutSeconds
if config.HandshakeTimeoutSecond != nil {
handshakeTimeout = *config.HandshakeTimeoutSecond
}
protoConf := apis.ProtocolConfig{
Key: config.Key,
AEADMethod: defaultConf.AEADMethod,
Table: table,
PaddingMin: paddingMin,
PaddingMax: paddingMax,
HandshakeTimeoutSeconds: handshakeTimeout,
}
if config.AEADMethod != "" {
protoConf.AEADMethod = config.AEADMethod
}
sl := &Listener{
listener: l,
addr: config.Listen,
protoConf: protoConf,
}
go func() {
for {
c, err := l.Accept()
if err != nil {
if sl.closed {
break
}
continue
}
go sl.handleConn(c, tunnel, additions...)
}
}()
return sl, nil
}

View File

@@ -3,18 +3,18 @@ package ntp
import (
"context"
"sync"
"sync/atomic"
"time"
"github.com/metacubex/mihomo/component/dialer"
"github.com/metacubex/mihomo/component/proxydialer"
"github.com/metacubex/mihomo/log"
mihomoNtp "github.com/metacubex/mihomo/ntp"
M "github.com/metacubex/sing/common/metadata"
"github.com/metacubex/sing/common/ntp"
)
var globalSrv atomic.Pointer[Service]
var globalSrv *Service
var globalMu sync.Mutex
type Service struct {
@@ -23,21 +23,20 @@ type Service struct {
ticker *time.Ticker
ctx context.Context
cancel context.CancelFunc
offset atomic.Int64 // [time.Duration]
syncSystemTime bool
}
func ReCreateNTPService(server string, interval time.Duration, dialerProxy string, syncSystemTime bool) {
globalMu.Lock()
defer globalMu.Unlock()
if service := globalSrv.Swap(nil); service != nil {
service.Stop()
if globalSrv != nil {
globalSrv.Stop()
}
if server == "" || interval <= 0 {
return
}
ctx, cancel := context.WithCancel(context.Background())
service := &Service{
globalSrv = &Service{
server: M.ParseSocksaddr(server),
dialer: proxydialer.NewByNameSingDialer(dialerProxy, dialer.NewDialer()),
ticker: time.NewTicker(interval * time.Minute),
@@ -45,8 +44,7 @@ func ReCreateNTPService(server string, interval time.Duration, dialerProxy strin
cancel: cancel,
syncSystemTime: syncSystemTime,
}
service.Start()
globalSrv.Store(service)
globalSrv.Start()
}
func (srv *Service) Start() {
@@ -59,10 +57,6 @@ func (srv *Service) Stop() {
srv.cancel()
}
func (srv *Service) Offset() time.Duration {
return time.Duration(srv.offset.Load())
}
func (srv *Service) update() error {
var response *ntp.Response
var err error
@@ -80,7 +74,7 @@ func (srv *Service) update() error {
} else if offset < time.Duration(0) {
log.Infoln("System clock is behind NTP time by %s", -offset)
}
srv.offset.Store(int64(offset))
mihomoNtp.SetOffset(offset)
if srv.syncSystemTime {
timeNow := response.Time
syncErr := setSystemTime(timeNow)
@@ -97,7 +91,7 @@ func (srv *Service) update() error {
}
func (srv *Service) loopUpdate() {
defer srv.offset.Store(0)
defer mihomoNtp.SetOffset(0)
defer srv.ticker.Stop()
for {
err := srv.update()
@@ -111,13 +105,3 @@ func (srv *Service) loopUpdate() {
}
}
}
func Now() time.Time {
now := time.Now()
if service := globalSrv.Load(); service != nil {
if offset := service.Offset(); offset.Abs() > 0 {
now = now.Add(offset)
}
}
return now
}

28
ntp/time.go Normal file
View File

@@ -0,0 +1,28 @@
// Package ntp provide time.Now
//
// DON'T import other package in mihomo to keep minimal internal dependencies
package ntp
import (
"time"
"sync/atomic"
)
var _offset atomic.Int64 // [time.Duration]
func SetOffset(offset time.Duration) {
_offset.Store(int64(offset))
}
func GetOffset() time.Duration {
return time.Duration(_offset.Load())
}
func Now() time.Time {
now := time.Now()
if offset := GetOffset(); offset != 0 {
now = now.Add(offset)
}
return now
}

View File

@@ -34,7 +34,7 @@ func ConvertToMrs(buf []byte, behavior P.RuleBehavior, format P.RuleFormat, w io
}
var encoder *zstd.Encoder
encoder, err = zstd.NewWriter(w, zstd.WithEncoderLevel(zstd.SpeedBestCompression))
encoder, err = zstd.NewWriter(w)
if err != nil {
return err
}

View File

@@ -183,7 +183,11 @@ func (pc *PacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, er
if err != nil {
return nil, nil, nil, err
}
addr = destination.UDPAddr()
udpAddr := destination.UDPAddr()
if udpAddr == nil {
return nil, nil, nil, errors.New("parse addr error")
}
addr = udpAddr
data = pool.Get(pool.UDPBufferSize)
put = func() {

View File

@@ -21,7 +21,6 @@ func SetCongestionController(quicConn *quic.Conn, cc string, cwnd int) {
case "cubic":
quicConn.SetCongestionControl(
congestion.NewCubicSender(
congestion.DefaultClock{},
congestion.GetInitialPacketSize(quicConn),
false,
),
@@ -29,7 +28,6 @@ func SetCongestionController(quicConn *quic.Conn, cc string, cwnd int) {
case "new_reno":
quicConn.SetCongestionControl(
congestion.NewCubicSender(
congestion.DefaultClock{},
congestion.GetInitialPacketSize(quicConn),
true,
),
@@ -37,7 +35,6 @@ func SetCongestionController(quicConn *quic.Conn, cc string, cwnd int) {
case "bbr_meta_v1":
quicConn.SetCongestionControl(
congestion.NewBBRSender(
congestion.DefaultClock{},
congestion.GetInitialPacketSize(quicConn),
c.ByteCount(cwnd)*congestion.InitialMaxDatagramSize,
congestion.DefaultBBRMaxCongestionWindow*congestion.InitialMaxDatagramSize,
@@ -48,7 +45,6 @@ func SetCongestionController(quicConn *quic.Conn, cc string, cwnd int) {
case "bbr":
quicConn.SetCongestionControl(
congestionv2.NewBbrSender(
congestionv2.DefaultClock{},
congestionv2.GetInitialPacketSize(quicConn),
c.ByteCount(cwnd),
),

View File

@@ -101,7 +101,6 @@ const (
type bbrSender struct {
mode bbrMode
clock Clock
rttStats congestion.RTTStatsProvider
bytesInFlight congestion.ByteCount
// return total bytes of unacked packets.
@@ -232,14 +231,12 @@ type bbrSender struct {
}
func NewBBRSender(
clock Clock,
initialMaxDatagramSize,
initialCongestionWindow,
initialMaxCongestionWindow congestion.ByteCount,
) *bbrSender {
b := &bbrSender{
mode: STARTUP,
clock: clock,
sampler: NewBandwidthSampler(),
maxBandwidth: NewWindowedFilter(int64(BandwidthWindowSize), MaxFilter),
maxAckHeight: NewWindowedFilter(int64(BandwidthWindowSize), MaxFilter),

View File

@@ -1,18 +0,0 @@
package congestion
import "time"
// A Clock returns the current time
type Clock interface {
Now() time.Time
}
// DefaultClock implements the Clock interface using the Go stdlib clock.
type DefaultClock struct{}
var _ Clock = DefaultClock{}
// Now gets the current time
func (DefaultClock) Now() time.Time {
return time.Now()
}

View File

@@ -37,8 +37,6 @@ const betaLastMax float32 = 0.85
// Cubic implements the cubic algorithm from TCP
type Cubic struct {
clock Clock
// Number of connections to simulate.
numConnections int
@@ -67,9 +65,8 @@ type Cubic struct {
}
// NewCubic returns a new Cubic instance
func NewCubic(clock Clock) *Cubic {
func NewCubic() *Cubic {
c := &Cubic{
clock: clock,
numConnections: defaultNumConnections,
}
c.Reset()

View File

@@ -23,7 +23,6 @@ type cubicSender struct {
rttStats congestion.RTTStatsProvider
cubic *Cubic
pacer *pacer
clock Clock
reno bool
@@ -61,12 +60,10 @@ var (
// NewCubicSender makes a new cubic sender
func NewCubicSender(
clock Clock,
initialMaxDatagramSize congestion.ByteCount,
reno bool,
) *cubicSender {
return newCubicSender(
clock,
reno,
initialMaxDatagramSize,
initialCongestionWindow*initialMaxDatagramSize,
@@ -75,7 +72,6 @@ func NewCubicSender(
}
func newCubicSender(
clock Clock,
reno bool,
initialMaxDatagramSize,
initialCongestionWindow,
@@ -89,8 +85,7 @@ func newCubicSender(
initialMaxCongestionWindow: initialMaxCongestionWindow,
congestionWindow: initialCongestionWindow,
slowStartThreshold: MaxByteCount,
cubic: NewCubic(clock),
clock: clock,
cubic: NewCubic(),
reno: reno,
maxDatagramSize: initialMaxDatagramSize,
}

View File

@@ -96,7 +96,6 @@ const (
type bbrSender struct {
rttStats congestion.RTTStatsProvider
clock Clock
pacer *Pacer
mode bbrMode
@@ -244,12 +243,10 @@ type bbrSender struct {
var _ congestion.CongestionControl = &bbrSender{}
func NewBbrSender(
clock Clock,
initialMaxDatagramSize congestion.ByteCount,
initialCongestionWindowPackets congestion.ByteCount,
) *bbrSender {
return newBbrSender(
clock,
initialMaxDatagramSize,
initialCongestionWindowPackets*initialMaxDatagramSize,
congestion.MaxCongestionWindowPackets*initialMaxDatagramSize,
@@ -257,13 +254,11 @@ func NewBbrSender(
}
func newBbrSender(
clock Clock,
initialMaxDatagramSize,
initialCongestionWindow,
initialMaxCongestionWindow congestion.ByteCount,
) *bbrSender {
b := &bbrSender{
clock: clock,
mode: bbrModeStartup,
sampler: newBandwidthSampler(roundTripCount(bandwidthWindowSize)),
lastSentPacket: invalidPacketNumber,
@@ -297,7 +292,7 @@ func newBbrSender(
}
*/
b.enterStartupMode(b.clock.Now())
b.enterStartupMode()
b.setHighCwndGain(derivedHighCWNDGain)
return b
@@ -605,7 +600,7 @@ func (b *bbrSender) maybeUpdateMinRtt(now monotime.Time, sampleMinRtt time.Durat
}
// Enters the STARTUP mode.
func (b *bbrSender) enterStartupMode(now monotime.Time) {
func (b *bbrSender) enterStartupMode() {
b.mode = bbrModeStartup
// b.maybeTraceStateChange(logging.CongestionStateStartup)
b.pacingGain = b.highGain
@@ -757,7 +752,7 @@ func (b *bbrSender) maybeEnterOrExitProbeRtt(now monotime.Time, isRoundStart, mi
if now.Sub(b.exitProbeRttAt) >= 0 && b.probeRttRoundPassed {
b.minRttTimestamp = now
if !b.isAtFullBandwidth {
b.enterStartupMode(now)
b.enterStartupMode()
} else {
b.enterProbeBandwidthMode(now)
}

View File

@@ -1,20 +0,0 @@
package congestion
import (
"github.com/metacubex/quic-go/monotime"
)
// A Clock returns the current time
type Clock interface {
Now() monotime.Time
}
// DefaultClock implements the Clock interface using the Go stdlib clock.
type DefaultClock struct{}
var _ Clock = DefaultClock{}
// Now gets the current time
func (DefaultClock) Now() monotime.Time {
return monotime.Now()
}

View File

@@ -242,14 +242,26 @@ func (vc *Conn) WriteBuffer(buffer *buf.Buffer) (err error) {
}
func (vc *Conn) FrontHeadroom() int {
fontHeadroom := PaddingHeaderLen - uuid.Size
if vc.readFilterUUID || vc.writeOnceUserUUID != nil {
return PaddingHeaderLen
fontHeadroom = PaddingHeaderLen
}
return PaddingHeaderLen - uuid.Size
if vc.writeFilterApplicationData { // The writer may be replaced, add the required value for vc.netConn
if abs := N.CalculateFrontHeadroom(vc.netConn) - N.CalculateFrontHeadroom(vc.Conn); abs > 0 {
fontHeadroom += abs
}
}
return fontHeadroom
}
func (vc *Conn) RearHeadroom() int {
return 500 + 900
rearHeadroom := 500 + 900
if vc.writeFilterApplicationData { // The writer may be replaced, add the required value for vc.netConn
if abs := N.CalculateRearHeadroom(vc.netConn) - N.CalculateRearHeadroom(vc.Conn); abs > 0 {
rearHeadroom += abs
}
}
return rearHeadroom
}
func (vc *Conn) NeedHandshake() bool {

View File

@@ -3,7 +3,6 @@ package vmess
import (
"bufio"
"bytes"
"errors"
"fmt"
"net"
"net/http"
@@ -55,11 +54,11 @@ func (hc *httpConn) Write(b []byte) (int, error) {
return hc.Conn.Write(b)
}
if len(hc.cfg.Path) == 0 {
return -1, errors.New("path is empty")
path := "/"
if len(hc.cfg.Path) > 0 {
path = hc.cfg.Path[randv2.IntN(len(hc.cfg.Path))]
}
path := hc.cfg.Path[randv2.IntN(len(hc.cfg.Path))]
host := hc.cfg.Host
if header := hc.cfg.Headers["Host"]; len(header) != 0 {
host = header[randv2.IntN(len(header))]

View File

@@ -70,7 +70,9 @@ func (d *DNSDialer) DialContext(ctx context.Context, network, addr string) (net.
} else {
var ok bool
proxyAdapter, ok = Proxies()[proxyName]
if !ok {
if ok {
metadata.SpecialProxy = proxyName // just for log
} else {
opts = append(opts, dialer.WithInterface(proxyName))
}
}
@@ -158,7 +160,9 @@ func (d *DNSDialer) ListenPacket(ctx context.Context, network, addr string) (net
} else {
var ok bool
proxyAdapter, ok = Proxies()[proxyName]
if !ok {
if ok {
metadata.SpecialProxy = proxyName // just for log
} else {
opts = append(opts, dialer.WithInterface(proxyName))
}
}

View File

@@ -17,13 +17,13 @@ import (
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/component/loopback"
"github.com/metacubex/mihomo/component/nat"
P "github.com/metacubex/mihomo/component/process"
"github.com/metacubex/mihomo/component/process"
"github.com/metacubex/mihomo/component/resolver"
"github.com/metacubex/mihomo/component/slowdown"
"github.com/metacubex/mihomo/component/sniffer"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/constant/features"
"github.com/metacubex/mihomo/constant/provider"
P "github.com/metacubex/mihomo/constant/provider"
icontext "github.com/metacubex/mihomo/context"
"github.com/metacubex/mihomo/log"
"github.com/metacubex/mihomo/tunnel/statistic"
@@ -43,8 +43,8 @@ var (
listeners = make(map[string]C.InboundListener)
subRules map[string][]C.Rule
proxies = make(map[string]C.Proxy)
providers map[string]provider.ProxyProvider
ruleProviders map[string]provider.RuleProvider
providers map[string]P.ProxyProvider
ruleProviders map[string]P.RuleProvider
configMux sync.RWMutex
// for compatibility, lazy init
@@ -59,21 +59,19 @@ var (
// default timeout for UDP session
udpTimeout = 60 * time.Second
findProcessMode = atomic.NewInt32Enum(P.FindProcessStrict)
fakeIPRange netip.Prefix
findProcessMode = atomic.NewInt32Enum(process.FindProcessStrict)
snifferDispatcher *sniffer.Dispatcher
sniffingEnable = false
ruleUpdateCallback = utils.NewCallback[provider.RuleProvider]()
ruleUpdateCallback = utils.NewCallback[P.RuleProvider]()
)
type tunnel struct{}
var Tunnel = tunnel{}
var _ C.Tunnel = Tunnel
var _ provider.Tunnel = Tunnel
var _ P.Tunnel = Tunnel
func (t tunnel) HandleTCPConn(conn net.Conn, metadata *C.Metadata) {
connCtx := icontext.NewConnContext(conn, metadata)
@@ -114,15 +112,15 @@ func (t tunnel) NatTable() C.NatTable {
return natTable
}
func (t tunnel) Providers() map[string]provider.ProxyProvider {
func (t tunnel) Providers() map[string]P.ProxyProvider {
return providers
}
func (t tunnel) RuleProviders() map[string]provider.RuleProvider {
func (t tunnel) RuleProviders() map[string]P.RuleProvider {
return ruleProviders
}
func (t tunnel) RuleUpdateCallback() *utils.Callback[provider.RuleProvider] {
func (t tunnel) RuleUpdateCallback() *utils.Callback[P.RuleProvider] {
return ruleUpdateCallback
}
@@ -142,14 +140,6 @@ func Status() TunnelStatus {
return status.Load()
}
func SetFakeIPRange(p netip.Prefix) {
fakeIPRange = p
}
func FakeIPRange() netip.Prefix {
return fakeIPRange
}
func SetSniffing(b bool) {
if snifferDispatcher.Enable() {
configMux.Lock()
@@ -205,7 +195,7 @@ func Listeners() map[string]C.InboundListener {
}
// UpdateRules handle update rules
func UpdateRules(newRules []C.Rule, newSubRule map[string][]C.Rule, rp map[string]provider.RuleProvider) {
func UpdateRules(newRules []C.Rule, newSubRule map[string][]C.Rule, rp map[string]P.RuleProvider) {
configMux.Lock()
rules = newRules
ruleProviders = rp
@@ -233,17 +223,17 @@ func ProxiesWithProviders() map[string]C.Proxy {
}
// Providers return all compatible providers
func Providers() map[string]provider.ProxyProvider {
func Providers() map[string]P.ProxyProvider {
return providers
}
// RuleProviders return all loaded rule providers
func RuleProviders() map[string]provider.RuleProvider {
func RuleProviders() map[string]P.RuleProvider {
return ruleProviders
}
// UpdateProxies handle update proxies
func UpdateProxies(newProxies map[string]C.Proxy, newProviders map[string]provider.ProxyProvider) {
func UpdateProxies(newProxies map[string]C.Proxy, newProviders map[string]P.ProxyProvider) {
configMux.Lock()
proxies = newProxies
providers = newProviders
@@ -273,13 +263,13 @@ func SetMode(m TunnelMode) {
mode = m
}
func FindProcessMode() P.FindProcessMode {
func FindProcessMode() process.FindProcessMode {
return findProcessMode.Load()
}
// SetFindProcessMode replace SetAlwaysFindProcess
// always find process info if legacyAlways = true or mode.Always() = true, may be increase many memory
func SetFindProcessMode(mode P.FindProcessMode) {
func SetFindProcessMode(mode process.FindProcessMode) {
findProcessMode.Store(mode)
}
@@ -368,7 +358,7 @@ func resolveMetadata(metadata *C.Metadata) (proxy C.Proxy, rule C.Rule, err erro
attemptProcessLookup = false
if !features.CMFA {
// normal check for process
uid, path, err := P.FindProcessName(metadata.NetWork.String(), metadata.SrcIP, int(metadata.SrcPort))
uid, path, err := process.FindProcessName(metadata.NetWork.String(), metadata.SrcIP, int(metadata.SrcPort))
if err != nil {
log.Debugln("[Process] find process error for %s: %v", metadata.String(), err)
} else {
@@ -376,13 +366,13 @@ func resolveMetadata(metadata *C.Metadata) (proxy C.Proxy, rule C.Rule, err erro
metadata.ProcessPath = path
metadata.Uid = uid
if pkg, err := P.FindPackageName(metadata); err == nil { // for android (not CMFA) package names
if pkg, err := process.FindPackageName(metadata); err == nil { // for android (not CMFA) package names
metadata.Process = pkg
}
}
} else {
// check package names
pkg, err := P.FindPackageName(metadata)
pkg, err := process.FindPackageName(metadata)
if err != nil {
log.Debugln("[Process] find process error for %s: %v", metadata.String(), err)
} else {
@@ -394,10 +384,10 @@ func resolveMetadata(metadata *C.Metadata) (proxy C.Proxy, rule C.Rule, err erro
}
switch FindProcessMode() {
case P.FindProcessAlways:
case process.FindProcessAlways:
helper.FindProcess()
helper.FindProcess = nil
case P.FindProcessOff:
case process.FindProcessOff:
helper.FindProcess = nil
}
@@ -563,7 +553,7 @@ func handleTCPConn(connCtx C.ConnContext) {
dialMetadata := metadata
if len(metadata.Host) > 0 {
if node, ok := resolver.DefaultHosts.Search(metadata.Host, false); ok {
if dstIp, _ := node.RandIP(); !FakeIPRange().Contains(dstIp) {
if dstIp, _ := node.RandIP(); !resolver.IsFakeIP(dstIp) {
dialMetadata.DstIP = dstIp
dialMetadata.DNSMode = C.DNSHosts
dialMetadata = dialMetadata.Pure()
@@ -637,7 +627,7 @@ func logMetadataErr(metadata *C.Metadata, rule C.Rule, proxy C.ProxyAdapter, err
func logMetadata(metadata *C.Metadata, rule C.Rule, remoteConn C.Connection) {
switch {
case metadata.SpecialProxy != "":
log.Infoln("[%s] %s --> %s using %s", strings.ToUpper(metadata.NetWork.String()), metadata.SourceDetail(), metadata.RemoteAddress(), metadata.SpecialProxy)
log.Infoln("[%s] %s --> %s using %s", strings.ToUpper(metadata.NetWork.String()), metadata.SourceDetail(), metadata.RemoteAddress(), remoteConn.Chains().String())
case rule != nil:
if rule.Payload() != "" {
log.Infoln("[%s] %s --> %s match %s using %s", strings.ToUpper(metadata.NetWork.String()), metadata.SourceDetail(), metadata.RemoteAddress(), fmt.Sprintf("%s(%s)", rule.RuleType().String(), rule.Payload()), remoteConn.Chains().String())
@@ -649,7 +639,7 @@ func logMetadata(metadata *C.Metadata, rule C.Rule, remoteConn C.Connection) {
case mode == Direct:
log.Infoln("[%s] %s --> %s using DIRECT", strings.ToUpper(metadata.NetWork.String()), metadata.SourceDetail(), metadata.RemoteAddress())
default:
log.Infoln("[%s] %s --> %s doesn't match any rule using %s", strings.ToUpper(metadata.NetWork.String()), metadata.SourceDetail(), metadata.RemoteAddress(), remoteConn.Chains().Last())
log.Infoln("[%s] %s --> %s doesn't match any rule using %s", strings.ToUpper(metadata.NetWork.String()), metadata.SourceDetail(), metadata.RemoteAddress(), remoteConn.Chains().String())
}
}