inbound.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. M "github.com/sagernet/sing/common/metadata"
  23. N "github.com/sagernet/sing/common/network"
  24. "github.com/sagernet/sing/common/ranges"
  25. "github.com/sagernet/sing/common/x/list"
  26. "github.com/sagernet/sing/service"
  27. "go4.org/netipx"
  28. )
  29. func RegisterInbound(registry *inbound.Registry) {
  30. inbound.Register[option.TunInboundOptions](registry, C.TypeTun, NewInbound)
  31. }
  32. type Inbound struct {
  33. tag string
  34. ctx context.Context
  35. router adapter.Router
  36. logger log.ContextLogger
  37. // Deprecated
  38. inboundOptions option.InboundOptions
  39. tunOptions tun.Options
  40. // Deprecated
  41. endpointIndependentNat bool
  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. inbound := &Inbound{
  160. tag: tag,
  161. ctx: ctx,
  162. router: router,
  163. logger: logger,
  164. inboundOptions: options.InboundOptions,
  165. tunOptions: tun.Options{
  166. Name: options.InterfaceName,
  167. MTU: tunMTU,
  168. GSO: options.GSO,
  169. Inet4Address: inet4Address,
  170. Inet6Address: inet6Address,
  171. AutoRoute: options.AutoRoute,
  172. IPRoute2TableIndex: tableIndex,
  173. IPRoute2RuleIndex: ruleIndex,
  174. AutoRedirectInputMark: inputMark,
  175. AutoRedirectOutputMark: outputMark,
  176. StrictRoute: options.StrictRoute,
  177. IncludeInterface: options.IncludeInterface,
  178. ExcludeInterface: options.ExcludeInterface,
  179. Inet4RouteAddress: inet4RouteAddress,
  180. Inet6RouteAddress: inet6RouteAddress,
  181. Inet4RouteExcludeAddress: inet4RouteExcludeAddress,
  182. Inet6RouteExcludeAddress: inet6RouteExcludeAddress,
  183. IncludeUID: includeUID,
  184. ExcludeUID: excludeUID,
  185. IncludeAndroidUser: options.IncludeAndroidUser,
  186. IncludePackage: options.IncludePackage,
  187. ExcludePackage: options.ExcludePackage,
  188. InterfaceMonitor: router.InterfaceMonitor(),
  189. },
  190. endpointIndependentNat: options.EndpointIndependentNat,
  191. udpTimeout: udpTimeout,
  192. stack: options.Stack,
  193. platformInterface: service.FromContext[platform.Interface](ctx),
  194. platformOptions: common.PtrValueOrDefault(options.Platform),
  195. }
  196. if options.AutoRedirect {
  197. if !options.AutoRoute {
  198. return nil, E.New("`auto_route` is required by `auto_redirect`")
  199. }
  200. disableNFTables, dErr := strconv.ParseBool(os.Getenv("DISABLE_NFTABLES"))
  201. inbound.autoRedirect, err = tun.NewAutoRedirect(tun.AutoRedirectOptions{
  202. TunOptions: &inbound.tunOptions,
  203. Context: ctx,
  204. Handler: (*autoRedirectHandler)(inbound),
  205. Logger: logger,
  206. NetworkMonitor: router.NetworkMonitor(),
  207. InterfaceFinder: router.InterfaceFinder(),
  208. TableName: "sing-box",
  209. DisableNFTables: dErr == nil && disableNFTables,
  210. RouteAddressSet: &inbound.routeAddressSet,
  211. RouteExcludeAddressSet: &inbound.routeExcludeAddressSet,
  212. })
  213. if err != nil {
  214. return nil, E.Cause(err, "initialize auto-redirect")
  215. }
  216. if runtime.GOOS != "android" {
  217. var markMode bool
  218. for _, routeAddressSet := range options.RouteAddressSet {
  219. ruleSet, loaded := router.RuleSet(routeAddressSet)
  220. if !loaded {
  221. return nil, E.New("parse route_address_set: rule-set not found: ", routeAddressSet)
  222. }
  223. ruleSet.IncRef()
  224. inbound.routeRuleSet = append(inbound.routeRuleSet, ruleSet)
  225. markMode = true
  226. }
  227. for _, routeExcludeAddressSet := range options.RouteExcludeAddressSet {
  228. ruleSet, loaded := router.RuleSet(routeExcludeAddressSet)
  229. if !loaded {
  230. return nil, E.New("parse route_exclude_address_set: rule-set not found: ", routeExcludeAddressSet)
  231. }
  232. ruleSet.IncRef()
  233. inbound.routeExcludeRuleSet = append(inbound.routeExcludeRuleSet, ruleSet)
  234. markMode = true
  235. }
  236. if markMode {
  237. inbound.tunOptions.AutoRedirectMarkMode = true
  238. err = router.RegisterAutoRedirectOutputMark(inbound.tunOptions.AutoRedirectOutputMark)
  239. if err != nil {
  240. return nil, err
  241. }
  242. }
  243. }
  244. }
  245. return inbound, nil
  246. }
  247. func uidToRange(uidList option.Listable[uint32]) []ranges.Range[uint32] {
  248. return common.Map(uidList, func(uid uint32) ranges.Range[uint32] {
  249. return ranges.NewSingle(uid)
  250. })
  251. }
  252. func parseRange(uidRanges []ranges.Range[uint32], rangeList []string) ([]ranges.Range[uint32], error) {
  253. for _, uidRange := range rangeList {
  254. if !strings.Contains(uidRange, ":") {
  255. return nil, E.New("missing ':' in range: ", uidRange)
  256. }
  257. subIndex := strings.Index(uidRange, ":")
  258. if subIndex == 0 {
  259. return nil, E.New("missing range start: ", uidRange)
  260. } else if subIndex == len(uidRange)-1 {
  261. return nil, E.New("missing range end: ", uidRange)
  262. }
  263. var start, end uint64
  264. var err error
  265. start, err = strconv.ParseUint(uidRange[:subIndex], 0, 32)
  266. if err != nil {
  267. return nil, E.Cause(err, "parse range start")
  268. }
  269. end, err = strconv.ParseUint(uidRange[subIndex+1:], 0, 32)
  270. if err != nil {
  271. return nil, E.Cause(err, "parse range end")
  272. }
  273. uidRanges = append(uidRanges, ranges.New(uint32(start), uint32(end)))
  274. }
  275. return uidRanges, nil
  276. }
  277. func (t *Inbound) Type() string {
  278. return C.TypeTun
  279. }
  280. func (t *Inbound) Tag() string {
  281. return t.tag
  282. }
  283. func (t *Inbound) Start() error {
  284. if C.IsAndroid && t.platformInterface == nil {
  285. t.tunOptions.BuildAndroidRules(t.router.PackageManager())
  286. }
  287. if t.tunOptions.Name == "" {
  288. t.tunOptions.Name = tun.CalculateInterfaceName("")
  289. }
  290. var (
  291. tunInterface tun.Tun
  292. err error
  293. )
  294. monitor := taskmonitor.New(t.logger, C.StartTimeout)
  295. monitor.Start("open tun interface")
  296. if t.platformInterface != nil {
  297. tunInterface, err = t.platformInterface.OpenTun(&t.tunOptions, t.platformOptions)
  298. } else {
  299. tunInterface, err = tun.New(t.tunOptions)
  300. }
  301. monitor.Finish()
  302. if err != nil {
  303. return E.Cause(err, "configure tun interface")
  304. }
  305. t.logger.Trace("creating stack")
  306. t.tunIf = tunInterface
  307. var (
  308. forwarderBindInterface bool
  309. includeAllNetworks bool
  310. )
  311. if t.platformInterface != nil {
  312. forwarderBindInterface = true
  313. includeAllNetworks = t.platformInterface.IncludeAllNetworks()
  314. }
  315. tunStack, err := tun.NewStack(t.stack, tun.StackOptions{
  316. Context: t.ctx,
  317. Tun: tunInterface,
  318. TunOptions: t.tunOptions,
  319. UDPTimeout: t.udpTimeout,
  320. Handler: t,
  321. Logger: t.logger,
  322. ForwarderBindInterface: forwarderBindInterface,
  323. InterfaceFinder: t.router.InterfaceFinder(),
  324. IncludeAllNetworks: includeAllNetworks,
  325. })
  326. if err != nil {
  327. return err
  328. }
  329. monitor.Start("initiating tun stack")
  330. err = tunStack.Start()
  331. monitor.Finish()
  332. t.tunStack = tunStack
  333. if err != nil {
  334. return err
  335. }
  336. t.logger.Info("started at ", t.tunOptions.Name)
  337. return nil
  338. }
  339. func (t *Inbound) PostStart() error {
  340. monitor := taskmonitor.New(t.logger, C.StartTimeout)
  341. if t.autoRedirect != nil {
  342. t.routeAddressSet = common.FlatMap(t.routeRuleSet, adapter.RuleSet.ExtractIPSet)
  343. for _, routeRuleSet := range t.routeRuleSet {
  344. ipSets := routeRuleSet.ExtractIPSet()
  345. if len(ipSets) == 0 {
  346. t.logger.Warn("route_address_set: no destination IP CIDR rules found in rule-set: ", routeRuleSet.Name())
  347. }
  348. t.routeAddressSet = append(t.routeAddressSet, ipSets...)
  349. }
  350. t.routeExcludeAddressSet = common.FlatMap(t.routeExcludeRuleSet, adapter.RuleSet.ExtractIPSet)
  351. for _, routeExcludeRuleSet := range t.routeExcludeRuleSet {
  352. ipSets := routeExcludeRuleSet.ExtractIPSet()
  353. if len(ipSets) == 0 {
  354. t.logger.Warn("route_address_set: no destination IP CIDR rules found in rule-set: ", routeExcludeRuleSet.Name())
  355. }
  356. t.routeExcludeAddressSet = append(t.routeExcludeAddressSet, ipSets...)
  357. }
  358. monitor.Start("initialize auto-redirect")
  359. err := t.autoRedirect.Start()
  360. monitor.Finish()
  361. if err != nil {
  362. return E.Cause(err, "auto-redirect")
  363. }
  364. for _, routeRuleSet := range t.routeRuleSet {
  365. t.routeRuleSetCallback = append(t.routeRuleSetCallback, routeRuleSet.RegisterCallback(t.updateRouteAddressSet))
  366. routeRuleSet.DecRef()
  367. }
  368. for _, routeExcludeRuleSet := range t.routeExcludeRuleSet {
  369. t.routeExcludeRuleSetCallback = append(t.routeExcludeRuleSetCallback, routeExcludeRuleSet.RegisterCallback(t.updateRouteAddressSet))
  370. routeExcludeRuleSet.DecRef()
  371. }
  372. t.routeAddressSet = nil
  373. t.routeExcludeAddressSet = nil
  374. }
  375. return nil
  376. }
  377. func (t *Inbound) updateRouteAddressSet(it adapter.RuleSet) {
  378. t.routeAddressSet = common.FlatMap(t.routeRuleSet, adapter.RuleSet.ExtractIPSet)
  379. t.routeExcludeAddressSet = common.FlatMap(t.routeExcludeRuleSet, adapter.RuleSet.ExtractIPSet)
  380. t.autoRedirect.UpdateRouteAddressSet()
  381. t.routeAddressSet = nil
  382. t.routeExcludeAddressSet = nil
  383. }
  384. func (t *Inbound) Close() error {
  385. return common.Close(
  386. t.tunStack,
  387. t.tunIf,
  388. t.autoRedirect,
  389. )
  390. }
  391. func (t *Inbound) PrepareConnection(network string, source M.Socksaddr, destination M.Socksaddr) error {
  392. return t.router.PreMatch(adapter.InboundContext{
  393. Inbound: t.tag,
  394. InboundType: C.TypeTun,
  395. Network: network,
  396. Source: source,
  397. Destination: destination,
  398. InboundOptions: t.inboundOptions,
  399. })
  400. }
  401. func (t *Inbound) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  402. ctx = log.ContextWithNewID(ctx)
  403. var metadata adapter.InboundContext
  404. metadata.Inbound = t.tag
  405. metadata.InboundType = C.TypeTun
  406. metadata.Source = source
  407. metadata.Destination = destination
  408. metadata.InboundOptions = t.inboundOptions
  409. t.logger.InfoContext(ctx, "inbound connection from ", metadata.Source)
  410. t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  411. t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  412. }
  413. func (t *Inbound) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  414. ctx = log.ContextWithNewID(ctx)
  415. var metadata adapter.InboundContext
  416. metadata.Inbound = t.tag
  417. metadata.InboundType = C.TypeTun
  418. metadata.Source = source
  419. metadata.Destination = destination
  420. metadata.InboundOptions = t.inboundOptions
  421. t.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source)
  422. t.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
  423. t.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  424. }
  425. type autoRedirectHandler Inbound
  426. func (t *autoRedirectHandler) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  427. ctx = log.ContextWithNewID(ctx)
  428. var metadata adapter.InboundContext
  429. metadata.Inbound = t.tag
  430. metadata.InboundType = C.TypeTun
  431. metadata.Source = source
  432. metadata.Destination = destination
  433. metadata.InboundOptions = t.inboundOptions
  434. t.logger.InfoContext(ctx, "inbound redirect connection from ", metadata.Source)
  435. t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  436. t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  437. }