sing-box/route/router.go

1027 lines
34 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"
2022-07-07 21:47:21 +08:00
"strings"
2022-07-02 22:55:10 +08:00
"time"
2022-06-30 21:27:56 +08:00
2022-07-06 15:01:09 +08:00
"github.com/sagernet/sing-box/adapter"
2022-07-07 21:47:21 +08:00
"github.com/sagernet/sing-box/common/dialer"
"github.com/sagernet/sing-box/common/dialer/conntrack"
2022-07-06 15:01:09 +08:00
"github.com/sagernet/sing-box/common/geoip"
"github.com/sagernet/sing-box/common/geosite"
2022-07-30 00:29:22 +08:00
"github.com/sagernet/sing-box/common/mux"
"github.com/sagernet/sing-box/common/process"
2022-07-06 15:01:09 +08:00
"github.com/sagernet/sing-box/common/sniff"
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"
2023-02-21 14:53:00 +08:00
"github.com/sagernet/sing-box/ntp"
2022-07-06 15:01:09 +08:00
"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"
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"
2023-08-08 16:14:03 +08:00
serviceNTP "github.com/sagernet/sing/common/ntp"
2022-08-11 10:36:28 +08:00
"github.com/sagernet/sing/common/uot"
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
dnsClient *dns.Client
defaultDomainStrategy dns.DomainStrategy
2022-07-24 14:05:06 +08:00
dnsRules []adapter.DNSRule
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
2022-09-14 12:46:02 +08:00
interfaceFinder myInterfaceFinder
autoDetectInterface bool
defaultInterface string
2022-07-24 17:46:25 +08:00
defaultMark int
2022-08-04 22:01:20 +08:00
networkMonitor tun.NetworkUpdateMonitor
interfaceMonitor tun.DefaultInterfaceMonitor
packageManager tun.PackageManager
processSearcher process.Searcher
2023-02-21 14:53:00 +08:00
timeService adapter.TimeService
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
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)),
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),
2022-07-07 21:47:21 +08:00
defaultDetour: options.Final,
2022-07-11 18:44:59 +08:00
defaultDomainStrategy: dns.DomainStrategy(dnsOptions.Strategy),
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-08-07 17:46:51 +08:00
pauseManager: pause.ManagerFromContext(ctx),
2022-10-25 12:55:00 +08:00
platformInterface: platformInterface,
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,
Logger: router.dnsLogger,
})
2022-07-02 22:55:10 +08:00
for i, ruleOptions := range options.Rules {
2022-11-28 13:10:56 +08:00
routeRule, err := NewRule(router, router.logger, ruleOptions)
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 {
2022-11-28 13:10:56 +08:00
dnsRule, err := NewDNSRule(router, router.logger, dnsRuleOptions)
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-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 := netip.ParseAddr(serverAddress)
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
}
2023-03-25 12:03:23 +08:00
} else if notIpAddress != nil && strings.Contains(server.Address, ".") {
return nil, E.New("parse dns server[", tag, "]: missing address_resolver")
2022-07-07 21:47:21 +08:00
}
}
2023-04-08 08:58:01 +08:00
transport, err := dns.CreateTransport(tag, ctx, logFactory.NewLogger(F.ToString("dns/transport[", tag, "]")), detour, server.Address)
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 {
2023-04-08 08:58:01 +08:00
transports = append(transports, dns.NewLocalTransport("local", N.SystemDialer))
2022-07-07 21:47:21 +08:00
}
defaultTransport = transports[0]
2022-07-02 14:07:50 +08:00
}
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 {
inet4Range = fakeIPOptions.Inet4Range.Build()
}
if fakeIPOptions.Inet6Range != nil {
inet6Range = fakeIPOptions.Inet6Range.Build()
}
2023-07-07 12:48:26 +08:00
router.fakeIPStore = fakeip.NewStore(router, 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() {
_ = router.interfaceFinder.update()
})
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
needFindProcess := hasRule(options.Rules, isProcessRule) || hasDNSRule(dnsOptions.Rules, isProcessDNSRule) || options.FindProcess
2022-10-25 12:55:00 +08:00
needPackageManager := C.IsAndroid && platformInterface == nil && (needFindProcess || common.Any(inbounds, func(inbound option.Inbound) bool {
return len(inbound.TunOptions.IncludePackage) > 0 || len(inbound.TunOptions.ExcludePackage) > 0
}))
if needPackageManager {
packageManager, err := tun.NewPackageManager(router)
if err != nil {
return nil, E.Cause(err, "create package manager")
}
router.packageManager = packageManager
}
if needFindProcess {
2022-10-25 12:55:00 +08:00
if platformInterface != nil {
router.processSearcher = platformInterface
2022-07-24 22:54:16 +08:00
} else {
2022-10-25 12:55:00 +08:00
searcher, err := process.NewSearcher(process.Config{
Logger: logFactory.NewLogger("router/process"),
PackageManager: router.packageManager,
})
if err != nil {
if err != os.ErrInvalid {
router.logger.Warn(E.Cause(err, "create process searcher"))
}
} else {
router.processSearcher = searcher
}
}
}
2023-02-21 14:53:00 +08:00
if ntpOptions.Enabled {
2023-08-08 16:14:03 +08:00
timeService, err := ntp.NewService(ctx, router, logFactory.NewLogger("ntp"), ntpOptions)
if err != nil {
return nil, err
}
service.ContextWith[serviceNTP.TimeService](ctx, timeService)
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
}
}
var index, packetIndex int
if defaultOutboundForConnection == nil {
for i, detour := range outbounds {
2022-07-30 00:29:22 +08:00
if common.Contains(detour.Network(), N.NetworkTCP) {
index = i
defaultOutboundForConnection = detour
break
}
}
}
if defaultOutboundForPacketConnection == nil {
for i, detour := range outbounds {
2022-07-30 00:29:22 +08:00
if common.Contains(detour.Network(), N.NetworkUDP) {
packetIndex = i
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
}
if defaultOutboundForConnection != defaultOutboundForPacketConnection {
var description string
if defaultOutboundForConnection.Tag() != "" {
description = defaultOutboundForConnection.Tag()
} else {
description = F.ToString(index)
}
var packetDescription string
if defaultOutboundForPacketConnection.Tag() != "" {
packetDescription = defaultOutboundForPacketConnection.Tag()
} else {
packetDescription = F.ToString(packetIndex)
}
r.logger.Info("using ", defaultOutboundForConnection.Type(), "[", description, "] as default outbound for connection")
r.logger.Info("using ", defaultOutboundForPacketConnection.Type(), "[", packetDescription, "] as default outbound for packet connection")
2022-07-02 14:07:50 +08:00
}
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 {
return r.outbounds
}
2022-07-02 22:55:10 +08:00
func (r *Router) Start() error {
2022-07-05 09:05:35 +08:00
if r.needGeoIPDatabase {
2022-07-04 19:34:45 +08:00
err := r.prepareGeoIPDatabase()
if err != nil {
return err
}
2022-07-02 14:07:50 +08:00
}
2022-07-05 09:05:35 +08:00
if r.needGeositeDatabase {
err := r.prepareGeositeDatabase()
if err != nil {
return err
}
}
2023-02-08 16:28:52 +08:00
if r.interfaceMonitor != nil {
err := r.interfaceMonitor.Start()
2022-07-05 09:05:35 +08:00
if err != nil {
return err
}
}
2023-02-08 16:28:52 +08:00
if r.networkMonitor != nil {
err := r.networkMonitor.Start()
if err != nil {
return err
}
}
if r.packageManager != nil {
err := r.packageManager.Start()
2022-07-07 23:36:32 +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
}
2023-02-08 16:28:52 +08:00
for i, rule := range r.rules {
err := rule.Start()
if err != nil {
2023-02-08 16:28:52 +08:00
return E.Cause(err, "initialize rule[", i, "]")
}
}
2023-02-08 16:28:52 +08:00
for i, rule := range r.dnsRules {
err := rule.Start()
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-03-25 12:03:23 +08:00
if r.fakeIPStore != nil {
err := r.fakeIPStore.Start()
if err != nil {
return err
}
}
2023-02-08 16:28:52 +08:00
for i, transport := range r.transports {
err := transport.Start()
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 {
err := r.timeService.Start()
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 {
2023-04-08 08:09:28 +08:00
var err error
for i, rule := range r.rules {
r.logger.Trace("closing rule[", i, "]")
err = E.Append(err, rule.Close(), func(err error) error {
return E.Cause(err, "close rule[", i, "]")
})
2022-07-07 23:36:32 +08:00
}
2023-04-08 08:09:28 +08:00
for i, rule := range r.dnsRules {
r.logger.Trace("closing dns rule[", i, "]")
err = E.Append(err, rule.Close(), func(err error) error {
return E.Cause(err, "close dns rule[", i, "]")
})
2022-07-07 23:36:32 +08:00
}
2023-04-08 08:09:28 +08:00
for i, transport := range r.transports {
r.logger.Trace("closing transport[", i, "] ")
err = E.Append(err, transport.Close(), func(err error) error {
return E.Cause(err, "close dns transport[", i, "]")
})
}
2023-09-07 12:54:45 +08:00
if r.geoIPReader != nil {
2023-04-08 08:09:28 +08:00
r.logger.Trace("closing geoip reader")
err = E.Append(err, common.Close(r.geoIPReader), func(err error) error {
return E.Cause(err, "close geoip reader")
})
}
if r.interfaceMonitor != nil {
r.logger.Trace("closing interface monitor")
err = E.Append(err, r.interfaceMonitor.Close(), func(err error) error {
return E.Cause(err, "close interface monitor")
})
}
if r.networkMonitor != nil {
r.logger.Trace("closing network monitor")
err = E.Append(err, r.networkMonitor.Close(), func(err error) error {
return E.Cause(err, "close network monitor")
})
}
if r.packageManager != nil {
r.logger.Trace("closing package manager")
err = E.Append(err, r.packageManager.Close(), func(err error) error {
return E.Cause(err, "close package manager")
})
}
if r.timeService != nil {
r.logger.Trace("closing time service")
err = E.Append(err, r.timeService.Close(), func(err error) error {
return E.Cause(err, "close time service")
})
2023-02-08 16:28:52 +08:00
}
2023-03-25 12:03:23 +08:00
if r.fakeIPStore != nil {
r.logger.Trace("closing fakeip store")
err = E.Append(err, r.fakeIPStore.Close(), func(err error) error {
return E.Cause(err, "close fakeip store")
})
}
2023-04-08 08:09:28 +08:00
return err
2022-07-02 22:55:10 +08:00
}
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
}
2022-07-06 23:11:48 +08:00
func (r *Router) DefaultOutbound(network string) adapter.Outbound {
2022-07-30 00:29:22 +08:00
if network == N.NetworkTCP {
2022-07-06 23:11:48 +08:00
return r.defaultOutboundForConnection
} else {
return r.defaultOutboundForPacketConnection
}
}
2023-03-25 12:03:23 +08:00
func (r *Router) FakeIPStore() adapter.FakeIPStore {
return r.fakeIPStore
}
2022-07-05 09:05:35 +08:00
func (r *Router) RouteConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
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
}
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:
2022-07-30 00:29:22 +08:00
r.logger.InfoContext(ctx, "inbound multiplex connection")
2023-04-20 11:16:22 +08:00
handler := adapter.NewUpstreamHandler(metadata, r.RouteConnection, r.RoutePacketConnection, r)
return mux.HandleConnection(ctx, handler, r.logger, conn, adapter.UpstreamMetadata(metadata))
case vmess.MuxDestination.Fqdn:
r.logger.InfoContext(ctx, "inbound legacy multiplex connection")
return vmess.HandleMuxConnection(ctx, conn, adapter.NewUpstreamHandler(metadata, r.RouteConnection, r.RoutePacketConnection, r))
2023-03-15 13:34:02 +08:00
case uot.MagicAddress:
request, err := uot.ReadRequest(conn)
if err != nil {
return E.Cause(err, "read UoT request")
}
if request.IsConnect {
r.logger.InfoContext(ctx, "inbound UoT connect connection to ", request.Destination)
} else {
r.logger.InfoContext(ctx, "inbound UoT connection to ", request.Destination)
}
metadata.Domain = metadata.Destination.Fqdn
metadata.Destination = request.Destination
2023-03-17 12:24:29 +08:00
return r.RoutePacketConnection(ctx, uot.NewConn(conn, *request), metadata)
2023-03-15 13:34:02 +08:00
case uot.LegacyMagicAddress:
r.logger.InfoContext(ctx, "inbound legacy UoT connection")
metadata.Domain = metadata.Destination.Fqdn
2023-03-03 11:34:51 +08:00
metadata.Destination = M.Socksaddr{Addr: netip.IPv4Unspecified()}
2023-03-17 12:24:29 +08:00
return r.RoutePacketConnection(ctx, uot.NewConn(conn, uot.Request{}), metadata)
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)
}
2022-10-07 20:30:27 +08:00
if metadata.InboundOptions.SniffEnabled {
2022-08-02 13:43:25 +08:00
buffer := buf.NewPacket()
buffer.FullReset()
2023-04-13 09:03:08 +08:00
sniffMetadata, err := sniff.PeekStream(ctx, conn, buffer, time.Duration(metadata.InboundOptions.SniffTimeout), sniff.StreamDomainNameQuery, sniff.TLSClientHello, sniff.HTTPHost)
2022-10-12 13:37:06 +08:00
if sniffMetadata != nil {
2022-07-06 12:39:44 +08:00
metadata.Protocol = sniffMetadata.Protocol
metadata.Domain = sniffMetadata.Domain
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
}
2023-04-13 09:03:08 +08:00
} else if err != nil {
r.logger.TraceContext(ctx, "sniffed no protocol: ", err)
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-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 {
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
}
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() {
2022-08-02 13:43:25 +08:00
buffer := buf.NewPacket()
buffer.FullReset()
2022-08-11 10:36:28 +08:00
destination, err := conn.ReadPacket(buffer)
2022-07-06 12:39:44 +08:00
if err != nil {
2022-08-02 13:43:25 +08:00
buffer.Release()
2022-07-06 12:39:44 +08:00
return err
}
2023-08-13 16:49:55 +08: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)
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 14:36:57 +08:00
}
2022-07-06 12:39:44 +08:00
}
}
2022-08-11 10:36:28 +08:00
conn = bufio.NewCachedPacketConn(conn, buffer, destination)
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-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 {
conn = fakeip.NewNATPacketConn(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 {
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 {
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() {
return r.interfaceFinder.update()
} else {
interfaces, err := r.platformInterface.Interfaces()
if err != nil {
return err
}
r.interfaceFinder.updateInterfaces(common.Map(interfaces, func(it platform.NetworkInterface) net.Interface {
return net.Interface{
Name: it.Name,
Index: it.Index,
MTU: it.MTU,
}
}))
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 {
return control.BindToInterfaceFunc(r.InterfaceFinder(), func(network string, address string) (interfaceName string, interfaceIndex int) {
remoteAddr := M.ParseSocksaddr(address).Addr
if C.IsLinux {
return r.InterfaceMonitor().DefaultInterfaceName(remoteAddr), -1
} else {
return "", r.InterfaceMonitor().DefaultInterfaceIndex(remoteAddr)
}
})
}
}
2022-07-15 11:51:51 +08:00
func (r *Router) DefaultInterface() string {
return r.defaultInterface
}
2022-07-24 17:46:25 +08:00
func (r *Router) DefaultMark() int {
return r.defaultMark
}
2022-07-19 22:16:49 +08:00
func (r *Router) Rules() []adapter.Rule {
return r.rules
}
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
}
2023-02-21 14:53:00 +08:00
func (r *Router) TimeFunc() func() time.Time {
if r.timeService == nil {
return nil
}
return r.timeService.TimeFunc()
}
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
}
}
r.ResetNetwork()
2023-07-23 14:42:19 +08:00
return
}
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
}