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