inbound.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. //goland:noinspection GoDeprecation
  61. if len(options.Inet4Address) > 0 {
  62. address = append(address, options.Inet4Address...)
  63. deprecatedAddressUsed = true
  64. }
  65. //nolint:staticcheck
  66. //goland:noinspection GoDeprecation
  67. if len(options.Inet6Address) > 0 {
  68. address = append(address, options.Inet6Address...)
  69. deprecatedAddressUsed = true
  70. }
  71. inet4Address := common.Filter(address, func(it netip.Prefix) bool {
  72. return it.Addr().Is4()
  73. })
  74. inet6Address := common.Filter(address, func(it netip.Prefix) bool {
  75. return it.Addr().Is6()
  76. })
  77. routeAddress := options.RouteAddress
  78. //nolint:staticcheck
  79. //goland:noinspection GoDeprecation
  80. if len(options.Inet4RouteAddress) > 0 {
  81. routeAddress = append(routeAddress, options.Inet4RouteAddress...)
  82. deprecatedAddressUsed = true
  83. }
  84. //nolint:staticcheck
  85. //goland:noinspection GoDeprecation
  86. if len(options.Inet6RouteAddress) > 0 {
  87. routeAddress = append(routeAddress, options.Inet6RouteAddress...)
  88. deprecatedAddressUsed = true
  89. }
  90. inet4RouteAddress := common.Filter(routeAddress, func(it netip.Prefix) bool {
  91. return it.Addr().Is4()
  92. })
  93. inet6RouteAddress := common.Filter(routeAddress, func(it netip.Prefix) bool {
  94. return it.Addr().Is6()
  95. })
  96. routeExcludeAddress := options.RouteExcludeAddress
  97. //nolint:staticcheck
  98. //goland:noinspection GoDeprecation
  99. if len(options.Inet4RouteExcludeAddress) > 0 {
  100. routeExcludeAddress = append(routeExcludeAddress, options.Inet4RouteExcludeAddress...)
  101. deprecatedAddressUsed = true
  102. }
  103. //nolint:staticcheck
  104. //goland:noinspection GoDeprecation
  105. if len(options.Inet6RouteExcludeAddress) > 0 {
  106. routeExcludeAddress = append(routeExcludeAddress, options.Inet6RouteExcludeAddress...)
  107. deprecatedAddressUsed = true
  108. }
  109. inet4RouteExcludeAddress := common.Filter(routeExcludeAddress, func(it netip.Prefix) bool {
  110. return it.Addr().Is4()
  111. })
  112. inet6RouteExcludeAddress := common.Filter(routeExcludeAddress, func(it netip.Prefix) bool {
  113. return it.Addr().Is6()
  114. })
  115. if deprecatedAddressUsed {
  116. deprecated.Report(ctx, deprecated.OptionTUNAddressX)
  117. }
  118. tunMTU := options.MTU
  119. if tunMTU == 0 {
  120. tunMTU = 9000
  121. }
  122. var udpTimeout time.Duration
  123. if options.UDPTimeout != 0 {
  124. udpTimeout = time.Duration(options.UDPTimeout)
  125. } else {
  126. udpTimeout = C.UDPTimeout
  127. }
  128. var err error
  129. includeUID := uidToRange(options.IncludeUID)
  130. if len(options.IncludeUIDRange) > 0 {
  131. includeUID, err = parseRange(includeUID, options.IncludeUIDRange)
  132. if err != nil {
  133. return nil, E.Cause(err, "parse include_uid_range")
  134. }
  135. }
  136. excludeUID := uidToRange(options.ExcludeUID)
  137. if len(options.ExcludeUIDRange) > 0 {
  138. excludeUID, err = parseRange(excludeUID, options.ExcludeUIDRange)
  139. if err != nil {
  140. return nil, E.Cause(err, "parse exclude_uid_range")
  141. }
  142. }
  143. tableIndex := options.IPRoute2TableIndex
  144. if tableIndex == 0 {
  145. tableIndex = tun.DefaultIPRoute2TableIndex
  146. }
  147. ruleIndex := options.IPRoute2RuleIndex
  148. if ruleIndex == 0 {
  149. ruleIndex = tun.DefaultIPRoute2RuleIndex
  150. }
  151. inputMark := uint32(options.AutoRedirectInputMark)
  152. if inputMark == 0 {
  153. inputMark = tun.DefaultAutoRedirectInputMark
  154. }
  155. outputMark := uint32(options.AutoRedirectOutputMark)
  156. if outputMark == 0 {
  157. outputMark = tun.DefaultAutoRedirectOutputMark
  158. }
  159. networkManager := service.FromContext[adapter.NetworkManager](ctx)
  160. inbound := &Inbound{
  161. tag: tag,
  162. ctx: ctx,
  163. router: router,
  164. networkManager: networkManager,
  165. logger: logger,
  166. inboundOptions: options.InboundOptions,
  167. tunOptions: tun.Options{
  168. Name: options.InterfaceName,
  169. MTU: tunMTU,
  170. GSO: options.GSO,
  171. Inet4Address: inet4Address,
  172. Inet6Address: inet6Address,
  173. AutoRoute: options.AutoRoute,
  174. IPRoute2TableIndex: tableIndex,
  175. IPRoute2RuleIndex: ruleIndex,
  176. AutoRedirectInputMark: inputMark,
  177. AutoRedirectOutputMark: outputMark,
  178. StrictRoute: options.StrictRoute,
  179. IncludeInterface: options.IncludeInterface,
  180. ExcludeInterface: options.ExcludeInterface,
  181. Inet4RouteAddress: inet4RouteAddress,
  182. Inet6RouteAddress: inet6RouteAddress,
  183. Inet4RouteExcludeAddress: inet4RouteExcludeAddress,
  184. Inet6RouteExcludeAddress: inet6RouteExcludeAddress,
  185. IncludeUID: includeUID,
  186. ExcludeUID: excludeUID,
  187. IncludeAndroidUser: options.IncludeAndroidUser,
  188. IncludePackage: options.IncludePackage,
  189. ExcludePackage: options.ExcludePackage,
  190. InterfaceMonitor: networkManager.InterfaceMonitor(),
  191. },
  192. udpTimeout: udpTimeout,
  193. stack: options.Stack,
  194. platformInterface: service.FromContext[platform.Interface](ctx),
  195. platformOptions: common.PtrValueOrDefault(options.Platform),
  196. }
  197. if options.AutoRedirect {
  198. if !options.AutoRoute {
  199. return nil, E.New("`auto_route` is required by `auto_redirect`")
  200. }
  201. disableNFTables, dErr := strconv.ParseBool(os.Getenv("DISABLE_NFTABLES"))
  202. inbound.autoRedirect, err = tun.NewAutoRedirect(tun.AutoRedirectOptions{
  203. TunOptions: &inbound.tunOptions,
  204. Context: ctx,
  205. Handler: (*autoRedirectHandler)(inbound),
  206. Logger: logger,
  207. NetworkMonitor: networkManager.NetworkMonitor(),
  208. InterfaceFinder: networkManager.InterfaceFinder(),
  209. TableName: "sing-box",
  210. DisableNFTables: dErr == nil && disableNFTables,
  211. RouteAddressSet: &inbound.routeAddressSet,
  212. RouteExcludeAddressSet: &inbound.routeExcludeAddressSet,
  213. })
  214. if err != nil {
  215. return nil, E.Cause(err, "initialize auto-redirect")
  216. }
  217. if runtime.GOOS != "android" {
  218. var markMode bool
  219. for _, routeAddressSet := range options.RouteAddressSet {
  220. ruleSet, loaded := router.RuleSet(routeAddressSet)
  221. if !loaded {
  222. return nil, E.New("parse route_address_set: rule-set not found: ", routeAddressSet)
  223. }
  224. ruleSet.IncRef()
  225. inbound.routeRuleSet = append(inbound.routeRuleSet, ruleSet)
  226. markMode = true
  227. }
  228. for _, routeExcludeAddressSet := range options.RouteExcludeAddressSet {
  229. ruleSet, loaded := router.RuleSet(routeExcludeAddressSet)
  230. if !loaded {
  231. return nil, E.New("parse route_exclude_address_set: rule-set not found: ", routeExcludeAddressSet)
  232. }
  233. ruleSet.IncRef()
  234. inbound.routeExcludeRuleSet = append(inbound.routeExcludeRuleSet, ruleSet)
  235. markMode = true
  236. }
  237. if markMode {
  238. inbound.tunOptions.AutoRedirectMarkMode = true
  239. err = networkManager.RegisterAutoRedirectOutputMark(inbound.tunOptions.AutoRedirectOutputMark)
  240. if err != nil {
  241. return nil, err
  242. }
  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. var (
  294. tunInterface tun.Tun
  295. err error
  296. )
  297. monitor := taskmonitor.New(t.logger, C.StartTimeout)
  298. monitor.Start("open tun interface")
  299. if t.platformInterface != nil {
  300. tunInterface, err = t.platformInterface.OpenTun(&t.tunOptions, t.platformOptions)
  301. } else {
  302. tunInterface, err = tun.New(t.tunOptions)
  303. }
  304. monitor.Finish()
  305. if err != nil {
  306. return E.Cause(err, "configure tun interface")
  307. }
  308. t.logger.Trace("creating stack")
  309. t.tunIf = tunInterface
  310. var (
  311. forwarderBindInterface bool
  312. includeAllNetworks bool
  313. )
  314. if t.platformInterface != nil {
  315. forwarderBindInterface = true
  316. includeAllNetworks = t.platformInterface.IncludeAllNetworks()
  317. }
  318. tunStack, err := tun.NewStack(t.stack, tun.StackOptions{
  319. Context: t.ctx,
  320. Tun: tunInterface,
  321. TunOptions: t.tunOptions,
  322. UDPTimeout: t.udpTimeout,
  323. Handler: t,
  324. Logger: t.logger,
  325. ForwarderBindInterface: forwarderBindInterface,
  326. InterfaceFinder: t.networkManager.InterfaceFinder(),
  327. IncludeAllNetworks: includeAllNetworks,
  328. })
  329. if err != nil {
  330. return err
  331. }
  332. t.tunStack = tunStack
  333. t.logger.Info("started at ", t.tunOptions.Name)
  334. case adapter.StartStatePostStart:
  335. monitor := taskmonitor.New(t.logger, C.StartTimeout)
  336. monitor.Start("starting tun stack")
  337. err := t.tunStack.Start()
  338. monitor.Finish()
  339. if err != nil {
  340. return E.Cause(err, "starting tun stack")
  341. }
  342. monitor.Start("starting tun interface")
  343. err = t.tunIf.Start()
  344. monitor.Finish()
  345. if err != nil {
  346. return E.Cause(err, "starting TUN interface")
  347. }
  348. if t.autoRedirect != nil {
  349. t.routeAddressSet = common.FlatMap(t.routeRuleSet, adapter.RuleSet.ExtractIPSet)
  350. for _, routeRuleSet := range t.routeRuleSet {
  351. ipSets := routeRuleSet.ExtractIPSet()
  352. if len(ipSets) == 0 {
  353. t.logger.Warn("route_address_set: no destination IP CIDR rules found in rule-set: ", routeRuleSet.Name())
  354. }
  355. t.routeAddressSet = append(t.routeAddressSet, ipSets...)
  356. }
  357. t.routeExcludeAddressSet = common.FlatMap(t.routeExcludeRuleSet, adapter.RuleSet.ExtractIPSet)
  358. for _, routeExcludeRuleSet := range t.routeExcludeRuleSet {
  359. ipSets := routeExcludeRuleSet.ExtractIPSet()
  360. if len(ipSets) == 0 {
  361. t.logger.Warn("route_address_set: no destination IP CIDR rules found in rule-set: ", routeExcludeRuleSet.Name())
  362. }
  363. t.routeExcludeAddressSet = append(t.routeExcludeAddressSet, ipSets...)
  364. }
  365. monitor.Start("initialize auto-redirect")
  366. err := t.autoRedirect.Start()
  367. monitor.Finish()
  368. if err != nil {
  369. return E.Cause(err, "auto-redirect")
  370. }
  371. for _, routeRuleSet := range t.routeRuleSet {
  372. t.routeRuleSetCallback = append(t.routeRuleSetCallback, routeRuleSet.RegisterCallback(t.updateRouteAddressSet))
  373. routeRuleSet.DecRef()
  374. }
  375. for _, routeExcludeRuleSet := range t.routeExcludeRuleSet {
  376. t.routeExcludeRuleSetCallback = append(t.routeExcludeRuleSetCallback, routeExcludeRuleSet.RegisterCallback(t.updateRouteAddressSet))
  377. routeExcludeRuleSet.DecRef()
  378. }
  379. t.routeAddressSet = nil
  380. t.routeExcludeAddressSet = nil
  381. }
  382. }
  383. return nil
  384. }
  385. func (t *Inbound) updateRouteAddressSet(it adapter.RuleSet) {
  386. t.routeAddressSet = common.FlatMap(t.routeRuleSet, adapter.RuleSet.ExtractIPSet)
  387. t.routeExcludeAddressSet = common.FlatMap(t.routeExcludeRuleSet, adapter.RuleSet.ExtractIPSet)
  388. t.autoRedirect.UpdateRouteAddressSet()
  389. t.routeAddressSet = nil
  390. t.routeExcludeAddressSet = nil
  391. }
  392. func (t *Inbound) Close() error {
  393. return common.Close(
  394. t.tunStack,
  395. t.tunIf,
  396. t.autoRedirect,
  397. )
  398. }
  399. func (t *Inbound) PrepareConnection(network string, source M.Socksaddr, destination M.Socksaddr) error {
  400. return t.router.PreMatch(adapter.InboundContext{
  401. Inbound: t.tag,
  402. InboundType: C.TypeTun,
  403. Network: network,
  404. Source: source,
  405. Destination: destination,
  406. InboundOptions: t.inboundOptions,
  407. })
  408. }
  409. func (t *Inbound) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  410. ctx = log.ContextWithNewID(ctx)
  411. var metadata adapter.InboundContext
  412. metadata.Inbound = t.tag
  413. metadata.InboundType = C.TypeTun
  414. metadata.Source = source
  415. metadata.Destination = destination
  416. //nolint:staticcheck
  417. metadata.InboundOptions = t.inboundOptions
  418. t.logger.InfoContext(ctx, "inbound connection from ", metadata.Source)
  419. t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  420. t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  421. }
  422. func (t *Inbound) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  423. ctx = log.ContextWithNewID(ctx)
  424. var metadata adapter.InboundContext
  425. metadata.Inbound = t.tag
  426. metadata.InboundType = C.TypeTun
  427. metadata.Source = source
  428. metadata.Destination = destination
  429. //nolint:staticcheck
  430. metadata.InboundOptions = t.inboundOptions
  431. t.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source)
  432. t.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
  433. t.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  434. }
  435. type autoRedirectHandler Inbound
  436. func (t *autoRedirectHandler) 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 redirect connection from ", metadata.Source)
  446. t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  447. t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  448. }