Implement route rules

This commit is contained in:
世界
2022-07-02 22:55:10 +08:00
parent 7c57eb70e8
commit 6eae8e361f
40 changed files with 1220 additions and 145 deletions

View File

@@ -0,0 +1,47 @@
package domain
import "unicode/utf8"
type Matcher struct {
set *succinctSet
}
func NewMatcher(domains []string, domainSuffix []string) *Matcher {
var domainList []string
for _, domain := range domains {
domainList = append(domainList, reverseDomain(domain))
}
for _, domain := range domainSuffix {
domainList = append(domainList, reverseDomainSuffix(domain))
}
return &Matcher{
newSuccinctSet(domainList),
}
}
func (m *Matcher) Match(domain string) bool {
return m.set.Has(reverseDomain(domain))
}
func reverseDomain(domain string) string {
l := len(domain)
b := make([]byte, l)
for i := 0; i < l; {
r, n := utf8.DecodeRuneInString(domain[i:])
i += n
utf8.EncodeRune(b[l-i:], r)
}
return string(b)
}
func reverseDomainSuffix(domain string) string {
l := len(domain)
b := make([]byte, l+1)
for i := 0; i < l; {
r, n := utf8.DecodeRuneInString(domain[i:])
i += n
utf8.EncodeRune(b[l-i:], r)
}
b[l] = prefixLabel
return string(b)
}

View File

@@ -0,0 +1,18 @@
package domain
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestMatch(t *testing.T) {
r := require.New(t)
matcher := NewMatcher([]string{"domain.com"}, []string{"suffix.com", ".suffix.org"})
r.True(matcher.Match("domain.com"))
r.False(matcher.Match("my.domain.com"))
r.True(matcher.Match("suffix.com"))
r.True(matcher.Match("my.suffix.com"))
r.False(matcher.Match("suffix.org"))
r.True(matcher.Match("my.suffix.org"))
}

232
adapter/route/domain/set.go Normal file
View File

