sing-box/route/router.go

515 lines
16 KiB
Go
Raw Normal View History

2022-06-30 21:27:56 +08:00
package route
import (
"context"
2022-07-07 21:47:21 +08:00
"net/netip"
"net/url"
2022-07-02 22:55:10 +08:00
"os"
2024-02-22 21:20:23 +08:00
"runtime"
2022-07-07 21:47:21 +08:00
"strings"
2022-07-02 22:55:10 +08:00
"time"
2022-06-30 21:27:56 +08:00
2022-07-06 15:01:09 +08:00
"github.com/sagernet/sing-box/adapter"
2022-07-07 21:47:21 +08:00
"github.com/sagernet/sing-box/common/dialer"
2022-07-06 15:01:09 +08:00
"github.com/sagernet/sing-box/common/geoip"
"github.com/sagernet/sing-box/common/geosite"
"github.com/sagernet/sing-box/common/process"
"github.com/sagernet/sing-box/common/taskmonitor"
2022-07-06 15:01:09 +08:00
C "github.com/sagernet/sing-box/constant"
2022-10-25 12:55:00 +08:00
"github.com/sagernet/sing-box/experimental/libbox/platform"
2022-07-06 15:01:09 +08:00
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
2024-10-21 23:38:34 +08:00
R "github.com/sagernet/sing-box/route/rule"
2023-03-25 12:03:23 +08:00
"github.com/sagernet/sing-box/transport/fakeip"
2022-07-11 18:44:59 +08:00
"github.com/sagernet/sing-dns"
2022-07-08 23:03:57 +08:00
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
F "github.com/sagernet/sing/common/format"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
2023-12-01 13:24:12 +08:00
"github.com/sagernet/sing/common/task"
2023-08-08 16:14:03 +08:00
"github.com/sagernet/sing/service"
2023-08-07 17:46:51 +08:00
"github.com/sagernet/sing/service/pause"
2022-06-30 21:27:56 +08:00
)
var _ adapter.Router = (*Router)(nil)
type Router struct {
2024-11-10 12:11:21 +08:00
ctx context.Context
logger log.ContextLogger
dnsLogger log.ContextLogger
inboundManager adapter.InboundManager
outboundManager adapter.OutboundManager
networkManager adapter.NetworkManager
rules []adapter.Rule
needGeoIPDatabase bool
needGeositeDatabase bool
geoIPOptions option.GeoIPOptions
geositeOptions option.GeositeOptions
geoIPReader *geoip.Reader
geositeReader *geosite.Reader
geositeCache map[string]adapter.Rule
needFindProcess bool
dnsClient *dns.Client
defaultDomainStrategy dns.DomainStrategy
dnsRules []adapter.DNSRule
ruleSets []adapter.RuleSet
ruleSetMap map[string]adapter.RuleSet
defaultTransport dns.Transport
transports []dns.Transport
transportMap map[string]dns.Transport
transportDomainStrategy map[dns.Transport]dns.DomainStrategy
dnsReverseMapping *DNSReverseMapping
fakeIPStore adapter.FakeIPStore
processSearcher process.Searcher
pauseManager pause.Manager
tracker adapter.ConnectionTracker
2024-11-10 12:11:21 +08:00
platformInterface platform.Interface
needWIFIState bool
started bool
}
func NewRouter(ctx context.Context, logFactory log.Factory, options option.RouteOptions, dnsOptions option.DNSOptions) (*Router, error) {
2022-07-02 22:55:10 +08:00
router := &Router{
2022-07-07 21:47:21 +08:00
ctx: ctx,
2022-11-28 13:10:56 +08:00
logger: logFactory.NewLogger("router"),
dnsLogger: logFactory.NewLogger("dns"),
2024-11-10 12:11:21 +08:00
inboundManager: service.FromContext[adapter.InboundManager](ctx),
outboundManager: service.FromContext[adapter.OutboundManager](ctx),
networkManager: service.FromContext[adapter.NetworkManager](ctx),
2022-07-07 21:47:21 +08:00
rules: make([]adapter.Rule, 0, len(options.Rules)),
2022-07-24 14:05:06 +08:00
dnsRules: make([]adapter.DNSRule, 0, len(dnsOptions.Rules)),
2023-12-01 13:24:12 +08:00
ruleSetMap: make(map[string]adapter.RuleSet),
needGeoIPDatabase: hasRule(options.Rules, isGeoIPRule) || hasDNSRule(dnsOptions.Rules, isGeoIPDNSRule),
needGeositeDatabase: hasRule(options.Rules, isGeositeRule) || hasDNSRule(dnsOptions.Rules, isGeositeDNSRule),
2022-07-07 21:47:21 +08:00
geoIPOptions: common.PtrValueOrDefault(options.GeoIP),
2022-07-07 23:36:32 +08:00
geositeOptions: common.PtrValueOrDefault(options.Geosite),
2022-07-08 11:00:46 +08:00
geositeCache: make(map[string]adapter.Rule),
2023-12-01 13:24:12 +08:00
needFindProcess: hasRule(options.Rules, isProcessRule) || hasDNSRule(dnsOptions.Rules, isProcessDNSRule) || options.FindProcess,
2022-07-11 18:44:59 +08:00
defaultDomainStrategy: dns.DomainStrategy(dnsOptions.Strategy),
2023-12-16 15:40:14 +08:00
pauseManager: service.FromContext[pause.Manager](ctx),
2024-11-02 00:39:02 +08:00
platformInterface: service.FromContext[platform.Interface](ctx),
needWIFIState: hasRule(options.Rules, isWIFIRule) || hasDNSRule(dnsOptions.Rules, isWIFIDNSRule),
2022-06-30 21:27:56 +08:00
}
service.MustRegister[adapter.Router](ctx, router)
2023-04-26 04:53:25 +08:00
router.dnsClient = dns.NewClient(dns.ClientOptions{
DisableCache: dnsOptions.DNSClientOptions.DisableCache,
DisableExpire: dnsOptions.DNSClientOptions.DisableExpire,
IndependentCache: dnsOptions.DNSClientOptions.IndependentCache,
2024-11-14 12:42:42 +08:00
CacheCapacity: dnsOptions.DNSClientOptions.CacheCapacity,
RDRC: func() dns.RDRCStore {
cacheFile := service.FromContext[adapter.CacheFile](ctx)
if cacheFile == nil {
return nil
}
if !cacheFile.StoreRDRC() {
return nil
}
return cacheFile
},
Logger: router.dnsLogger,
2023-04-26 04:53:25 +08:00
})
2022-07-02 22:55:10 +08:00
for i, ruleOptions := range options.Rules {
2024-11-10 12:11:21 +08:00
routeRule, err := R.NewRule(ctx, router.logger, ruleOptions, true)
2022-07-02 22:55:10 +08:00
if err != nil {
return nil, E.Cause(err, "parse rule[", i, "]")
2022-07-02 14:07:50 +08:00
}
2022-07-07 21:47:21 +08:00
router.rules = append(router.rules, routeRule)
}
for i, dnsRuleOptions := range dnsOptions.Rules {
2024-11-10 12:11:21 +08:00
dnsRule, err := R.NewDNSRule(ctx, router.logger, dnsRuleOptions, true)
2022-07-07 21:47:21 +08:00
if err != nil {
return nil, E.Cause(err, "parse dns rule[", i, "]")
}
2022-07-07 23:36:32 +08:00
router.dnsRules = append(router.dnsRules, dnsRule)
2022-07-07 21:47:21 +08:00
}
2023-12-01 13:24:12 +08:00
for i, ruleSetOptions := range options.RuleSet {
if _, exists := router.ruleSetMap[ruleSetOptions.Tag]; exists {
return nil, E.New("duplicate rule-set tag: ", ruleSetOptions.Tag)
}
2024-11-10 12:11:21 +08:00
ruleSet, err := R.NewRuleSet(ctx, router.logger, ruleSetOptions)
2023-12-01 13:24:12 +08:00
if err != nil {
return nil, E.Cause(err, "parse rule-set[", i, "]")
}
router.ruleSets = append(router.ruleSets, ruleSet)
router.ruleSetMap[ruleSetOptions.Tag] = ruleSet
}
2023-06-07 20:28:21 +08:00
2022-07-11 18:44:59 +08:00
transports := make([]dns.Transport, len(dnsOptions.Servers))
dummyTransportMap := make(map[string]dns.Transport)
transportMap := make(map[string]dns.Transport)
2022-07-07 21:47:21 +08:00
transportTags := make([]string, len(dnsOptions.Servers))
transportTagMap := make(map[string]bool)
transportDomainStrategy := make(map[dns.Transport]dns.DomainStrategy)
2022-07-07 21:47:21 +08:00
for i, server := range dnsOptions.Servers {
var tag string
if server.Tag != "" {
tag = server.Tag
} else {
tag = F.ToString(i)
}
2023-03-18 19:15:28 +08:00
if transportTagMap[tag] {
return nil, E.New("duplicate dns server tag: ", tag)
}
2022-07-07 21:47:21 +08:00
transportTags[i] = tag
transportTagMap[tag] = true
}
outboundManager := service.FromContext[adapter.OutboundManager](ctx)
2022-07-07 21:47:21 +08:00
for {
lastLen := len(dummyTransportMap)
for i, server := range dnsOptions.Servers {
tag := transportTags[i]
if _, exists := dummyTransportMap[tag]; exists {
continue
}
var detour N.Dialer
if server.Detour == "" {
detour = dialer.NewDefaultOutbound(outboundManager)
} else {
detour = dialer.NewDetour(outboundManager, server.Detour)
}
2024-11-06 12:51:53 +08:00
var serverProtocol string
2022-07-24 13:44:44 +08:00
switch server.Address {
2023-02-08 16:28:52 +08:00
case "local":
2024-11-06 12:51:53 +08:00
serverProtocol = "local"
2022-07-24 13:44:44 +08:00
default:
serverURL, _ := url.Parse(server.Address)
var serverAddress string
if serverURL != nil {
2024-11-06 12:51:53 +08:00
if serverURL.Scheme == "" {
serverProtocol = "udp"
} else {
serverProtocol = serverURL.Scheme
}
serverAddress = serverURL.Hostname()
2022-07-07 21:47:21 +08:00
}
2022-07-10 09:15:01 +08:00
if serverAddress == "" {
serverAddress = server.Address
}
notIpAddress := !M.ParseSocksaddr(serverAddress).Addr.IsValid()
2022-07-10 09:15:01 +08:00
if server.AddressResolver != "" {
if !transportTagMap[server.AddressResolver] {
return nil, E.New("parse dns server[", tag, "]: address resolver not found: ", server.AddressResolver)
}
if upstream, exists := dummyTransportMap[server.AddressResolver]; exists {
2022-07-11 18:44:59 +08:00
detour = dns.NewDialerWrapper(detour, router.dnsClient, upstream, dns.DomainStrategy(server.AddressStrategy), time.Duration(server.AddressFallbackDelay))
2022-07-10 09:15:01 +08:00
} else {
continue
}
} else if notIpAddress && strings.Contains(server.Address, ".") {
2023-03-25 12:03:23 +08:00
return nil, E.New("parse dns server[", tag, "]: missing address_resolver")
2022-07-07 21:47:21 +08:00
}
}
var clientSubnet netip.Prefix
if server.ClientSubnet != nil {
2024-11-07 21:44:04 +08:00
clientSubnet = netip.Prefix(common.PtrValueOrDefault(server.ClientSubnet))
} else if dnsOptions.ClientSubnet != nil {
2024-11-07 21:44:04 +08:00
clientSubnet = netip.Prefix(common.PtrValueOrDefault(dnsOptions.ClientSubnet))
}
2024-11-06 12:51:53 +08:00
if serverProtocol == "" {
serverProtocol = "transport"
}
transport, err := dns.CreateTransport(dns.TransportOptions{
Context: ctx,
2024-11-06 12:51:53 +08:00
Logger: logFactory.NewLogger(F.ToString("dns/", serverProtocol, "[", tag, "]")),
Name: tag,
Dialer: detour,
Address: server.Address,
ClientSubnet: clientSubnet,
})
2022-07-07 21:47:21 +08:00
if err != nil {
return nil, E.Cause(err, "parse dns server[", tag, "]")
}
transports[i] = transport
dummyTransportMap[tag] = transport
if server.Tag != "" {
transportMap[server.Tag] = transport
}
strategy := dns.DomainStrategy(server.Strategy)
if strategy != dns.DomainStrategyAsIS {
transportDomainStrategy[transport] = strategy
}
2022-07-07 21:47:21 +08:00
}
if len(transports) == len(dummyTransportMap) {
break
}
if lastLen != len(dummyTransportMap) {
continue
}
unresolvedTags := common.MapIndexed(common.FilterIndexed(dnsOptions.Servers, func(index int, server option.DNSServerOptions) bool {
_, exists := dummyTransportMap[transportTags[index]]
return !exists
}), func(index int, server option.DNSServerOptions) string {
return transportTags[index]
})
2023-03-18 19:15:28 +08:00
if len(unresolvedTags) == 0 {
panic(F.ToString("unexpected unresolved dns servers: ", len(transports), " ", len(dummyTransportMap), " ", len(transportMap)))
}
2022-07-07 21:47:21 +08:00
return nil, E.New("found circular reference in dns servers: ", strings.Join(unresolvedTags, " "))
}
2022-07-11 18:44:59 +08:00
var defaultTransport dns.Transport
2022-07-13 19:01:20 +08:00
if dnsOptions.Final != "" {
2022-08-10 12:18:03 +08:00
defaultTransport = dummyTransportMap[dnsOptions.Final]
2022-07-07 21:47:21 +08:00
if defaultTransport == nil {
2022-08-10 12:18:03 +08:00
return nil, E.New("default dns server not found: ", dnsOptions.Final)
2022-07-07 21:47:21 +08:00
}
}
if defaultTransport == nil {
if len(transports) == 0 {
transports = append(transports, common.Must1(dns.CreateTransport(dns.TransportOptions{
Context: ctx,
Name: "local",
Address: "local",
2024-11-10 12:11:21 +08:00
Dialer: common.Must1(dialer.NewDefault(router.networkManager, option.DialerOptions{})),
})))
2022-07-07 21:47:21 +08:00
}
defaultTransport = transports[0]
2022-07-02 14:07:50 +08:00
}
2023-12-01 21:48:21 +08:00
if _, isFakeIP := defaultTransport.(adapter.FakeIPTransport); isFakeIP {
return nil, E.New("default DNS server cannot be fakeip")
}
2022-07-07 21:47:21 +08:00
router.defaultTransport = defaultTransport
router.transports = transports
router.transportMap = transportMap
router.transportDomainStrategy = transportDomainStrategy
2023-03-23 19:08:48 +08:00
if dnsOptions.ReverseMapping {
router.dnsReverseMapping = NewDNSReverseMapping()
}
2023-03-25 12:03:23 +08:00
if fakeIPOptions := dnsOptions.FakeIP; fakeIPOptions != nil && dnsOptions.FakeIP.Enabled {
var inet4Range netip.Prefix
var inet6Range netip.Prefix
if fakeIPOptions.Inet4Range != nil {
2023-10-21 12:00:00 +08:00
inet4Range = *fakeIPOptions.Inet4Range
2023-03-25 12:03:23 +08:00
}
if fakeIPOptions.Inet6Range != nil {
2023-10-21 12:00:00 +08:00
inet6Range = *fakeIPOptions.Inet6Range
2023-03-25 12:03:23 +08:00
}
2023-11-28 12:00:28 +08:00
router.fakeIPStore = fakeip.NewStore(ctx, router.logger, inet4Range, inet6Range)
2023-03-25 12:03:23 +08:00
}
2022-07-02 22:55:10 +08:00
return router, nil
2022-06-30 21:27:56 +08:00
}
func (r *Router) Start(stage adapter.StartStage) error {
2024-04-02 23:07:26 +08:00
monitor := taskmonitor.New(r.logger, C.StartTimeout)
switch stage {
case adapter.StartStateInitialize:
if r.fakeIPStore != nil {
monitor.Start("initialize fakeip store")
err := r.fakeIPStore.Start()
monitor.Finish()
if err != nil {
return err
}
}
case adapter.StartStateStart:
if r.needGeoIPDatabase {
monitor.Start("initialize geoip database")
err := r.prepareGeoIPDatabase()
monitor.Finish()
if err != nil {
return err
}
2023-02-08 16:28:52 +08:00
}
if r.needGeositeDatabase {
monitor.Start("initialize geosite database")
err := r.prepareGeositeDatabase()
monitor.Finish()
2022-07-05 13:23:47 +08:00
if err != nil {
return err
2022-07-05 13:23:47 +08:00
}
}
if r.needGeositeDatabase {
for _, rule := range r.rules {
err := rule.UpdateGeosite()
if err != nil {
r.logger.Error("failed to initialize geosite: ", err)
}
}
for _, rule := range r.dnsRules {
err := rule.UpdateGeosite()
if err != nil {
r.logger.Error("failed to initialize geosite: ", err)
}
}
err := common.Close(r.geositeReader)
2022-07-07 23:36:32 +08:00
if err != nil {
return err
2022-07-07 23:36:32 +08:00
}
r.geositeCache = nil
r.geositeReader = nil
2022-07-07 23:36:32 +08:00
}
monitor.Start("initialize DNS client")
r.dnsClient.Start()
2024-02-22 21:20:23 +08:00
monitor.Finish()
for i, rule := range r.dnsRules {
monitor.Start("initialize DNS rule[", i, "]")
err := rule.Start()
monitor.Finish()
if err != nil {
return E.Cause(err, "initialize DNS rule[", i, "]")
}
2024-06-09 07:21:50 +08:00
}
for i, transport := range r.transports {
monitor.Start("initialize DNS transport[", i, "]")
err := transport.Start()
monitor.Finish()
if err != nil {
return E.Cause(err, "initialize DNS server[", i, "]")
}
2024-06-09 07:21:50 +08:00
}
case adapter.StartStatePostStart:
var cacheContext *adapter.HTTPStartContext
if len(r.ruleSets) > 0 {
monitor.Start("initialize rule-set")
cacheContext = adapter.NewHTTPStartContext()
var ruleSetStartGroup task.Group
for i, ruleSet := range r.ruleSets {
ruleSetInPlace := ruleSet
ruleSetStartGroup.Append0(func(ctx context.Context) error {
err := ruleSetInPlace.StartContext(ctx, cacheContext)
if err != nil {
return E.Cause(err, "initialize rule-set[", i, "]")
}
return nil
})
}
ruleSetStartGroup.Concurrency(5)
ruleSetStartGroup.FastFail()
err := ruleSetStartGroup.Run(r.ctx)
monitor.Finish()
if err != nil {
return err
}
}
if cacheContext != nil {
cacheContext.Close()
}
needFindProcess := r.needFindProcess
for _, ruleSet := range r.ruleSets {
metadata := ruleSet.Metadata()
if metadata.ContainsProcessRule {
needFindProcess = true
}
if metadata.ContainsWIFIRule {
2024-11-10 12:11:21 +08:00
r.needWIFIState = true
}
}
if needFindProcess {
if r.platformInterface != nil {
r.processSearcher = r.platformInterface
} else {
monitor.Start("initialize process searcher")
searcher, err := process.NewSearcher(process.Config{
Logger: r.logger,
2024-11-10 12:11:21 +08:00
PackageManager: r.networkManager.PackageManager(),
})
monitor.Finish()
if err != nil {
if err != os.ErrInvalid {
r.logger.Warn(E.Cause(err, "create process searcher"))
}
} else {
r.processSearcher = searcher
}
}
}
for i, rule := range r.rules {
monitor.Start("initialize rule[", i, "]")
err := rule.Start()
monitor.Finish()
if err != nil {
return E.Cause(err, "initialize rule[", i, "]")
}
}
for _, ruleSet := range r.ruleSets {
monitor.Start("post start rule_set[", ruleSet.Name(), "]")
err := ruleSet.PostStart()
monitor.Finish()
if err != nil {
return E.Cause(err, "post start rule_set[", ruleSet.Name(), "]")
}
}
r.started = true
return nil
case adapter.StartStateStarted:
for _, ruleSet := range r.ruleSetMap {
ruleSet.Cleanup()
}
runtime.GC()
2023-02-21 14:53:00 +08:00
}
2022-07-02 14:07:50 +08:00
return nil
}
2022-07-02 22:55:10 +08:00
func (r *Router) Close() error {
2024-04-02 23:07:26 +08:00
monitor := taskmonitor.New(r.logger, C.StopTimeout)
2023-04-08 08:09:28 +08:00
var err error
for i, rule := range r.rules {
monitor.Start("close rule[", i, "]")
2023-04-08 08:09:28 +08:00
err = E.Append(err, rule.Close(), func(err error) error {
return E.Cause(err, "close rule[", i, "]")
})
monitor.Finish()
2022-07-07 23:36:32 +08:00
}
2023-04-08 08:09:28 +08:00
for i, rule := range r.dnsRules {
monitor.Start("close dns rule[", i, "]")
2023-04-08 08:09:28 +08:00
err = E.Append(err, rule.Close(), func(err error) error {
return E.Cause(err, "close dns rule[", i, "]")
})
monitor.Finish()
2022-07-07 23:36:32 +08:00
}
2023-04-08 08:09:28 +08:00
for i, transport := range r.transports {
monitor.Start("close dns transport[", i, "]")
2023-04-08 08:09:28 +08:00
err = E.Append(err, transport.Close(), func(err error) error {
return E.Cause(err, "close dns transport[", i, "]")
})
monitor.Finish()
2023-04-08 08:09:28 +08:00
}
2023-09-07 12:54:45 +08:00
if r.geoIPReader != nil {
monitor.Start("close geoip reader")
2024-01-01 21:36:06 +08:00
err = E.Append(err, r.geoIPReader.Close(), func(err error) error {
2023-04-08 08:09:28 +08:00
return E.Cause(err, "close geoip reader")
})
monitor.Finish()
2023-04-08 08:09:28 +08:00
}
2023-03-25 12:03:23 +08:00
if r.fakeIPStore != nil {
monitor.Start("close fakeip store")
2023-03-25 12:03:23 +08:00
err = E.Append(err, r.fakeIPStore.Close(), func(err error) error {
return E.Cause(err, "close fakeip store")
})
monitor.Finish()
2023-03-25 12:03:23 +08:00
}
2023-04-08 08:09:28 +08:00
return err
2022-07-02 22:55:10 +08:00
}
2023-03-25 12:03:23 +08:00
func (r *Router) FakeIPStore() adapter.FakeIPStore {
return r.fakeIPStore
}
2023-12-01 13:24:12 +08:00
func (r *Router) RuleSet(tag string) (adapter.RuleSet, bool) {
ruleSet, loaded := r.ruleSetMap[tag]
return ruleSet, loaded
}
func (r *Router) NeedWIFIState() bool {
return r.needWIFIState
}
2022-07-19 22:16:49 +08:00
func (r *Router) Rules() []adapter.Rule {
return r.rules
}
func (r *Router) SetTracker(tracker adapter.ConnectionTracker) {
r.tracker = tracker
2022-07-14 23:06:03 +08:00
}
2022-11-06 10:36:19 +08:00
2024-11-10 12:11:21 +08:00
func (r *Router) ResetNetwork() {
r.networkManager.ResetNetwork()
for _, transport := range r.transports {
transport.Reset()
}
2024-02-22 21:20:23 +08:00
}