diff --git a/adapter/outbound/rematch.go b/adapter/outbound/rematch.go new file mode 100644 index 000000000..247b6c50e --- /dev/null +++ b/adapter/outbound/rematch.go @@ -0,0 +1,56 @@ +package outbound + +import ( + "context" + "fmt" + + C "github.com/metacubex/mihomo/constant" +) + +type Rematch struct { + *Base + targetRematchName *string + targetSubRule *string +} + +type RematchOption struct { + BasicOption + Name string `proxy:"name"` + TargetRematchName *string `proxy:"target-rematch-name,omitempty"` + TargetSubRule *string `proxy:"target-sub-rule,omitempty"` +} + +func (l *Rematch) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) { + l.applyMetadata(metadata) + return NewConn(nopConn{}, l), nil +} + +func (l *Rematch) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) { + l.applyMetadata(metadata) + return NewPacketConn(&nopPacketConn{}, l), nil +} + +func (l *Rematch) applyMetadata(metadata *C.Metadata) { + if l.targetRematchName != nil { + metadata.RematchName = *l.targetRematchName + } + if l.targetSubRule != nil { + metadata.SpecialRules = *l.targetSubRule + } +} + +func NewRematch(option RematchOption) (*Rematch, error) { + if option.TargetRematchName == nil && option.TargetSubRule == nil { + return nil, fmt.Errorf("rematch %s requires at least one of target-rematch-name or target-sub-rule", option.Name) + } + return &Rematch{ + Base: NewBase(BaseOption{ + Name: option.Name, + Type: C.Rematch, + ProviderName: option.ProviderName, + UDP: true, + }), + targetRematchName: option.TargetRematchName, + targetSubRule: option.TargetSubRule, + }, nil +} diff --git a/adapter/parser.go b/adapter/parser.go index 006354ad2..651f4cc0b 100644 --- a/adapter/parser.go +++ b/adapter/parser.go @@ -139,6 +139,13 @@ func ParseProxy(mapping map[string]any, options ...ProxyOption) (C.Proxy, error) break } proxy = outbound.NewRejectWithOption(*rejectOption) + case "rematch": + rematchOption := &outbound.RematchOption{BasicOption: basicOption} + err = decoder.Decode(mapping, rematchOption) + if err != nil { + break + } + proxy, err = outbound.NewRematch(*rematchOption) case "ssh": sshOption := &outbound.SshOption{BasicOption: basicOption} err = decoder.Decode(mapping, sshOption) diff --git a/constant/adapters.go b/constant/adapters.go index 37d8af666..5c282b613 100644 --- a/constant/adapters.go +++ b/constant/adapters.go @@ -22,6 +22,7 @@ const ( Compatible Pass PassRule + Rematch Dns Relay @@ -186,6 +187,8 @@ func (at AdapterType) String() string { return "Pass" case PassRule: return "PassRule" + case Rematch: + return "Rematch" case Dns: return "Dns" case Shadowsocks: diff --git a/constant/metadata.go b/constant/metadata.go index 7407e47ca..ea5775366 100644 --- a/constant/metadata.go +++ b/constant/metadata.go @@ -197,6 +197,7 @@ type Metadata struct { InPort uint16 `json:"inboundPort,string"` // `,string` is used to compatible with old version json output InName string `json:"inboundName"` InUser string `json:"inboundUser"` + RematchName string `json:"rematchName"` Host string `json:"host"` DNSMode DNSMode `json:"dnsMode"` Uid uint32 `json:"uid"` diff --git a/constant/rule.go b/constant/rule.go index c7463e1f6..05ea8ebd3 100644 --- a/constant/rule.go +++ b/constant/rule.go @@ -31,6 +31,7 @@ const ( ProcessPathRegex ProcessNameWildcard ProcessPathWildcard + RematchName RuleSet Network Uid @@ -97,6 +98,8 @@ func (rt RuleType) String() string { return "ProcessNameWildcard" case ProcessPathWildcard: return "ProcessPathWildcard" + case RematchName: + return "RematchName" case MATCH: return "Match" case RuleSet: @@ -150,8 +153,8 @@ type RuleWrapper interface { } type RuleMatchHelper struct { - ResolveIP func() - FindProcess func() + ResolveIP func() + FindProcess func() CheckPassRule func(adapterName string) bool } diff --git a/docs/config.yaml b/docs/config.yaml index b73d84500..b4f74acb1 100644 --- a/docs/config.yaml +++ b/docs/config.yaml @@ -1393,6 +1393,11 @@ proxies: # socks5 - name: "dns-out" type: dns + - name: "rematch" + type: rematch + target-rematch-name: "rematch1" # 如果填写则覆盖原始 metadata 中的 rematch-name(可用REMATCH-NAME规则匹配) + target-sub-rule: "sub-rule1" # 如果填写则接下来会直接用指定的 sub-rule 匹配,如果名字不存在或为空会回退到主rules + # 配置指定 interface-name 和 fwmark 的 DIRECT - name: en1-direct type: direct diff --git a/rules/common/rematch_name.go b/rules/common/rematch_name.go new file mode 100644 index 000000000..08f821c41 --- /dev/null +++ b/rules/common/rematch_name.go @@ -0,0 +1,56 @@ +package common + +import ( + "fmt" + "strings" + + C "github.com/metacubex/mihomo/constant" +) + +type RematchName struct { + Base + names []string + adapter string + payload string +} + +func (u *RematchName) Match(metadata *C.Metadata, helper C.RuleMatchHelper) (bool, string) { + for _, name := range u.names { + if metadata.RematchName == name { + return true, u.adapter + } + } + return false, "" +} + +func (u *RematchName) RuleType() C.RuleType { + return C.RematchName +} + +func (u *RematchName) Adapter() string { + return u.adapter +} + +func (u *RematchName) Payload() string { + return u.payload +} + +func NewRematchName(iNames, adapter string) (*RematchName, error) { + names := strings.Split(iNames, "/") + for i, name := range names { + name = strings.TrimSpace(name) + if len(name) == 0 { + return nil, fmt.Errorf("rematch name couldn't be empty") + } + names[i] = name + } + + return &RematchName{ + Base: Base{}, + names: names, + adapter: adapter, + payload: iNames, + }, nil +} + +var _ C.Rule = (*RematchName)(nil) diff --git a/rules/parser.go b/rules/parser.go index b2bf96424..474d01ef4 100644 --- a/rules/parser.go +++ b/rules/parser.go @@ -77,6 +77,8 @@ func ParseRule(tp, payload, target string, params []string, subRules map[string] parsed, parseErr = RC.NewInUser(payload, target) case "IN-NAME": parsed, parseErr = RC.NewInName(payload, target) + case "REMATCH-NAME": + parsed, parseErr = RC.NewRematchName(payload, target) case "SUB-RULE": parsed, parseErr = logic.NewSubRule(payload, target, subRules, ParseRule) case "AND": diff --git a/tunnel/tunnel.go b/tunnel/tunnel.go index 470f72998..86dbc14ae 100644 --- a/tunnel/tunnel.go +++ b/tunnel/tunnel.go @@ -28,6 +28,8 @@ import ( icontext "github.com/metacubex/mihomo/context" "github.com/metacubex/mihomo/log" "github.com/metacubex/mihomo/tunnel/statistic" + + "golang.org/x/exp/slices" ) const ( @@ -653,36 +655,59 @@ func match(metadata *C.Metadata, helper C.RuleMatchHelper) (C.Proxy, C.Rule, err configMux.RLock() defer configMux.RUnlock() - for _, rule := range getRules(metadata) { - if matched, ada := rule.Match(metadata, helper); matched { - adapter, ok := proxies[ada] - if !ok { - continue - } - - // parse multi-layer nesting - passed := false - for adapter := adapter; adapter != nil; adapter = adapter.Unwrap(metadata, false) { - if adapter.Type() == C.Pass { - passed = true - break + var rematchChain []string + for { + var rematchProxy C.Proxy + var rematchRule C.Rule + GetRules: + for _, rule := range getRules(metadata) { + if matched, ada := rule.Match(metadata, helper); matched { + adapter, ok := proxies[ada] + if !ok { + continue } - } - if passed { - log.Debugln("%s match Pass rule", adapter.Name()) - continue - } - if metadata.NetWork == C.UDP && !adapter.SupportUDP() { - log.Debugln("%s UDP is not supported", adapter.Name()) - continue - } + // parse multi-layer nesting + for adapter := adapter; adapter != nil; adapter = adapter.Unwrap(metadata, false) { + if adapter.Type() == C.Pass { + log.Debugln("%s match Pass rule", adapter.Name()) + continue GetRules + } + if adapter.Type() == C.Rematch { + log.Debugln("%s match Rematch rule", adapter.Name()) + rematchProxy = adapter + rematchRule = rule + break GetRules + } + } - return adapter, rule, nil + if metadata.NetWork == C.UDP && !adapter.SupportUDP() { + log.Debugln("%s UDP is not supported", adapter.Name()) + continue + } + + return adapter, rule, nil + } } + if rematchProxy != nil { + if slices.Contains(rematchChain, rematchProxy.Name()) { + log.Warnln("[Rule] rematch cycle detected on %s", rematchProxy.Name()) + return rematchProxy, rematchRule, nil + } + rematchChain = append(rematchChain, rematchProxy.Name()) + conn, err := rematchProxy.DialContext(context.Background(), metadata) // not a real connection, just for metadata update + if conn != nil { + _ = conn.Close() + } + if err != nil { + log.Warnln("[Rule] rematch proxy %s failed to update metadata: %s", rematchProxy.Name(), err) + return rematchProxy, rematchRule, nil + } + log.Debugln("[Rule] rematch proxy %s update metadata to rematch-name=%q sub-rule=%q", rematchProxy.Name(), metadata.InName, metadata.SpecialRules) + continue + } + return proxies["DIRECT"], nil, nil } - - return proxies["DIRECT"], nil, nil } func getRules(metadata *C.Metadata) []C.Rule {