Refactor struct & Add override dialer options

This commit is contained in:
世界
2022-07-03 20:59:25 +08:00
parent ffedce0f5f
commit f510323dca
33 changed files with 282 additions and 166 deletions

226
route/router.go Normal file
View File

@@ -0,0 +1,226 @@
package route
import (
"context"
"io"
"net"
"net/http"
"os"
"path/filepath"
"time"
"github.com/oschwald/geoip2-golang"
"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"
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
needGeoDatabase bool
geoOptions option.GeoIPOptions
geoReader *geoip2.Reader
}
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),
}
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 router, nil
}
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
}
}
}
}
return false
}
func isGeoRule(rule option.DefaultRule) bool {
return len(rule.SourceGeoIP) > 0 && common.Any(rule.SourceGeoIP, notPrivateNode) || len(rule.GeoIP) > 0 && common.Any(rule.GeoIP, notPrivateNode)
}
func notPrivateNode(code string) bool {
return code == "private"
}
func (r *Router) UpdateOutbounds(outbounds []adapter.Outbound) {
var defaultOutbound adapter.Outbound
outboundByTag := make(map[string]adapter.Outbound)
if len(outbounds) > 0 {
defaultOutbound = outbounds[0]
}
for _, outbound := range outbounds {
outboundByTag[outbound.Tag()] = outbound
}
r.defaultOutbound = defaultOutbound
r.outboundByTag = outboundByTag
}
func (r *Router) Start() error {
if r.needGeoDatabase {
go r.prepareGeoIPDatabase()
}
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
}

130
route/rule.go Normal file
View File

@@ -0,0 +1,130 @@
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) {
if common.IsEmptyByEquals(options) {
return nil, E.New("empty rule config")
}
switch options.Type {
case "", C.RuleTypeDefault:
if !options.DefaultOptions.IsValid() {
return nil, E.New("missing conditions")
}
if options.DefaultOptions.Outbound == "" {
return nil, E.New("missing outbound field")
}
return NewDefaultRule(router, logger, common.PtrValueOrDefault(options.DefaultOptions))
case C.RuleTypeLogical:
if !options.LogicalOptions.IsValid() {
return nil, E.New("missing conditions")
}
if options.LogicalOptions.Outbound == "" {
return nil, E.New("missing outbound field")
}
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 {
index int
outbound string
items []RuleItem
}
type RuleItem interface {
Match(metadata *adapter.InboundContext) bool
String() string
}
func NewDefaultRule(router adapter.Router, logger log.Logger, options option.DefaultRule) (*DefaultRule, error) {
rule := &DefaultRule{
outbound: options.Outbound,
}
if len(options.Inbound) > 0 {
rule.items = append(rule.items, NewInboundRule(options.Inbound))
}
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 {
for _, item := range r.items {
if item.Match(metadata) {
return true
}
}
return false
}
func (r *DefaultRule) Outbound() string {
return r.outbound
}
func (r *DefaultRule) String() string {
return strings.Join(common.Map(r.items, F.ToString0[RuleItem]), " ")
}

68
route/rule_cidr.go Normal file
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
}

64
route/rule_domain.go Normal file
View File

@@ -0,0 +1,64 @@
package route
import (
"strings"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/common/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, " ") + "]"
}
}

102
route/rule_geoip.go Normal file
View File

@@ -0,0 +1,102 @@
package route
import (
"strings"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/log"
N "github.com/sagernet/sing/common/network"
)
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 r.match(metadata)
}
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 = strings.ToLower(country.Country.IsoCode)
}
} 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 = strings.ToLower(country.Country.IsoCode)
}
}
return r.match(metadata)
}
func (r *GeoIPItem) match(metadata *adapter.InboundContext) bool {
if r.isSource {
if metadata.SourceGeoIPCode == "" {
if !N.IsPublicAddr(metadata.Source.Addr) {
metadata.SourceGeoIPCode = "private"
}
}
return r.codeMap[metadata.SourceGeoIPCode]
} else {
if metadata.Destination.IsFqdn() {
return false
}
if metadata.GeoIPCode == "" {
if !N.IsPublicAddr(metadata.Destination.Addr) {
metadata.GeoIPCode = "private"
}
}
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
}

35
route/rule_inbound.go Normal file
View File

@@ -0,0 +1,35 @@
package route
import (
"strings"
"github.com/sagernet/sing-box/adapter"
F "github.com/sagernet/sing/common/format"
)
var _ RuleItem = (*InboundItem)(nil)
type InboundItem struct {
inbounds []string
inboundMap 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 *InboundItem) Match(metadata *adapter.InboundContext) bool {
return r.inboundMap[metadata.Inbound]
}
func (r *InboundItem) String() string {
if len(r.inbounds) == 1 {
return F.ToString("inbound=", r.inbounds[0])
} else {
return F.ToString("inbound=[", strings.Join(r.inbounds, " "), "]")
}
}

29
route/rule_ipversion.go Normal file
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
}

71
route/rule_logical.go Normal file
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+" ") + ")"
}

23
route/rule_network.go Normal file
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
}

53
route/rule_port.go Normal file
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
}

37
route/rule_protocol.go Normal file
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, " "), "]")
}