sing-box/route/router.go

996 lines
30 KiB
Go
Raw Normal View History

2022-06-30 21:27:56 +08:00
package route
import (
"context"
2023-08-07 17:46:51 +08:00
"errors"
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"
2024-11-06 12:51:53 +08:00
"syscall"
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"
2023-09-20 14:12:08 +08:00
"github.com/sagernet/sing-box/common/conntrack"
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-08-04 22:01:20 +08:00
"github.com/sagernet/sing-tun"
2022-07-08 23:03:57 +08:00
"github.com/sagernet/sing/common"
2022-07-14 23:06:03 +08:00
"github.com/sagernet/sing/common/control"
2022-07-08 23:03:57 +08:00
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"
2024-03-26 20:58:47 +08:00
"github.com/sagernet/sing/common/ntp"
2023-12-01 13:24:12 +08:00
"github.com/sagernet/sing/common/task"
2024-02-22 21:20:23 +08:00
"github.com/sagernet/sing/common/winpowrprof"
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 {
ctx context.Context
logger log.ContextLogger
dnsLogger log.ContextLogger
2022-08-29 19:43:13 +08:00
inboundByTag map[string]adapter.Inbound
outbounds []adapter.Outbound
outboundByTag map[string]adapter.Outbound
rules []adapter.Rule
defaultDetour string
defaultOutboundForConnection adapter.Outbound
defaultOutboundForPacketConnection adapter.Outbound
needGeoIPDatabase bool
needGeositeDatabase bool
geoIPOptions option.GeoIPOptions
geositeOptions option.GeositeOptions
geoIPReader *geoip.Reader
geositeReader *geosite.Reader
geositeCache map[string]adapter.Rule
2023-12-01 13:24:12 +08:00
needFindProcess bool
dnsClient *dns.Client
defaultDomainStrategy dns.DomainStrategy
2022-07-24 14:05:06 +08:00
dnsRules []adapter.DNSRule
2023-12-01 13:24:12 +08:00
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
2023-03-23 19:08:48 +08:00
dnsReverseMapping *DNSReverseMapping
2023-03-25 12:03:23 +08:00
fakeIPStore adapter.FakeIPStore
2024-04-12 09:24:49 +08:00
interfaceFinder *control.DefaultInterfaceFinder
autoDetectInterface bool
defaultInterface string
2024-06-24 09:49:15 +08:00
defaultMark uint32
2024-06-07 15:55:21 +08:00
autoRedirectOutputMark uint32
2022-08-04 22:01:20 +08:00
networkMonitor tun.NetworkUpdateMonitor
interfaceMonitor tun.DefaultInterfaceMonitor
packageManager tun.PackageManager
2024-02-22 21:20:23 +08:00
powerListener winpowrprof.EventListener
processSearcher process.Searcher
2023-08-31 14:00:47 +08:00
timeService *ntp.Service
2023-08-07 17:46:51 +08:00
pauseManager pause.Manager
2022-09-26 19:37:06 +08:00
clashServer adapter.ClashServer
v2rayServer adapter.V2RayServer
2022-10-25 12:55:00 +08:00
platformInterface platform.Interface
needWIFIState bool
needPackageManager bool
wifiState adapter.WIFIState
2023-12-02 17:47:57 +08:00
started bool
2022-06-30 21:27:56 +08:00
}
2023-02-21 14:53:00 +08:00
func NewRouter(
ctx context.Context,
logFactory log.Factory,
options option.RouteOptions,
dnsOptions option.DNSOptions,
ntpOptions option.NTPOptions,
inbounds []option.Inbound,
platformInterface platform.Interface,
) (*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"),
2022-07-07 21:47:21 +08:00
outboundByTag: make(map[string]adapter.Outbound),
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-07 21:47:21 +08:00
defaultDetour: options.Final,
2022-07-11 18:44:59 +08:00
defaultDomainStrategy: dns.DomainStrategy(dnsOptions.Strategy),
2024-04-12 09:24:49 +08:00
interfaceFinder: control.NewDefaultInterfaceFinder(),
autoDetectInterface: options.AutoDetectInterface,
2022-07-15 11:51:51 +08:00
defaultInterface: options.DefaultInterface,
2022-07-24 17:46:25 +08:00
defaultMark: options.DefaultMark,
2023-12-16 15:40:14 +08:00
pauseManager: service.FromContext[pause.Manager](ctx),
2022-10-25 12:55:00 +08:00
platformInterface: platformInterface,
needWIFIState: hasRule(options.Rules, isWIFIRule) || hasDNSRule(dnsOptions.Rules, isWIFIDNSRule),
needPackageManager: common.Any(inbounds, func(inbound option.Inbound) bool {
return len(inbound.TunOptions.IncludePackage) > 0 || len(inbound.TunOptions.ExcludePackage) > 0
}),
2022-06-30 21:27:56 +08:00
}
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,
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-10-21 23:38:34 +08:00
routeRule, err := R.NewRule(ctx, router, 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-10-21 23:38:34 +08:00
dnsRule, err := R.NewDNSRule(ctx, router, 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-10-21 23:38:34 +08:00
ruleSet, err := R.NewRuleSet(ctx, router, 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
}
2023-02-08 16:28:52 +08:00
ctx = adapter.ContextWithRouter(ctx, router)
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.NewRouter(router)
} else {
detour = dialer.NewDetour(router, 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 {
clientSubnet = server.ClientSubnet.Build()
} else if dnsOptions.ClientSubnet != nil {
clientSubnet = dnsOptions.ClientSubnet.Build()
}
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",
Dialer: common.Must1(dialer.NewDefault(router, 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
}
2023-04-18 14:04:09 +08:00
usePlatformDefaultInterfaceMonitor := platformInterface != nil && platformInterface.UsePlatformDefaultInterfaceMonitor()
needInterfaceMonitor := options.AutoDetectInterface || common.Any(inbounds, func(inbound option.Inbound) bool {
2022-10-08 16:48:30 +08:00
return inbound.HTTPOptions.SetSystemProxy || inbound.MixedOptions.SetSystemProxy || inbound.TunOptions.AutoRoute
})
2022-08-04 22:01:20 +08:00
2023-08-07 17:46:51 +08:00
if !usePlatformDefaultInterfaceMonitor {
networkMonitor, err := tun.NewNetworkUpdateMonitor(router.logger)
if !((err != nil && !needInterfaceMonitor) || errors.Is(err, os.ErrInvalid)) {
if err != nil {
return nil, err
}
router.networkMonitor = networkMonitor
networkMonitor.RegisterCallback(func() {
2024-04-12 09:24:49 +08:00
_ = router.interfaceFinder.Update()
2023-08-07 17:46:51 +08:00
})
interfaceMonitor, err := tun.NewDefaultInterfaceMonitor(router.networkMonitor, router.logger, tun.DefaultInterfaceMonitorOptions{
InterfaceFinder: router.interfaceFinder,
2023-08-07 17:46:51 +08:00
OverrideAndroidVPN: options.OverrideAndroidVPN,
UnderNetworkExtension: platformInterface != nil && platformInterface.UnderNetworkExtension(),
})
if err != nil {
return nil, E.New("auto_detect_interface unsupported on current platform")
2023-04-18 14:04:09 +08:00
}
interfaceMonitor.RegisterCallback(router.notifyNetworkUpdate)
router.interfaceMonitor = interfaceMonitor
}
2023-08-07 17:46:51 +08:00
} else {
interfaceMonitor := platformInterface.CreateDefaultInterfaceMonitor(router.logger)
interfaceMonitor.RegisterCallback(router.notifyNetworkUpdate)
router.interfaceMonitor = interfaceMonitor
}
2022-08-04 22:01:20 +08:00
2023-02-21 14:53:00 +08:00
if ntpOptions.Enabled {
2024-03-26 20:58:47 +08:00
ntpDialer, err := dialer.New(router, ntpOptions.DialerOptions)
2023-08-08 16:14:03 +08:00
if err != nil {
2024-03-26 20:58:47 +08:00
return nil, E.Cause(err, "create NTP service")
2023-08-08 16:14:03 +08:00
}
2024-03-26 20:58:47 +08:00
timeService := ntp.NewService(ntp.Options{
Context: ctx,
Dialer: ntpDialer,
Logger: logFactory.NewLogger("ntp"),
Server: ntpOptions.ServerOptions.Build(),
Interval: time.Duration(ntpOptions.Interval),
WriteToSystem: ntpOptions.WriteToSystem,
})
service.MustRegister[ntp.TimeService](ctx, timeService)
2023-08-08 16:14:03 +08:00
router.timeService = timeService
2023-02-21 14:53:00 +08:00
}
2022-07-02 22:55:10 +08:00
return router, nil
2022-06-30 21:27:56 +08:00
}
2022-08-29 19:43:13 +08:00
func (r *Router) Initialize(inbounds []adapter.Inbound, outbounds []adapter.Outbound, defaultOutbound func() adapter.Outbound) error {
inboundByTag := make(map[string]adapter.Inbound)
for _, inbound := range inbounds {
inboundByTag[inbound.Tag()] = inbound
}
2022-07-02 14:07:50 +08:00
outboundByTag := make(map[string]adapter.Outbound)
for _, detour := range outbounds {
outboundByTag[detour.Tag()] = detour
}
var defaultOutboundForConnection adapter.Outbound
var defaultOutboundForPacketConnection adapter.Outbound
if r.defaultDetour != "" {
detour, loaded := outboundByTag[r.defaultDetour]
if !loaded {
return E.New("default detour not found: ", r.defaultDetour)
}
2022-07-30 00:29:22 +08:00
if common.Contains(detour.Network(), N.NetworkTCP) {
defaultOutboundForConnection = detour
}
2022-07-30 00:29:22 +08:00
if common.Contains(detour.Network(), N.NetworkUDP) {
defaultOutboundForPacketConnection = detour
}
}
if defaultOutboundForConnection == nil {
2024-06-03 13:03:07 +08:00
for _, detour := range outbounds {
2022-07-30 00:29:22 +08:00
if common.Contains(detour.Network(), N.NetworkTCP) {
defaultOutboundForConnection = detour
break
}
}
}
if defaultOutboundForPacketConnection == nil {
2024-06-03 13:03:07 +08:00
for _, detour := range outbounds {
2022-07-30 00:29:22 +08:00
if common.Contains(detour.Network(), N.NetworkUDP) {
defaultOutboundForPacketConnection = detour
break
}
}
2022-07-02 14:07:50 +08:00
}
if defaultOutboundForConnection == nil || defaultOutboundForPacketConnection == nil {
detour := defaultOutbound()
if defaultOutboundForConnection == nil {
defaultOutboundForConnection = detour
}
if defaultOutboundForPacketConnection == nil {
defaultOutboundForPacketConnection = detour
}
2022-07-21 21:03:41 +08:00
outbounds = append(outbounds, detour)
outboundByTag[detour.Tag()] = detour
}
2022-08-29 19:43:13 +08:00
r.inboundByTag = inboundByTag
2022-07-21 21:03:41 +08:00
r.outbounds = outbounds
r.defaultOutboundForConnection = defaultOutboundForConnection
r.defaultOutboundForPacketConnection = defaultOutboundForPacketConnection
2022-07-02 14:07:50 +08:00
r.outboundByTag = outboundByTag
2022-07-07 21:47:21 +08:00
for i, rule := range r.rules {
2024-10-21 23:38:34 +08:00
routeAction, isRoute := rule.Action().(*R.RuleActionRoute)
if !isRoute {
continue
}
if _, loaded := outboundByTag[routeAction.Outbound]; !loaded {
return E.New("outbound not found for rule[", i, "]: ", routeAction.Outbound)
2022-07-07 21:47:21 +08:00
}
}
return nil
2022-07-02 14:07:50 +08:00
}
2022-07-21 21:03:41 +08:00
func (r *Router) Outbounds() []adapter.Outbound {
if !r.started {
return nil
}
2022-07-21 21:03:41 +08:00
return r.outbounds
}
func (r *Router) PreStart() error {
2024-04-02 23:07:26 +08:00
monitor := taskmonitor.New(r.logger, C.StartTimeout)
if r.interfaceMonitor != nil {
monitor.Start("initialize interface monitor")
err := r.interfaceMonitor.Start()
monitor.Finish()
2022-07-04 19:34:45 +08:00
if err != nil {
return err
}
2022-07-02 14:07:50 +08:00
}
if r.networkMonitor != nil {
monitor.Start("initialize network monitor")
err := r.networkMonitor.Start()
monitor.Finish()
2022-07-05 09:05:35 +08:00
if err != nil {
return err
}
}
if r.fakeIPStore != nil {
monitor.Start("initialize fakeip store")
err := r.fakeIPStore.Start()
monitor.Finish()
2022-07-05 09:05:35 +08:00
if err != nil {
return err
}
}
return nil
}
func (r *Router) Start() error {
2024-04-02 23:07:26 +08:00
monitor := taskmonitor.New(r.logger, C.StartTimeout)
if r.needGeoIPDatabase {
monitor.Start("initialize geoip database")
err := r.prepareGeoIPDatabase()
monitor.Finish()
if err != nil {
return err
}
}
if r.needGeositeDatabase {
monitor.Start("initialize geosite database")
err := r.prepareGeositeDatabase()
monitor.Finish()
2023-02-08 16:28:52 +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)
}
}
2022-07-07 23:36:32 +08:00
for _, rule := range r.dnsRules {
err := rule.UpdateGeosite()
if err != nil {
r.logger.Error("failed to initialize geosite: ", err)
}
}
2022-07-05 13:23:47 +08:00
err := common.Close(r.geositeReader)
if err != nil {
return err
}
2022-07-08 11:00:46 +08:00
r.geositeCache = nil
r.geositeReader = nil
2022-07-05 13:23:47 +08:00
}
2024-06-06 20:51:21 +08:00
if runtime.GOOS == "windows" {
powerListener, err := winpowrprof.NewEventListener(r.notifyWindowsPowerEvent)
if err == nil {
r.powerListener = powerListener
} else {
r.logger.Warn("initialize power listener: ", err)
}
}
2024-02-22 21:20:23 +08:00
if r.powerListener != nil {
monitor.Start("start power listener")
err := r.powerListener.Start()
monitor.Finish()
if err != nil {
return E.Cause(err, "start power listener")
}
}
monitor.Start("initialize DNS client")
r.dnsClient.Start()
monitor.Finish()
if C.IsAndroid && r.platformInterface == nil {
2024-06-09 07:21:50 +08:00
monitor.Start("initialize package manager")
2024-06-07 15:55:21 +08:00
packageManager, err := tun.NewPackageManager(tun.PackageManagerOptions{
Callback: r,
Logger: r.logger,
})
2024-06-09 07:21:50 +08:00
monitor.Finish()
if err != nil {
return E.Cause(err, "create package manager")
}
if r.needPackageManager {
monitor.Start("start package manager")
err = packageManager.Start()
monitor.Finish()
if err != nil {
return E.Cause(err, "start package manager")
}
2024-06-09 07:21:50 +08:00
}
r.packageManager = packageManager
}
2023-02-08 16:28:52 +08:00
for i, rule := range r.dnsRules {
monitor.Start("initialize DNS rule[", i, "]")
2023-02-08 16:28:52 +08:00
err := rule.Start()
monitor.Finish()
2022-07-14 23:06:03 +08:00
if err != nil {
2023-02-08 16:28:52 +08:00
return E.Cause(err, "initialize DNS rule[", i, "]")
2022-07-14 23:06:03 +08:00
}
}
2023-02-08 16:28:52 +08:00
for i, transport := range r.transports {
monitor.Start("initialize DNS transport[", i, "]")
2023-02-08 16:28:52 +08:00
err := transport.Start()
monitor.Finish()
if err != nil {
2023-02-08 16:28:52 +08:00
return E.Cause(err, "initialize DNS server[", i, "]")
}
}
2023-02-21 14:53:00 +08:00
if r.timeService != nil {
monitor.Start("initialize time service")
2023-02-21 14:53:00 +08:00
err := r.timeService.Start()
monitor.Finish()
2023-02-21 14:53:00 +08:00
if err != nil {
return E.Cause(err, "initialize time service")
}
}
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
}
if r.interfaceMonitor != nil {
monitor.Start("close interface monitor")
2023-04-08 08:09:28 +08:00
err = E.Append(err, r.interfaceMonitor.Close(), func(err error) error {
return E.Cause(err, "close interface monitor")
})
monitor.Finish()
2023-04-08 08:09:28 +08:00
}
if r.networkMonitor != nil {
monitor.Start("close network monitor")
2023-04-08 08:09:28 +08:00
err = E.Append(err, r.networkMonitor.Close(), func(err error) error {
return E.Cause(err, "close network monitor")
})
monitor.Finish()
2023-04-08 08:09:28 +08:00
}
if r.packageManager != nil {
monitor.Start("close package manager")
2023-04-08 08:09:28 +08:00
err = E.Append(err, r.packageManager.Close(), func(err error) error {
return E.Cause(err, "close package manager")
})
monitor.Finish()
2023-04-08 08:09:28 +08:00
}
2024-02-22 21:20:23 +08:00
if r.powerListener != nil {
monitor.Start("close power listener")
err = E.Append(err, r.powerListener.Close(), func(err error) error {
return E.Cause(err, "close power listener")
})
monitor.Finish()
}
2023-04-08 08:09:28 +08:00
if r.timeService != nil {
monitor.Start("close time service")
2023-04-08 08:09:28 +08:00
err = E.Append(err, r.timeService.Close(), func(err error) error {
return E.Cause(err, "close time service")
})
monitor.Finish()
2023-02-08 16:28:52 +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-12-02 17:47:57 +08:00
func (r *Router) PostStart() error {
2024-06-08 20:02:52 +08:00
monitor := taskmonitor.New(r.logger, C.StopTimeout)
2024-10-25 22:24:19 +08:00
var cacheContext *adapter.HTTPStartContext
2023-12-01 13:24:12 +08:00
if len(r.ruleSets) > 0 {
2024-06-08 20:02:52 +08:00
monitor.Start("initialize rule-set")
2024-10-25 22:24:19 +08:00
cacheContext = adapter.NewHTTPStartContext()
2024-06-08 20:02:52 +08:00
var ruleSetStartGroup task.Group
2023-12-01 13:24:12 +08:00
for i, ruleSet := range r.ruleSets {
2024-06-08 20:02:52 +08:00
ruleSetInPlace := ruleSet
ruleSetStartGroup.Append0(func(ctx context.Context) error {
2024-10-25 22:24:19 +08:00
err := ruleSetInPlace.StartContext(ctx, cacheContext)
2024-06-08 20:02:52 +08:00
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
}
2024-10-25 22:24:19 +08:00
}
if cacheContext != nil {
cacheContext.Close()
2024-06-08 20:02:52 +08:00
}
needFindProcess := r.needFindProcess
needWIFIState := r.needWIFIState
2024-06-08 20:02:52 +08:00
for _, ruleSet := range r.ruleSets {
metadata := ruleSet.Metadata()
if metadata.ContainsProcessRule {
needFindProcess = true
2024-06-08 20:02:52 +08:00
}
if metadata.ContainsWIFIRule {
needWIFIState = true
}
}
if C.IsAndroid && r.platformInterface == nil && !r.needPackageManager {
if needFindProcess {
monitor.Start("start package manager")
err := r.packageManager.Start()
monitor.Finish()
if err != nil {
return E.Cause(err, "start package manager")
}
} else {
r.packageManager = nil
2024-06-08 20:02:52 +08:00
}
}
if needFindProcess {
2024-06-08 20:02:52 +08:00
if r.platformInterface != nil {
r.processSearcher = r.platformInterface
} else {
monitor.Start("initialize process searcher")
searcher, err := process.NewSearcher(process.Config{
Logger: r.logger,
PackageManager: r.packageManager,
})
monitor.Finish()
if err != nil {
if err != os.ErrInvalid {
r.logger.Warn(E.Cause(err, "create process searcher"))
}
} else {
r.processSearcher = searcher
}
}
}
if needWIFIState && r.platformInterface != nil {
2024-06-08 20:02:52 +08:00
monitor.Start("initialize WIFI state")
r.needWIFIState = true
r.interfaceMonitor.RegisterCallback(func(_ int) {
r.updateWIFIState()
})
r.updateWIFIState()
monitor.Finish()
}
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, "]")
2023-12-01 13:24:12 +08:00
}
}
2024-06-07 15:55:21 +08:00
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(), "]")
}
}
2023-12-02 17:47:57 +08:00
r.started = true
return nil
}
2024-06-07 15:55:21 +08:00
func (r *Router) Cleanup() error {
for _, ruleSet := range r.ruleSetMap {
ruleSet.Cleanup()
}
runtime.GC()
return nil
}
2022-07-05 09:05:35 +08:00
func (r *Router) Outbound(tag string) (adapter.Outbound, bool) {
outbound, loaded := r.outboundByTag[tag]
return outbound, loaded
}
2023-12-01 13:24:12 +08:00
func (r *Router) DefaultOutbound(network string) (adapter.Outbound, error) {
2022-07-30 00:29:22 +08:00
if network == N.NetworkTCP {
2023-12-01 13:24:12 +08:00
if r.defaultOutboundForConnection == nil {
return nil, E.New("missing default outbound for TCP connections")
}
return r.defaultOutboundForConnection, nil
2022-07-06 23:11:48 +08:00
} else {
2023-12-01 13:24:12 +08:00
if r.defaultOutboundForPacketConnection == nil {
return nil, E.New("missing default outbound for UDP connections")
}
return r.defaultOutboundForPacketConnection, nil
2022-07-06 23:11:48 +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-09-14 12:46:02 +08:00
func (r *Router) InterfaceFinder() control.InterfaceFinder {
2024-04-12 09:24:49 +08:00
return r.interfaceFinder
2022-07-14 23:06:03 +08:00
}
2023-04-18 14:04:09 +08:00
func (r *Router) UpdateInterfaces() error {
if r.platformInterface == nil || !r.platformInterface.UsePlatformInterfaceGetter() {
2024-04-12 09:24:49 +08:00
return r.interfaceFinder.Update()
2023-04-18 14:04:09 +08:00
} else {
interfaces, err := r.platformInterface.Interfaces()
if err != nil {
return err
}
2024-04-12 09:24:49 +08:00
r.interfaceFinder.UpdateInterfaces(interfaces)
2023-04-18 14:04:09 +08:00
return nil
}
}
func (r *Router) AutoDetectInterface() bool {
return r.autoDetectInterface
}
2022-10-25 12:55:00 +08:00
func (r *Router) AutoDetectInterfaceFunc() control.Func {
if r.platformInterface != nil && r.platformInterface.UsePlatformAutoDetectInterfaceControl() {
2024-11-06 12:51:53 +08:00
return func(network, address string, conn syscall.RawConn) error {
return control.Raw(conn, func(fd uintptr) error {
return r.platformInterface.AutoDetectInterfaceControl(int(fd))
})
}
2022-10-25 12:55:00 +08:00
} else {
2024-06-03 12:54:54 +08:00
if r.interfaceMonitor == nil {
return nil
}
2023-09-20 14:12:08 +08:00
return control.BindToInterfaceFunc(r.InterfaceFinder(), func(network string, address string) (interfaceName string, interfaceIndex int, err error) {
2022-10-25 12:55:00 +08:00
remoteAddr := M.ParseSocksaddr(address).Addr
if C.IsLinux {
2023-10-21 12:00:00 +08:00
interfaceName, interfaceIndex = r.InterfaceMonitor().DefaultInterface(remoteAddr)
if interfaceIndex == -1 {
2023-09-20 14:12:08 +08:00
err = tun.ErrNoRoute
}
2022-10-25 12:55:00 +08:00
} else {
2023-09-20 14:12:08 +08:00
interfaceIndex = r.InterfaceMonitor().DefaultInterfaceIndex(remoteAddr)
if interfaceIndex == -1 {
err = tun.ErrNoRoute
}
2022-10-25 12:55:00 +08:00
}
2023-09-20 14:12:08 +08:00
return
2022-10-25 12:55:00 +08:00
})
}
}
2024-06-07 15:55:21 +08:00
func (r *Router) RegisterAutoRedirectOutputMark(mark uint32) error {
if r.autoRedirectOutputMark > 0 {
return E.New("only one auto-redirect can be configured")
}
r.autoRedirectOutputMark = mark
return nil
}
func (r *Router) AutoRedirectOutputMark() uint32 {
return r.autoRedirectOutputMark
}
2022-07-15 11:51:51 +08:00
func (r *Router) DefaultInterface() string {
return r.defaultInterface
}
2024-06-24 09:49:15 +08:00
func (r *Router) DefaultMark() uint32 {
2022-07-24 17:46:25 +08:00
return r.defaultMark
}
2022-07-19 22:16:49 +08:00
func (r *Router) Rules() []adapter.Rule {
return r.rules
}
func (r *Router) WIFIState() adapter.WIFIState {
return r.wifiState
}
2022-08-04 22:01:20 +08:00
func (r *Router) NetworkMonitor() tun.NetworkUpdateMonitor {
return r.networkMonitor
}
func (r *Router) InterfaceMonitor() tun.DefaultInterfaceMonitor {
return r.interfaceMonitor
}
func (r *Router) PackageManager() tun.PackageManager {
return r.packageManager
}
2022-09-10 14:09:47 +08:00
func (r *Router) ClashServer() adapter.ClashServer {
return r.clashServer
}
2022-09-26 19:37:06 +08:00
func (r *Router) SetClashServer(server adapter.ClashServer) {
r.clashServer = server
}
func (r *Router) V2RayServer() adapter.V2RayServer {
return r.v2rayServer
}
func (r *Router) SetV2RayServer(server adapter.V2RayServer) {
r.v2rayServer = server
2022-07-19 22:16:49 +08:00
}
func (r *Router) OnPackagesUpdated(packages int, sharedUsers int) {
r.logger.Info("updated packages list: ", packages, " packages, ", sharedUsers, " shared users")
}
2022-07-14 23:06:03 +08:00
func (r *Router) NewError(ctx context.Context, err error) {
2022-07-30 00:29:22 +08:00
common.Close(err)
if E.IsClosedOrCanceled(err) {
2022-08-16 23:37:51 +08:00
r.logger.DebugContext(ctx, "connection closed: ", err)
2022-07-30 00:29:22 +08:00
return
}
2022-07-14 23:06:03 +08:00
r.logger.ErrorContext(ctx, err)
}
2022-11-06 10:36:19 +08:00
2023-07-23 14:42:19 +08:00
func (r *Router) notifyNetworkUpdate(event int) {
if event == tun.EventNoRoute {
2023-08-07 17:46:51 +08:00
r.pauseManager.NetworkPause()
r.logger.Error("missing default interface")
2023-07-23 14:42:19 +08:00
} else {
2023-08-07 17:46:51 +08:00
r.pauseManager.NetworkWake()
2023-07-23 14:42:19 +08:00
if C.IsAndroid && r.platformInterface == nil {
var vpnStatus string
if r.interfaceMonitor.AndroidVPNEnabled() {
vpnStatus = "enabled"
} else {
vpnStatus = "disabled"
}
r.logger.Info("updated default interface ", r.interfaceMonitor.DefaultInterfaceName(netip.IPv4Unspecified()), ", index ", r.interfaceMonitor.DefaultInterfaceIndex(netip.IPv4Unspecified()), ", vpn ", vpnStatus)
2022-11-06 10:36:19 +08:00
} else {
2023-07-23 14:42:19 +08:00
r.logger.Info("updated default interface ", r.interfaceMonitor.DefaultInterfaceName(netip.IPv4Unspecified()), ", index ", r.interfaceMonitor.DefaultInterfaceIndex(netip.IPv4Unspecified()))
2022-11-06 10:36:19 +08:00
}
}
2023-12-02 17:47:57 +08:00
if !r.started {
return
}
_ = r.ResetNetwork()
}
func (r *Router) ResetNetwork() error {
conntrack.Close()
2023-04-18 14:04:09 +08:00
2022-11-06 10:36:19 +08:00
for _, outbound := range r.outbounds {
listener, isListener := outbound.(adapter.InterfaceUpdateListener)
if isListener {
2023-07-23 14:42:19 +08:00
listener.InterfaceUpdated()
2022-11-06 10:36:19 +08:00
}
}
for _, transport := range r.transports {
transport.Reset()
}
2022-11-06 10:36:19 +08:00
return nil
}
func (r *Router) updateWIFIState() {
if r.platformInterface == nil {
return
}
state := r.platformInterface.ReadWIFIState()
if state != r.wifiState {
r.wifiState = state
2024-02-26 13:24:19 +08:00
if state.SSID == "" && state.BSSID == "" {
r.logger.Info("updated WIFI state: disconnected")
} else {
r.logger.Info("updated WIFI state: SSID=", state.SSID, ", BSSID=", state.BSSID)
}
}
}
2024-02-22 21:20:23 +08:00
func (r *Router) notifyWindowsPowerEvent(event int) {
switch event {
case winpowrprof.EVENT_SUSPEND:
r.pauseManager.DevicePause()
_ = r.ResetNetwork()
case winpowrprof.EVENT_RESUME:
if !r.pauseManager.IsDevicePaused() {
return
}
fallthrough
case winpowrprof.EVENT_RESUME_AUTOMATIC:
r.pauseManager.DeviceWake()
_ = r.ResetNetwork()
}
}