sing-box/protocol/tun/inbound.go

476 lines
16 KiB
Go
Raw Permalink Normal View History

2024-11-01 16:39:02 +00:00
package tun
2022-07-09 11:18:37 +00:00
import (
"context"
"net"
2024-06-07 07:55:21 +00:00
"net/netip"
"os"
"runtime"
2022-07-09 11:18:37 +00:00
"strconv"
"strings"
"time"
2022-07-09 11:18:37 +00:00
"github.com/sagernet/sing-box/adapter"
2024-11-01 16:39:02 +00:00
"github.com/sagernet/sing-box/adapter/inbound"
"github.com/sagernet/sing-box/common/taskmonitor"
2022-07-09 11:18:37 +00:00
C "github.com/sagernet/sing-box/constant"
2024-10-18 01:58:03 +00:00
"github.com/sagernet/sing-box/experimental/deprecated"
2022-10-25 04:55:00 +00:00
"github.com/sagernet/sing-box/experimental/libbox/platform"
2022-07-09 11:18:37 +00:00
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
2022-07-11 10:44:59 +00:00
"github.com/sagernet/sing-tun"
2022-07-13 11:01:20 +00:00
"github.com/sagernet/sing/common"
2022-07-09 11:18:37 +00:00
E "github.com/sagernet/sing/common/exceptions"
2024-11-18 10:55:34 +00:00
"github.com/sagernet/sing/common/json/badoption"
2022-07-09 11:18:37 +00:00
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/common/ranges"
2024-06-07 07:55:21 +00:00
"github.com/sagernet/sing/common/x/list"
2024-11-01 16:39:02 +00:00
"github.com/sagernet/sing/service"
2024-06-07 07:55:21 +00:00
"go4.org/netipx"
2022-07-09 11:18:37 +00:00
)
2024-11-01 16:39:02 +00:00
func RegisterInbound(registry *inbound.Registry) {
inbound.Register[option.TunInboundOptions](registry, C.TypeTun, NewInbound)
}
2022-07-09 11:18:37 +00:00
2024-11-01 16:39:02 +00:00
type Inbound struct {
2024-11-10 04:11:21 +00:00
tag string
ctx context.Context
router adapter.Router
networkManager adapter.NetworkManager
logger log.ContextLogger
2024-11-23 14:34:02 +00:00
//nolint:staticcheck
inboundOptions option.InboundOptions
tunOptions tun.Options
2024-10-21 15:38:34 +00:00
udpTimeout time.Duration
2024-06-07 07:55:21 +00:00
stack string
tunIf tun.Tun
tunStack tun.Stack
platformInterface platform.Interface
platformOptions option.TunPlatformOptions
autoRedirect tun.AutoRedirect
routeRuleSet []adapter.RuleSet
routeRuleSetCallback []*list.Element[adapter.RuleSetUpdateCallback]
routeExcludeRuleSet []adapter.RuleSet
routeExcludeRuleSetCallback []*list.Element[adapter.RuleSetUpdateCallback]
routeAddressSet []*netipx.IPSet
routeExcludeAddressSet []*netipx.IPSet
2022-07-09 11:18:37 +00:00
}
2024-11-01 16:39:02 +00:00
func NewInbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TunInboundOptions) (adapter.Inbound, error) {
2024-06-07 07:55:21 +00:00
address := options.Address
2024-10-18 01:58:03 +00:00
var deprecatedAddressUsed bool
2024-11-22 09:17:01 +00:00
2024-06-07 07:55:21 +00:00
//nolint:staticcheck
if len(options.Inet4Address) > 0 {
address = append(address, options.Inet4Address...)
2024-10-18 01:58:03 +00:00
deprecatedAddressUsed = true
2024-06-07 07:55:21 +00:00
}
2024-11-22 09:17:01 +00:00
2024-06-07 07:55:21 +00:00
//nolint:staticcheck
if len(options.Inet6Address) > 0 {
address = append(address, options.Inet6Address...)
2024-10-18 01:58:03 +00:00
deprecatedAddressUsed = true
2024-06-07 07:55:21 +00:00
}
inet4Address := common.Filter(address, func(it netip.Prefix) bool {
return it.Addr().Is4()
})
inet6Address := common.Filter(address, func(it netip.Prefix) bool {
return it.Addr().Is6()
})
routeAddress := options.RouteAddress
2024-11-22 09:17:01 +00:00
2024-06-07 07:55:21 +00:00
//nolint:staticcheck
if len(options.Inet4RouteAddress) > 0 {
routeAddress = append(routeAddress, options.Inet4RouteAddress...)
2024-10-18 01:58:03 +00:00
deprecatedAddressUsed = true
2024-06-07 07:55:21 +00:00
}
2024-11-22 09:17:01 +00:00
2024-06-07 07:55:21 +00:00
//nolint:staticcheck
if len(options.Inet6RouteAddress) > 0 {
routeAddress = append(routeAddress, options.Inet6RouteAddress...)
2024-10-18 01:58:03 +00:00
deprecatedAddressUsed = true
2024-06-07 07:55:21 +00:00
}
inet4RouteAddress := common.Filter(routeAddress, func(it netip.Prefix) bool {
return it.Addr().Is4()
})
inet6RouteAddress := common.Filter(routeAddress, func(it netip.Prefix) bool {
return it.Addr().Is6()
})
routeExcludeAddress := options.RouteExcludeAddress
2024-11-22 09:17:01 +00:00
2024-06-07 07:55:21 +00:00
//nolint:staticcheck
if len(options.Inet4RouteExcludeAddress) > 0 {
routeExcludeAddress = append(routeExcludeAddress, options.Inet4RouteExcludeAddress...)
2024-10-18 01:58:03 +00:00
deprecatedAddressUsed = true
2024-06-07 07:55:21 +00:00
}
2024-11-22 09:17:01 +00:00
2024-06-07 07:55:21 +00:00
//nolint:staticcheck
if len(options.Inet6RouteExcludeAddress) > 0 {
routeExcludeAddress = append(routeExcludeAddress, options.Inet6RouteExcludeAddress...)
2024-10-18 01:58:03 +00:00
deprecatedAddressUsed = true
2024-06-07 07:55:21 +00:00
}
inet4RouteExcludeAddress := common.Filter(routeExcludeAddress, func(it netip.Prefix) bool {
return it.Addr().Is4()
})
inet6RouteExcludeAddress := common.Filter(routeExcludeAddress, func(it netip.Prefix) bool {
return it.Addr().Is6()
})
2024-10-18 01:58:03 +00:00
if deprecatedAddressUsed {
deprecated.Report(ctx, deprecated.OptionTUNAddressX)
}
2024-11-22 09:17:01 +00:00
//nolint:staticcheck
if options.GSO {
deprecated.Report(ctx, deprecated.OptionTUNGSO)
}
2022-07-10 01:15:01 +00:00
tunMTU := options.MTU
if tunMTU == 0 {
tunMTU = 9000
2022-07-10 01:15:01 +00:00
}
var udpTimeout time.Duration
if options.UDPTimeout != 0 {
udpTimeout = time.Duration(options.UDPTimeout)
} else {
udpTimeout = C.UDPTimeout
}
2024-06-07 07:55:21 +00:00
var err error
includeUID := uidToRange(options.IncludeUID)
if len(options.IncludeUIDRange) > 0 {
includeUID, err = parseRange(includeUID, options.IncludeUIDRange)
if err != nil {
return nil, E.Cause(err, "parse include_uid_range")
}
}
excludeUID := uidToRange(options.ExcludeUID)
if len(options.ExcludeUIDRange) > 0 {
excludeUID, err = parseRange(excludeUID, options.ExcludeUIDRange)
if err != nil {
return nil, E.Cause(err, "parse exclude_uid_range")
}
}
2024-06-07 07:55:21 +00:00
tableIndex := options.IPRoute2TableIndex
if tableIndex == 0 {
tableIndex = tun.DefaultIPRoute2TableIndex
}
ruleIndex := options.IPRoute2RuleIndex
if ruleIndex == 0 {
ruleIndex = tun.DefaultIPRoute2RuleIndex
}
inputMark := uint32(options.AutoRedirectInputMark)
2024-06-07 07:55:21 +00:00
if inputMark == 0 {
inputMark = tun.DefaultAutoRedirectInputMark
}
outputMark := uint32(options.AutoRedirectOutputMark)
2024-06-07 07:55:21 +00:00
if outputMark == 0 {
outputMark = tun.DefaultAutoRedirectOutputMark
}
2024-11-10 04:11:21 +00:00
networkManager := service.FromContext[adapter.NetworkManager](ctx)
2024-11-01 16:39:02 +00:00
inbound := &Inbound{
tag: tag,
ctx: ctx,
router: router,
2024-11-10 04:11:21 +00:00
networkManager: networkManager,
logger: logger,
inboundOptions: options.InboundOptions,
tunOptions: tun.Options{
Name: options.InterfaceName,
MTU: tunMTU,
2024-06-07 07:55:21 +00:00
Inet4Address: inet4Address,
Inet6Address: inet6Address,
AutoRoute: options.AutoRoute,
2024-06-07 07:55:21 +00:00
IPRoute2TableIndex: tableIndex,
IPRoute2RuleIndex: ruleIndex,
AutoRedirectInputMark: inputMark,
AutoRedirectOutputMark: outputMark,
StrictRoute: options.StrictRoute,
IncludeInterface: options.IncludeInterface,
ExcludeInterface: options.ExcludeInterface,
2024-06-07 07:55:21 +00:00
Inet4RouteAddress: inet4RouteAddress,
Inet6RouteAddress: inet6RouteAddress,
Inet4RouteExcludeAddress: inet4RouteExcludeAddress,
Inet6RouteExcludeAddress: inet6RouteExcludeAddress,
IncludeUID: includeUID,
ExcludeUID: excludeUID,
IncludeAndroidUser: options.IncludeAndroidUser,
IncludePackage: options.IncludePackage,
ExcludePackage: options.ExcludePackage,
2024-11-10 04:11:21 +00:00
InterfaceMonitor: networkManager.InterfaceMonitor(),
},
2024-11-23 14:34:02 +00:00
udpTimeout: udpTimeout,
stack: options.Stack,
platformInterface: service.FromContext[platform.Interface](ctx),
platformOptions: common.PtrValueOrDefault(options.Platform),
2024-06-07 07:55:21 +00:00
}
if options.AutoRedirect {
if !options.AutoRoute {
return nil, E.New("`auto_route` is required by `auto_redirect`")
}
disableNFTables, dErr := strconv.ParseBool(os.Getenv("DISABLE_NFTABLES"))
inbound.autoRedirect, err = tun.NewAutoRedirect(tun.AutoRedirectOptions{
TunOptions: &inbound.tunOptions,
Context: ctx,
2024-10-21 15:38:34 +00:00
Handler: (*autoRedirectHandler)(inbound),
2024-06-07 07:55:21 +00:00
Logger: logger,
2024-11-10 04:11:21 +00:00
NetworkMonitor: networkManager.NetworkMonitor(),
InterfaceFinder: networkManager.InterfaceFinder(),
2024-06-07 07:55:21 +00:00
TableName: "sing-box",
DisableNFTables: dErr == nil && disableNFTables,
RouteAddressSet: &inbound.routeAddressSet,
RouteExcludeAddressSet: &inbound.routeExcludeAddressSet,
})
if err != nil {
return nil, E.Cause(err, "initialize auto-redirect")
}
if runtime.GOOS != "android" {
var markMode bool
for _, routeAddressSet := range options.RouteAddressSet {
ruleSet, loaded := router.RuleSet(routeAddressSet)
if !loaded {
return nil, E.New("parse route_address_set: rule-set not found: ", routeAddressSet)
}
ruleSet.IncRef()
inbound.routeRuleSet = append(inbound.routeRuleSet, ruleSet)
markMode = true
}
for _, routeExcludeAddressSet := range options.RouteExcludeAddressSet {
ruleSet, loaded := router.RuleSet(routeExcludeAddressSet)
if !loaded {
return nil, E.New("parse route_exclude_address_set: rule-set not found: ", routeExcludeAddressSet)
}
ruleSet.IncRef()
inbound.routeExcludeRuleSet = append(inbound.routeExcludeRuleSet, ruleSet)
markMode = true
}
if markMode {
inbound.tunOptions.AutoRedirectMarkMode = true
2024-11-10 04:11:21 +00:00
err = networkManager.RegisterAutoRedirectOutputMark(inbound.tunOptions.AutoRedirectOutputMark)
2024-06-07 07:55:21 +00:00
if err != nil {
return nil, err
}
}
}
}
return inbound, nil
2022-07-09 11:18:37 +00:00
}
2024-11-18 10:55:34 +00:00
func uidToRange(uidList badoption.Listable[uint32]) []ranges.Range[uint32] {
return common.Map(uidList, func(uid uint32) ranges.Range[uint32] {
return ranges.NewSingle(uid)
})
}
func parseRange(uidRanges []ranges.Range[uint32], rangeList []string) ([]ranges.Range[uint32], error) {
for _, uidRange := range rangeList {
if !strings.Contains(uidRange, ":") {
return nil, E.New("missing ':' in range: ", uidRange)
}
subIndex := strings.Index(uidRange, ":")
if subIndex == 0 {
return nil, E.New("missing range start: ", uidRange)
} else if subIndex == len(uidRange)-1 {
return nil, E.New("missing range end: ", uidRange)
}
var start, end uint64
var err error
2024-06-07 07:55:21 +00:00
start, err = strconv.ParseUint(uidRange[:subIndex], 0, 32)
if err != nil {
return nil, E.Cause(err, "parse range start")
}
2024-06-07 07:55:21 +00:00
end, err = strconv.ParseUint(uidRange[subIndex+1:], 0, 32)
if err != nil {
return nil, E.Cause(err, "parse range end")
}
uidRanges = append(uidRanges, ranges.New(uint32(start), uint32(end)))
}
return uidRanges, nil
}
2024-11-01 16:39:02 +00:00
func (t *Inbound) Type() string {
2022-07-09 11:18:37 +00:00
return C.TypeTun
}
2024-11-01 16:39:02 +00:00
func (t *Inbound) Tag() string {
2022-07-09 11:18:37 +00:00
return t.tag
}
2024-11-21 10:10:41 +00:00
func (t *Inbound) Start(stage adapter.StartStage) error {
switch stage {
case adapter.StartStateStart:
if C.IsAndroid && t.platformInterface == nil {
t.tunOptions.BuildAndroidRules(t.networkManager.PackageManager())
2024-06-07 07:55:21 +00:00
}
2024-11-21 10:10:41 +00:00
if t.tunOptions.Name == "" {
t.tunOptions.Name = tun.CalculateInterfaceName("")
}
var (
tunInterface tun.Tun
err error
)
monitor := taskmonitor.New(t.logger, C.StartTimeout)
monitor.Start("open tun interface")
if t.platformInterface != nil {
tunInterface, err = t.platformInterface.OpenTun(&t.tunOptions, t.platformOptions)
} else {
tunInterface, err = tun.New(t.tunOptions)
2024-06-07 07:55:21 +00:00
}
monitor.Finish()
if err != nil {
2024-11-21 10:10:41 +00:00
return E.Cause(err, "configure tun interface")
2024-06-07 07:55:21 +00:00
}
2024-11-21 10:10:41 +00:00
t.logger.Trace("creating stack")
t.tunIf = tunInterface
var (
forwarderBindInterface bool
includeAllNetworks bool
)
if t.platformInterface != nil {
forwarderBindInterface = true
includeAllNetworks = t.platformInterface.IncludeAllNetworks()
2024-06-07 07:55:21 +00:00
}
2024-11-21 10:10:41 +00:00
tunStack, err := tun.NewStack(t.stack, tun.StackOptions{
Context: t.ctx,
Tun: tunInterface,
TunOptions: t.tunOptions,
UDPTimeout: t.udpTimeout,
Handler: t,
Logger: t.logger,
ForwarderBindInterface: forwarderBindInterface,
InterfaceFinder: t.networkManager.InterfaceFinder(),
IncludeAllNetworks: includeAllNetworks,
})
if err != nil {
return err
}
t.tunStack = tunStack
t.logger.Info("started at ", t.tunOptions.Name)
case adapter.StartStatePostStart:
monitor := taskmonitor.New(t.logger, C.StartTimeout)
monitor.Start("starting tun stack")
err := t.tunStack.Start()
monitor.Finish()
if err != nil {
return E.Cause(err, "starting tun stack")
}
monitor.Start("starting tun interface")
err = t.tunIf.Start()
monitor.Finish()
if err != nil {
return E.Cause(err, "starting TUN interface")
}
if t.autoRedirect != nil {
t.routeAddressSet = common.FlatMap(t.routeRuleSet, adapter.RuleSet.ExtractIPSet)
for _, routeRuleSet := range t.routeRuleSet {
ipSets := routeRuleSet.ExtractIPSet()
if len(ipSets) == 0 {
t.logger.Warn("route_address_set: no destination IP CIDR rules found in rule-set: ", routeRuleSet.Name())
}
t.routeAddressSet = append(t.routeAddressSet, ipSets...)
}
t.routeExcludeAddressSet = common.FlatMap(t.routeExcludeRuleSet, adapter.RuleSet.ExtractIPSet)
for _, routeExcludeRuleSet := range t.routeExcludeRuleSet {
ipSets := routeExcludeRuleSet.ExtractIPSet()
if len(ipSets) == 0 {
t.logger.Warn("route_address_set: no destination IP CIDR rules found in rule-set: ", routeExcludeRuleSet.Name())
}
t.routeExcludeAddressSet = append(t.routeExcludeAddressSet, ipSets...)
}
monitor.Start("initialize auto-redirect")
err := t.autoRedirect.Start()
monitor.Finish()
if err != nil {
return E.Cause(err, "auto-redirect")
}
for _, routeRuleSet := range t.routeRuleSet {
t.routeRuleSetCallback = append(t.routeRuleSetCallback, routeRuleSet.RegisterCallback(t.updateRouteAddressSet))
routeRuleSet.DecRef()
}
for _, routeExcludeRuleSet := range t.routeExcludeRuleSet {
t.routeExcludeRuleSetCallback = append(t.routeExcludeRuleSetCallback, routeExcludeRuleSet.RegisterCallback(t.updateRouteAddressSet))
routeExcludeRuleSet.DecRef()
}
t.routeAddressSet = nil
t.routeExcludeAddressSet = nil
2024-06-07 07:55:21 +00:00
}
}
return nil
}
2024-11-01 16:39:02 +00:00
func (t *Inbound) updateRouteAddressSet(it adapter.RuleSet) {
2024-06-07 07:55:21 +00:00
t.routeAddressSet = common.FlatMap(t.routeRuleSet, adapter.RuleSet.ExtractIPSet)
t.routeExcludeAddressSet = common.FlatMap(t.routeExcludeRuleSet, adapter.RuleSet.ExtractIPSet)
t.autoRedirect.UpdateRouteAddressSet()
t.routeAddressSet = nil
t.routeExcludeAddressSet = nil
}
2024-11-01 16:39:02 +00:00
func (t *Inbound) Close() error {
2022-07-13 11:01:20 +00:00
return common.Close(
t.tunStack,
t.tunIf,
2024-06-07 07:55:21 +00:00
t.autoRedirect,
2022-07-09 11:18:37 +00:00
)
}
2024-11-01 16:39:02 +00:00
func (t *Inbound) PrepareConnection(network string, source M.Socksaddr, destination M.Socksaddr) error {
2024-10-22 13:28:22 +00:00
return t.router.PreMatch(adapter.InboundContext{
Inbound: t.tag,
InboundType: C.TypeTun,
Network: network,
Source: source,
Destination: destination,
InboundOptions: t.inboundOptions,
})
2024-10-21 15:38:34 +00:00
}
2024-11-01 16:39:02 +00:00
func (t *Inbound) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
2022-07-12 07:17:29 +00:00
ctx = log.ContextWithNewID(ctx)
2022-07-09 11:18:37 +00:00
var metadata adapter.InboundContext
metadata.Inbound = t.tag
2022-07-19 14:16:49 +00:00
metadata.InboundType = C.TypeTun
2024-10-21 15:38:34 +00:00
metadata.Source = source
metadata.Destination = destination
2024-11-23 14:34:02 +00:00
//nolint:staticcheck
2022-10-07 12:30:27 +00:00
metadata.InboundOptions = t.inboundOptions
2024-10-21 15:38:34 +00:00
t.logger.InfoContext(ctx, "inbound connection from ", metadata.Source)
2022-07-12 07:17:29 +00:00
t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
2024-10-21 15:38:34 +00:00
t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
2022-07-09 11:18:37 +00:00
}
2024-11-01 16:39:02 +00:00
func (t *Inbound) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
2022-07-12 07:17:29 +00:00
ctx = log.ContextWithNewID(ctx)
2022-07-09 11:18:37 +00:00
var metadata adapter.InboundContext
metadata.Inbound = t.tag
2022-07-19 14:16:49 +00:00
metadata.InboundType = C.TypeTun
2024-10-21 15:38:34 +00:00
metadata.Source = source
metadata.Destination = destination
2024-11-23 14:34:02 +00:00
//nolint:staticcheck
2022-10-07 12:30:27 +00:00
metadata.InboundOptions = t.inboundOptions
2022-07-12 07:17:29 +00:00
t.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source)
t.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
2024-10-21 15:38:34 +00:00
t.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
2022-07-09 11:18:37 +00:00
}
2024-11-01 16:39:02 +00:00
type autoRedirectHandler Inbound
2024-10-21 15:38:34 +00:00
func (t *autoRedirectHandler) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
ctx = log.ContextWithNewID(ctx)
var metadata adapter.InboundContext
metadata.Inbound = t.tag
metadata.InboundType = C.TypeTun
metadata.Source = source
metadata.Destination = destination
2024-11-23 14:34:02 +00:00
//nolint:staticcheck
2024-10-21 15:38:34 +00:00
metadata.InboundOptions = t.inboundOptions
t.logger.InfoContext(ctx, "inbound redirect connection from ", metadata.Source)
t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
2022-07-09 11:18:37 +00:00
}