@@ -0,0 +1,232 @@
package domain
import (
"math/bits"
)
const prefixLabel = '\r'
// mod from https://github.com/openacid/succinct
type succinctSet struct {
leaves, labelBitmap []uint64
labels []byte
ranks, selects []int32
}
func newSuccinctSet(keys []string) *succinctSet {
ss := &succinctSet{}
lIdx := 0
type qElt struct{ s, e, col int }
queue := []qElt{{0, len(keys), 0}}
for i := 0; i < len(queue); i++ {
elt := queue[i]
if elt.col == len(keys[elt.s]) {
// a leaf node
elt.s++
setBit(&ss.leaves, i, 1)
}
for j := elt.s; j < elt.e; {
frm := j
for ; j < elt.e && keys[j][elt.col] == keys[frm][elt.col]; j++ {
}
queue = append(queue, qElt{frm, j, elt.col + 1})
ss.labels = append(ss.labels, keys[frm][elt.col])
setBit(&ss.labelBitmap, lIdx, 0)
lIdx++
}
setBit(&ss.labelBitmap, lIdx, 1)
lIdx++
}
ss.init()
return ss
}
func (ss *succinctSet) Has(key string) bool {
var nodeId, bmIdx int
for i := 0; i < len(key); i++ {
currentChar := key[i]
for ; ; bmIdx++ {
if getBit(ss.labelBitmap, bmIdx) != 0 {
return false
}
nextLabel := ss.labels[bmIdx-nodeId]
if nextLabel == prefixLabel {
return true
}
if nextLabel == currentChar {
break
}
}
nodeId = countZeros(ss.labelBitmap, ss.ranks, bmIdx+1)
bmIdx = selectIthOne(ss.labelBitmap, ss.ranks, ss.selects, nodeId-1) + 1
}
if getBit(ss.leaves, nodeId) != 0 {
return true
}
for ; ; bmIdx++ {
if getBit(ss.labelBitmap, bmIdx) != 0 {
return false
}
if ss.labels[bmIdx-nodeId] == prefixLabel {
return true
}
}
}
func setBit(bm *[]uint64, i int, v int) {
for i>>6 >= len(*bm) {
*bm = append(*bm, 0)
}
(*bm)[i>>6] |= uint64(v) << uint(i&63)
}
func getBit(bm []uint64, i int) uint64 {
return bm[i>>6] & (1 << uint(i&63))
}
func (ss *succinctSet) init() {
ss.selects, ss.ranks = indexSelect32R64(ss.labelBitmap)
}
func countZeros(bm []uint64, ranks []int32, i int) int {
a, _ := rank64(bm, ranks, int32(i))
return i - int(a)
}
func selectIthOne(bm []uint64, ranks, selects []int32, i int) int {
a, _ := select32R64(bm, selects, ranks, int32(i))
return int(a)
}
func rank64(words []uint64, rindex []int32, i int32) (int32, int32) {
wordI := i >> 6
j := uint32(i & 63)
n := rindex[wordI]
w := words[wordI]
c1 := n + int32(bits.OnesCount64(w&mask[j]))
return c1, int32(w>>uint(j)) & 1
}
func indexRank64(words []uint64, opts ...bool) []int32 {
trailing := false
if len(opts) > 0 {
trailing = opts[0]
}
l := len(words)
if trailing {
l++
}
idx := make([]int32, l)
n := int32(0)
for i := 0; i < len(words); i++ {
idx[i] = n
n += int32(bits.OnesCount64(words[i]))
}
if trailing {
idx[len(words)] = n
}
return idx
}
func select32R64(words []uint64, selectIndex, rankIndex []int32, i int32) (int32, int32) {
a := int32(0)
l := int32(len(words))
wordI := selectIndex[i>>5] >> 6
for ; rankIndex[wordI+1] <= i; wordI++ {
}
w := words[wordI]
ww := w
base := wordI << 6
findIth := int(i - rankIndex[wordI])
offset := int32(0)
ones := bits.OnesCount32(uint32(ww))
if ones <= findIth {
findIth -= ones
offset |= 32
ww >>= 32
}
ones = bits.OnesCount16(uint16(ww))
if ones <= findIth {
findIth -= ones
offset |= 16
ww >>= 16
}
ones = bits.OnesCount8(uint8(ww))
if ones <= findIth {
a = int32(select8Lookup[(ww>>5)&(0x7f8)|uint64(findIth-ones)]) + offset + 8
} else {
a = int32(select8Lookup[(ww&0xff)<<3|uint64(findIth)]) + offset
}
a += base
w &= rMaskUpto[a&63]
if w != 0 {
return a, base + int32(bits.TrailingZeros64(w))
}
wordI++
for ; wordI < l; wordI++ {
w = words[wordI]
if w != 0 {
return a, wordI<<6 + int32(bits.TrailingZeros64(w))
}
}
return a, l << 6
}
func indexSelect32R64(words []uint64) ([]int32, []int32) {
l := len(words) << 6
sidx := make([]int32, 0, len(words))
ith := -1
for i := 0; i < l; i++ {
if words[i>>6]&(1<<uint(i&63)) != 0 {
ith++
if ith&31 == 0 {
sidx = append(sidx, int32(i))
}
}
}
// clone to reduce cap to len
sidx = append(sidx[:0:0], sidx...)
return sidx, indexRank64(words, true)
}
func init() {
initMasks()
initSelectLookup()
}
var (
mask [65]uint64
rMaskUpto [64]uint64
)
func initMasks() {
for i := 0; i < 65; i++ {
mask[i] = (1 << uint(i)) - 1
}
var maskUpto [64]uint64
for i := 0; i < 64; i++ {
maskUpto[i] = (1 << uint(i+1)) - 1
rMaskUpto[i] = ^maskUpto[i]
}
}
var select8Lookup [256 * 8]uint8
func initSelectLookup() {
for i := 0; i < 256; i++ {
w := uint8(i)
for j := 0; j < 8; j++ {
// x-th 1 in w
// if x-th 1 is not found, it is 8
x := bits.TrailingZeros8(w)
w &= w - 1
select8Lookup[i*8+j] = uint8(x)
}
}
}

View File

