inbound.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. tunMTU := options.MTU
  117. if tunMTU == 0 {
  118. tunMTU = 9000
  119. }
  120. var udpTimeout time.Duration
  121. if options.UDPTimeout != 0 {
  122. udpTimeout = time.Duration(options.UDPTimeout)
  123. } else {
  124. udpTimeout = C.UDPTimeout
  125. }
  126. var err error
  127. includeUID := uidToRange(options.IncludeUID)
  128. if len(options.IncludeUIDRange) > 0 {
  129. includeUID, err = parseRange(includeUID, options.IncludeUIDRange)
  130. if err != nil {
  131. return nil, E.Cause(err, "parse include_uid_range")
  132. }
  133. }
  134. excludeUID := uidToRange(options.ExcludeUID)
  135. if len(options.ExcludeUIDRange) > 0 {
  136. excludeUID, err = parseRange(excludeUID, options.ExcludeUIDRange)
  137. if err != nil {
  138. return nil, E.Cause(err, "parse exclude_uid_range")
  139. }
  140. }
  141. tableIndex := options.IPRoute2TableIndex
  142. if tableIndex == 0 {
  143. tableIndex = tun.DefaultIPRoute2TableIndex
  144. }
  145. ruleIndex := options.IPRoute2RuleIndex
  146. if ruleIndex == 0 {
  147. ruleIndex = tun.DefaultIPRoute2RuleIndex
  148. }
  149. inputMark := uint32(options.AutoRedirectInputMark)
  150. if inputMark == 0 {
  151. inputMark = tun.DefaultAutoRedirectInputMark
  152. }
  153. outputMark := uint32(options.AutoRedirectOutputMark)
  154. if outputMark == 0 {
  155. outputMark = tun.DefaultAutoRedirectOutputMark
  156. }
  157. networkManager := service.FromContext[adapter.NetworkManager](ctx)
  158. inbound := &Inbound{
  159. tag: tag,
  160. ctx: ctx,
  161. router: router,
  162. networkManager: networkManager,
  163. logger: logger,
  164. inboundOptions: options.InboundOptions,
  165. tunOptions: tun.Options{
  166. Name: options.InterfaceName,
  167. MTU: tunMTU,
  168. Inet4Address: inet4Address,
  169. Inet6Address: inet6Address,
  170. AutoRoute: options.AutoRoute,
  171. IPRoute2TableIndex: tableIndex,
  172. IPRoute2RuleIndex: ruleIndex,
  173. AutoRedirectInputMark: inputMark,
  174. AutoRedirectOutputMark: outputMark,
  175. StrictRoute: options.StrictRoute,
  176. IncludeInterface: options.IncludeInterface,
  177. ExcludeInterface: options.ExcludeInterface,
  178. Inet4RouteAddress: inet4RouteAddress,
  179. Inet6RouteAddress: inet6RouteAddress,
  180. Inet4RouteExcludeAddress: inet4RouteExcludeAddress,
  181. Inet6RouteExcludeAddress: inet6RouteExcludeAddress,
  182. IncludeUID: includeUID,
  183. ExcludeUID: excludeUID,
  184. IncludeAndroidUser: options.IncludeAndroidUser,
  185. IncludePackage: options.IncludePackage,
  186. ExcludePackage: options.ExcludePackage,
  187. InterfaceMonitor: networkManager.InterfaceMonitor(),
  188. },
  189. udpTimeout: udpTimeout,
  190. stack: options.Stack,
  191. platformInterface: service.FromContext[platform.Interface](ctx),
  192. platformOptions: common.PtrValueOrDefault(options.Platform),
  193. }
  194. for _, routeAddressSet := range options.RouteAddressSet {
  195. ruleSet, loaded := router.RuleSet(routeAddressSet)
  196. if !loaded {
  197. return nil, E.New("parse route_address_set: rule-set not found: ", routeAddressSet)
  198. }
  199. ruleSet.IncRef()
  200. inbound.routeRuleSet = append(inbound.routeRuleSet, ruleSet)
  201. }
  202. for _, routeExcludeAddressSet := range options.RouteExcludeAddressSet {
  203. ruleSet, loaded := router.RuleSet(routeExcludeAddressSet)
  204. if !loaded {
  205. return nil, E.New("parse route_exclude_address_set: rule-set not found: ", routeExcludeAddressSet)
  206. }
  207. ruleSet.IncRef()
  208. inbound.routeExcludeRuleSet = append(inbound.routeExcludeRuleSet, ruleSet)
  209. }
  210. if options.AutoRedirect {
  211. if !options.AutoRoute {
  212. return nil, E.New("`auto_route` is required by `auto_redirect`")
  213. }
  214. disableNFTables, dErr := strconv.ParseBool(os.Getenv("DISABLE_NFTABLES"))
  215. inbound.autoRedirect, err = tun.NewAutoRedirect(tun.AutoRedirectOptions{
  216. TunOptions: &inbound.tunOptions,
  217. Context: ctx,
  218. Handler: (*autoRedirectHandler)(inbound),
  219. Logger: logger,
  220. NetworkMonitor: networkManager.NetworkMonitor(),
  221. InterfaceFinder: networkManager.InterfaceFinder(),
  222. TableName: "sing-box",
  223. DisableNFTables: dErr == nil && disableNFTables,
  224. RouteAddressSet: &inbound.routeAddressSet,
  225. RouteExcludeAddressSet: &inbound.routeExcludeAddressSet,
  226. })
  227. if err != nil {
  228. return nil, E.Cause(err, "initialize auto-redirect")
  229. }
  230. if !C.IsAndroid && (len(inbound.routeRuleSet) > 0 || len(inbound.routeExcludeRuleSet) > 0) {
  231. inbound.tunOptions.AutoRedirectMarkMode = true
  232. err = networkManager.RegisterAutoRedirectOutputMark(inbound.tunOptions.AutoRedirectOutputMark)
  233. if err != nil {
  234. return nil, err
  235. }
  236. }
  237. }
  238. return inbound, nil
  239. }
  240. func uidToRange(uidList badoption.Listable[uint32]) []ranges.Range[uint32] {
  241. return common.Map(uidList, func(uid uint32) ranges.Range[uint32] {
  242. return ranges.NewSingle(uid)
  243. })
  244. }
  245. func parseRange(uidRanges []ranges.Range[uint32], rangeList []string) ([]ranges.Range[uint32], error) {
  246. for _, uidRange := range rangeList {
  247. if !strings.Contains(uidRange, ":") {
  248. return nil, E.New("missing ':' in range: ", uidRange)
  249. }
  250. subIndex := strings.Index(uidRange, ":")
  251. if subIndex == 0 {
  252. return nil, E.New("missing range start: ", uidRange)
  253. } else if subIndex == len(uidRange)-1 {
  254. return nil, E.New("missing range end: ", uidRange)
  255. }
  256. var start, end uint64
  257. var err error
  258. start, err = strconv.ParseUint(uidRange[:subIndex], 0, 32)
  259. if err != nil {
  260. return nil, E.Cause(err, "parse range start")
  261. }
  262. end, err = strconv.ParseUint(uidRange[subIndex+1:], 0, 32)
  263. if err != nil {
  264. return nil, E.Cause(err, "parse range end")
  265. }
  266. uidRanges = append(uidRanges, ranges.New(uint32(start), uint32(end)))
  267. }
  268. return uidRanges, nil
  269. }
  270. func (t *Inbound) Type() string {
  271. return C.TypeTun
  272. }
  273. func (t *Inbound) Tag() string {
  274. return t.tag
  275. }
  276. func (t *Inbound) Start(stage adapter.StartStage) error {
  277. switch stage {
  278. case adapter.StartStateStart:
  279. if C.IsAndroid && t.platformInterface == nil {
  280. t.tunOptions.BuildAndroidRules(t.networkManager.PackageManager())
  281. }
  282. if t.tunOptions.Name == "" {
  283. t.tunOptions.Name = tun.CalculateInterfaceName("")
  284. }
  285. if t.platformInterface == nil || runtime.GOOS != "android" {
  286. t.routeAddressSet = common.FlatMap(t.routeRuleSet, adapter.RuleSet.ExtractIPSet)
  287. for _, routeRuleSet := range t.routeRuleSet {
  288. ipSets := routeRuleSet.ExtractIPSet()
  289. if len(ipSets) == 0 {
  290. t.logger.Warn("route_address_set: no destination IP CIDR rules found in rule-set: ", routeRuleSet.Name())
  291. }
  292. t.routeRuleSetCallback = append(t.routeRuleSetCallback, routeRuleSet.RegisterCallback(t.updateRouteAddressSet))
  293. routeRuleSet.DecRef()
  294. t.routeAddressSet = append(t.routeAddressSet, ipSets...)
  295. }
  296. t.routeExcludeAddressSet = common.FlatMap(t.routeExcludeRuleSet, adapter.RuleSet.ExtractIPSet)
  297. for _, routeExcludeRuleSet := range t.routeExcludeRuleSet {
  298. ipSets := routeExcludeRuleSet.ExtractIPSet()
  299. if len(ipSets) == 0 {
  300. t.logger.Warn("route_address_set: no destination IP CIDR rules found in rule-set: ", routeExcludeRuleSet.Name())
  301. }
  302. t.routeExcludeRuleSetCallback = append(t.routeExcludeRuleSetCallback, routeExcludeRuleSet.RegisterCallback(t.updateRouteAddressSet))
  303. routeExcludeRuleSet.DecRef()
  304. t.routeExcludeAddressSet = append(t.routeExcludeAddressSet, ipSets...)
  305. }
  306. }
  307. var (
  308. tunInterface tun.Tun
  309. err error
  310. )
  311. monitor := taskmonitor.New(t.logger, C.StartTimeout)
  312. tunOptions := t.tunOptions
  313. if t.autoRedirect == nil && !(runtime.GOOS == "android" && t.platformInterface != nil) {
  314. for _, ipSet := range t.routeAddressSet {
  315. for _, prefix := range ipSet.Prefixes() {
  316. if prefix.Addr().Is4() {
  317. tunOptions.Inet4RouteAddress = append(tunOptions.Inet4RouteAddress, prefix)
  318. } else {
  319. tunOptions.Inet6RouteAddress = append(tunOptions.Inet6RouteAddress, prefix)
  320. }
  321. }
  322. }
  323. for _, ipSet := range t.routeExcludeAddressSet {
  324. for _, prefix := range ipSet.Prefixes() {
  325. if prefix.Addr().Is4() {
  326. tunOptions.Inet4RouteExcludeAddress = append(tunOptions.Inet4RouteExcludeAddress, prefix)
  327. } else {
  328. tunOptions.Inet6RouteExcludeAddress = append(tunOptions.Inet6RouteExcludeAddress, prefix)
  329. }
  330. }
  331. }
  332. }
  333. monitor.Start("open interface")
  334. if t.platformInterface != nil {
  335. tunInterface, err = t.platformInterface.OpenTun(&tunOptions, t.platformOptions)
  336. } else {
  337. tunInterface, err = tun.New(tunOptions)
  338. }
  339. monitor.Finish()
  340. t.tunOptions.Name = tunOptions.Name
  341. if err != nil {
  342. return E.Cause(err, "configure tun interface")
  343. }
  344. t.logger.Trace("creating stack")
  345. t.tunIf = tunInterface
  346. var (
  347. forwarderBindInterface bool
  348. includeAllNetworks bool
  349. )
  350. if t.platformInterface != nil {
  351. forwarderBindInterface = true
  352. includeAllNetworks = t.platformInterface.IncludeAllNetworks()
  353. }
  354. tunStack, err := tun.NewStack(t.stack, tun.StackOptions{
  355. Context: t.ctx,
  356. Tun: tunInterface,
  357. TunOptions: t.tunOptions,
  358. UDPTimeout: t.udpTimeout,
  359. Handler: t,
  360. Logger: t.logger,
  361. ForwarderBindInterface: forwarderBindInterface,
  362. InterfaceFinder: t.networkManager.InterfaceFinder(),
  363. IncludeAllNetworks: includeAllNetworks,
  364. })
  365. if err != nil {
  366. return err
  367. }
  368. t.tunStack = tunStack
  369. t.logger.Info("started at ", t.tunOptions.Name)
  370. case adapter.StartStatePostStart:
  371. monitor := taskmonitor.New(t.logger, C.StartTimeout)
  372. monitor.Start("starting tun stack")
  373. err := t.tunStack.Start()
  374. monitor.Finish()
  375. if err != nil {
  376. return E.Cause(err, "starting tun stack")
  377. }
  378. monitor.Start("starting tun interface")
  379. err = t.tunIf.Start()
  380. monitor.Finish()
  381. if err != nil {
  382. return E.Cause(err, "starting TUN interface")
  383. }
  384. if t.autoRedirect != nil {
  385. monitor.Start("initialize auto-redirect")
  386. err := t.autoRedirect.Start()
  387. monitor.Finish()
  388. if err != nil {
  389. return E.Cause(err, "auto-redirect")
  390. }
  391. }
  392. t.routeAddressSet = nil
  393. t.routeExcludeAddressSet = nil
  394. }
  395. return nil
  396. }
  397. func (t *Inbound) updateRouteAddressSet(it adapter.RuleSet) {
  398. t.routeAddressSet = common.FlatMap(t.routeRuleSet, adapter.RuleSet.ExtractIPSet)
  399. t.routeExcludeAddressSet = common.FlatMap(t.routeExcludeRuleSet, adapter.RuleSet.ExtractIPSet)
  400. if t.autoRedirect != nil {
  401. t.autoRedirect.UpdateRouteAddressSet()
  402. } else {
  403. tunOptions := t.tunOptions
  404. for _, ipSet := range t.routeAddressSet {
  405. for _, prefix := range ipSet.Prefixes() {
  406. if prefix.Addr().Is4() {
  407. tunOptions.Inet4RouteAddress = append(tunOptions.Inet4RouteAddress, prefix)
  408. } else {
  409. tunOptions.Inet6RouteAddress = append(tunOptions.Inet6RouteAddress, prefix)
  410. }
  411. }
  412. }
  413. for _, ipSet := range t.routeExcludeAddressSet {
  414. for _, prefix := range ipSet.Prefixes() {
  415. if prefix.Addr().Is4() {
  416. tunOptions.Inet4RouteExcludeAddress = append(tunOptions.Inet4RouteExcludeAddress, prefix)
  417. } else {
  418. tunOptions.Inet6RouteExcludeAddress = append(tunOptions.Inet6RouteExcludeAddress, prefix)
  419. }
  420. }
  421. }
  422. if t.platformInterface != nil {
  423. err := t.platformInterface.UpdateRouteOptions(&tunOptions, t.platformOptions)
  424. if err != nil {
  425. t.logger.Error("update route addresses: ", err)
  426. }
  427. } else {
  428. err := t.tunIf.UpdateRouteOptions(tunOptions)
  429. if err != nil {
  430. t.logger.Error("update route addresses: ", err)
  431. }
  432. }
  433. t.logger.Info("updated route addresses")
  434. }
  435. t.routeAddressSet = nil
  436. t.routeExcludeAddressSet = nil
  437. }
  438. func (t *Inbound) Close() error {
  439. return common.Close(
  440. t.tunStack,
  441. t.tunIf,
  442. t.autoRedirect,
  443. )
  444. }
  445. func (t *Inbound) PrepareConnection(network string, source M.Socksaddr, destination M.Socksaddr) error {
  446. return t.router.PreMatch(adapter.InboundContext{
  447. Inbound: t.tag,
  448. InboundType: C.TypeTun,
  449. Network: network,
  450. Source: source,
  451. Destination: destination,
  452. InboundOptions: t.inboundOptions,
  453. })
  454. }
  455. func (t *Inbound) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  456. ctx = log.ContextWithNewID(ctx)
  457. var metadata adapter.InboundContext
  458. metadata.Inbound = t.tag
  459. metadata.InboundType = C.TypeTun
  460. metadata.Source = source
  461. metadata.Destination = destination
  462. //nolint:staticcheck
  463. metadata.InboundOptions = t.inboundOptions
  464. t.logger.InfoContext(ctx, "inbound connection from ", metadata.Source)
  465. t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  466. t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  467. }
  468. func (t *Inbound) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  469. ctx = log.ContextWithNewID(ctx)
  470. var metadata adapter.InboundContext
  471. metadata.Inbound = t.tag
  472. metadata.InboundType = C.TypeTun
  473. metadata.Source = source
  474. metadata.Destination = destination
  475. //nolint:staticcheck
  476. metadata.InboundOptions = t.inboundOptions
  477. t.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source)
  478. t.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
  479. t.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  480. }
  481. type autoRedirectHandler Inbound
  482. func (t *autoRedirectHandler) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  483. ctx = log.ContextWithNewID(ctx)
  484. var metadata adapter.InboundContext
  485. metadata.Inbound = t.tag
  486. metadata.InboundType = C.TypeTun
  487. metadata.Source = source
  488. metadata.Destination = destination
  489. //nolint:staticcheck
  490. metadata.InboundOptions = t.inboundOptions
  491. t.logger.InfoContext(ctx, "inbound redirect connection from ", metadata.Source)
  492. t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  493. t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  494. }