sing-box/route/router.go

1012 lines
34 KiB
Go
Raw Normal View History

2022-06-30 13:27:56 +00:00
package route
import (
"context"
"net"
2022-07-07 13:47:21 +00:00
"net/netip"
"net/url"
2022-07-02 14:55:10 +00:00
"os"
"os/user"
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"
2022-07-07 13:47:21 +00:00
"github.com/sagernet/sing-box/common/dialer"
"github.com/sagernet/sing-box/common/dialer/conntrack"
2022-07-06 07:01:09 +00:00
"github.com/sagernet/sing-box/common/geoip"
"github.com/sagernet/sing-box/common/geosite"
2022-07-29 16:29:22 +00:00
"github.com/sagernet/sing-box/common/mux"
"github.com/sagernet/sing-box/common/process"
2022-07-06 07:01:09 +00:00
"github.com/sagernet/sing-box/common/sniff"
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"
2023-02-21 06:53:00 +00:00
"github.com/sagernet/sing-box/ntp"
2022-07-06 07:01:09 +00:00
"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"
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"
2022-08-11 02:36:28 +00:00
"github.com/sagernet/sing/common/uot"
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
dnsClient *dns.Client
defaultDomainStrategy dns.DomainStrategy
2022-07-24 06:05:06 +00:00
dnsRules []adapter.DNSRule
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
2022-09-14 04:46:02 +00:00
interfaceFinder myInterfaceFinder
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
processSearcher process.Searcher
2023-02-21 06:53:00 +00:00
timeService adapter.TimeService
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
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)),
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),
2022-07-07 13:47:21 +00:00
defaultDetour: options.Final,
2022-07-11 10:44:59 +00:00
defaultDomainStrategy: dns.DomainStrategy(dnsOptions.Strategy),
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,
2022-10-25 04:55:00 +00:00
platformInterface: platformInterface,
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,
Logger: router.dnsLogger,
})
2022-07-02 14:55:10 +00:00
for i, ruleOptions := range options.Rules {
2022-11-28 05:10:56 +00:00
routeRule, err := NewRule(router, router.logger, ruleOptions)
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 {
2022-11-28 05:10:56 +00:00
dnsRule, err := NewDNSRule(router, router.logger, dnsRuleOptions)
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-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 := 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 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
}
2023-03-25 04:03:23 +00:00
} else if notIpAddress != nil && strings.Contains(server.Address, ".") {
return nil, E.New("parse dns server[", tag, "]: missing address_resolver")
2022-07-07 13:47:21 +00:00
}
}
2023-04-08 00:58:01 +00:00
transport, err := dns.CreateTransport(tag, ctx, logFactory.NewLogger(F.ToString("dns/transport[", tag, "]")), detour, server.Address)
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 {
2023-04-08 00:58:01 +00:00
transports = append(transports, dns.NewLocalTransport("local", N.SystemDialer))
2022-07-07 13:47:21 +00:00
}
defaultTransport = transports[0]
2022-07-02 06:07:50 +00:00
}
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 {
inet4Range = fakeIPOptions.Inet4Range.Build()
}
if fakeIPOptions.Inet6Range != nil {
inet6Range = fakeIPOptions.Inet6Range.Build()
}
router.fakeIPStore = fakeip.NewStore(router, inet4Range, inet6Range)
}
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
2022-09-14 04:46:02 +00:00
if needInterfaceMonitor {
2023-04-18 06:04:09 +00:00
if !usePlatformDefaultInterfaceMonitor {
networkMonitor, err := tun.NewNetworkUpdateMonitor(router)
if err != os.ErrInvalid {
if err != nil {
return nil, err
}
2023-04-18 06:04:09 +00:00
router.networkMonitor = networkMonitor
networkMonitor.RegisterCallback(router.interfaceFinder.update)
interfaceMonitor, err := tun.NewDefaultInterfaceMonitor(router.networkMonitor, tun.DefaultInterfaceMonitorOptions{
OverrideAndroidVPN: options.OverrideAndroidVPN,
UnderNetworkExtension: platformInterface != nil && platformInterface.UnderNetworkExtension(),
})
if err != nil {
return nil, E.New("auto_detect_interface unsupported on current platform")
}
interfaceMonitor.RegisterCallback(router.notifyNetworkUpdate)
router.interfaceMonitor = interfaceMonitor
2023-04-18 06:04:09 +00:00
}
} else {
interfaceMonitor := platformInterface.CreateDefaultInterfaceMonitor(router)
interfaceMonitor.RegisterCallback(router.notifyNetworkUpdate)
router.interfaceMonitor = interfaceMonitor
}
}
2022-08-04 14:01:20 +00:00
needFindProcess := hasRule(options.Rules, isProcessRule) || hasDNSRule(dnsOptions.Rules, isProcessDNSRule) || options.FindProcess
2022-10-25 04:55:00 +00: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 04:55:00 +00:00
if platformInterface != nil {
router.processSearcher = platformInterface
2022-07-24 14:54:16 +00:00
} else {
2022-10-25 04:55:00 +00: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 06:53:00 +00:00
if ntpOptions.Enabled {
router.timeService = ntp.NewService(ctx, router, logFactory.NewLogger("ntp"), ntpOptions)
}
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
}
}
var index, packetIndex int
if defaultOutboundForConnection == nil {
for i, detour := range outbounds {
2022-07-29 16:29:22 +00:00
if common.Contains(detour.Network(), N.NetworkTCP) {
index = i
defaultOutboundForConnection = detour
break
}
}
}
if defaultOutboundForPacketConnection == nil {
for i, detour := range outbounds {
2022-07-29 16:29:22 +00:00
if common.Contains(detour.Network(), N.NetworkUDP) {
packetIndex = i
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
}
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 06:07:50 +00:00
}
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 {
return r.outbounds
}
2022-07-02 14:55:10 +00:00
func (r *Router) Start() error {
2022-07-05 01:05:35 +00:00
if r.needGeoIPDatabase {
2022-07-04 11:34:45 +00:00
err := r.prepareGeoIPDatabase()
if err != nil {
return err
}
2022-07-02 06:07:50 +00:00
}
2022-07-05 01:05:35 +00:00
if r.needGeositeDatabase {
err := r.prepareGeositeDatabase()
if err != nil {
return err
}
}
2023-02-08 08:28:52 +00:00
if r.interfaceMonitor != nil {
err := r.interfaceMonitor.Start()
2022-07-05 01:05:35 +00:00
if err != nil {
return err
}
}
2023-02-08 08:28:52 +00: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 15:36:32 +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
}
2023-02-08 08:28:52 +00:00
for i, rule := range r.rules {
err := rule.Start()
if err != nil {
2023-02-08 08:28:52 +00:00
return E.Cause(err, "initialize rule[", i, "]")
}
}
2023-02-08 08:28:52 +00:00
for i, rule := range r.dnsRules {
err := rule.Start()
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-03-25 04:03:23 +00:00
if r.fakeIPStore != nil {
err := r.fakeIPStore.Start()
if err != nil {
return err
}
}
2023-02-08 08:28:52 +00:00
for i, transport := range r.transports {
err := transport.Start()
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 {
err := r.timeService.Start()
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 {
2023-04-08 00:09:28 +00: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 15:36:32 +00:00
}
2023-04-08 00:09:28 +00: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 15:36:32 +00:00
}
2023-04-08 00:09:28 +00: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, "]")
})
}
if r.geositeReader != nil {
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 08:28:52 +00:00
}
2023-03-25 04:03:23 +00: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 00:09:28 +00:00
return err
2022-07-02 14:55:10 +00:00
}
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
}
2022-07-06 15:11:48 +00:00
func (r *Router) DefaultOutbound(network string) adapter.Outbound {
2022-07-29 16:29:22 +00:00
if network == N.NetworkTCP {
2022-07-06 15:11:48 +00:00
return r.defaultOutboundForConnection
} else {
return r.defaultOutboundForPacketConnection
}
}
2023-03-25 04:03:23 +00:00
func (r *Router) FakeIPStore() adapter.FakeIPStore {
return r.fakeIPStore
}
2022-07-05 01:05:35 +00:00
func (r *Router) RouteConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
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
}
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:
2022-07-29 16:29:22 +00:00
r.logger.InfoContext(ctx, "inbound multiplex connection")
2023-04-20 03:16:22 +00: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 05:34:02 +00: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 04:24:29 +00:00
return r.RoutePacketConnection(ctx, uot.NewConn(conn, *request), metadata)
2023-03-15 05:34:02 +00:00
case uot.LegacyMagicAddress:
r.logger.InfoContext(ctx, "inbound legacy UoT connection")
metadata.Domain = metadata.Destination.Fqdn
2023-03-03 03:34:51 +00:00
metadata.Destination = M.Socksaddr{Addr: netip.IPv4Unspecified()}
2023-03-17 04:24:29 +00:00
return r.RoutePacketConnection(ctx, uot.NewConn(conn, uot.Request{}), metadata)
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")
}
metadata.Destination = M.Socksaddr{
Fqdn: domain,
Port: metadata.Destination.Port,
}
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()
buffer.FullReset()
2023-04-13 01:03:08 +00:00
sniffMetadata, err := sniff.PeekStream(ctx, conn, buffer, time.Duration(metadata.InboundOptions.SniffTimeout), sniff.StreamDomainNameQuery, sniff.TLSClientHello, sniff.HTTPHost)
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-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 {
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
}
2022-08-25 11:25:35 +00:00
metadata.Network = N.NetworkUDP
2023-03-25 04:03:23 +00:00
var originAddress M.Socksaddr
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")
}
originAddress = metadata.Destination
metadata.Destination = M.Socksaddr{
Fqdn: domain,
Port: metadata.Destination.Port,
}
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))
}*/
2022-10-07 12:30:27 +00:00
if metadata.InboundOptions.SniffEnabled {
2022-08-02 05:43:25 +00:00
buffer := buf.NewPacket()
buffer.FullReset()
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
}
2022-10-12 05:37:06 +00:00
sniffMetadata, _ := sniff.PeekPacket(ctx, buffer.Bytes(), sniff.DomainNameQuery, sniff.QUICClientHello, sniff.STUNMessage)
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 packet 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 packet protocol: ", metadata.Protocol)
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-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-03-25 04:03:23 +00:00
if originAddress.IsValid() {
conn = fakeip.NewNATPacketConn(conn, originAddress, metadata.Destination)
}
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 {
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 {
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() {
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 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 {
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 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
}
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
}
2023-02-21 06:53:00 +00:00
func (r *Router) TimeFunc() func() time.Time {
if r.timeService == nil {
return nil
}
return r.timeService.TimeFunc()
}
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
func (r *Router) notifyNetworkUpdate(int) error {
2023-04-18 06:04:09 +00:00
if C.IsAndroid && r.platformInterface == nil {
2022-11-06 02:36:19 +00:00
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)
} else {
r.logger.Info("updated default interface ", r.interfaceMonitor.DefaultInterfaceName(netip.IPv4Unspecified()), ", index ", r.interfaceMonitor.DefaultInterfaceIndex(netip.IPv4Unspecified()))
}
conntrack.Close()
for _, outbound := range r.outbounds {
listener, isListener := outbound.(adapter.InterfaceUpdateListener)
if isListener {
err := listener.InterfaceUpdated()
if err != nil {
return err
}
}
2023-04-18 06:04:09 +00:00
}
return nil
}
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 {
err := listener.InterfaceUpdated()
if err != nil {
return err
}
}
}
return nil
}