@@ -2,7 +2,12 @@ package route
import (
"context"
"io"
"net"
"net/http"
"os"
"path/filepath"
"time"
"github.com/oschwald/geoip2-golang"
"github.com/sagernet/sing-box/adapter"
@@ -10,71 +15,63 @@ import (
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
)
var _ adapter.Router = (*Router)(nil)
type Router struct {
ctx context.Context
logger log.Logger
defaultOutbound adapter.Outbound
outboundByTag map[string]adapter.Outbound
rules []adapter.Rule
rules []adapter.Rule
geoReader *geoip2.Reader
needGeoDatabase bool
geoOptions option.GeoIPOptions
geoReader *geoip2.Reader
}
func NewRouter(logger log.Logger) *Router {
return &Router{
logger: logger.WithPrefix("router: "),
outboundByTag: make(map[string]adapter.Outbound),
func NewRouter(ctx context.Context, logger log.Logger, options option.RouteOptions) (*Router, error) {
router := &Router{
ctx: ctx,
logger: logger.WithPrefix("router: "),
outboundByTag: make(map[string]adapter.Outbound),
rules: make([]adapter.Rule, 0, len(options.Rules)),
needGeoDatabase: hasGeoRule(options.Rules),
geoOptions: common.PtrValueOrDefault(options.GeoIP),
}
}
func (r *Router) DefaultOutbound() adapter.Outbound {
if r.defaultOutbound == nil {
panic("missing default outbound")
for i, ruleOptions := range options.Rules {
rule, err := NewRule(router, logger, ruleOptions)
if err != nil {
return nil, E.Cause(err, "parse rule[", i, "]")
}
router.rules = append(router.rules, rule)
}
return r.defaultOutbound
return router, nil
}
func (r *Router) Outbound(tag string) (adapter.Outbound, bool) {
outbound, loaded := r.outboundByTag[tag]
return outbound, loaded
}
func (r *Router) RouteConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
for _, rule := range r.rules {
if rule.Match(metadata) {
r.logger.WithContext(ctx).Info("match ", rule.String())
if outbound, loaded := r.Outbound(rule.Outbound()); loaded {
return outbound.NewConnection(ctx, conn, metadata.Destination)
func hasGeoRule(rules []option.Rule) bool {
for _, rule := range rules {
if rule.DefaultOptions != nil {
if isGeoRule(common.PtrValueOrDefault(rule.DefaultOptions)) {
return true
}
} else if rule.LogicalOptions != nil {
for _, subRule := range rule.LogicalOptions.Rules {
if isGeoRule(subRule) {
return true
}
}
r.logger.WithContext(ctx).Error("outbound ", rule.Outbound(), " not found")
}
}
r.logger.WithContext(ctx).Info("no match => ", r.defaultOutbound.Tag())
return r.defaultOutbound.NewConnection(ctx, conn, metadata.Destination)
return false
}
func (r *Router) RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
for _, rule := range r.rules {
if rule.Match(metadata) {
r.logger.WithContext(ctx).Info("match ", rule.String())
if outbound, loaded := r.Outbound(rule.Outbound()); loaded {
return outbound.NewPacketConnection(ctx, conn, metadata.Destination)
}
r.logger.WithContext(ctx).Error("outbound ", rule.Outbound(), " not found")
}
}
r.logger.WithContext(ctx).Info("no match => ", r.defaultOutbound.Tag())
return r.defaultOutbound.NewPacketConnection(ctx, conn, metadata.Destination)
}
func (r *Router) Close() error {
return common.Close(
common.PtrOrNil(r.geoReader),
)
func isGeoRule(rule option.DefaultRule) bool {
return len(rule.SourceGeoIP) > 0 || len(rule.GeoIP) > 0
}
func (r *Router) UpdateOutbounds(outbounds []adapter.Outbound) {
@@ -90,14 +87,136 @@ func (r *Router) UpdateOutbounds(outbounds []adapter.Outbound) {
r.outboundByTag = outboundByTag
}
func (r *Router) UpdateRules(options []option.Rule) error {
rules := make([]adapter.Rule, 0, len(options))
for i, rule := range options {
switch rule.Type {
case "", C.RuleTypeDefault:
rules = append(rules, NewDefaultRule(i, rule.DefaultOptions))
}
func (r *Router) Start() error {
if r.needGeoDatabase {
go r.prepareGeoIPDatabase()
}
r.rules = rules
return nil
}
func (r *Router) Close() error {
return common.Close(
common.PtrOrNil(r.geoReader),
)
}
func (r *Router) GeoIPReader() *geoip2.Reader {
return r.geoReader
}
func (r *Router) prepareGeoIPDatabase() {
var geoPath string
if r.geoOptions.Path != "" {
geoPath = r.geoOptions.Path
} else {
geoPath = "Country.mmdb"
}
geoPath, loaded := C.Find(geoPath)
if !loaded {
r.logger.Warn("geoip database not exists: ", geoPath)
var err error
for attempts := 0; attempts < 3; attempts++ {
err = r.downloadGeoIPDatabase(geoPath)
if err == nil {
break
}
r.logger.Error("download geoip database: ", err)
os.Remove(geoPath)
time.Sleep(10 * time.Second)
}
if err != nil {
return
}
}
geoReader, err := geoip2.Open(geoPath)
if err == nil {
r.logger.Info("loaded geoip database")
r.geoReader = geoReader
} else {
r.logger.Error("open geoip database: ", err)
return
}
}
func (r *Router) downloadGeoIPDatabase(savePath string) error {
var downloadURL string
if r.geoOptions.DownloadURL != "" {
downloadURL = r.geoOptions.DownloadURL
} else {
downloadURL = "https://cdn.jsdelivr.net/gh/Dreamacro/maxmind-geoip@release/Country.mmdb"
}
r.logger.Info("downloading geoip database")
var detour adapter.Outbound
if r.geoOptions.DownloadDetour != "" {
outbound, loaded := r.Outbound(r.geoOptions.DownloadDetour)
if !loaded {
return E.New("detour outbound not found: ", r.geoOptions.DownloadDetour)
}
detour = outbound
} else {
detour = r.defaultOutbound
}
if parentDir := filepath.Dir(savePath); parentDir != "" {
os.MkdirAll(parentDir, 0o755)
}
saveFile, err := os.OpenFile(savePath, os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
return E.Cause(err, "open output file: ", downloadURL)
}
defer saveFile.Close()
httpClient := &http.Client{
Timeout: 5 * time.Second,
Transport: &http.Transport{
ForceAttemptHTTP2: true,
TLSHandshakeTimeout: 5 * time.Second,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return detour.DialContext(ctx, network, M.ParseSocksaddr(addr))
},
},
}
response, err := httpClient.Get(downloadURL)
if err != nil {
return err
}
defer response.Body.Close()
_, err = io.Copy(saveFile, response.Body)
return err
}
func (r *Router) DefaultOutbound() adapter.Outbound {
if r.defaultOutbound == nil {
panic("missing default outbound")
}
return r.defaultOutbound
}
func (r *Router) Outbound(tag string) (adapter.Outbound, bool) {
outbound, loaded := r.outboundByTag[tag]
return outbound, loaded
}
func (r *Router) RouteConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
return r.match(ctx, metadata).NewConnection(ctx, conn, metadata.Destination)
}
func (r *Router) RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
return r.match(ctx, metadata).NewPacketConnection(ctx, conn, metadata.Destination)
}
func (r *Router) match(ctx context.Context, metadata adapter.InboundContext) adapter.Outbound {
for i, rule := range r.rules {
if rule.Match(&metadata) {
detour := rule.Outbound()
r.logger.WithContext(ctx).Info("match [", i, "]", rule.String(), " => ", detour)
if outbound, loaded := r.Outbound(detour); loaded {
return outbound
}
r.logger.WithContext(ctx).Error("outbound not found: ", detour)
}
}
r.logger.WithContext(ctx).Info("no match")
return r.defaultOutbound
}

View File

@@ -1,11 +1,28 @@
package route
import (
"strings"
"github.com/sagernet/sing-box/adapter"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
F "github.com/sagernet/sing/common/format"
)
func NewRule(router adapter.Router, logger log.Logger, options option.Rule) (adapter.Rule, error) {
switch options.Type {
case "", C.RuleTypeDefault:
return NewDefaultRule(router, logger, common.PtrValueOrDefault(options.DefaultOptions))
case C.RuleTypeLogical:
return NewLogicalRule(router, logger, common.PtrValueOrDefault(options.LogicalOptions))
default:
return nil, E.New("unknown rule type: ", options.Type)
}
}
var _ adapter.Rule = (*DefaultRule)(nil)
type DefaultRule struct {
@@ -15,22 +32,72 @@ type DefaultRule struct {
}
type RuleItem interface {
Match(metadata adapter.InboundContext) bool
Match(metadata *adapter.InboundContext) bool
String() string
}
func NewDefaultRule(index int, options option.DefaultRule) *DefaultRule {
func NewDefaultRule(router adapter.Router, logger log.Logger, options option.DefaultRule) (*DefaultRule, error) {
rule := &DefaultRule{
index: index,
outbound: options.Outbound,
}
if len(options.Inbound) > 0 {
rule.items = append(rule.items, NewInboundRule(options.Inbound))
}
return rule
if options.IPVersion > 0 {
switch options.IPVersion {
case 4, 6:
rule.items = append(rule.items, NewIPVersionItem(options.IPVersion == 6))
default:
return nil, E.New("invalid ip version: ", options.IPVersion)
}
}
if options.Network != "" {
switch options.Network {
case C.NetworkTCP, C.NetworkUDP:
rule.items = append(rule.items, NewNetworkItem(options.Network))
default:
return nil, E.New("invalid network: ", options.Network)
}
}
if len(options.Protocol) > 0 {
rule.items = append(rule.items, NewProtocolItem(options.Protocol))
}
if len(options.Domain) > 0 || len(options.DomainSuffix) > 0 {
rule.items = append(rule.items, NewDomainItem(options.Domain, options.DomainSuffix))
}
if len(options.DomainKeyword) > 0 {
rule.items = append(rule.items, NewDomainKeywordItem(options.DomainKeyword))
}
if len(options.SourceGeoIP) > 0 {
rule.items = append(rule.items, NewGeoIPItem(router, logger, true, options.SourceGeoIP))
}
if len(options.GeoIP) > 0 {
rule.items = append(rule.items, NewGeoIPItem(router, logger, false, options.GeoIP))
}
if len(options.SourceIPCIDR) > 0 {
item, err := NewIPCIDRItem(true, options.SourceIPCIDR)
if err != nil {
return nil, err
}
rule.items = append(rule.items, item)
}
if len(options.IPCIDR) > 0 {
item, err := NewIPCIDRItem(false, options.IPCIDR)
if err != nil {
return nil, err
}
rule.items = append(rule.items, item)
}
if len(options.SourcePort) > 0 {
rule.items = append(rule.items, NewPortItem(true, options.SourcePort))
}
if len(options.Port) > 0 {
rule.items = append(rule.items, NewPortItem(false, options.Port))
}
return rule, nil
}
func (r *DefaultRule) Match(metadata adapter.InboundContext) bool {
func (r *DefaultRule) Match(metadata *adapter.InboundContext) bool {
for _, item := range r.items {
if item.Match(metadata) {
return true
@@ -44,12 +111,5 @@ func (r *DefaultRule) Outbound() string {
}
func (r *DefaultRule) String() string {
var description string
description = F.ToString("[", r.index, "]")
for _, item := range r.items {
description += " "
description += item.String()
}
description += " => " + r.outbound
return description
return strings.Join(common.Map(r.items, F.ToString0[RuleItem]), " ")
}

View File

@@ -0,0 +1,68 @@
package route
import (
"net/netip"
"strings"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing/common"
F "github.com/sagernet/sing/common/format"
)
var _ RuleItem = (*IPCIDRItem)(nil)
type IPCIDRItem struct {
prefixes []netip.Prefix
isSource bool
}
func NewIPCIDRItem(isSource bool, prefixStrings []string) (*IPCIDRItem, error) {
prefixes := make([]netip.Prefix, 0, len(prefixStrings))
for _, prefixString := range prefixStrings {
prefix, err := netip.ParsePrefix(prefixString)
if err != nil {
return nil, err
}
prefixes = append(prefixes, prefix)
}
return &IPCIDRItem{
prefixes: prefixes,
isSource: isSource,
}, nil
}
func (r *IPCIDRItem) Match(metadata *adapter.InboundContext) bool {
if r.isSource {
for _, prefix := range r.prefixes {
if prefix.Contains(metadata.Source.Addr) {
return true
}
}
} else {
if metadata.Destination.IsFqdn() {
return false
}
for _, prefix := range r.prefixes {
if prefix.Contains(metadata.Destination.Addr) {
return true
}
}
}
return false
}
func (r *IPCIDRItem) String() string {
var description string
if r.isSource {
description = "source_ipcidr="
} else {
description = "ipcidr="
}
pLen := len(r.prefixes)
if pLen == 1 {
description += r.prefixes[0].String()
} else {
description += "[" + strings.Join(common.Map(r.prefixes, F.ToString0[netip.Prefix]), " ") + "]"
}
return description
}

View File

@@ -0,0 +1,64 @@
package route
import (
"strings"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/adapter/route/domain"
"github.com/sagernet/sing/common"
)
var _ RuleItem = (*DomainItem)(nil)
type DomainItem struct {
description string
matcher *domain.Matcher
}
func NewDomainItem(domains []string, domainSuffixes []string) *DomainItem {
domains = common.Uniq(domains)
domainSuffixes = common.Uniq(domainSuffixes)
var description string
if dLen := len(domains); dLen > 0 {
if dLen == 1 {
description = "domain=" + domains[0]
} else if dLen > 3 {
description = "domain=[" + strings.Join(domains[:3], " ") + "...]"
} else {
description = "domain=[" + strings.Join(domains, " ") + "]"
}
}
if dsLen := len(domainSuffixes); dsLen > 0 {
if len(description) > 0 {
description += " "
}
if dsLen == 1 {
description += "domainSuffix=" + domainSuffixes[0]
} else if dsLen > 3 {
description += "domainSuffix=[" + strings.Join(domainSuffixes[:3], " ") + "...]"
} else {
description += "domainSuffix=[" + strings.Join(domainSuffixes, " ") + "]"
}
}
return &DomainItem{
description,
domain.NewMatcher(domains, domainSuffixes),
}
}
func (r *DomainItem) Match(metadata *adapter.InboundContext) bool {
var domainHost string
if metadata.Domain != "" {
domainHost = metadata.Domain
} else {
domainHost = metadata.Destination.Fqdn
}
if domainHost == "" {
return false
}
return r.matcher.Match(domainHost)
}
func (r *DomainItem) String() string {
return r.description
}

View File

@@ -0,0 +1,46 @@
package route
import (
"strings"
"github.com/sagernet/sing-box/adapter"
)
var _ RuleItem = (*DomainKeywordItem)(nil)
type DomainKeywordItem struct {
keywords []string
}
func NewDomainKeywordItem(keywords []string) *DomainKeywordItem {
return &DomainKeywordItem{keywords}
}
func (r *DomainKeywordItem) Match(metadata *adapter.InboundContext) bool {
var domainHost string
if metadata.Domain != "" {
domainHost = metadata.Domain
} else {
domainHost = metadata.Destination.Fqdn
}
if domainHost == "" {
return false
}
for _, keyword := range r.keywords {
if strings.Contains(domainHost, keyword) {
return true
}
}
return false
}
func (r *DomainKeywordItem) String() string {
kLen := len(r.keywords)
if kLen == 1 {
return "domain_keyword=" + r.keywords[0]
} else if kLen > 3 {
return "domain_keyword=[" + strings.Join(r.keywords[:3], " ") + "...]"
} else {
return "domain_keyword=[" + strings.Join(r.keywords, " ") + "]"
}
}

View File

@@ -0,0 +1,81 @@
package route
import (
"strings"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/log"
)
var _ RuleItem = (*GeoIPItem)(nil)
type GeoIPItem struct {
router adapter.Router
logger log.Logger
isSource bool
codes []string
codeMap map[string]bool
}
func NewGeoIPItem(router adapter.Router, logger log.Logger, isSource bool, codes []string) *GeoIPItem {
codeMap := make(map[string]bool)
for _, code := range codes {
codeMap[code] = true
}
return &GeoIPItem{
router: router,
logger: logger,
codes: codes,
isSource: isSource,
codeMap: codeMap,
}
}
func (r *GeoIPItem) Match(metadata *adapter.InboundContext) bool {
geoReader := r.router.GeoIPReader()
if geoReader == nil {
return false
}
if r.isSource {
if metadata.SourceGeoIPCode == "" {
country, err := geoReader.Country(metadata.Source.Addr.AsSlice())
if err != nil {
r.logger.Error("query geoip for ", metadata.Source.Addr, ": ", err)
return false
}
metadata.SourceGeoIPCode = country.Country.IsoCode
}
return r.codeMap[metadata.SourceGeoIPCode]
} else {
if metadata.Destination.IsFqdn() {
return false
}
if metadata.GeoIPCode == "" {
country, err := geoReader.Country(metadata.Destination.Addr.AsSlice())
if err != nil {
r.logger.Error("query geoip for ", metadata.Destination.Addr, ": ", err)
return false
}
metadata.GeoIPCode = country.Country.IsoCode
}
return r.codeMap[metadata.GeoIPCode]
}
}
func (r *GeoIPItem) String() string {
var description string
if r.isSource {
description = "source_geoip="
} else {
description = "geoip="
}
cLen := len(r.codes)
if cLen == 1 {
description += r.codes[0]
} else if cLen > 3 {
description += "[" + strings.Join(r.codes[:3], " ") + "...]"
} else {
description += "[" + strings.Join(r.codes, " ") + "]"
}
return description
}

View File

@@ -7,26 +7,26 @@ import (
F "github.com/sagernet/sing/common/format"
)
var _ RuleItem = (*InboundRule)(nil)
var _ RuleItem = (*InboundItem)(nil)
type InboundRule struct {
type InboundItem struct {
inbounds []string
inboundMap map[string]bool
}
func NewInboundRule(inbounds []string) RuleItem {
rule := &InboundRule{inbounds, make(map[string]bool)}
func NewInboundRule(inbounds []string) *InboundItem {
rule := &InboundItem{inbounds, make(map[string]bool)}
for _, inbound := range inbounds {
rule.inboundMap[inbound] = true
}
return rule
}
func (r *InboundRule) Match(metadata adapter.InboundContext) bool {
func (r *InboundItem) Match(metadata *adapter.InboundContext) bool {
return r.inboundMap[metadata.Inbound]
}
func (r *InboundRule) String() string {
func (r *InboundItem) String() string {
if len(r.inbounds) == 1 {
return F.ToString("inbound=", r.inbounds[0])
} else {

View File

@@ -0,0 +1,29 @@
package route
import (
"github.com/sagernet/sing-box/adapter"
)
var _ RuleItem = (*IPVersionItem)(nil)
type IPVersionItem struct {
isIPv6 bool
}
func NewIPVersionItem(isIPv6 bool) *IPVersionItem {
return &IPVersionItem{isIPv6}
}
func (r *IPVersionItem) Match(metadata *adapter.InboundContext) bool {
return metadata.Destination.IsIP() && metadata.Destination.Family().IsIPv6() == r.isIPv6
}
func (r *IPVersionItem) String() string {
var versionStr string
if r.isIPv6 {
versionStr = "6"
} else {
versionStr = "4"
}
return "ip_version=" + versionStr
}

View File

@@ -0,0 +1,71 @@
package route
import (
"strings"
"github.com/sagernet/sing-box/adapter"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
F "github.com/sagernet/sing/common/format"
)
var _ adapter.Rule = (*LogicalRule)(nil)
type LogicalRule struct {
mode string
rules []*DefaultRule
outbound string
}
func NewLogicalRule(router adapter.Router, logger log.Logger, options option.LogicalRule) (*LogicalRule, error) {
r := &LogicalRule{
rules: make([]*DefaultRule, len(options.Rules)),
outbound: options.Outbound,
}
switch options.Mode {
case C.LogicalTypeAnd:
r.mode = C.LogicalTypeAnd
case C.LogicalTypeOr:
r.mode = C.LogicalTypeOr
default:
return nil, E.New("unknown logical mode: ", options.Mode)
}
for i, subRule := range options.Rules {
rule, err := NewDefaultRule(router, logger, subRule)
if err != nil {
return nil, E.Cause(err, "sub rule[", i, "]")
}
r.rules[i] = rule
}
return r, nil
}
func (r *LogicalRule) Match(metadata *adapter.InboundContext) bool {
if r.mode == C.LogicalTypeAnd {
return common.All(r.rules, func(it *DefaultRule) bool {
return it.Match(metadata)
})
} else {
return common.Any(r.rules, func(it *DefaultRule) bool {
return it.Match(metadata)
})
}
}
func (r *LogicalRule) Outbound() string {
return r.outbound
}
func (r *LogicalRule) String() string {
var op string
switch r.mode {
case C.LogicalTypeAnd:
op = "&&"
case C.LogicalTypeOr:
op = "||"
}
return "logical(" + strings.Join(common.Map(r.rules, F.ToString0[*DefaultRule]), " "+op+" ") + ")"
}

View File

@@ -0,0 +1,23 @@
package route
import (
"github.com/sagernet/sing-box/adapter"
)
var _ RuleItem = (*NetworkItem)(nil)
type NetworkItem struct {
network string
}
func NewNetworkItem(network string) *NetworkItem {
return &NetworkItem{network}
}
func (r *NetworkItem) Match(metadata *adapter.InboundContext) bool {
return r.network == metadata.Network
}
func (r *NetworkItem) String() string {
return "network=" + r.network
}

View File

@@ -0,0 +1,53 @@
package route
import (
"strings"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing/common"
F "github.com/sagernet/sing/common/format"
)
var _ RuleItem = (*PortItem)(nil)
type PortItem struct {
ports []uint16
portMap map[uint16]bool
isSource bool
}
func NewPortItem(isSource bool, ports []uint16) *PortItem {
portMap := make(map[uint16]bool)
for _, port := range ports {
portMap[port] = true
}
return &PortItem{
ports: ports,
portMap: portMap,
isSource: isSource,
}
}
func (r *PortItem) Match(metadata *adapter.InboundContext) bool {
if r.isSource {
return r.portMap[metadata.Source.Port]
} else {
return r.portMap[metadata.Destination.Port]
}
}
func (r *PortItem) String() string {
var description string
if r.isSource {
description = "source_port="
} else {
description = "port="
}
pLen := len(r.ports)
if pLen == 1 {
description += F.ToString(r.ports[0])
} else {
description += "[" + strings.Join(common.Map(r.ports, F.ToString0[uint16]), " ") + "]"
}
return description
}

View File

@@ -0,0 +1,37 @@
package route
import (
"strings"
"github.com/sagernet/sing-box/adapter"
F "github.com/sagernet/sing/common/format"
)
var _ RuleItem = (*ProtocolItem)(nil)
type ProtocolItem struct {
protocols []string
protocolMap map[string]bool
}
func NewProtocolItem(protocols []string) *ProtocolItem {
protocolMap := make(map[string]bool)
for _, protocol := range protocols {
protocolMap[protocol] = true
}
return &ProtocolItem{
protocols: protocols,
protocolMap: protocolMap,
}
}
func (r *ProtocolItem) Match(metadata *adapter.InboundContext) bool {
return r.protocolMap[metadata.Protocol]
}
func (r *ProtocolItem) String() string {
if len(r.protocols) == 1 {
return F.ToString("protocol=", r.protocols[0])
}
return F.ToString("protocol=[", strings.Join(r.protocols, " "), "]")
}