mihomo/rule/common/ipcidr.go

78 lines
1.2 KiB
Go
Raw Normal View History

package common
2018-06-10 22:50:03 +08:00
import (
2022-04-20 01:52:51 +08:00
"net/netip"
2018-06-10 22:50:03 +08:00
C "github.com/Dreamacro/clash/constant"
)
type IPCIDROption func(*IPCIDR)
func WithIPCIDRSourceIP(b bool) IPCIDROption {
return func(i *IPCIDR) {
i.isSourceIP = b
}
}
func WithIPCIDRNoResolve(noResolve bool) IPCIDROption {
return func(i *IPCIDR) {
i.noResolveIP = noResolve
}
}
2018-06-10 22:50:03 +08:00
type IPCIDR struct {
2022-03-13 01:21:23 +08:00
*Base
2022-04-20 01:52:51 +08:00
ipnet *netip.Prefix
adapter string
isSourceIP bool
noResolveIP bool
2018-06-10 22:50:03 +08:00
}
func (i *IPCIDR) RuleType() C.RuleType {
if i.isSourceIP {
2019-05-09 21:00:29 +08:00
return C.SrcIPCIDR
}
2018-06-10 22:50:03 +08:00
return C.IPCIDR
}
func (i *IPCIDR) Match(metadata *C.Metadata) bool {
2019-05-09 21:00:29 +08:00
ip := metadata.DstIP
if i.isSourceIP {
2019-05-09 21:00:29 +08:00
ip = metadata.SrcIP
2018-06-10 22:50:03 +08:00
}
2022-04-20 01:52:51 +08:00
return ip.IsValid() && i.ipnet.Contains(ip)
2018-06-10 22:50:03 +08:00
}
2018-06-20 22:41:02 +08:00
func (i *IPCIDR) Adapter() string {
return i.adapter
}
func (i *IPCIDR) Payload() string {
return i.ipnet.String()
2018-06-10 22:50:03 +08:00
}
func (i *IPCIDR) ShouldResolveIP() bool {
return !i.noResolveIP
}
2022-03-13 01:21:23 +08:00
func NewIPCIDR(s string, adapter string, opts ...IPCIDROption) (*IPCIDR, error) {
2022-04-20 01:52:51 +08:00
ipnet, err := netip.ParsePrefix(s)
2018-06-10 22:50:03 +08:00
if err != nil {
return nil, errPayload
}
ipcidr := &IPCIDR{
2022-03-13 01:21:23 +08:00
Base: &Base{},
2022-04-20 01:52:51 +08:00
ipnet: &ipnet,
2022-03-13 01:21:23 +08:00
adapter: adapter,
2018-06-10 22:50:03 +08:00
}
for _, o := range opts {
o(ipcidr)
2018-06-10 22:50:03 +08:00
}
return ipcidr, nil
2018-06-10 22:50:03 +08:00
}
2022-03-13 01:21:23 +08:00
var _ C.Rule = (*IPCIDR)(nil)