sing-box/route/router.go

1263 lines
40 KiB
Go
Raw Normal View History

2022-06-30 13:27:56 +00:00
package route
import (
"context"
2023-08-07 09:46:51 +00:00
"errors"
2022-06-30 13:27:56 +00:00
"net"
2022-07-07 13:47:21 +00:00
"net/netip"
"net/url"
2022-07-02 14:55:10 +00:00
"os"
"os/user"
2024-02-22 13:20:23 +00:00
"runtime"
2022-07-07 13:47:21 +00:00
"strings"
2022-07-02 14:55:10 +00:00
"time"
2022-06-30 13:27:56 +00:00
2022-07-06 07:01:09 +00:00
"github.com/sagernet/sing-box/adapter"
2023-09-20 06:12:08 +00:00
"github.com/sagernet/sing-box/common/conntrack"
2022-07-07 13:47:21 +00:00
"github.com/sagernet/sing-box/common/dialer"
2022-07-06 07:01:09 +00:00
"github.com/sagernet/sing-box/common/geoip"
"github.com/sagernet/sing-box/common/geosite"
"github.com/sagernet/sing-box/common/process"
2022-07-06 07:01:09 +00:00
"github.com/sagernet/sing-box/common/sniff"
"github.com/sagernet/sing-box/common/taskmonitor"
2022-07-06 07:01:09 +00:00
C "github.com/sagernet/sing-box/constant"
2022-10-25 04:55:00 +00:00
"github.com/sagernet/sing-box/experimental/libbox/platform"
2022-07-06 07:01:09 +00:00
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
2023-04-08 00:58:01 +00:00
"github.com/sagernet/sing-box/outbound"
2023-03-25 04:03:23 +00:00
"github.com/sagernet/sing-box/transport/fakeip"
2022-07-11 10:44:59 +00:00
"github.com/sagernet/sing-dns"
"github.com/sagernet/sing-mux"
2022-08-04 14:01:20 +00:00
"github.com/sagernet/sing-tun"
"github.com/sagernet/sing-vmess"
2022-07-08 15:03:57 +00:00
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/bufio"
2023-04-17 10:22:05 +00:00
"github.com/sagernet/sing/common/bufio/deadline"
2022-07-14 15:06:03 +00:00
"github.com/sagernet/sing/common/control"
2022-07-08 15:03:57 +00: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 12:58:47 +00:00
"github.com/sagernet/sing/common/ntp"
2023-12-01 05:24:12 +00:00
"github.com/sagernet/sing/common/task"
2022-08-11 02:36:28 +00:00
"github.com/sagernet/sing/common/uot"
2024-02-22 13:20:23 +00:00
"github.com/sagernet/sing/common/winpowrprof"
2023-08-08 08:14:03 +00:00
"github.com/sagernet/sing/service"
2023-08-07 09:46:51 +00:00
"github.com/sagernet/sing/service/pause"
2022-06-30 13:27:56 +00:00
)
var _ adapter.Router = (*Router)(nil)
type Router struct {
ctx context.Context
logger log.ContextLogger
dnsLogger log.ContextLogger
2022-08-29 11:43:13 +00: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 05:24:12 +00:00
needFindProcess bool
dnsClient *dns.Client
defaultDomainStrategy dns.DomainStrategy
2022-07-24 06:05:06 +00:00
dnsRules []adapter.DNSRule
2023-12-01 05:24:12 +00: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 11:08:48 +00:00
dnsReverseMapping *DNSReverseMapping
2023-03-25 04:03:23 +00:00
fakeIPStore adapter.FakeIPStore
2024-04-12 01:24:49 +00:00
interfaceFinder *control.DefaultInterfaceFinder
autoDetectInterface bool
defaultInterface string
2022-07-24 09:46:25 +00:00
defaultMark int
2022-08-04 14:01:20 +00:00
networkMonitor tun.NetworkUpdateMonitor
interfaceMonitor tun.DefaultInterfaceMonitor
packageManager tun.PackageManager
2024-02-22 13:20:23 +00:00
powerListener winpowrprof.EventListener
processSearcher process.Searcher
2023-08-31 06:00:47 +00:00
timeService *ntp.Service
2023-08-07 09:46:51 +00:00
pauseManager pause.Manager
2022-09-26 11:37:06 +00:00
clashServer adapter.ClashServer
v2rayServer adapter.V2RayServer
2022-10-25 04:55:00 +00:00
platformInterface platform.Interface
needWIFIState bool
needPackageManager bool
wifiState adapter.WIFIState
2023-12-02 09:47:57 +00:00
started bool
2022-06-30 13:27:56 +00:00
}
2023-02-21 06:53:00 +00: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 14:55:10 +00:00
router := &Router{
2022-07-07 13:47:21 +00:00
ctx: ctx,
2022-11-28 05:10:56 +00:00
logger: logFactory.NewLogger("router"),
dnsLogger: logFactory.NewLogger("dns"),
2022-07-07 13:47:21 +00:00
outboundByTag: make(map[string]adapter.Outbound),
rules: make([]adapter.Rule, 0, len(options.Rules)),
2022-07-24 06:05:06 +00:00
dnsRules: make([]adapter.DNSRule, 0, len(dnsOptions.Rules)),
2023-12-01 05:24:12 +00: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 13:47:21 +00:00
geoIPOptions: common.PtrValueOrDefault(options.GeoIP),
2022-07-07 15:36:32 +00:00
geositeOptions: common.PtrValueOrDefault(options.Geosite),
2022-07-08 03:00:46 +00:00
geositeCache: make(map[string]adapter.Rule),
2023-12-01 05:24:12 +00:00
needFindProcess: hasRule(options.Rules, isProcessRule) || hasDNSRule(dnsOptions.Rules, isProcessDNSRule) || options.FindProcess,
2022-07-07 13:47:21 +00:00
defaultDetour: options.Final,
2022-07-11 10:44:59 +00:00
defaultDomainStrategy: dns.DomainStrategy(dnsOptions.Strategy),
2024-04-12 01:24:49 +00:00
interfaceFinder: control.NewDefaultInterfaceFinder(),
autoDetectInterface: options.AutoDetectInterface,
2022-07-15 03:51:51 +00:00
defaultInterface: options.DefaultInterface,
2022-07-24 09:46:25 +00:00
defaultMark: options.DefaultMark,
2023-12-16 07:40:14 +00:00
pauseManager: service.FromContext[pause.Manager](ctx),
2022-10-25 04:55:00 +00:00
platformInterface: platformInterface,
needWIFIState: hasRule(options.Rules, isWIFIRule) || hasDNSRule(dnsOptions.Rules, isWIFIDNSRule),
needPackageManager: C.IsAndroid && platformInterface == nil && common.Any(inbounds, func(inbound option.Inbound) bool {
return len(inbound.TunOptions.IncludePackage) > 0 || len(inbound.TunOptions.ExcludePackage) > 0
}),
2022-06-30 13:27:56 +00:00
}
2023-04-25 20:53:25 +00: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-25 20:53:25 +00:00
})
2022-07-02 14:55:10 +00:00
for i, ruleOptions := range options.Rules {
2023-11-28 15:47:32 +00:00
routeRule, err := NewRule(router, router.logger, ruleOptions, true)
2022-07-02 14:55:10 +00:00
if err != nil {
return nil, E.Cause(err, "parse rule[", i, "]")
2022-07-02 06:07:50 +00:00
}
2022-07-07 13:47:21 +00:00
router.rules = append(router.rules, routeRule)
}
for i, dnsRuleOptions := range dnsOptions.Rules {
2023-11-28 15:47:32 +00:00
dnsRule, err := NewDNSRule(router, router.logger, dnsRuleOptions, true)
2022-07-07 13:47:21 +00:00
if err != nil {
return nil, E.Cause(err, "parse dns rule[", i, "]")
}
2022-07-07 15:36:32 +00:00
router.dnsRules = append(router.dnsRules, dnsRule)
2022-07-07 13:47:21 +00:00
}
2023-12-01 05:24:12 +00:00
for i, ruleSetOptions := range options.RuleSet {
if _, exists := router.ruleSetMap[ruleSetOptions.Tag]; exists {
return nil, E.New("duplicate rule-set tag: ", ruleSetOptions.Tag)
}
ruleSet, err := NewRuleSet(ctx, router, router.logger, ruleSetOptions)
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 12:28:21 +00:00
2022-07-11 10:44:59 +00:00
transports := make([]dns.Transport, len(dnsOptions.Servers))
dummyTransportMap := make(map[string]dns.Transport)
transportMap := make(map[string]dns.Transport)
2022-07-07 13:47:21 +00:00
transportTags := make([]string, len(dnsOptions.Servers))
transportTagMap := make(map[string]bool)
transportDomainStrategy := make(map[dns.Transport]dns.DomainStrategy)
2022-07-07 13:47:21 +00:00
for i, server := range dnsOptions.Servers {
var tag string
if server.Tag != "" {
tag = server.Tag
} else {
tag = F.ToString(i)
}
2023-03-18 11:15:28 +00:00
if transportTagMap[tag] {
return nil, E.New("duplicate dns server tag: ", tag)
}
2022-07-07 13:47:21 +00:00
transportTags[i] = tag
transportTagMap[tag] = true
}
2023-02-08 08:28:52 +00:00
ctx = adapter.ContextWithRouter(ctx, router)
2022-07-07 13:47:21 +00: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)
}
2022-07-24 05:44:44 +00:00
switch server.Address {
2023-02-08 08:28:52 +00:00
case "local":
2022-07-24 05:44:44 +00:00
default:
serverURL, _ := url.Parse(server.Address)
var serverAddress string
if serverURL != nil {
serverAddress = serverURL.Hostname()
2022-07-07 13:47:21 +00:00
}
2022-07-10 01:15:01 +00:00
if serverAddress == "" {
serverAddress = server.Address
}
notIpAddress := !M.ParseSocksaddr(serverAddress).Addr.IsValid()
2022-07-10 01:15:01 +00: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 10:44:59 +00:00
detour = dns.NewDialerWrapper(detour, router.dnsClient, upstream, dns.DomainStrategy(server.AddressStrategy), time.Duration(server.AddressFallbackDelay))
2022-07-10 01:15:01 +00:00
} else {
continue
}
} else if notIpAddress && strings.Contains(server.Address, ".") {
2023-03-25 04:03:23 +00:00
return nil, E.New("parse dns server[", tag, "]: missing address_resolver")
2022-07-07 13:47:21 +00:00
}
}
var clientSubnet netip.Prefix
if server.ClientSubnet != nil {
clientSubnet = server.ClientSubnet.Build()
} else if dnsOptions.ClientSubnet != nil {
clientSubnet = dnsOptions.ClientSubnet.Build()
}
transport, err := dns.CreateTransport(dns.TransportOptions{
Context: ctx,
Logger: logFactory.NewLogger(F.ToString("dns/transport[", tag, "]")),
Name: tag,
Dialer: detour,
Address: server.Address,
ClientSubnet: clientSubnet,
})
2022-07-07 13:47:21 +00: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 13:47:21 +00: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 11:15:28 +00:00
if len(unresolvedTags) == 0 {
panic(F.ToString("unexpected unresolved dns servers: ", len(transports), " ", len(dummyTransportMap), " ", len(transportMap)))
}
2022-07-07 13:47:21 +00:00
return nil, E.New("found circular reference in dns servers: ", strings.Join(unresolvedTags, " "))
}
2022-07-11 10:44:59 +00:00
var defaultTransport dns.Transport
2022-07-13 11:01:20 +00:00
if dnsOptions.Final != "" {
2022-08-10 04:18:03 +00:00
defaultTransport = dummyTransportMap[dnsOptions.Final]
2022-07-07 13:47:21 +00:00
if defaultTransport == nil {
2022-08-10 04:18:03 +00:00
return nil, E.New("default dns server not found: ", dnsOptions.Final)
2022-07-07 13:47:21 +00: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 13:47:21 +00:00
}
defaultTransport = transports[0]
2022-07-02 06:07:50 +00:00
}
2023-12-01 13:48:21 +00:00
if _, isFakeIP := defaultTransport.(adapter.FakeIPTransport); isFakeIP {
return nil, E.New("default DNS server cannot be fakeip")
}
2022-07-07 13:47:21 +00:00
router.defaultTransport = defaultTransport
router.transports = transports
router.transportMap = transportMap
router.transportDomainStrategy = transportDomainStrategy
2023-03-23 11:08:48 +00:00
if dnsOptions.ReverseMapping {
router.dnsReverseMapping = NewDNSReverseMapping()
}
2023-03-25 04:03:23 +00: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 04:00:00 +00:00
inet4Range = *fakeIPOptions.Inet4Range
2023-03-25 04:03:23 +00:00
}
if fakeIPOptions.Inet6Range != nil {
2023-10-21 04:00:00 +00:00
inet6Range = *fakeIPOptions.Inet6Range
2023-03-25 04:03:23 +00:00
}
2023-11-28 04:00:28 +00:00
router.fakeIPStore = fakeip.NewStore(ctx, router.logger, inet4Range, inet6Range)
2023-03-25 04:03:23 +00:00
}
2023-04-18 06:04:09 +00:00
usePlatformDefaultInterfaceMonitor := platformInterface != nil && platformInterface.UsePlatformDefaultInterfaceMonitor()
needInterfaceMonitor := options.AutoDetectInterface || common.Any(inbounds, func(inbound option.Inbound) bool {
2022-10-08 08:48:30 +00:00
return inbound.HTTPOptions.SetSystemProxy || inbound.MixedOptions.SetSystemProxy || inbound.TunOptions.AutoRoute
})
2022-08-04 14:01:20 +00:00
2023-08-07 09:46:51 +00: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 01:24:49 +00:00
_ = router.interfaceFinder.Update()
2023-08-07 09:46:51 +00:00
})
interfaceMonitor, err := tun.NewDefaultInterfaceMonitor(router.networkMonitor, router.logger, tun.DefaultInterfaceMonitorOptions{
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 06:04:09 +00:00
}
interfaceMonitor.RegisterCallback(router.notifyNetworkUpdate)
router.interfaceMonitor = interfaceMonitor
}
2023-08-07 09:46:51 +00:00
} else {
interfaceMonitor := platformInterface.CreateDefaultInterfaceMonitor(router.logger)
interfaceMonitor.RegisterCallback(router.notifyNetworkUpdate)
router.interfaceMonitor = interfaceMonitor
}
2022-08-04 14:01:20 +00:00
2023-02-21 06:53:00 +00:00
if ntpOptions.Enabled {
2024-03-26 12:58:47 +00:00
ntpDialer, err := dialer.New(router, ntpOptions.DialerOptions)
2023-08-08 08:14:03 +00:00
if err != nil {
2024-03-26 12:58:47 +00:00
return nil, E.Cause(err, "create NTP service")
2023-08-08 08:14:03 +00:00
}
2024-03-26 12:58:47 +00: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 08:14:03 +00:00
router.timeService = timeService
2023-02-21 06:53:00 +00:00
}
2022-07-02 14:55:10 +00:00
return router, nil
2022-06-30 13:27:56 +00:00
}
2022-08-29 11:43:13 +00: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 06:07:50 +00: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-29 16:29:22 +00:00
if common.Contains(detour.Network(), N.NetworkTCP) {
defaultOutboundForConnection = detour
}
2022-07-29 16:29:22 +00:00
if common.Contains(detour.Network(), N.NetworkUDP) {
defaultOutboundForPacketConnection = detour
}
}
if defaultOutboundForConnection == nil {
2024-06-03 05:03:07 +00:00
for _, detour := range outbounds {
2022-07-29 16:29:22 +00:00
if common.Contains(detour.Network(), N.NetworkTCP) {
defaultOutboundForConnection = detour
break
}
}
}
if defaultOutboundForPacketConnection == nil {
2024-06-03 05:03:07 +00:00
for _, detour := range outbounds {
2022-07-29 16:29:22 +00:00
if common.Contains(detour.Network(), N.NetworkUDP) {
defaultOutboundForPacketConnection = detour
break
}
}
2022-07-02 06:07:50 +00:00
}
if defaultOutboundForConnection == nil || defaultOutboundForPacketConnection == nil {
detour := defaultOutbound()
if defaultOutboundForConnection == nil {
defaultOutboundForConnection = detour
}
if defaultOutboundForPacketConnection == nil {
defaultOutboundForPacketConnection = detour
}
2022-07-21 13:03:41 +00:00
outbounds = append(outbounds, detour)
outboundByTag[detour.Tag()] = detour
}
2022-08-29 11:43:13 +00:00
r.inboundByTag = inboundByTag
2022-07-21 13:03:41 +00:00
r.outbounds = outbounds
r.defaultOutboundForConnection = defaultOutboundForConnection
r.defaultOutboundForPacketConnection = defaultOutboundForPacketConnection
2022-07-02 06:07:50 +00:00
r.outboundByTag = outboundByTag
2022-07-07 13:47:21 +00:00
for i, rule := range r.rules {
if _, loaded := outboundByTag[rule.Outbound()]; !loaded {
return E.New("outbound not found for rule[", i, "]: ", rule.Outbound())
}
}
return nil
2022-07-02 06:07:50 +00:00
}
2022-07-21 13:03:41 +00:00
func (r *Router) Outbounds() []adapter.Outbound {
if !r.started {
return nil
}
2022-07-21 13:03:41 +00:00
return r.outbounds
}
func (r *Router) PreStart() error {
2024-04-02 15:07:26 +00: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 11:34:45 +00:00
if err != nil {
return err
}
2022-07-02 06:07:50 +00:00
}
if r.networkMonitor != nil {
monitor.Start("initialize network monitor")
err := r.networkMonitor.Start()
monitor.Finish()
2022-07-05 01:05:35 +00:00
if err != nil {
return err
}
}
if r.fakeIPStore != nil {
monitor.Start("initialize fakeip store")
err := r.fakeIPStore.Start()
monitor.Finish()
2022-07-05 01:05:35 +00:00
if err != nil {
return err
}
}
return nil
}
func (r *Router) Start() error {
2024-04-02 15:07:26 +00: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 08:28:52 +00:00
if err != nil {
return err
}
}
2022-07-05 05:23:47 +00: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 15:36:32 +00:00
for _, rule := range r.dnsRules {
err := rule.UpdateGeosite()
if err != nil {
r.logger.Error("failed to initialize geosite: ", err)
}
}
2022-07-05 05:23:47 +00:00
err := common.Close(r.geositeReader)
if err != nil {
return err
}
2022-07-08 03:00:46 +00:00
r.geositeCache = nil
r.geositeReader = nil
2022-07-05 05:23:47 +00:00
}
2024-06-06 12:51:21 +00: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 13:20:23 +00: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()
2024-06-09 16:03:01 +00:00
if r.needPackageManager && r.platformInterface == nil {
2024-06-08 23:21:50 +00:00
monitor.Start("initialize package manager")
packageManager, err := tun.NewPackageManager(r)
monitor.Finish()
if err != nil {
return E.Cause(err, "create package manager")
}
monitor.Start("start package manager")
err = packageManager.Start()
monitor.Finish()
if err != nil {
return E.Cause(err, "start package manager")
}
r.packageManager = packageManager
}
2023-02-08 08:28:52 +00:00
for i, rule := range r.dnsRules {
monitor.Start("initialize DNS rule[", i, "]")
2023-02-08 08:28:52 +00:00
err := rule.Start()
monitor.Finish()
2022-07-14 15:06:03 +00:00
if err != nil {
2023-02-08 08:28:52 +00:00
return E.Cause(err, "initialize DNS rule[", i, "]")
2022-07-14 15:06:03 +00:00
}
}
2023-02-08 08:28:52 +00:00
for i, transport := range r.transports {
monitor.Start("initialize DNS transport[", i, "]")
2023-02-08 08:28:52 +00:00
err := transport.Start()
monitor.Finish()
if err != nil {
2023-02-08 08:28:52 +00:00
return E.Cause(err, "initialize DNS server[", i, "]")
}
}
2023-02-21 06:53:00 +00:00
if r.timeService != nil {
monitor.Start("initialize time service")
2023-02-21 06:53:00 +00:00
err := r.timeService.Start()
monitor.Finish()
2023-02-21 06:53:00 +00:00
if err != nil {
return E.Cause(err, "initialize time service")
}
}
2022-07-02 06:07:50 +00:00
return nil
}
2022-07-02 14:55:10 +00:00
func (r *Router) Close() error {
2024-04-02 15:07:26 +00:00
monitor := taskmonitor.New(r.logger, C.StopTimeout)
2023-04-08 00:09:28 +00:00
var err error
for i, rule := range r.rules {
monitor.Start("close rule[", i, "]")
2023-04-08 00:09:28 +00:00
err = E.Append(err, rule.Close(), func(err error) error {
return E.Cause(err, "close rule[", i, "]")
})
monitor.Finish()
2022-07-07 15:36:32 +00:00
}
2023-04-08 00:09:28 +00:00
for i, rule := range r.dnsRules {
monitor.Start("close dns rule[", i, "]")
2023-04-08 00:09:28 +00:00
err = E.Append(err, rule.Close(), func(err error) error {
return E.Cause(err, "close dns rule[", i, "]")
})
monitor.Finish()
2022-07-07 15:36:32 +00:00
}
2023-04-08 00:09:28 +00:00
for i, transport := range r.transports {
monitor.Start("close dns transport[", i, "]")
2023-04-08 00:09:28 +00:00
err = E.Append(err, transport.Close(), func(err error) error {
return E.Cause(err, "close dns transport[", i, "]")
})
monitor.Finish()
2023-04-08 00:09:28 +00:00
}
2023-09-07 04:54:45 +00:00
if r.geoIPReader != nil {
monitor.Start("close geoip reader")
2024-01-01 13:36:06 +00:00
err = E.Append(err, r.geoIPReader.Close(), func(err error) error {
2023-04-08 00:09:28 +00:00
return E.Cause(err, "close geoip reader")
})
monitor.Finish()
2023-04-08 00:09:28 +00:00
}
if r.interfaceMonitor != nil {
monitor.Start("close interface monitor")
2023-04-08 00:09:28 +00:00
err = E.Append(err, r.interfaceMonitor.Close(), func(err error) error {
return E.Cause(err, "close interface monitor")
})
monitor.Finish()
2023-04-08 00:09:28 +00:00
}
if r.networkMonitor != nil {
monitor.Start("close network monitor")
2023-04-08 00:09:28 +00:00
err = E.Append(err, r.networkMonitor.Close(), func(err error) error {
return E.Cause(err, "close network monitor")
})
monitor.Finish()
2023-04-08 00:09:28 +00:00
}
if r.packageManager != nil {
monitor.Start("close package manager")
2023-04-08 00:09:28 +00:00
err = E.Append(err, r.packageManager.Close(), func(err error) error {
return E.Cause(err, "close package manager")
})
monitor.Finish()
2023-04-08 00:09:28 +00:00
}
2024-02-22 13:20:23 +00: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 00:09:28 +00:00
if r.timeService != nil {
monitor.Start("close time service")
2023-04-08 00:09:28 +00:00
err = E.Append(err, r.timeService.Close(), func(err error) error {
return E.Cause(err, "close time service")
})
monitor.Finish()
2023-02-08 08:28:52 +00:00
}
2023-03-25 04:03:23 +00:00
if r.fakeIPStore != nil {
monitor.Start("close fakeip store")
2023-03-25 04:03:23 +00:00
err = E.Append(err, r.fakeIPStore.Close(), func(err error) error {
return E.Cause(err, "close fakeip store")
})
monitor.Finish()
2023-03-25 04:03:23 +00:00
}
2023-04-08 00:09:28 +00:00
return err
2022-07-02 14:55:10 +00:00
}
2023-12-02 09:47:57 +00:00
func (r *Router) PostStart() error {
2024-06-08 12:02:52 +00:00
monitor := taskmonitor.New(r.logger, C.StopTimeout)
2023-12-01 05:24:12 +00:00
if len(r.ruleSets) > 0 {
2024-06-08 12:02:52 +00:00
monitor.Start("initialize rule-set")
ruleSetStartContext := NewRuleSetStartContext()
var ruleSetStartGroup task.Group
2023-12-01 05:24:12 +00:00
for i, ruleSet := range r.ruleSets {
2024-06-08 12:02:52 +00:00
ruleSetInPlace := ruleSet
ruleSetStartGroup.Append0(func(ctx context.Context) error {
err := ruleSetInPlace.StartContext(ctx, ruleSetStartContext)
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
}
ruleSetStartContext.Close()
}
var (
needProcessFromRuleSet bool
needWIFIStateFromRuleSet bool
)
for _, ruleSet := range r.ruleSets {
metadata := ruleSet.Metadata()
if metadata.ContainsProcessRule {
needProcessFromRuleSet = true
}
if metadata.ContainsWIFIRule {
needWIFIStateFromRuleSet = true
}
}
2024-06-08 23:21:50 +00:00
if needProcessFromRuleSet || r.needFindProcess {
2024-06-08 12:02:52 +00: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 (needWIFIStateFromRuleSet || r.needWIFIState) && r.platformInterface != nil {
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 05:24:12 +00:00
}
}
2023-12-02 09:47:57 +00:00
r.started = true
return nil
}
2022-07-05 01:05:35 +00:00
func (r *Router) Outbound(tag string) (adapter.Outbound, bool) {
outbound, loaded := r.outboundByTag[tag]
return outbound, loaded
}
2023-12-01 05:24:12 +00:00
func (r *Router) DefaultOutbound(network string) (adapter.Outbound, error) {
2022-07-29 16:29:22 +00:00
if network == N.NetworkTCP {
2023-12-01 05:24:12 +00:00
if r.defaultOutboundForConnection == nil {
return nil, E.New("missing default outbound for TCP connections")
}
return r.defaultOutboundForConnection, nil
2022-07-06 15:11:48 +00:00
} else {
2023-12-01 05:24:12 +00:00
if r.defaultOutboundForPacketConnection == nil {
return nil, E.New("missing default outbound for UDP connections")
}
return r.defaultOutboundForPacketConnection, nil
2022-07-06 15:11:48 +00:00
}
}
2023-03-25 04:03:23 +00:00
func (r *Router) FakeIPStore() adapter.FakeIPStore {
return r.fakeIPStore
}
2023-12-01 05:24:12 +00: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-05 01:05:35 +00:00
func (r *Router) RouteConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
if r.pauseManager.IsDevicePaused() {
return E.New("reject connection to ", metadata.Destination, " while device paused")
}
2022-08-29 11:43:13 +00:00
if metadata.InboundDetour != "" {
if metadata.LastInbound == metadata.InboundDetour {
return E.New("routing loop on detour: ", metadata.InboundDetour)
}
detour := r.inboundByTag[metadata.InboundDetour]
if detour == nil {
return E.New("inbound detour not found: ", metadata.InboundDetour)
}
injectable, isInjectable := detour.(adapter.InjectableInbound)
if !isInjectable {
return E.New("inbound detour is not injectable: ", metadata.InboundDetour)
}
if !common.Contains(injectable.Network(), N.NetworkTCP) {
return E.New("inject: TCP unsupported")
}
metadata.LastInbound = metadata.Inbound
metadata.Inbound = metadata.InboundDetour
metadata.InboundDetour = ""
2022-08-29 11:43:13 +00:00
err := injectable.NewConnection(ctx, conn, metadata)
if err != nil {
return E.Cause(err, "inject ", detour.Tag())
}
return nil
}
2023-09-20 06:12:08 +00:00
conntrack.KillerCheck()
2022-08-25 11:25:35 +00:00
metadata.Network = N.NetworkTCP
2022-08-11 02:36:28 +00:00
switch metadata.Destination.Fqdn {
case mux.Destination.Fqdn:
return E.New("global multiplex is deprecated since sing-box v1.7.0, enable multiplex in inbound options instead.")
case vmess.MuxDestination.Fqdn:
return E.New("global multiplex (v2ray legacy) not supported since sing-box v1.7.0.")
2023-03-15 05:34:02 +00:00
case uot.MagicAddress:
return E.New("global UoT not supported since sing-box v1.7.0.")
2023-03-15 05:34:02 +00:00
case uot.LegacyMagicAddress:
return E.New("global UoT (legacy) not supported since sing-box v1.7.0.")
2022-07-29 16:29:22 +00:00
}
2023-03-25 04:03:23 +00:00
if r.fakeIPStore != nil && r.fakeIPStore.Contains(metadata.Destination.Addr) {
domain, loaded := r.fakeIPStore.Lookup(metadata.Destination.Addr)
if !loaded {
return E.New("missing fakeip context")
}
2023-08-13 08:38:27 +00:00
metadata.OriginDestination = metadata.Destination
2023-03-25 04:03:23 +00:00
metadata.Destination = M.Socksaddr{
Fqdn: domain,
Port: metadata.Destination.Port,
}
2023-06-10 08:26:40 +00:00
metadata.FakeIP = true
2023-03-25 04:03:23 +00:00
r.logger.DebugContext(ctx, "found fakeip domain: ", domain)
}
2023-04-17 10:22:05 +00:00
if deadline.NeedAdditionalReadDeadline(conn) {
conn = deadline.NewConn(conn)
}
2022-10-07 12:30:27 +00:00
if metadata.InboundOptions.SniffEnabled {
2022-08-02 05:43:25 +00:00
buffer := buf.NewPacket()
sniffMetadata, err := sniff.PeekStream(
ctx,
conn,
buffer,
time.Duration(metadata.InboundOptions.SniffTimeout),
sniff.StreamDomainNameQuery,
sniff.TLSClientHello,
sniff.HTTPHost,
sniff.BitTorrent,
)
2022-10-12 05:37:06 +00:00
if sniffMetadata != nil {
2022-07-06 04:39:44 +00:00
metadata.Protocol = sniffMetadata.Protocol
metadata.Domain = sniffMetadata.Domain
2022-10-07 12:30:27 +00:00
if metadata.InboundOptions.SniffOverrideDestination && M.IsDomainName(metadata.Domain) {
2022-08-27 06:36:57 +00:00
metadata.Destination = M.Socksaddr{
Fqdn: metadata.Domain,
Port: metadata.Destination.Port,
}
2022-07-06 04:39:44 +00:00
}
if metadata.Domain != "" {
2022-07-12 07:17:29 +00:00
r.logger.DebugContext(ctx, "sniffed protocol: ", metadata.Protocol, ", domain: ", metadata.Domain)
2022-07-06 04:39:44 +00:00
} else {
2022-07-12 07:17:29 +00:00
r.logger.DebugContext(ctx, "sniffed protocol: ", metadata.Protocol)
2022-07-06 04:39:44 +00:00
}
2023-04-13 01:03:08 +00:00
} else if err != nil {
r.logger.TraceContext(ctx, "sniffed no protocol: ", err)
2022-07-06 04:39:44 +00:00
}
if !buffer.IsEmpty() {
conn = bufio.NewCachedConn(conn, buffer)
2022-08-02 05:43:25 +00:00
} else {
buffer.Release()
2022-07-06 04:39:44 +00:00
}
}
2023-03-23 11:08:48 +00:00
if r.dnsReverseMapping != nil && metadata.Domain == "" {
domain, loaded := r.dnsReverseMapping.Query(metadata.Destination.Addr)
if loaded {
metadata.Domain = domain
r.logger.DebugContext(ctx, "found reserve mapped domain: ", metadata.Domain)
}
}
2022-10-07 12:30:27 +00:00
if metadata.Destination.IsFqdn() && dns.DomainStrategy(metadata.InboundOptions.DomainStrategy) != dns.DomainStrategyAsIS {
addresses, err := r.Lookup(adapter.WithContext(ctx, &metadata), metadata.Destination.Fqdn, dns.DomainStrategy(metadata.InboundOptions.DomainStrategy))
2022-07-07 15:36:32 +00:00
if err != nil {
return err
}
metadata.DestinationAddresses = addresses
2022-07-12 07:17:29 +00:00
r.dnsLogger.DebugContext(ctx, "resolved [", strings.Join(F.MapToString(metadata.DestinationAddresses), " "), "]")
2022-07-07 15:36:32 +00:00
}
2023-10-03 03:01:25 +00:00
if metadata.Destination.IsIPv4() {
metadata.IPVersion = 4
} else if metadata.Destination.IsIPv6() {
metadata.IPVersion = 6
}
2023-04-08 00:58:01 +00:00
ctx, matchedRule, detour, err := r.match(ctx, &metadata, r.defaultOutboundForConnection)
if err != nil {
return err
}
2022-07-29 16:29:22 +00:00
if !common.Contains(detour.Network(), N.NetworkTCP) {
2022-07-05 01:05:35 +00:00
return E.New("missing supported outbound, closing connection")
}
2022-09-10 06:09:47 +00:00
if r.clashServer != nil {
trackerConn, tracker := r.clashServer.RoutedConnection(ctx, conn, metadata, matchedRule)
2022-07-25 22:56:13 +00:00
defer tracker.Leave()
conn = trackerConn
2022-07-19 14:16:49 +00:00
}
2022-09-26 11:37:06 +00:00
if r.v2rayServer != nil {
if statsService := r.v2rayServer.StatsService(); statsService != nil {
2023-02-08 08:50:15 +00:00
conn = statsService.RoutedConnection(metadata.Inbound, detour.Tag(), metadata.User, conn)
2022-09-26 11:37:06 +00:00
}
}
2022-07-07 15:36:32 +00:00
return detour.NewConnection(ctx, conn, metadata)
2022-07-05 01:05:35 +00:00
}
func (r *Router) RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
if r.pauseManager.IsDevicePaused() {
return E.New("reject packet connection to ", metadata.Destination, " while device paused")
}
2022-08-29 11:43:13 +00:00
if metadata.InboundDetour != "" {
if metadata.LastInbound == metadata.InboundDetour {
return E.New("routing loop on detour: ", metadata.InboundDetour)
}
detour := r.inboundByTag[metadata.InboundDetour]
if detour == nil {
return E.New("inbound detour not found: ", metadata.InboundDetour)
}
injectable, isInjectable := detour.(adapter.InjectableInbound)
if !isInjectable {
return E.New("inbound detour is not injectable: ", metadata.InboundDetour)
}
if !common.Contains(injectable.Network(), N.NetworkUDP) {
return E.New("inject: UDP unsupported")
}
metadata.LastInbound = metadata.Inbound
metadata.Inbound = metadata.InboundDetour
metadata.InboundDetour = ""
2022-08-29 11:43:13 +00:00
err := injectable.NewPacketConnection(ctx, conn, metadata)
if err != nil {
return E.Cause(err, "inject ", detour.Tag())
}
return nil
}
2023-09-20 06:12:08 +00:00
conntrack.KillerCheck()
2022-08-25 11:25:35 +00:00
metadata.Network = N.NetworkUDP
2023-03-25 04:03:23 +00:00
if r.fakeIPStore != nil && r.fakeIPStore.Contains(metadata.Destination.Addr) {
domain, loaded := r.fakeIPStore.Lookup(metadata.Destination.Addr)
if !loaded {
return E.New("missing fakeip context")
}
2023-08-13 08:38:27 +00:00
metadata.OriginDestination = metadata.Destination
2023-03-25 04:03:23 +00:00
metadata.Destination = M.Socksaddr{
Fqdn: domain,
Port: metadata.Destination.Port,
}
2023-06-10 08:26:40 +00:00
metadata.FakeIP = true
2023-03-25 04:03:23 +00:00
r.logger.DebugContext(ctx, "found fakeip domain: ", domain)
}
2023-04-17 10:22:05 +00:00
// Currently we don't have deadline usages for UDP connections
/*if deadline.NeedAdditionalReadDeadline(conn) {
conn = deadline.NewPacketConn(bufio.NewNetPacketConn(conn))
}*/
2023-08-13 08:49:55 +00:00
if metadata.InboundOptions.SniffEnabled || metadata.Destination.Addr.IsUnspecified() {
2022-08-02 05:43:25 +00:00
buffer := buf.NewPacket()
2022-08-11 02:36:28 +00:00
destination, err := conn.ReadPacket(buffer)
2022-07-06 04:39:44 +00:00
if err != nil {
2022-08-02 05:43:25 +00:00
buffer.Release()
2022-07-06 04:39:44 +00:00
return err
}
2023-08-13 08:49:55 +00:00
if metadata.Destination.Addr.IsUnspecified() {
metadata.Destination = destination
}
if metadata.InboundOptions.SniffEnabled {
sniffMetadata, _ := sniff.PeekPacket(
ctx,
buffer.Bytes(),
sniff.DomainNameQuery,
sniff.QUICClientHello,
sniff.STUNMessage,
sniff.UTP,
sniff.UDPTracker,
)
if sniffMetadata != nil {
metadata.Protocol = sniffMetadata.Protocol
metadata.Domain = sniffMetadata.Domain
if metadata.InboundOptions.SniffOverrideDestination && M.IsDomainName(metadata.Domain) {
metadata.Destination = M.Socksaddr{
Fqdn: metadata.Domain,
Port: metadata.Destination.Port,
}
}
if metadata.Domain != "" {
r.logger.DebugContext(ctx, "sniffed packet protocol: ", metadata.Protocol, ", domain: ", metadata.Domain)
} else {
r.logger.DebugContext(ctx, "sniffed packet protocol: ", metadata.Protocol)
2022-08-27 06:36:57 +00:00
}
2022-07-06 04:39:44 +00:00
}
}
2022-08-11 02:36:28 +00:00
conn = bufio.NewCachedPacketConn(conn, buffer, destination)
2022-07-06 04:39:44 +00:00
}
2023-06-07 12:28:21 +00:00
if r.dnsReverseMapping != nil && metadata.Domain == "" {
domain, loaded := r.dnsReverseMapping.Query(metadata.Destination.Addr)
if loaded {
metadata.Domain = domain
r.logger.DebugContext(ctx, "found reserve mapped domain: ", metadata.Domain)
}
}
2023-03-15 05:34:02 +00:00
if metadata.Destination.IsFqdn() && dns.DomainStrategy(metadata.InboundOptions.DomainStrategy) != dns.DomainStrategyAsIS {
2022-10-07 12:30:27 +00:00
addresses, err := r.Lookup(adapter.WithContext(ctx, &metadata), metadata.Destination.Fqdn, dns.DomainStrategy(metadata.InboundOptions.DomainStrategy))
2022-07-07 15:36:32 +00:00
if err != nil {
return err
}
metadata.DestinationAddresses = addresses
2022-07-12 07:17:29 +00:00
r.dnsLogger.DebugContext(ctx, "resolved [", strings.Join(F.MapToString(metadata.DestinationAddresses), " "), "]")
2022-07-07 15:36:32 +00:00
}
2023-10-03 03:01:25 +00:00
if metadata.Destination.IsIPv4() {
metadata.IPVersion = 4
} else if metadata.Destination.IsIPv6() {
metadata.IPVersion = 6
}
2023-04-08 00:58:01 +00:00
ctx, matchedRule, detour, err := r.match(ctx, &metadata, r.defaultOutboundForPacketConnection)
if err != nil {
return err
}
2022-07-29 16:29:22 +00:00
if !common.Contains(detour.Network(), N.NetworkUDP) {
2022-07-05 01:05:35 +00:00
return E.New("missing supported outbound, closing packet connection")
}
2022-09-10 06:09:47 +00:00
if r.clashServer != nil {
trackerConn, tracker := r.clashServer.RoutedPacketConnection(ctx, conn, metadata, matchedRule)
2022-07-25 22:56:13 +00:00
defer tracker.Leave()
conn = trackerConn
2022-07-19 14:16:49 +00:00
}
2022-09-26 11:37:06 +00:00
if r.v2rayServer != nil {
if statsService := r.v2rayServer.StatsService(); statsService != nil {
2023-02-08 08:50:15 +00:00
conn = statsService.RoutedPacketConnection(metadata.Inbound, detour.Tag(), metadata.User, conn)
2022-09-26 11:37:06 +00:00
}
}
2023-08-13 08:49:55 +00:00
if metadata.FakeIP {
2023-10-25 04:00:00 +00:00
conn = bufio.NewNATPacketConn(bufio.NewNetPacketConn(conn), metadata.OriginDestination, metadata.Destination)
2023-03-25 04:03:23 +00:00
}
2022-07-07 15:36:32 +00:00
return detour.NewPacketConnection(ctx, conn, metadata)
2022-07-07 13:47:21 +00:00
}
2023-04-08 00:58:01 +00:00
func (r *Router) match(ctx context.Context, metadata *adapter.InboundContext, defaultOutbound adapter.Outbound) (context.Context, adapter.Rule, adapter.Outbound, error) {
matchRule, matchOutbound := r.match0(ctx, metadata, defaultOutbound)
if contextOutbound, loaded := outbound.TagFromContext(ctx); loaded {
if contextOutbound == matchOutbound.Tag() {
return nil, nil, nil, E.New("connection loopback in outbound/", matchOutbound.Type(), "[", matchOutbound.Tag(), "]")
}
}
ctx = outbound.ContextWithTag(ctx, matchOutbound.Tag())
return ctx, matchRule, matchOutbound, nil
}
func (r *Router) match0(ctx context.Context, metadata *adapter.InboundContext, defaultOutbound adapter.Outbound) (adapter.Rule, adapter.Outbound) {
if r.processSearcher != nil {
2022-08-20 02:38:12 +00:00
var originDestination netip.AddrPort
if metadata.OriginDestination.IsValid() {
originDestination = metadata.OriginDestination.AddrPort()
} else if metadata.Destination.IsIP() {
originDestination = metadata.Destination.AddrPort()
}
processInfo, err := process.FindProcessInfo(r.processSearcher, ctx, metadata.Network, metadata.Source.AddrPort(), originDestination)
if err != nil {
r.logger.InfoContext(ctx, "failed to search process: ", err)
} else {
if processInfo.ProcessPath != "" {
r.logger.InfoContext(ctx, "found process path: ", processInfo.ProcessPath)
} else if processInfo.PackageName != "" {
r.logger.InfoContext(ctx, "found package name: ", processInfo.PackageName)
} else if processInfo.UserId != -1 {
if /*needUserName &&*/ true {
osUser, _ := user.LookupId(F.ToString(processInfo.UserId))
if osUser != nil {
processInfo.User = osUser.Username
}
}
if processInfo.User != "" {
r.logger.InfoContext(ctx, "found user: ", processInfo.User)
} else {
r.logger.InfoContext(ctx, "found user id: ", processInfo.UserId)
}
}
metadata.ProcessInfo = processInfo
}
}
2022-07-05 01:05:35 +00:00
for i, rule := range r.rules {
2023-12-01 05:24:12 +00:00
metadata.ResetRuleCache()
if rule.Match(metadata) {
2022-07-05 01:05:35 +00:00
detour := rule.Outbound()
2022-07-12 07:17:29 +00:00
r.logger.DebugContext(ctx, "match[", i, "] ", rule.String(), " => ", detour)
2022-07-05 01:05:35 +00:00
if outbound, loaded := r.Outbound(detour); loaded {
2022-07-19 14:16:49 +00:00
return rule, outbound
2022-07-05 01:05:35 +00:00
}
2022-07-12 07:17:29 +00:00
r.logger.ErrorContext(ctx, "outbound not found: ", detour)
2022-07-05 01:05:35 +00:00
}
}
2022-07-19 14:16:49 +00:00
return nil, defaultOutbound
2022-07-05 01:05:35 +00:00
}
2022-09-14 04:46:02 +00:00
func (r *Router) InterfaceFinder() control.InterfaceFinder {
2024-04-12 01:24:49 +00:00
return r.interfaceFinder
2022-07-14 15:06:03 +00:00
}
2023-04-18 06:04:09 +00:00
func (r *Router) UpdateInterfaces() error {
if r.platformInterface == nil || !r.platformInterface.UsePlatformInterfaceGetter() {
2024-04-12 01:24:49 +00:00
return r.interfaceFinder.Update()
2023-04-18 06:04:09 +00:00
} else {
interfaces, err := r.platformInterface.Interfaces()
if err != nil {
return err
}
2024-04-12 01:24:49 +00:00
r.interfaceFinder.UpdateInterfaces(interfaces)
2023-04-18 06:04:09 +00:00
return nil
}
}
func (r *Router) AutoDetectInterface() bool {
return r.autoDetectInterface
}
2022-10-25 04:55:00 +00:00
func (r *Router) AutoDetectInterfaceFunc() control.Func {
if r.platformInterface != nil && r.platformInterface.UsePlatformAutoDetectInterfaceControl() {
2022-10-25 04:55:00 +00:00
return r.platformInterface.AutoDetectInterfaceControl()
} else {
2024-06-03 04:54:54 +00:00
if r.interfaceMonitor == nil {
return nil
}
2023-09-20 06:12:08 +00:00
return control.BindToInterfaceFunc(r.InterfaceFinder(), func(network string, address string) (interfaceName string, interfaceIndex int, err error) {
2022-10-25 04:55:00 +00:00
remoteAddr := M.ParseSocksaddr(address).Addr
if C.IsLinux {
2023-10-21 04:00:00 +00:00
interfaceName, interfaceIndex = r.InterfaceMonitor().DefaultInterface(remoteAddr)
if interfaceIndex == -1 {
2023-09-20 06:12:08 +00:00
err = tun.ErrNoRoute
}
2022-10-25 04:55:00 +00:00
} else {
2023-09-20 06:12:08 +00:00
interfaceIndex = r.InterfaceMonitor().DefaultInterfaceIndex(remoteAddr)
if interfaceIndex == -1 {
err = tun.ErrNoRoute
}
2022-10-25 04:55:00 +00:00
}
2023-09-20 06:12:08 +00:00
return
2022-10-25 04:55:00 +00:00
})
}
}
2022-07-15 03:51:51 +00:00
func (r *Router) DefaultInterface() string {
return r.defaultInterface
}
2022-07-24 09:46:25 +00:00
func (r *Router) DefaultMark() int {
return r.defaultMark
}
2022-07-19 14:16:49 +00:00
func (r *Router) Rules() []adapter.Rule {
return r.rules
}
func (r *Router) WIFIState() adapter.WIFIState {
return r.wifiState
}
2022-08-04 14:01:20 +00: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 06:09:47 +00:00
func (r *Router) ClashServer() adapter.ClashServer {
return r.clashServer
}
2022-09-26 11:37:06 +00: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 14:16:49 +00:00
}
func (r *Router) OnPackagesUpdated(packages int, sharedUsers int) {
r.logger.Info("updated packages list: ", packages, " packages, ", sharedUsers, " shared users")
}
2022-07-14 15:06:03 +00:00
func (r *Router) NewError(ctx context.Context, err error) {
2022-07-29 16:29:22 +00:00
common.Close(err)
if E.IsClosedOrCanceled(err) {
2022-08-16 15:37:51 +00:00
r.logger.DebugContext(ctx, "connection closed: ", err)
2022-07-29 16:29:22 +00:00
return
}
2022-07-14 15:06:03 +00:00
r.logger.ErrorContext(ctx, err)
}
2022-11-06 02:36:19 +00:00
2023-07-23 06:42:19 +00:00
func (r *Router) notifyNetworkUpdate(event int) {
if event == tun.EventNoRoute {
2023-08-07 09:46:51 +00:00
r.pauseManager.NetworkPause()
r.logger.Error("missing default interface")
2023-07-23 06:42:19 +00:00
} else {
2023-08-07 09:46:51 +00:00
r.pauseManager.NetworkWake()
2023-07-23 06:42:19 +00: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 02:36:19 +00:00
} else {
2023-07-23 06:42:19 +00:00
r.logger.Info("updated default interface ", r.interfaceMonitor.DefaultInterfaceName(netip.IPv4Unspecified()), ", index ", r.interfaceMonitor.DefaultInterfaceIndex(netip.IPv4Unspecified()))
2022-11-06 02:36:19 +00:00
}
}
2023-12-02 09:47:57 +00:00
if !r.started {
return
}
_ = r.ResetNetwork()
}
func (r *Router) ResetNetwork() error {
conntrack.Close()
2023-04-18 06:04:09 +00:00
2022-11-06 02:36:19 +00:00
for _, outbound := range r.outbounds {
listener, isListener := outbound.(adapter.InterfaceUpdateListener)
if isListener {
2023-07-23 06:42:19 +00:00
listener.InterfaceUpdated()
2022-11-06 02:36:19 +00:00
}
}
for _, transport := range r.transports {
transport.Reset()
}
2022-11-06 02:36:19 +00: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 05:24:19 +00: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 13:20:23 +00: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()
}
}