sing-box/inbound/tun.go

221 lines
6.7 KiB
Go
Raw Normal View History

2022-07-09 11:18:37 +00:00
package inbound
import (
"context"
"net"
"strconv"
"strings"
"time"
2022-07-09 11:18:37 +00:00
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/common/canceler"
2022-07-09 11:18:37 +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"
"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"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/common/ranges"
2022-07-09 11:18:37 +00:00
)
var _ adapter.Inbound = (*Tun)(nil)
type Tun struct {
2022-08-07 09:21:49 +00:00
tag string
ctx context.Context
router adapter.Router
logger log.ContextLogger
inboundOptions option.InboundOptions
tunOptions tun.Options
endpointIndependentNat bool
udpTimeout int64
2022-08-07 09:21:49 +00:00
stack string
tunIf tun.Tun
tunStack tun.Stack
2022-07-09 11:18:37 +00:00
}
2022-07-12 07:17:29 +00:00
func NewTun(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TunInboundOptions) (*Tun, error) {
2022-07-10 01:15:01 +00:00
tunName := options.InterfaceName
if tunName == "" {
2022-09-05 16:15:09 +00:00
tunName = tun.CalculateInterfaceName("")
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 int64
if options.UDPTimeout != 0 {
udpTimeout = options.UDPTimeout
} else {
udpTimeout = int64(C.UDPTimeout.Seconds())
}
includeUID := uidToRange(options.IncludeUID)
if len(options.IncludeUIDRange) > 0 {
var err error
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 {
var err error
excludeUID, err = parseRange(excludeUID, options.ExcludeUIDRange)
if err != nil {
return nil, E.Cause(err, "parse exclude_uid_range")
}
}
2022-07-09 11:18:37 +00:00
return &Tun{
tag: tag,
ctx: ctx,
router: router,
logger: logger,
inboundOptions: options.InboundOptions,
tunOptions: tun.Options{
Name: tunName,
MTU: tunMTU,
2022-09-05 16:15:09 +00:00
Inet4Address: common.Map(options.Inet4Address, option.ListenPrefix.Build),
Inet6Address: common.Map(options.Inet6Address, option.ListenPrefix.Build),
AutoRoute: options.AutoRoute,
2022-08-26 13:53:08 +00:00
StrictRoute: options.StrictRoute,
IncludeUID: includeUID,
ExcludeUID: excludeUID,
IncludeAndroidUser: options.IncludeAndroidUser,
IncludePackage: options.IncludePackage,
ExcludePackage: options.ExcludePackage,
InterfaceMonitor: router.InterfaceMonitor(),
2022-09-05 16:15:09 +00:00
TableIndex: 2022,
},
endpointIndependentNat: options.EndpointIndependentNat,
udpTimeout: udpTimeout,
2022-08-07 09:21:49 +00:00
stack: options.Stack,
2022-07-09 11:18:37 +00:00
}, nil
}
func uidToRange(uidList option.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
start, err = strconv.ParseUint(uidRange[:subIndex], 10, 32)
if err != nil {
return nil, E.Cause(err, "parse range start")
}
end, err = strconv.ParseUint(uidRange[subIndex+1:], 10, 32)
if err != nil {
return nil, E.Cause(err, "parse range end")
}
uidRanges = append(uidRanges, ranges.New(uint32(start), uint32(end)))
}
return uidRanges, nil
}
2022-07-09 11:18:37 +00:00
func (t *Tun) Type() string {
return C.TypeTun
}
func (t *Tun) Tag() string {
return t.tag
}
func (t *Tun) Start() error {
if C.IsAndroid {
t.tunOptions.BuildAndroidRules(t.router.PackageManager(), t)
}
tunIf, err := tun.Open(t.tunOptions)
2022-07-09 11:18:37 +00:00
if err != nil {
return E.Cause(err, "configure tun interface")
}
2022-07-13 11:01:20 +00:00
t.tunIf = tunIf
2022-09-06 11:30:12 +00:00
t.tunStack, err = tun.NewStack(t.stack, tun.StackOptions{
Context: t.ctx,
Tun: tunIf,
MTU: t.tunOptions.MTU,
Name: t.tunOptions.Name,
Inet4Address: t.tunOptions.Inet4Address,
Inet6Address: t.tunOptions.Inet6Address,
EndpointIndependentNat: t.endpointIndependentNat,
UDPTimeout: t.udpTimeout,
Handler: t,
Logger: t.logger,
2022-09-06 11:30:12 +00:00
})
2022-08-07 09:21:49 +00:00
if err != nil {
return err
}
2022-07-13 11:01:20 +00:00
err = t.tunStack.Start()
2022-07-09 11:18:37 +00:00
if err != nil {
return err
}
t.logger.Info("started at ", t.tunOptions.Name)
2022-07-09 11:18:37 +00:00
return nil
}
func (t *Tun) Close() error {
2022-07-13 11:01:20 +00:00
return common.Close(
t.tunStack,
t.tunIf,
2022-07-09 11:18:37 +00:00
)
}
func (t *Tun) NewConnection(ctx context.Context, conn net.Conn, upstreamMetadata M.Metadata) error {
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
2022-07-09 11:18:37 +00:00
metadata.Source = upstreamMetadata.Source
metadata.Destination = upstreamMetadata.Destination
2022-07-10 01:15:01 +00:00
metadata.SniffEnabled = t.inboundOptions.SniffEnabled
metadata.SniffOverrideDestination = t.inboundOptions.SniffOverrideDestination
2022-07-11 10:44:59 +00:00
metadata.DomainStrategy = dns.DomainStrategy(t.inboundOptions.DomainStrategy)
2022-07-12 07:17:29 +00:00
t.logger.InfoContext(ctx, "inbound connection from ", metadata.Source)
t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
2022-07-20 01:41:44 +00:00
err := t.router.RouteConnection(ctx, conn, metadata)
if err != nil {
t.NewError(ctx, err)
}
2022-09-16 07:32:50 +00:00
return nil
2022-07-09 11:18:37 +00:00
}
func (t *Tun) NewPacketConnection(ctx context.Context, conn N.PacketConn, upstreamMetadata M.Metadata) error {
2022-07-12 07:17:29 +00:00
ctx = log.ContextWithNewID(ctx)
if tun.NeedTimeoutFromContext(ctx) {
ctx, conn = canceler.NewPacketConn(ctx, conn, time.Duration(t.udpTimeout)*time.Second)
}
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
2022-07-09 11:18:37 +00:00
metadata.Source = upstreamMetadata.Source
metadata.Destination = upstreamMetadata.Destination
2022-07-10 01:15:01 +00:00
metadata.SniffEnabled = t.inboundOptions.SniffEnabled
metadata.SniffOverrideDestination = t.inboundOptions.SniffOverrideDestination
2022-07-11 10:44:59 +00:00
metadata.DomainStrategy = dns.DomainStrategy(t.inboundOptions.DomainStrategy)
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)
2022-07-20 01:41:44 +00:00
err := t.router.RoutePacketConnection(ctx, conn, metadata)
if err != nil {
t.NewError(ctx, err)
}
2022-09-16 07:32:50 +00:00
return nil
2022-07-09 11:18:37 +00:00
}
func (t *Tun) NewError(ctx context.Context, err error) {
NewError(t.logger, ctx, err)
}