2022-01-22 22:10:45 +08:00
|
|
|
package common
|
2018-06-10 22:50:03 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
|
|
|
|
C "github.com/Dreamacro/clash/constant"
|
|
|
|
)
|
|
|
|
|
2019-10-28 00:02:23 +08:00
|
|
|
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) {
|
2019-11-04 10:42:39 +08:00
|
|
|
i.noResolveIP = noResolve
|
2019-10-28 00:02:23 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-06-10 22:50:03 +08:00
|
|
|
type IPCIDR struct {
|
2019-10-28 00:02:23 +08:00
|
|
|
ipnet *net.IPNet
|
|
|
|
adapter string
|
2021-11-17 16:03:47 +08:00
|
|
|
ruleExtra *C.RuleExtra
|
2019-10-28 00:02:23 +08:00
|
|
|
isSourceIP bool
|
|
|
|
noResolveIP bool
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (i *IPCIDR) RuleType() C.RuleType {
|
2019-02-02 21:03:13 +08:00
|
|
|
if i.isSourceIP {
|
2019-05-09 21:00:29 +08:00
|
|
|
return C.SrcIPCIDR
|
2019-02-02 21:03:13 +08:00
|
|
|
}
|
2018-06-10 22:50:03 +08:00
|
|
|
return C.IPCIDR
|
|
|
|
}
|
|
|
|
|
2019-10-28 00:02:23 +08:00
|
|
|
func (i *IPCIDR) Match(metadata *C.Metadata) bool {
|
2019-05-09 21:00:29 +08:00
|
|
|
ip := metadata.DstIP
|
2019-02-02 21:03:13 +08:00
|
|
|
if i.isSourceIP {
|
2019-05-09 21:00:29 +08:00
|
|
|
ip = metadata.SrcIP
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
2019-10-27 21:44:07 +08:00
|
|
|
return ip != nil && 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
|
|
|
}
|
|
|
|
|
2020-07-27 11:57:55 +08:00
|
|
|
func (i *IPCIDR) ShouldResolveIP() bool {
|
|
|
|
return !i.noResolveIP
|
2019-10-28 00:02:23 +08:00
|
|
|
}
|
|
|
|
|
2021-11-17 16:03:47 +08:00
|
|
|
func (i *IPCIDR) RuleExtra() *C.RuleExtra {
|
|
|
|
return i.ruleExtra
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewIPCIDR(s string, adapter string, ruleExtra *C.RuleExtra, opts ...IPCIDROption) (*IPCIDR, error) {
|
2018-06-10 22:50:03 +08:00
|
|
|
_, ipnet, err := net.ParseCIDR(s)
|
|
|
|
if err != nil {
|
2019-10-28 00:02:23 +08:00
|
|
|
return nil, errPayload
|
|
|
|
}
|
|
|
|
|
|
|
|
ipcidr := &IPCIDR{
|
2021-11-17 16:03:47 +08:00
|
|
|
ipnet: ipnet,
|
|
|
|
adapter: adapter,
|
|
|
|
ruleExtra: ruleExtra,
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
2019-10-28 00:02:23 +08:00
|
|
|
|
|
|
|
for _, o := range opts {
|
|
|
|
o(ipcidr)
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
2019-10-28 00:02:23 +08:00
|
|
|
|
|
|
|
return ipcidr, nil
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|