inbound.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. logger log.ContextLogger
  38. // Deprecated
  39. inboundOptions option.InboundOptions
  40. tunOptions tun.Options
  41. // Deprecated
  42. endpointIndependentNat bool
  43. udpTimeout time.Duration
  44. stack string
  45. tunIf tun.Tun
  46. tunStack tun.Stack
  47. platformInterface platform.Interface
  48. platformOptions option.TunPlatformOptions
  49. autoRedirect tun.AutoRedirect
  50. routeRuleSet []adapter.RuleSet
  51. routeRuleSetCallback []*list.Element[adapter.RuleSetUpdateCallback]
  52. routeExcludeRuleSet []adapter.RuleSet
  53. routeExcludeRuleSetCallback []*list.Element[adapter.RuleSetUpdateCallback]
  54. routeAddressSet []*netipx.IPSet
  55. routeExcludeAddressSet []*netipx.IPSet
  56. }
  57. func NewInbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TunInboundOptions) (adapter.Inbound, error) {
  58. address := options.Address
  59. var deprecatedAddressUsed bool
  60. //nolint:staticcheck
  61. //goland:noinspection GoDeprecation
  62. if len(options.Inet4Address) > 0 {
  63. address = append(address, options.Inet4Address...)
  64. deprecatedAddressUsed = true
  65. }
  66. //nolint:staticcheck
  67. //goland:noinspection GoDeprecation
  68. if len(options.Inet6Address) > 0 {
  69. address = append(address, options.Inet6Address...)
  70. deprecatedAddressUsed = true
  71. }
  72. inet4Address := common.Filter(address, func(it netip.Prefix) bool {
  73. return it.Addr().Is4()
  74. })
  75. inet6Address := common.Filter(address, func(it netip.Prefix) bool {
  76. return it.Addr().Is6()
  77. })
  78. routeAddress := options.RouteAddress
  79. //nolint:staticcheck
  80. //goland:noinspection GoDeprecation
  81. if len(options.Inet4RouteAddress) > 0 {
  82. routeAddress = append(routeAddress, options.Inet4RouteAddress...)
  83. deprecatedAddressUsed = true
  84. }
  85. //nolint:staticcheck
  86. //goland:noinspection GoDeprecation
  87. if len(options.Inet6RouteAddress) > 0 {
  88. routeAddress = append(routeAddress, options.Inet6RouteAddress...)
  89. deprecatedAddressUsed = true
  90. }
  91. inet4RouteAddress := common.Filter(routeAddress, func(it netip.Prefix) bool {
  92. return it.Addr().Is4()
  93. })
  94. inet6RouteAddress := common.Filter(routeAddress, func(it netip.Prefix) bool {
  95. return it.Addr().Is6()
  96. })
  97. routeExcludeAddress := options.RouteExcludeAddress
  98. //nolint:staticcheck
  99. //goland:noinspection GoDeprecation
  100. if len(options.Inet4RouteExcludeAddress) > 0 {
  101. routeExcludeAddress = append(routeExcludeAddress, options.Inet4RouteExcludeAddress...)
  102. deprecatedAddressUsed = true
  103. }
  104. //nolint:staticcheck
  105. //goland:noinspection GoDeprecation
  106. if len(options.Inet6RouteExcludeAddress) > 0 {
  107. routeExcludeAddress = append(routeExcludeAddress, options.Inet6RouteExcludeAddress...)
  108. deprecatedAddressUsed = true
  109. }
  110. inet4RouteExcludeAddress := common.Filter(routeExcludeAddress, func(it netip.Prefix) bool {
  111. return it.Addr().Is4()
  112. })
  113. inet6RouteExcludeAddress := common.Filter(routeExcludeAddress, func(it netip.Prefix) bool {
  114. return it.Addr().Is6()
  115. })
  116. if deprecatedAddressUsed {
  117. deprecated.Report(ctx, deprecated.OptionTUNAddressX)
  118. }
  119. tunMTU := options.MTU
  120. if tunMTU == 0 {
  121. tunMTU = 9000
  122. }
  123. var udpTimeout time.Duration
  124. if options.UDPTimeout != 0 {
  125. udpTimeout = time.Duration(options.UDPTimeout)
  126. } else {
  127. udpTimeout = C.UDPTimeout
  128. }
  129. var err error
  130. includeUID := uidToRange(options.IncludeUID)
  131. if len(options.IncludeUIDRange) > 0 {
  132. includeUID, err = parseRange(includeUID, options.IncludeUIDRange)
  133. if err != nil {
  134. return nil, E.Cause(err, "parse include_uid_range")
  135. }
  136. }
  137. excludeUID := uidToRange(options.ExcludeUID)
  138. if len(options.ExcludeUIDRange) > 0 {
  139. excludeUID, err = parseRange(excludeUID, options.ExcludeUIDRange)
  140. if err != nil {
  141. return nil, E.Cause(err, "parse exclude_uid_range")
  142. }
  143. }
  144. tableIndex := options.IPRoute2TableIndex
  145. if tableIndex == 0 {
  146. tableIndex = tun.DefaultIPRoute2TableIndex
  147. }
  148. ruleIndex := options.IPRoute2RuleIndex
  149. if ruleIndex == 0 {
  150. ruleIndex = tun.DefaultIPRoute2RuleIndex
  151. }
  152. inputMark := uint32(options.AutoRedirectInputMark)
  153. if inputMark == 0 {
  154. inputMark = tun.DefaultAutoRedirectInputMark
  155. }
  156. outputMark := uint32(options.AutoRedirectOutputMark)
  157. if outputMark == 0 {
  158. outputMark = tun.DefaultAutoRedirectOutputMark
  159. }
  160. inbound := &Inbound{
  161. tag: tag,
  162. ctx: ctx,
  163. router: router,
  164. logger: logger,
  165. inboundOptions: options.InboundOptions,
  166. tunOptions: tun.Options{
  167. Name: options.InterfaceName,
  168. MTU: tunMTU,
  169. GSO: options.GSO,
  170. Inet4Address: inet4Address,
  171. Inet6Address: inet6Address,
  172. AutoRoute: options.AutoRoute,
  173. IPRoute2TableIndex: tableIndex,
  174. IPRoute2RuleIndex: ruleIndex,
  175. AutoRedirectInputMark: inputMark,
  176. AutoRedirectOutputMark: outputMark,
  177. StrictRoute: options.StrictRoute,
  178. IncludeInterface: options.IncludeInterface,
  179. ExcludeInterface: options.ExcludeInterface,
  180. Inet4RouteAddress: inet4RouteAddress,
  181. Inet6RouteAddress: inet6RouteAddress,
  182. Inet4RouteExcludeAddress: inet4RouteExcludeAddress,
  183. Inet6RouteExcludeAddress: inet6RouteExcludeAddress,
  184. IncludeUID: includeUID,
  185. ExcludeUID: excludeUID,
  186. IncludeAndroidUser: options.IncludeAndroidUser,
  187. IncludePackage: options.IncludePackage,
  188. ExcludePackage: options.ExcludePackage,
  189. InterfaceMonitor: router.InterfaceMonitor(),
  190. },
  191. endpointIndependentNat: options.EndpointIndependentNat,
  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: router.NetworkMonitor(),
  208. InterfaceFinder: router.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 = router.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() error {
  285. if C.IsAndroid && t.platformInterface == nil {
  286. t.tunOptions.BuildAndroidRules(t.router.PackageManager())
  287. }
  288. if t.tunOptions.Name == "" {
  289. t.tunOptions.Name = tun.CalculateInterfaceName("")
  290. }
  291. var (
  292. tunInterface tun.Tun
  293. err error
  294. )
  295. monitor := taskmonitor.New(t.logger, C.StartTimeout)
  296. monitor.Start("open tun interface")
  297. if t.platformInterface != nil {
  298. tunInterface, err = t.platformInterface.OpenTun(&t.tunOptions, t.platformOptions)
  299. } else {
  300. tunInterface, err = tun.New(t.tunOptions)
  301. }
  302. monitor.Finish()
  303. if err != nil {
  304. return E.Cause(err, "configure tun interface")
  305. }
  306. t.logger.Trace("creating stack")
  307. t.tunIf = tunInterface
  308. var (
  309. forwarderBindInterface bool
  310. includeAllNetworks bool
  311. )
  312. if t.platformInterface != nil {
  313. forwarderBindInterface = true
  314. includeAllNetworks = t.platformInterface.IncludeAllNetworks()
  315. }
  316. tunStack, err := tun.NewStack(t.stack, tun.StackOptions{
  317. Context: t.ctx,
  318. Tun: tunInterface,
  319. TunOptions: t.tunOptions,
  320. UDPTimeout: t.udpTimeout,
  321. Handler: t,
  322. Logger: t.logger,
  323. ForwarderBindInterface: forwarderBindInterface,
  324. InterfaceFinder: t.router.InterfaceFinder(),
  325. IncludeAllNetworks: includeAllNetworks,
  326. })
  327. if err != nil {
  328. return err
  329. }
  330. t.tunStack = tunStack
  331. t.logger.Info("started at ", t.tunOptions.Name)
  332. return nil
  333. }
  334. func (t *Inbound) PostStart() error {
  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. return nil
  383. }
  384. func (t *Inbound) updateRouteAddressSet(it adapter.RuleSet) {
  385. t.routeAddressSet = common.FlatMap(t.routeRuleSet, adapter.RuleSet.ExtractIPSet)
  386. t.routeExcludeAddressSet = common.FlatMap(t.routeExcludeRuleSet, adapter.RuleSet.ExtractIPSet)
  387. t.autoRedirect.UpdateRouteAddressSet()
  388. t.routeAddressSet = nil
  389. t.routeExcludeAddressSet = nil
  390. }
  391. func (t *Inbound) Close() error {
  392. return common.Close(
  393. t.tunStack,
  394. t.tunIf,
  395. t.autoRedirect,
  396. )
  397. }
  398. func (t *Inbound) PrepareConnection(network string, source M.Socksaddr, destination M.Socksaddr) error {
  399. return t.router.PreMatch(adapter.InboundContext{
  400. Inbound: t.tag,
  401. InboundType: C.TypeTun,
  402. Network: network,
  403. Source: source,
  404. Destination: destination,
  405. InboundOptions: t.inboundOptions,
  406. })
  407. }
  408. func (t *Inbound) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  409. ctx = log.ContextWithNewID(ctx)
  410. var metadata adapter.InboundContext
  411. metadata.Inbound = t.tag
  412. metadata.InboundType = C.TypeTun
  413. metadata.Source = source
  414. metadata.Destination = destination
  415. metadata.InboundOptions = t.inboundOptions
  416. t.logger.InfoContext(ctx, "inbound connection from ", metadata.Source)
  417. t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  418. t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  419. }
  420. func (t *Inbound) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  421. ctx = log.ContextWithNewID(ctx)
  422. var metadata adapter.InboundContext
  423. metadata.Inbound = t.tag
  424. metadata.InboundType = C.TypeTun
  425. metadata.Source = source
  426. metadata.Destination = destination
  427. metadata.InboundOptions = t.inboundOptions
  428. t.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source)
  429. t.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
  430. t.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  431. }
  432. type autoRedirectHandler Inbound
  433. func (t *autoRedirectHandler) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  434. ctx = log.ContextWithNewID(ctx)
  435. var metadata adapter.InboundContext
  436. metadata.Inbound = t.tag
  437. metadata.InboundType = C.TypeTun
  438. metadata.Source = source
  439. metadata.Destination = destination
  440. metadata.InboundOptions = t.inboundOptions
  441. t.logger.InfoContext(ctx, "inbound redirect connection from ", metadata.Source)
  442. t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  443. t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  444. }