sing-box/route/rule_item_cidr.go

80 lines
1.7 KiB
Go
Raw Normal View History

2022-07-02 22:55:10 +08:00
package route
import (
"net/netip"
"strings"
2022-07-08 23:03:57 +08:00
"github.com/sagernet/sing-box/adapter"
2022-07-04 15:51:41 +08:00
E "github.com/sagernet/sing/common/exceptions"
2022-08-25 22:22:20 +08:00
"go4.org/netipx"
2022-07-02 22:55:10 +08:00
)
var _ RuleItem = (*IPCIDRItem)(nil)
type IPCIDRItem struct {
2022-08-25 22:22:20 +08:00
ipSet *netipx.IPSet
isSource bool
description string
2022-07-02 22:55:10 +08:00
}
func NewIPCIDRItem(isSource bool, prefixStrings []string) (*IPCIDRItem, error) {
2022-08-25 22:22:20 +08:00
var builder netipx.IPSetBuilder
2022-07-04 15:51:41 +08:00
for i, prefixString := range prefixStrings {
2022-07-02 22:55:10 +08:00
prefix, err := netip.ParsePrefix(prefixString)
2022-08-25 22:22:20 +08:00
if err == nil {
builder.AddPrefix(prefix)
continue
}
addr, addrErr := netip.ParseAddr(prefixString)
if addrErr == nil {
builder.Add(addr)
continue
2022-07-02 22:55:10 +08:00
}
2022-08-25 22:22:20 +08:00
return nil, E.Cause(err, "parse ip_cidr [", i, "]")
}
var description string
if isSource {
description = "source_ipcidr="
} else {
description = "ipcidr="
}
if dLen := len(prefixStrings); dLen == 1 {
description += prefixStrings[0]
} else if dLen > 3 {
description += "[" + strings.Join(prefixStrings[:3], " ") + "...]"
} else {
description += "[" + strings.Join(prefixStrings, " ") + "]"
}
ipSet, err := builder.IPSet()
if err != nil {
return nil, err
2022-07-02 22:55:10 +08:00
}
return &IPCIDRItem{
2022-08-25 22:22:20 +08:00
ipSet: ipSet,
isSource: isSource,
description: description,
2022-07-02 22:55:10 +08:00
}, nil
}
func (r *IPCIDRItem) Match(metadata *adapter.InboundContext) bool {
if r.isSource {
2022-09-25 22:16:24 +08:00
return r.ipSet.Contains(metadata.Source.Addr)
2022-07-02 22:55:10 +08:00
} else {
2022-07-07 23:36:32 +08:00
if metadata.Destination.IsIP() {
2022-09-25 22:16:24 +08:00
return r.ipSet.Contains(metadata.Destination.Addr)
2022-07-07 23:36:32 +08:00
} else {
for _, address := range metadata.DestinationAddresses {
2022-09-25 22:16:24 +08:00
if r.ipSet.Contains(address) {
2022-08-25 22:22:20 +08:00
return true
2022-07-07 23:36:32 +08:00
}
2022-07-02 22:55:10 +08:00
}
}
}
return false
}
func (r *IPCIDRItem) String() string {
2022-08-25 22:22:20 +08:00
return r.description
2022-07-02 22:55:10 +08:00
}