sing-box/route/router.go

1351 lines
42 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-06-30 21:27:56 +08:00
"net"
2022-07-07 21:47:21 +08:00
"net/netip"
"net/url"
2022-07-02 22:55:10 +08:00
"os"
"os/user"
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"
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"
2022-07-06 15:01:09 +08:00
"github.com/sagernet/sing-box/common/sniff"
"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"
2023-04-08 08:58:01 +08:00
"github.com/sagernet/sing-box/outbound"
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"
"github.com/sagernet/sing-mux"
2022-08-04 22:01:20 +08:00
"github.com/sagernet/sing-tun"
"github.com/sagernet/sing-vmess"
2022-07-08 23:03:57 +08:00
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/bufio"
2023-04-17 18:22:05 +08:00
"github.com/sagernet/sing/common/bufio/deadline"
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"
2022-08-11 10:36:28 +08:00
"github.com/sagernet/sing/common/uot"
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 {
2023-11-28 23:47:32 +08:00
routeRule, err := NewRule(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 {
2023-11-28 23:47:32 +08:00
dnsRule, err := NewDNSRule(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)
}
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 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)
}
2022-07-24 13:44:44 +08:00
switch server.Address {
2023-02-08 16:28:52 +08:00
case "local":
2022-07-24 13:44:44 +08:00
default:
serverURL, _ := url.Parse(server.Address)
var serverAddress string
if serverURL != nil {
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()
}
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 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{
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 {
if _, loaded := outboundByTag[rule.Outbound()]; !loaded {
return E.New("outbound not found for rule[", i, "]: ", rule.Outbound())
}
}
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)
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")
ruleSetStartContext := NewRuleSetStartContext()
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 {
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()
}
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-07-05 09:05:35 +08: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 19:43:13 +08: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 19:43:13 +08:00
err := injectable.NewConnection(ctx, conn, metadata)
if err != nil {
return E.Cause(err, "inject ", detour.Tag())
}
return nil
}
2023-09-20 14:12:08 +08:00
conntrack.KillerCheck()
2022-08-25 19:25:35 +08:00
metadata.Network = N.NetworkTCP
2022-08-11 10:36:28 +08: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 13:34:02 +08:00
case uot.MagicAddress:
return E.New("global UoT not supported since sing-box v1.7.0.")
2023-03-15 13:34:02 +08:00
case uot.LegacyMagicAddress:
return E.New("global UoT (legacy) not supported since sing-box v1.7.0.")
2022-07-30 00:29:22 +08:00
}
2023-03-25 12:03:23 +08: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 16:38:27 +08:00
metadata.OriginDestination = metadata.Destination
2023-03-25 12:03:23 +08:00
metadata.Destination = M.Socksaddr{
Fqdn: domain,
Port: metadata.Destination.Port,
}
2023-06-10 16:26:40 +08:00
metadata.FakeIP = true
2023-03-25 12:03:23 +08:00
r.logger.DebugContext(ctx, "found fakeip domain: ", domain)
}
2023-04-17 18:22:05 +08:00
if deadline.NeedAdditionalReadDeadline(conn) {
conn = deadline.NewConn(conn)
}
2024-08-28 11:40:43 +08:00
if metadata.InboundOptions.SniffEnabled && !sniff.Skip(metadata) {
2022-08-02 13:43:25 +08:00
buffer := buf.NewPacket()
2024-07-07 15:45:50 +08:00
err := sniff.PeekStream(
ctx,
2024-07-07 15:45:50 +08:00
&metadata,
conn,
buffer,
time.Duration(metadata.InboundOptions.SniffTimeout),
sniff.TLSClientHello,
sniff.HTTPHost,
2024-08-20 18:56:50 +08:00
sniff.StreamDomainNameQuery,
sniff.SSH,
sniff.BitTorrent,
)
2024-07-07 15:45:50 +08:00
if err == nil {
2022-10-07 20:30:27 +08:00
if metadata.InboundOptions.SniffOverrideDestination && M.IsDomainName(metadata.Domain) {
2022-08-27 14:36:57 +08:00
metadata.Destination = M.Socksaddr{
Fqdn: metadata.Domain,
Port: metadata.Destination.Port,
}
2022-07-06 12:39:44 +08:00
}
if metadata.Domain != "" {
2022-07-12 15:17:29 +08:00
r.logger.DebugContext(ctx, "sniffed protocol: ", metadata.Protocol, ", domain: ", metadata.Domain)
2022-07-06 12:39:44 +08:00
} else {
2022-07-12 15:17:29 +08:00
r.logger.DebugContext(ctx, "sniffed protocol: ", metadata.Protocol)
2022-07-06 12:39:44 +08:00
}
}
if !buffer.IsEmpty() {
conn = bufio.NewCachedConn(conn, buffer)
2022-08-02 13:43:25 +08:00
} else {
buffer.Release()
2022-07-06 12:39:44 +08:00
}
}
2023-03-23 19:08:48 +08: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 20:30:27 +08: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 23:36:32 +08:00
if err != nil {
return err
}
metadata.DestinationAddresses = addresses
2022-07-12 15:17:29 +08:00
r.dnsLogger.DebugContext(ctx, "resolved [", strings.Join(F.MapToString(metadata.DestinationAddresses), " "), "]")
2022-07-07 23:36:32 +08:00
}
2023-10-03 11:01:25 +08:00
if metadata.Destination.IsIPv4() {
metadata.IPVersion = 4
} else if metadata.Destination.IsIPv6() {
metadata.IPVersion = 6
}
2023-04-08 08:58:01 +08:00
ctx, matchedRule, detour, err := r.match(ctx, &metadata, r.defaultOutboundForConnection)
if err != nil {
return err
}
2022-07-30 00:29:22 +08:00
if !common.Contains(detour.Network(), N.NetworkTCP) {
2022-07-05 09:05:35 +08:00
return E.New("missing supported outbound, closing connection")
}
2022-09-10 14:09:47 +08:00
if r.clashServer != nil {
trackerConn, tracker := r.clashServer.RoutedConnection(ctx, conn, metadata, matchedRule)
2022-07-26 06:56:13 +08:00
defer tracker.Leave()
conn = trackerConn
2022-07-19 22:16:49 +08:00
}
2022-09-26 19:37:06 +08:00
if r.v2rayServer != nil {
if statsService := r.v2rayServer.StatsService(); statsService != nil {
2023-02-08 16:50:15 +08:00
conn = statsService.RoutedConnection(metadata.Inbound, detour.Tag(), metadata.User, conn)
2022-09-26 19:37:06 +08:00
}
}
2022-07-07 23:36:32 +08:00
return detour.NewConnection(ctx, conn, metadata)
2022-07-05 09:05:35 +08: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 19:43:13 +08: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 19:43:13 +08:00
err := injectable.NewPacketConnection(ctx, conn, metadata)
if err != nil {
return E.Cause(err, "inject ", detour.Tag())
}
return nil
}
2023-09-20 14:12:08 +08:00
conntrack.KillerCheck()
2022-08-25 19:25:35 +08:00
metadata.Network = N.NetworkUDP
2023-03-25 12:03:23 +08: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 16:38:27 +08:00
metadata.OriginDestination = metadata.Destination
2023-03-25 12:03:23 +08:00
metadata.Destination = M.Socksaddr{
Fqdn: domain,
Port: metadata.Destination.Port,
}
2023-06-10 16:26:40 +08:00
metadata.FakeIP = true
2023-03-25 12:03:23 +08:00
r.logger.DebugContext(ctx, "found fakeip domain: ", domain)
}
2023-04-17 18:22:05 +08:00
// Currently we don't have deadline usages for UDP connections
/*if deadline.NeedAdditionalReadDeadline(conn) {
conn = deadline.NewPacketConn(bufio.NewNetPacketConn(conn))
}*/
2023-08-13 16:49:55 +08:00
if metadata.InboundOptions.SniffEnabled || metadata.Destination.Addr.IsUnspecified() {
2024-07-07 15:45:50 +08:00
var bufferList []*buf.Buffer
for {
var (
buffer = buf.NewPacket()
destination M.Socksaddr
done = make(chan struct{})
err error
)
go func() {
sniffTimeout := C.ReadPayloadTimeout
if metadata.InboundOptions.SniffTimeout > 0 {
sniffTimeout = time.Duration(metadata.InboundOptions.SniffTimeout)
}
conn.SetReadDeadline(time.Now().Add(sniffTimeout))
destination, err = conn.ReadPacket(buffer)
conn.SetReadDeadline(time.Time{})
close(done)
}()
select {
case <-done:
case <-ctx.Done():
conn.Close()
return ctx.Err()
}
2024-07-07 15:45:50 +08:00
if err != nil {
buffer.Release()
if !errors.Is(err, os.ErrDeadlineExceeded) {
return err
}
} else {
if metadata.Destination.Addr.IsUnspecified() {
metadata.Destination = destination
}
if metadata.InboundOptions.SniffEnabled {
if len(bufferList) > 0 {
err = sniff.PeekPacket(
ctx,
&metadata,
buffer.Bytes(),
sniff.QUICClientHello,
)
} else {
2024-07-07 15:45:50 +08:00
err = sniff.PeekPacket(
ctx, &metadata,
buffer.Bytes(),
sniff.DomainNameQuery,
sniff.QUICClientHello,
sniff.STUNMessage,
sniff.UTP,
sniff.UDPTracker,
sniff.DTLSRecord)
}
if E.IsMulti(err, sniff.ErrClientHelloFragmented) && len(bufferList) == 0 {
bufferList = append(bufferList, buffer)
r.logger.DebugContext(ctx, "attempt to sniff fragmented QUIC client hello")
continue
}
if metadata.Protocol != "" {
if metadata.InboundOptions.SniffOverrideDestination && M.IsDomainName(metadata.Domain) {
metadata.Destination = M.Socksaddr{
Fqdn: metadata.Domain,
Port: metadata.Destination.Port,
}
}
if metadata.Domain != "" && metadata.Client != "" {
r.logger.DebugContext(ctx, "sniffed packet protocol: ", metadata.Protocol, ", domain: ", metadata.Domain, ", client: ", metadata.Client)
} else if metadata.Domain != "" {
r.logger.DebugContext(ctx, "sniffed packet protocol: ", metadata.Protocol, ", domain: ", metadata.Domain)
} else if metadata.Client != "" {
r.logger.DebugContext(ctx, "sniffed packet protocol: ", metadata.Protocol, ", client: ", metadata.Client)
} else {
r.logger.DebugContext(ctx, "sniffed packet protocol: ", metadata.Protocol)
}
}
2022-08-27 14:36:57 +08:00
}
2024-07-07 15:45:50 +08:00
conn = bufio.NewCachedPacketConn(conn, buffer, destination)
2022-07-06 12:39:44 +08:00
}
2024-07-07 15:45:50 +08:00
for _, cachedBuffer := range common.Reverse(bufferList) {
conn = bufio.NewCachedPacketConn(conn, cachedBuffer, destination)
}
break
2022-07-06 12:39:44 +08:00
}
}
2023-06-07 20:28:21 +08: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 13:34:02 +08:00
if metadata.Destination.IsFqdn() && dns.DomainStrategy(metadata.InboundOptions.DomainStrategy) != dns.DomainStrategyAsIS {
2022-10-07 20:30:27 +08:00
addresses, err := r.Lookup(adapter.WithContext(ctx, &metadata), metadata.Destination.Fqdn, dns.DomainStrategy(metadata.InboundOptions.DomainStrategy))
2022-07-07 23:36:32 +08:00
if err != nil {
return err
}
metadata.DestinationAddresses = addresses
2022-07-12 15:17:29 +08:00
r.dnsLogger.DebugContext(ctx, "resolved [", strings.Join(F.MapToString(metadata.DestinationAddresses), " "), "]")
2022-07-07 23:36:32 +08:00
}
2023-10-03 11:01:25 +08:00
if metadata.Destination.IsIPv4() {
metadata.IPVersion = 4
} else if metadata.Destination.IsIPv6() {
metadata.IPVersion = 6
}
2023-04-08 08:58:01 +08:00
ctx, matchedRule, detour, err := r.match(ctx, &metadata, r.defaultOutboundForPacketConnection)
if err != nil {
return err
}
2022-07-30 00:29:22 +08:00
if !common.Contains(detour.Network(), N.NetworkUDP) {
2022-07-05 09:05:35 +08:00
return E.New("missing supported outbound, closing packet connection")
}
2022-09-10 14:09:47 +08:00
if r.clashServer != nil {
trackerConn, tracker := r.clashServer.RoutedPacketConnection(ctx, conn, metadata, matchedRule)
2022-07-26 06:56:13 +08:00
defer tracker.Leave()
conn = trackerConn
2022-07-19 22:16:49 +08:00
}
2022-09-26 19:37:06 +08:00
if r.v2rayServer != nil {
if statsService := r.v2rayServer.StatsService(); statsService != nil {
2023-02-08 16:50:15 +08:00
conn = statsService.RoutedPacketConnection(metadata.Inbound, detour.Tag(), metadata.User, conn)
2022-09-26 19:37:06 +08:00
}
}
2023-08-13 16:49:55 +08:00
if metadata.FakeIP {
2023-10-25 12:00:00 +08:00
conn = bufio.NewNATPacketConn(bufio.NewNetPacketConn(conn), metadata.OriginDestination, metadata.Destination)
2023-03-25 12:03:23 +08:00
}
2022-07-07 23:36:32 +08:00
return detour.NewPacketConnection(ctx, conn, metadata)
2022-07-07 21:47:21 +08:00
}
2023-04-08 08:58:01 +08: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 10:38:12 +08: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 09:05:35 +08:00
for i, rule := range r.rules {
2023-12-01 13:24:12 +08:00
metadata.ResetRuleCache()
if rule.Match(metadata) {
2022-07-05 09:05:35 +08:00
detour := rule.Outbound()
2022-07-12 15:17:29 +08:00
r.logger.DebugContext(ctx, "match[", i, "] ", rule.String(), " => ", detour)
2022-07-05 09:05:35 +08:00
if outbound, loaded := r.Outbound(detour); loaded {
2022-07-19 22:16:49 +08:00
return rule, outbound
2022-07-05 09:05:35 +08:00
}
2022-07-12 15:17:29 +08:00
r.logger.ErrorContext(ctx, "outbound not found: ", detour)
2022-07-05 09:05:35 +08:00
}
}
2022-07-19 22:16:49 +08:00
return nil, defaultOutbound
2022-07-05 09:05:35 +08:00
}
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() {
2022-10-25 12:55:00 +08:00
return r.platformInterface.AutoDetectInterfaceControl()
} 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()
}
}