clash/rule/ipcidr.go

80 lines
1.3 KiB
Go
Raw Normal View History

2018-06-10 14:50:03 +00:00
package rules
import (
"net"
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 14:50:03 +00:00
type IPCIDR struct {
ipnet *net.IPNet
adapter string
2021-07-01 14:49:29 +00:00
network C.NetWork
isSourceIP bool
noResolveIP bool
2018-06-10 14:50:03 +00:00
}
func (i *IPCIDR) RuleType() C.RuleType {
if i.isSourceIP {
2019-05-09 13:00:29 +00:00
return C.SrcIPCIDR
}
2018-06-10 14:50:03 +00:00
return C.IPCIDR
}
func (i *IPCIDR) Match(metadata *C.Metadata) bool {
2019-05-09 13:00:29 +00:00
ip := metadata.DstIP
if i.isSourceIP {
2019-05-09 13:00:29 +00:00
ip = metadata.SrcIP
2018-06-10 14:50:03 +00:00
}
return ip != nil && i.ipnet.Contains(ip)
2018-06-10 14:50:03 +00:00
}
2018-06-20 14:41:02 +00:00
func (i *IPCIDR) Adapter() string {
return i.adapter
}
func (i *IPCIDR) Payload() string {
return i.ipnet.String()
2018-06-10 14:50:03 +00:00
}
func (i *IPCIDR) ShouldResolveIP() bool {
return !i.noResolveIP
}
2021-07-01 14:49:29 +00:00
func (i *IPCIDR) NetWork() C.NetWork {
return i.network
}
func NewIPCIDR(s string, adapter string, network C.NetWork, opts ...IPCIDROption) (*IPCIDR, error) {
2018-06-10 14:50:03 +00:00
_, ipnet, err := net.ParseCIDR(s)
if err != nil {
return nil, errPayload
}
ipcidr := &IPCIDR{
ipnet: ipnet,
adapter: adapter,
2021-07-01 14:49:29 +00:00
network: network,
2018-06-10 14:50:03 +00:00
}
for _, o := range opts {
o(ipcidr)
2018-06-10 14:50:03 +00:00
}
return ipcidr, nil
2018-06-10 14:50:03 +00:00
}