inbound.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. package tun
  2. import (
  3. "context"
  4. "net"
  5. "net/netip"
  6. "os"
  7. "runtime"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/sagernet/sing-box/adapter"
  12. "github.com/sagernet/sing-box/adapter/inbound"
  13. "github.com/sagernet/sing-box/common/taskmonitor"
  14. C "github.com/sagernet/sing-box/constant"
  15. "github.com/sagernet/sing-box/experimental/deprecated"
  16. "github.com/sagernet/sing-box/experimental/libbox/platform"
  17. "github.com/sagernet/sing-box/log"
  18. "github.com/sagernet/sing-box/option"
  19. "github.com/sagernet/sing-tun"
  20. "github.com/sagernet/sing/common"
  21. E "github.com/sagernet/sing/common/exceptions"
  22. "github.com/sagernet/sing/common/json/badoption"
  23. M "github.com/sagernet/sing/common/metadata"
  24. N "github.com/sagernet/sing/common/network"
  25. "github.com/sagernet/sing/common/ranges"
  26. "github.com/sagernet/sing/common/x/list"
  27. "github.com/sagernet/sing/service"
  28. "go4.org/netipx"
  29. )
  30. func RegisterInbound(registry *inbound.Registry) {
  31. inbound.Register[option.TunInboundOptions](registry, C.TypeTun, NewInbound)
  32. }
  33. type Inbound struct {
  34. tag string
  35. ctx context.Context
  36. router adapter.Router
  37. networkManager adapter.NetworkManager
  38. logger log.ContextLogger
  39. //nolint:staticcheck
  40. inboundOptions option.InboundOptions
  41. tunOptions tun.Options
  42. udpTimeout time.Duration
  43. stack string
  44. tunIf tun.Tun
  45. tunStack tun.Stack
  46. platformInterface platform.Interface
  47. platformOptions option.TunPlatformOptions
  48. autoRedirect tun.AutoRedirect
  49. routeRuleSet []adapter.RuleSet
  50. routeRuleSetCallback []*list.Element[adapter.RuleSetUpdateCallback]
  51. routeExcludeRuleSet []adapter.RuleSet
  52. routeExcludeRuleSetCallback []*list.Element[adapter.RuleSetUpdateCallback]
  53. routeAddressSet []*netipx.IPSet
  54. routeExcludeAddressSet []*netipx.IPSet
  55. }
  56. func NewInbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TunInboundOptions) (adapter.Inbound, error) {
  57. address := options.Address
  58. var deprecatedAddressUsed bool
  59. //nolint:staticcheck
  60. if len(options.Inet4Address) > 0 {
  61. address = append(address, options.Inet4Address...)
  62. deprecatedAddressUsed = true
  63. }
  64. //nolint:staticcheck
  65. if len(options.Inet6Address) > 0 {
  66. address = append(address, options.Inet6Address...)
  67. deprecatedAddressUsed = true
  68. }
  69. inet4Address := common.Filter(address, func(it netip.Prefix) bool {
  70. return it.Addr().Is4()
  71. })
  72. inet6Address := common.Filter(address, func(it netip.Prefix) bool {
  73. return it.Addr().Is6()
  74. })
  75. routeAddress := options.RouteAddress
  76. //nolint:staticcheck
  77. if len(options.Inet4RouteAddress) > 0 {
  78. routeAddress = append(routeAddress, options.Inet4RouteAddress...)
  79. deprecatedAddressUsed = true
  80. }
  81. //nolint:staticcheck
  82. if len(options.Inet6RouteAddress) > 0 {
  83. routeAddress = append(routeAddress, options.Inet6RouteAddress...)
  84. deprecatedAddressUsed = true
  85. }
  86. inet4RouteAddress := common.Filter(routeAddress, func(it netip.Prefix) bool {
  87. return it.Addr().Is4()
  88. })
  89. inet6RouteAddress := common.Filter(routeAddress, func(it netip.Prefix) bool {
  90. return it.Addr().Is6()
  91. })
  92. routeExcludeAddress := options.RouteExcludeAddress
  93. //nolint:staticcheck
  94. if len(options.Inet4RouteExcludeAddress) > 0 {
  95. routeExcludeAddress = append(routeExcludeAddress, options.Inet4RouteExcludeAddress...)
  96. deprecatedAddressUsed = true
  97. }
  98. //nolint:staticcheck
  99. if len(options.Inet6RouteExcludeAddress) > 0 {
  100. routeExcludeAddress = append(routeExcludeAddress, options.Inet6RouteExcludeAddress...)
  101. deprecatedAddressUsed = true
  102. }
  103. inet4RouteExcludeAddress := common.Filter(routeExcludeAddress, func(it netip.Prefix) bool {
  104. return it.Addr().Is4()
  105. })
  106. inet6RouteExcludeAddress := common.Filter(routeExcludeAddress, func(it netip.Prefix) bool {
  107. return it.Addr().Is6()
  108. })
  109. if deprecatedAddressUsed {
  110. deprecated.Report(ctx, deprecated.OptionTUNAddressX)
  111. }
  112. //nolint:staticcheck
  113. if options.GSO {
  114. deprecated.Report(ctx, deprecated.OptionTUNGSO)
  115. }
  116. platformInterface := service.FromContext[platform.Interface](ctx)
  117. tunMTU := options.MTU
  118. enableGSO := C.IsLinux && options.Stack == "gvisor" && platformInterface == nil && tunMTU > 0 && tunMTU < 49152
  119. if tunMTU == 0 {
  120. if platformInterface != nil && platformInterface.UnderNetworkExtension() {
  121. // In Network Extension, when MTU exceeds 4064 (4096-UTUN_IF_HEADROOM_SIZE), the performance of tun will drop significantly, which may be a system bug.
  122. tunMTU = 4064
  123. } else {
  124. tunMTU = 65535
  125. }
  126. }
  127. var udpTimeout time.Duration
  128. if options.UDPTimeout != 0 {
  129. udpTimeout = time.Duration(options.UDPTimeout)
  130. } else {
  131. udpTimeout = C.UDPTimeout
  132. }
  133. var err error
  134. includeUID := uidToRange(options.IncludeUID)
  135. if len(options.IncludeUIDRange) > 0 {
  136. includeUID, err = parseRange(includeUID, options.IncludeUIDRange)
  137. if err != nil {
  138. return nil, E.Cause(err, "parse include_uid_range")
  139. }
  140. }
  141. excludeUID := uidToRange(options.ExcludeUID)
  142. if len(options.ExcludeUIDRange) > 0 {
  143. excludeUID, err = parseRange(excludeUID, options.ExcludeUIDRange)
  144. if err != nil {
  145. return nil, E.Cause(err, "parse exclude_uid_range")
  146. }
  147. }
  148. tableIndex := options.IPRoute2TableIndex
  149. if tableIndex == 0 {
  150. tableIndex = tun.DefaultIPRoute2TableIndex
  151. }
  152. ruleIndex := options.IPRoute2RuleIndex
  153. if ruleIndex == 0 {
  154. ruleIndex = tun.DefaultIPRoute2RuleIndex
  155. }
  156. inputMark := uint32(options.AutoRedirectInputMark)
  157. if inputMark == 0 {
  158. inputMark = tun.DefaultAutoRedirectInputMark
  159. }
  160. outputMark := uint32(options.AutoRedirectOutputMark)
  161. if outputMark == 0 {
  162. outputMark = tun.DefaultAutoRedirectOutputMark
  163. }
  164. networkManager := service.FromContext[adapter.NetworkManager](ctx)
  165. inbound := &Inbound{
  166. tag: tag,
  167. ctx: ctx,
  168. router: router,
  169. networkManager: networkManager,
  170. logger: logger,
  171. inboundOptions: options.InboundOptions,
  172. tunOptions: tun.Options{
  173. Name: options.InterfaceName,
  174. MTU: tunMTU,
  175. GSO: enableGSO,
  176. Inet4Address: inet4Address,
  177. Inet6Address: inet6Address,
  178. AutoRoute: options.AutoRoute,
  179. IPRoute2TableIndex: tableIndex,
  180. IPRoute2RuleIndex: ruleIndex,
  181. AutoRedirectInputMark: inputMark,
  182. AutoRedirectOutputMark: outputMark,
  183. Inet4LoopbackAddress: common.Filter(options.LoopbackAddress, netip.Addr.Is4),
  184. Inet6LoopbackAddress: common.Filter(options.LoopbackAddress, netip.Addr.Is6),
  185. StrictRoute: options.StrictRoute,
  186. IncludeInterface: options.IncludeInterface,
  187. ExcludeInterface: options.ExcludeInterface,
  188. Inet4RouteAddress: inet4RouteAddress,
  189. Inet6RouteAddress: inet6RouteAddress,
  190. Inet4RouteExcludeAddress: inet4RouteExcludeAddress,
  191. Inet6RouteExcludeAddress: inet6RouteExcludeAddress,
  192. IncludeUID: includeUID,
  193. ExcludeUID: excludeUID,
  194. IncludeAndroidUser: options.IncludeAndroidUser,
  195. IncludePackage: options.IncludePackage,
  196. ExcludePackage: options.ExcludePackage,
  197. InterfaceMonitor: networkManager.InterfaceMonitor(),
  198. },
  199. udpTimeout: udpTimeout,
  200. stack: options.Stack,
  201. platformInterface: platformInterface,
  202. platformOptions: common.PtrValueOrDefault(options.Platform),
  203. }
  204. for _, routeAddressSet := range options.RouteAddressSet {
  205. ruleSet, loaded := router.RuleSet(routeAddressSet)
  206. if !loaded {
  207. return nil, E.New("parse route_address_set: rule-set not found: ", routeAddressSet)
  208. }
  209. inbound.routeRuleSet = append(inbound.routeRuleSet, ruleSet)
  210. }
  211. for _, routeExcludeAddressSet := range options.RouteExcludeAddressSet {
  212. ruleSet, loaded := router.RuleSet(routeExcludeAddressSet)
  213. if !loaded {
  214. return nil, E.New("parse route_exclude_address_set: rule-set not found: ", routeExcludeAddressSet)
  215. }
  216. inbound.routeExcludeRuleSet = append(inbound.routeExcludeRuleSet, ruleSet)
  217. }
  218. if options.AutoRedirect {
  219. if !options.AutoRoute {
  220. return nil, E.New("`auto_route` is required by `auto_redirect`")
  221. }
  222. disableNFTables, dErr := strconv.ParseBool(os.Getenv("DISABLE_NFTABLES"))
  223. inbound.autoRedirect, err = tun.NewAutoRedirect(tun.AutoRedirectOptions{
  224. TunOptions: &inbound.tunOptions,
  225. Context: ctx,
  226. Handler: (*autoRedirectHandler)(inbound),
  227. Logger: logger,
  228. NetworkMonitor: networkManager.NetworkMonitor(),
  229. InterfaceFinder: networkManager.InterfaceFinder(),
  230. TableName: "sing-box",
  231. DisableNFTables: dErr == nil && disableNFTables,
  232. RouteAddressSet: &inbound.routeAddressSet,
  233. RouteExcludeAddressSet: &inbound.routeExcludeAddressSet,
  234. })
  235. if err != nil {
  236. return nil, E.Cause(err, "initialize auto-redirect")
  237. }
  238. if !C.IsAndroid {
  239. inbound.tunOptions.AutoRedirectMarkMode = true
  240. err = networkManager.RegisterAutoRedirectOutputMark(inbound.tunOptions.AutoRedirectOutputMark)
  241. if err != nil {
  242. return nil, err
  243. }
  244. }
  245. }
  246. return inbound, nil
  247. }
  248. func uidToRange(uidList badoption.Listable[uint32]) []ranges.Range[uint32] {
  249. return common.Map(uidList, func(uid uint32) ranges.Range[uint32] {
  250. return ranges.NewSingle(uid)
  251. })
  252. }
  253. func parseRange(uidRanges []ranges.Range[uint32], rangeList []string) ([]ranges.Range[uint32], error) {
  254. for _, uidRange := range rangeList {
  255. if !strings.Contains(uidRange, ":") {
  256. return nil, E.New("missing ':' in range: ", uidRange)
  257. }
  258. subIndex := strings.Index(uidRange, ":")
  259. if subIndex == 0 {
  260. return nil, E.New("missing range start: ", uidRange)
  261. } else if subIndex == len(uidRange)-1 {
  262. return nil, E.New("missing range end: ", uidRange)
  263. }
  264. var start, end uint64
  265. var err error
  266. start, err = strconv.ParseUint(uidRange[:subIndex], 0, 32)
  267. if err != nil {
  268. return nil, E.Cause(err, "parse range start")
  269. }
  270. end, err = strconv.ParseUint(uidRange[subIndex+1:], 0, 32)
  271. if err != nil {
  272. return nil, E.Cause(err, "parse range end")
  273. }
  274. uidRanges = append(uidRanges, ranges.New(uint32(start), uint32(end)))
  275. }
  276. return uidRanges, nil
  277. }
  278. func (t *Inbound) Type() string {
  279. return C.TypeTun
  280. }
  281. func (t *Inbound) Tag() string {
  282. return t.tag
  283. }
  284. func (t *Inbound) Start(stage adapter.StartStage) error {
  285. switch stage {
  286. case adapter.StartStateStart:
  287. if C.IsAndroid && t.platformInterface == nil {
  288. t.tunOptions.BuildAndroidRules(t.networkManager.PackageManager())
  289. }
  290. if t.tunOptions.Name == "" {
  291. t.tunOptions.Name = tun.CalculateInterfaceName("")
  292. }
  293. if t.platformInterface == nil {
  294. t.routeAddressSet = common.FlatMap(t.routeRuleSet, adapter.RuleSet.ExtractIPSet)
  295. for _, routeRuleSet := range t.routeRuleSet {
  296. ipSets := routeRuleSet.ExtractIPSet()
  297. if len(ipSets) == 0 {
  298. t.logger.Warn("route_address_set: no destination IP CIDR rules found in rule-set: ", routeRuleSet.Name())
  299. }
  300. routeRuleSet.IncRef()
  301. t.routeAddressSet = append(t.routeAddressSet, ipSets...)
  302. if t.autoRedirect != nil {
  303. t.routeRuleSetCallback = append(t.routeRuleSetCallback, routeRuleSet.RegisterCallback(t.updateRouteAddressSet))
  304. }
  305. }
  306. t.routeExcludeAddressSet = common.FlatMap(t.routeExcludeRuleSet, adapter.RuleSet.ExtractIPSet)
  307. for _, routeExcludeRuleSet := range t.routeExcludeRuleSet {
  308. ipSets := routeExcludeRuleSet.ExtractIPSet()
  309. if len(ipSets) == 0 {
  310. t.logger.Warn("route_address_set: no destination IP CIDR rules found in rule-set: ", routeExcludeRuleSet.Name())
  311. }
  312. routeExcludeRuleSet.IncRef()
  313. t.routeExcludeAddressSet = append(t.routeExcludeAddressSet, ipSets...)
  314. if t.autoRedirect != nil {
  315. t.routeExcludeRuleSetCallback = append(t.routeExcludeRuleSetCallback, routeExcludeRuleSet.RegisterCallback(t.updateRouteAddressSet))
  316. }
  317. }
  318. }
  319. var (
  320. tunInterface tun.Tun
  321. err error
  322. )
  323. monitor := taskmonitor.New(t.logger, C.StartTimeout)
  324. tunOptions := t.tunOptions
  325. if t.autoRedirect == nil && !(runtime.GOOS == "android" && t.platformInterface != nil) {
  326. for _, ipSet := range t.routeAddressSet {
  327. for _, prefix := range ipSet.Prefixes() {
  328. if prefix.Addr().Is4() {
  329. tunOptions.Inet4RouteAddress = append(tunOptions.Inet4RouteAddress, prefix)
  330. } else {
  331. tunOptions.Inet6RouteAddress = append(tunOptions.Inet6RouteAddress, prefix)
  332. }
  333. }
  334. }
  335. for _, ipSet := range t.routeExcludeAddressSet {
  336. for _, prefix := range ipSet.Prefixes() {
  337. if prefix.Addr().Is4() {
  338. tunOptions.Inet4RouteExcludeAddress = append(tunOptions.Inet4RouteExcludeAddress, prefix)
  339. } else {
  340. tunOptions.Inet6RouteExcludeAddress = append(tunOptions.Inet6RouteExcludeAddress, prefix)
  341. }
  342. }
  343. }
  344. }
  345. monitor.Start("open interface")
  346. if t.platformInterface != nil {
  347. tunInterface, err = t.platformInterface.OpenTun(&tunOptions, t.platformOptions)
  348. } else {
  349. if HookBeforeCreatePlatformInterface != nil {
  350. HookBeforeCreatePlatformInterface()
  351. }
  352. tunInterface, err = tun.New(tunOptions)
  353. }
  354. monitor.Finish()
  355. t.tunOptions.Name = tunOptions.Name
  356. if err != nil {
  357. return E.Cause(err, "configure tun interface")
  358. }
  359. t.logger.Trace("creating stack")
  360. t.tunIf = tunInterface
  361. var (
  362. forwarderBindInterface bool
  363. includeAllNetworks bool
  364. )
  365. if t.platformInterface != nil {
  366. forwarderBindInterface = true
  367. includeAllNetworks = t.platformInterface.IncludeAllNetworks()
  368. }
  369. tunStack, err := tun.NewStack(t.stack, tun.StackOptions{
  370. Context: t.ctx,
  371. Tun: tunInterface,
  372. TunOptions: t.tunOptions,
  373. UDPTimeout: t.udpTimeout,
  374. Handler: t,
  375. Logger: t.logger,
  376. ForwarderBindInterface: forwarderBindInterface,
  377. InterfaceFinder: t.networkManager.InterfaceFinder(),
  378. IncludeAllNetworks: includeAllNetworks,
  379. })
  380. if err != nil {
  381. return err
  382. }
  383. t.tunStack = tunStack
  384. t.logger.Info("started at ", t.tunOptions.Name)
  385. case adapter.StartStatePostStart:
  386. monitor := taskmonitor.New(t.logger, C.StartTimeout)
  387. monitor.Start("starting tun stack")
  388. err := t.tunStack.Start()
  389. monitor.Finish()
  390. if err != nil {
  391. return E.Cause(err, "starting tun stack")
  392. }
  393. monitor.Start("starting tun interface")
  394. err = t.tunIf.Start()
  395. monitor.Finish()
  396. if err != nil {
  397. return E.Cause(err, "starting TUN interface")
  398. }
  399. if t.autoRedirect != nil {
  400. monitor.Start("initialize auto-redirect")
  401. err := t.autoRedirect.Start()
  402. monitor.Finish()
  403. if err != nil {
  404. return E.Cause(err, "auto-redirect")
  405. }
  406. }
  407. t.routeAddressSet = nil
  408. t.routeExcludeAddressSet = nil
  409. }
  410. return nil
  411. }
  412. func (t *Inbound) updateRouteAddressSet(it adapter.RuleSet) {
  413. t.routeAddressSet = common.FlatMap(t.routeRuleSet, adapter.RuleSet.ExtractIPSet)
  414. t.routeExcludeAddressSet = common.FlatMap(t.routeExcludeRuleSet, adapter.RuleSet.ExtractIPSet)
  415. t.autoRedirect.UpdateRouteAddressSet()
  416. t.routeAddressSet = nil
  417. t.routeExcludeAddressSet = nil
  418. }
  419. func (t *Inbound) Close() error {
  420. return common.Close(
  421. t.tunStack,
  422. t.tunIf,
  423. t.autoRedirect,
  424. )
  425. }
  426. func (t *Inbound) PrepareConnection(network string, source M.Socksaddr, destination M.Socksaddr) error {
  427. return t.router.PreMatch(adapter.InboundContext{
  428. Inbound: t.tag,
  429. InboundType: C.TypeTun,
  430. Network: network,
  431. Source: source,
  432. Destination: destination,
  433. InboundOptions: t.inboundOptions,
  434. })
  435. }
  436. func (t *Inbound) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  437. ctx = log.ContextWithNewID(ctx)
  438. var metadata adapter.InboundContext
  439. metadata.Inbound = t.tag
  440. metadata.InboundType = C.TypeTun
  441. metadata.Source = source
  442. metadata.Destination = destination
  443. //nolint:staticcheck
  444. metadata.InboundOptions = t.inboundOptions
  445. t.logger.InfoContext(ctx, "inbound connection from ", metadata.Source)
  446. t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  447. t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  448. }
  449. func (t *Inbound) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  450. ctx = log.ContextWithNewID(ctx)
  451. var metadata adapter.InboundContext
  452. metadata.Inbound = t.tag
  453. metadata.InboundType = C.TypeTun
  454. metadata.Source = source
  455. metadata.Destination = destination
  456. //nolint:staticcheck
  457. metadata.InboundOptions = t.inboundOptions
  458. t.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source)
  459. t.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
  460. t.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  461. }
  462. type autoRedirectHandler Inbound
  463. func (t *autoRedirectHandler) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  464. ctx = log.ContextWithNewID(ctx)
  465. var metadata adapter.InboundContext
  466. metadata.Inbound = t.tag
  467. metadata.InboundType = C.TypeTun
  468. metadata.Source = source
  469. metadata.Destination = destination
  470. //nolint:staticcheck
  471. metadata.InboundOptions = t.inboundOptions
  472. t.logger.InfoContext(ctx, "inbound redirect connection from ", metadata.Source)
  473. t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  474. t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  475. }