sing-box/route/router.go

982 lines
30 KiB
Go
Raw Normal View History

2022-06-30 13:27:56 +00:00
package route
import (
"context"
2022-07-02 14:55:10 +00:00
"io"
2022-06-30 13:27:56 +00:00
"net"
2022-07-02 14:55:10 +00:00
"net/http"
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-02 14:55:10 +00:00
"path/filepath"
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"
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"
2022-07-24 14:54:16 +00:00
"github.com/sagernet/sing-box/common/warning"
2022-07-06 07:01:09 +00:00
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
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"
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"
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"
"github.com/sagernet/sing/common/rw"
2022-08-11 02:36:28 +00:00
"github.com/sagernet/sing/common/uot"
2022-06-30 13:27:56 +00:00
)
2022-07-24 14:54:16 +00:00
var warnDefaultInterfaceOnUnsupportedPlatform = warning.New(
func() bool {
2022-08-05 08:55:46 +00:00
return !(C.IsLinux || C.IsWindows || C.IsDarwin)
2022-07-24 14:54:16 +00:00
},
"route option `default_mark` is only supported on Linux and Windows",
)
var warnDefaultMarkOnNonLinux = warning.New(
func() bool {
return !C.IsLinux
},
"route option `default_mark` is only supported on Linux",
)
var warnFindProcessOnUnsupportedPlatform = warning.New(
func() bool {
return !(C.IsLinux || C.IsWindows || C.IsDarwin)
},
2022-07-27 04:03:07 +00:00
"route option `find_process` is only supported on Linux, Windows, and macOS",
2022-07-24 14:54:16 +00:00
)
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
interfaceBindManager control.BindManager
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
trafficController adapter.TrafficController
processSearcher process.Searcher
2022-06-30 13:27:56 +00:00
}
2022-08-04 14:01:20 +00:00
func NewRouter(ctx context.Context, logger log.ContextLogger, dnsLogger log.ContextLogger, options option.RouteOptions, dnsOptions option.DNSOptions, inbounds []option.Inbound) (*Router, error) {
2022-07-24 14:54:16 +00:00
if options.DefaultInterface != "" {
warnDefaultInterfaceOnUnsupportedPlatform.Check()
}
if options.DefaultMark != 0 {
warnDefaultMarkOnNonLinux.Check()
}
if options.FindProcess {
warnFindProcessOnUnsupportedPlatform.Check()
}
2022-07-02 14:55:10 +00:00
router := &Router{
2022-07-07 13:47:21 +00:00
ctx: ctx,
2022-07-12 07:17:29 +00:00
logger: logger,
dnsLogger: dnsLogger,
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,
dnsClient: dns.NewClient(dnsOptions.DNSClientOptions.DisableCache, dnsOptions.DNSClientOptions.DisableExpire),
2022-07-11 10:44:59 +00:00
defaultDomainStrategy: dns.DomainStrategy(dnsOptions.Strategy),
2022-07-14 15:06:03 +00:00
interfaceBindManager: control.NewBindManager(),
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-06-30 13:27:56 +00:00
}
2022-07-02 14:55:10 +00:00
for i, ruleOptions := range options.Rules {
2022-07-07 13:47:21 +00:00
routeRule, err := NewRule(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 {
dnsRule, err := NewDNSRule(router, logger, dnsRuleOptions)
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
}
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)
}
transportTags[i] = tag
transportTagMap[tag] = true
}
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 {
case "local", "rcode":
default:
2022-07-10 01:15:01 +00:00
serverURL, err := url.Parse(server.Address)
if err != nil {
return nil, err
2022-07-07 13:47:21 +00:00
}
2022-07-10 01:15:01 +00:00
serverAddress := serverURL.Hostname()
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
}
2022-07-24 05:44:44 +00:00
} else if notIpAddress != nil && (serverURL == nil || serverURL.Scheme != "rcode") {
2022-07-10 01:15:01 +00:00
return nil, E.New("parse dns server[", tag, "]: missing address_resolver")
2022-07-07 13:47:21 +00:00
}
}
2022-07-11 10:44:59 +00:00
transport, err := dns.NewTransport(ctx, 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]
})
return nil, E.New("found circular reference in dns servers: ", strings.Join(unresolvedTags, " "))
}
2022-07-11 10:44:59 +00:00
var defaultTransport dns.Transport
2022-07-13 11:01:20 +00:00
if dnsOptions.Final != "" {
2022-08-10 04:18:03 +00:00
defaultTransport = dummyTransportMap[dnsOptions.Final]
2022-07-07 13:47:21 +00:00
if defaultTransport == nil {
2022-08-10 04:18:03 +00:00
return nil, E.New("default dns server not found: ", dnsOptions.Final)
2022-07-07 13:47:21 +00:00
}
}
if defaultTransport == nil {
if len(transports) == 0 {
transports = append(transports, dns.NewLocalTransport())
}
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
2022-08-04 14:01:20 +00:00
needInterfaceMonitor := options.AutoDetectInterface ||
C.IsDarwin && common.Any(inbounds, func(inbound option.Inbound) bool {
return inbound.HTTPOptions.SetSystemProxy || inbound.MixedOptions.SetSystemProxy
})
if router.interfaceBindManager != nil || needInterfaceMonitor {
networkMonitor, err := tun.NewNetworkUpdateMonitor(router)
2022-07-14 15:06:03 +00:00
if err == nil {
router.networkMonitor = networkMonitor
if router.interfaceBindManager != nil {
networkMonitor.RegisterCallback(router.interfaceBindManager.Update)
}
}
}
2022-08-04 14:01:20 +00:00
if router.networkMonitor != nil && needInterfaceMonitor {
interfaceMonitor, err := tun.NewDefaultInterfaceMonitor(router.networkMonitor)
if err != nil {
2022-07-13 11:01:20 +00:00
return nil, E.New("auto_detect_interface unsupported on current platform")
}
2022-08-04 14:01:20 +00:00
interfaceMonitor.RegisterCallback(func() error {
router.logger.Info("updated default interface ", router.interfaceMonitor.DefaultInterfaceName(netip.IPv4Unspecified()), ", index ", router.interfaceMonitor.DefaultInterfaceIndex(netip.IPv4Unspecified()))
2022-08-04 14:01:20 +00:00
return nil
})
2022-07-14 15:06:03 +00:00
router.interfaceMonitor = interfaceMonitor
}
2022-08-04 14:01:20 +00:00
needFindProcess := hasRule(options.Rules, isProcessRule) || hasDNSRule(dnsOptions.Rules, isProcessDNSRule) || options.FindProcess
needPackageManager := C.IsAndroid && (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 {
searcher, err := process.NewSearcher(process.Config{
Logger: logger,
PackageManager: router.packageManager,
})
if err != nil {
2022-07-24 14:54:16 +00:00
if err != os.ErrInvalid {
logger.Warn(E.Cause(err, "create process searcher"))
}
} else {
router.processSearcher = searcher
}
}
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
}
}
for _, rule := range r.rules {
err := rule.Start()
if err != nil {
return err
}
}
2022-07-07 15:36:32 +00:00
for _, rule := range r.dnsRules {
err := rule.Start()
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
}
if r.interfaceMonitor != nil {
err := r.interfaceMonitor.Start()
if err != nil {
return err
}
}
2022-07-14 15:06:03 +00:00
if r.networkMonitor != nil {
err := r.networkMonitor.Start()
if err != nil {
return err
}
}
if r.packageManager != nil {
err := r.packageManager.Start()
if err != nil {
return err
}
}
2022-07-02 06:07:50 +00:00
return nil
}
2022-07-02 14:55:10 +00:00
func (r *Router) Close() error {
2022-07-07 15:36:32 +00:00
for _, rule := range r.rules {
err := rule.Close()
if err != nil {
return err
}
}
for _, rule := range r.dnsRules {
err := rule.Close()
if err != nil {
return err
}
}
2022-07-02 14:55:10 +00:00
return common.Close(
2022-07-05 01:05:35 +00:00
common.PtrOrNil(r.geoIPReader),
r.interfaceMonitor,
2022-07-14 15:06:03 +00:00
r.networkMonitor,
r.packageManager,
2022-07-02 14:55:10 +00:00
)
}
2022-07-05 05:23:47 +00:00
func (r *Router) GeoIPReader() *geoip.Reader {
2022-07-05 01:05:35 +00:00
return r.geoIPReader
}
2022-07-08 03:00:46 +00:00
func (r *Router) LoadGeosite(code string) (adapter.Rule, error) {
rule, cached := r.geositeCache[code]
if cached {
return rule, nil
}
items, err := r.geositeReader.Read(code)
if err != nil {
return nil, err
}
rule, err = NewDefaultRule(r, nil, geosite.Compile(items))
if err != nil {
return nil, err
}
r.geositeCache[code] = rule
return rule, nil
2022-07-05 01:05:35 +00:00
}
func (r *Router) Outbound(tag string) (adapter.Outbound, bool) {
outbound, loaded := r.outboundByTag[tag]
return outbound, loaded
}
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
}
}
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")
return mux.NewConnection(ctx, r, r, r.logger, conn, metadata)
2022-08-11 02:36:28 +00:00
case uot.UOTMagicAddress:
r.logger.InfoContext(ctx, "inbound UoT connection")
metadata.Destination = M.Socksaddr{}
return r.RoutePacketConnection(ctx, uot.NewClientConn(conn), metadata)
2022-07-29 16:29:22 +00:00
}
2022-07-06 04:39:44 +00:00
if metadata.SniffEnabled {
2022-08-02 05:43:25 +00:00
buffer := buf.NewPacket()
buffer.FullReset()
2022-10-12 05:37:06 +00:00
sniffMetadata, _ := sniff.PeekStream(ctx, conn, buffer, sniff.StreamDomainNameQuery, sniff.TLSClientHello, sniff.HTTPHost)
if sniffMetadata != nil {
2022-07-06 04:39:44 +00:00
metadata.Protocol = sniffMetadata.Protocol
metadata.Domain = sniffMetadata.Domain
if metadata.SniffOverrideDestination && sniff.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
}
}
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
}
}
2022-07-11 10:44:59 +00:00
if metadata.Destination.IsFqdn() && metadata.DomainStrategy != dns.DomainStrategyAsIS {
2022-07-07 15:36:32 +00:00
addresses, err := r.Lookup(adapter.WithContext(ctx, &metadata), metadata.Destination.Fqdn, metadata.DomainStrategy)
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
}
matchedRule, detour := r.match(ctx, &metadata, r.defaultOutboundForConnection)
2022-07-29 16:29:22 +00:00
if !common.Contains(detour.Network(), N.NetworkTCP) {
2022-07-05 01:05:35 +00:00
conn.Close()
return E.New("missing supported outbound, closing connection")
}
2022-07-19 14:16:49 +00:00
if r.trafficController != nil {
2022-07-25 22:56:13 +00:00
trackerConn, tracker := r.trafficController.RoutedConnection(ctx, conn, metadata, matchedRule)
defer tracker.Leave()
conn = trackerConn
2022-07-19 14:16:49 +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
2022-07-10 01:15:01 +00:00
if metadata.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
if metadata.SniffOverrideDestination && sniff.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
}
2022-08-11 02:36:28 +00:00
if metadata.Destination.IsFqdn() && metadata.Destination.Fqdn != uot.UOTMagicAddress && metadata.DomainStrategy != dns.DomainStrategyAsIS {
2022-07-07 15:36:32 +00:00
addresses, err := r.Lookup(adapter.WithContext(ctx, &metadata), metadata.Destination.Fqdn, metadata.DomainStrategy)
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
}
matchedRule, detour := r.match(ctx, &metadata, r.defaultOutboundForPacketConnection)
2022-07-29 16:29:22 +00:00
if !common.Contains(detour.Network(), N.NetworkUDP) {
2022-07-05 01:05:35 +00:00
conn.Close()
return E.New("missing supported outbound, closing packet connection")
}
2022-07-19 14:16:49 +00:00
if r.trafficController != nil {
2022-07-25 22:56:13 +00:00
trackerConn, tracker := r.trafficController.RoutedPacketConnection(ctx, conn, metadata, matchedRule)
defer tracker.Leave()
conn = trackerConn
2022-07-19 14:16:49 +00:00
}
2022-07-07 15:36:32 +00:00
return detour.NewPacketConnection(ctx, conn, metadata)
2022-07-07 13:47:21 +00:00
}
func (r *Router) match(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.DebugContext(ctx, "failed to search process: ", err)
} else {
if processInfo.ProcessPath != "" {
r.logger.DebugContext(ctx, "found process path: ", processInfo.ProcessPath)
} else if processInfo.PackageName != "" {
r.logger.DebugContext(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.DebugContext(ctx, "found user: ", processInfo.User)
} else {
r.logger.DebugContext(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-07-14 15:06:03 +00:00
func (r *Router) InterfaceBindManager() control.BindManager {
return r.interfaceBindManager
}
func (r *Router) AutoDetectInterface() bool {
return r.autoDetectInterface
}
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
}
2022-07-19 14:16:49 +00:00
func (r *Router) SetTrafficController(controller adapter.TrafficController) {
r.trafficController = controller
}
func hasRule(rules []option.Rule, cond func(rule option.DefaultRule) bool) bool {
2022-07-05 01:05:35 +00:00
for _, rule := range rules {
switch rule.Type {
case C.RuleTypeDefault:
if cond(rule.DefaultOptions) {
return true
}
case C.RuleTypeLogical:
for _, subRule := range rule.LogicalOptions.Rules {
if cond(subRule) {
return true
}
}
}
}
return false
}
func hasDNSRule(rules []option.DNSRule, cond func(rule option.DefaultDNSRule) bool) bool {
2022-07-07 13:47:21 +00:00
for _, rule := range rules {
switch rule.Type {
case C.RuleTypeDefault:
if cond(rule.DefaultOptions) {
return true
}
case C.RuleTypeLogical:
for _, subRule := range rule.LogicalOptions.Rules {
if cond(subRule) {
return true
}
}
}
}
return false
}
2022-07-05 01:05:35 +00:00
func isGeoIPRule(rule option.DefaultRule) bool {
return len(rule.SourceGeoIP) > 0 && common.Any(rule.SourceGeoIP, notPrivateNode) || len(rule.GeoIP) > 0 && common.Any(rule.GeoIP, notPrivateNode)
}
2022-07-07 13:47:21 +00:00
func isGeoIPDNSRule(rule option.DefaultDNSRule) bool {
return len(rule.SourceGeoIP) > 0 && common.Any(rule.SourceGeoIP, notPrivateNode)
}
2022-07-05 01:05:35 +00:00
func isGeositeRule(rule option.DefaultRule) bool {
return len(rule.Geosite) > 0
}
2022-07-07 13:47:21 +00:00
func isGeositeDNSRule(rule option.DefaultDNSRule) bool {
return len(rule.Geosite) > 0
}
func isProcessRule(rule option.DefaultRule) bool {
return len(rule.ProcessName) > 0 || len(rule.ProcessPath) > 0 || len(rule.PackageName) > 0 || len(rule.User) > 0 || len(rule.UserID) > 0
}
func isProcessDNSRule(rule option.DefaultDNSRule) bool {
return len(rule.ProcessName) > 0 || len(rule.ProcessPath) > 0 || len(rule.PackageName) > 0 || len(rule.User) > 0 || len(rule.UserID) > 0
}
2022-07-05 01:05:35 +00:00
func notPrivateNode(code string) bool {
return code != "private"
2022-07-02 14:55:10 +00:00
}
2022-07-04 11:34:45 +00:00
func (r *Router) prepareGeoIPDatabase() error {
2022-07-02 14:55:10 +00:00
var geoPath string
2022-07-05 01:05:35 +00:00
if r.geoIPOptions.Path != "" {
geoPath = r.geoIPOptions.Path
2022-07-02 14:55:10 +00:00
} else {
2022-07-05 05:23:47 +00:00
geoPath = "geoip.db"
2022-07-06 06:44:51 +00:00
if foundPath, loaded := C.FindPath(geoPath); loaded {
2022-07-04 11:34:45 +00:00
geoPath = foundPath
}
2022-07-02 14:55:10 +00:00
}
2022-07-04 11:34:45 +00:00
if !rw.FileExists(geoPath) {
2022-07-02 14:55:10 +00:00
r.logger.Warn("geoip database not exists: ", geoPath)
var err error
for attempts := 0; attempts < 3; attempts++ {
err = r.downloadGeoIPDatabase(geoPath)
if err == nil {
break
}
r.logger.Error("download geoip database: ", err)
os.Remove(geoPath)
time.Sleep(10 * time.Second)
}
if err != nil {
2022-07-04 11:34:45 +00:00
return err
2022-07-02 14:55:10 +00:00
}
}
2022-07-05 05:23:47 +00:00
geoReader, codes, err := geoip.Open(geoPath)
if err != nil {
2022-07-04 11:34:45 +00:00
return E.Cause(err, "open geoip database")
2022-07-02 14:55:10 +00:00
}
2022-07-05 05:23:47 +00:00
r.logger.Info("loaded geoip database: ", len(codes), " codes")
r.geoIPReader = geoReader
2022-07-04 11:34:45 +00:00
return nil
2022-07-02 14:55:10 +00:00
}
2022-07-05 01:05:35 +00:00
func (r *Router) prepareGeositeDatabase() error {
var geoPath string
if r.geositeOptions.Path != "" {
geoPath = r.geositeOptions.Path
2022-07-05 01:05:35 +00:00
} else {
geoPath = "geosite.db"
2022-07-06 06:44:51 +00:00
if foundPath, loaded := C.FindPath(geoPath); loaded {
2022-07-05 01:05:35 +00:00
geoPath = foundPath
}
}
if !rw.FileExists(geoPath) {
r.logger.Warn("geosite database not exists: ", geoPath)
var err error
for attempts := 0; attempts < 3; attempts++ {
err = r.downloadGeositeDatabase(geoPath)
if err == nil {
break
}
r.logger.Error("download geosite database: ", err)
os.Remove(geoPath)
time.Sleep(10 * time.Second)
}
if err != nil {
return err
}
}
2022-07-05 05:23:47 +00:00
geoReader, codes, err := geosite.Open(geoPath)
2022-07-05 01:05:35 +00:00
if err == nil {
2022-07-05 05:23:47 +00:00
r.logger.Info("loaded geosite database: ", len(codes), " codes")
2022-07-05 01:05:35 +00:00
r.geositeReader = geoReader
} else {
return E.Cause(err, "open geosite database")
}
return nil
}
2022-07-02 14:55:10 +00:00
func (r *Router) downloadGeoIPDatabase(savePath string) error {
var downloadURL string
2022-07-05 01:05:35 +00:00
if r.geoIPOptions.DownloadURL != "" {
downloadURL = r.geoIPOptions.DownloadURL
2022-07-02 14:55:10 +00:00
} else {
2022-07-05 05:23:47 +00:00
downloadURL = "https://github.com/SagerNet/sing-geoip/releases/latest/download/geoip.db"
2022-07-02 14:55:10 +00:00
}
r.logger.Info("downloading geoip database")
var detour adapter.Outbound
2022-07-05 01:05:35 +00:00
if r.geoIPOptions.DownloadDetour != "" {
outbound, loaded := r.Outbound(r.geoIPOptions.DownloadDetour)
2022-07-02 14:55:10 +00:00
if !loaded {
2022-07-05 01:05:35 +00:00
return E.New("detour outbound not found: ", r.geoIPOptions.DownloadDetour)
2022-07-02 14:55:10 +00:00
}
detour = outbound
} else {
detour = r.defaultOutboundForConnection
2022-07-02 14:55:10 +00:00
}
if parentDir := filepath.Dir(savePath); parentDir != "" {
os.MkdirAll(parentDir, 0o755)
}
saveFile, err := os.OpenFile(savePath, os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
return E.Cause(err, "open output file: ", downloadURL)
}
defer saveFile.Close()
httpClient := &http.Client{
Transport: &http.Transport{
ForceAttemptHTTP2: true,
TLSHandshakeTimeout: 5 * time.Second,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return detour.DialContext(ctx, network, M.ParseSocksaddr(addr))
},
},
}
response, err := httpClient.Get(downloadURL)
if err != nil {
return err
}
defer response.Body.Close()
_, err = io.Copy(saveFile, response.Body)
return err
}
2022-07-05 01:05:35 +00:00
func (r *Router) downloadGeositeDatabase(savePath string) error {
var downloadURL string
if r.geositeOptions.DownloadURL != "" {
downloadURL = r.geositeOptions.DownloadURL
} else {
downloadURL = "https://github.com/SagerNet/sing-geosite/releases/latest/download/geosite.db"
}
r.logger.Info("downloading geosite database")
2022-07-05 01:05:35 +00:00
var detour adapter.Outbound
if r.geositeOptions.DownloadDetour != "" {
outbound, loaded := r.Outbound(r.geositeOptions.DownloadDetour)
if !loaded {
return E.New("detour outbound not found: ", r.geositeOptions.DownloadDetour)
2022-07-05 01:05:35 +00:00
}
detour = outbound
} else {
detour = r.defaultOutboundForConnection
}
2022-07-02 14:55:10 +00:00
2022-07-05 01:05:35 +00:00
if parentDir := filepath.Dir(savePath); parentDir != "" {
os.MkdirAll(parentDir, 0o755)
}
2022-07-02 14:55:10 +00:00
2022-07-05 01:05:35 +00:00
saveFile, err := os.OpenFile(savePath, os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
return E.Cause(err, "open output file: ", downloadURL)
}
2022-07-05 01:05:35 +00:00
defer saveFile.Close()
2022-07-02 14:55:10 +00:00
2022-07-05 01:05:35 +00:00
httpClient := &http.Client{
Transport: &http.Transport{
ForceAttemptHTTP2: true,
TLSHandshakeTimeout: 5 * time.Second,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return detour.DialContext(ctx, network, M.ParseSocksaddr(addr))
},
},
2022-07-02 14:55:10 +00:00
}
2022-07-05 01:05:35 +00:00
response, err := httpClient.Get(downloadURL)
if err != nil {
return err
}
defer response.Body.Close()
_, err = io.Copy(saveFile, response.Body)
return err
2022-07-02 14:55:10 +00:00
}
2022-07-14 15:06:03 +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)
}