inbound.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. package tun
  2. import (
  3. "context"
  4. "net"
  5. "net/netip"
  6. "os"
  7. "runtime"
  8. "strconv"
  9. "strings"
  10. "syscall"
  11. "time"
  12. "github.com/sagernet/sing-box/adapter"
  13. "github.com/sagernet/sing-box/adapter/inbound"
  14. "github.com/sagernet/sing-box/common/taskmonitor"
  15. C "github.com/sagernet/sing-box/constant"
  16. "github.com/sagernet/sing-box/experimental/deprecated"
  17. "github.com/sagernet/sing-box/experimental/libbox/platform"
  18. "github.com/sagernet/sing-box/log"
  19. "github.com/sagernet/sing-box/option"
  20. "github.com/sagernet/sing-tun"
  21. "github.com/sagernet/sing/common"
  22. E "github.com/sagernet/sing/common/exceptions"
  23. "github.com/sagernet/sing/common/json/badoption"
  24. M "github.com/sagernet/sing/common/metadata"
  25. N "github.com/sagernet/sing/common/network"
  26. "github.com/sagernet/sing/common/ranges"
  27. "github.com/sagernet/sing/common/x/list"
  28. "github.com/sagernet/sing/service"
  29. "go4.org/netipx"
  30. )
  31. func RegisterInbound(registry *inbound.Registry) {
  32. inbound.Register[option.TunInboundOptions](registry, C.TypeTun, NewInbound)
  33. }
  34. type Inbound struct {
  35. tag string
  36. ctx context.Context
  37. router adapter.Router
  38. networkManager adapter.NetworkManager
  39. logger log.ContextLogger
  40. //nolint:staticcheck
  41. inboundOptions option.InboundOptions
  42. tunOptions tun.Options
  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. if len(options.Inet4Address) > 0 {
  62. address = append(address, options.Inet4Address...)
  63. deprecatedAddressUsed = true
  64. }
  65. //nolint:staticcheck
  66. if len(options.Inet6Address) > 0 {
  67. address = append(address, options.Inet6Address...)
  68. deprecatedAddressUsed = true
  69. }
  70. inet4Address := common.Filter(address, func(it netip.Prefix) bool {
  71. return it.Addr().Is4()
  72. })
  73. inet6Address := common.Filter(address, func(it netip.Prefix) bool {
  74. return it.Addr().Is6()
  75. })
  76. routeAddress := options.RouteAddress
  77. //nolint:staticcheck
  78. if len(options.Inet4RouteAddress) > 0 {
  79. routeAddress = append(routeAddress, options.Inet4RouteAddress...)
  80. deprecatedAddressUsed = true
  81. }
  82. //nolint:staticcheck
  83. if len(options.Inet6RouteAddress) > 0 {
  84. routeAddress = append(routeAddress, options.Inet6RouteAddress...)
  85. deprecatedAddressUsed = true
  86. }
  87. inet4RouteAddress := common.Filter(routeAddress, func(it netip.Prefix) bool {
  88. return it.Addr().Is4()
  89. })
  90. inet6RouteAddress := common.Filter(routeAddress, func(it netip.Prefix) bool {
  91. return it.Addr().Is6()
  92. })
  93. routeExcludeAddress := options.RouteExcludeAddress
  94. //nolint:staticcheck
  95. if len(options.Inet4RouteExcludeAddress) > 0 {
  96. routeExcludeAddress = append(routeExcludeAddress, options.Inet4RouteExcludeAddress...)
  97. deprecatedAddressUsed = true
  98. }
  99. //nolint:staticcheck
  100. if len(options.Inet6RouteExcludeAddress) > 0 {
  101. routeExcludeAddress = append(routeExcludeAddress, options.Inet6RouteExcludeAddress...)
  102. deprecatedAddressUsed = true
  103. }
  104. inet4RouteExcludeAddress := common.Filter(routeExcludeAddress, func(it netip.Prefix) bool {
  105. return it.Addr().Is4()
  106. })
  107. inet6RouteExcludeAddress := common.Filter(routeExcludeAddress, func(it netip.Prefix) bool {
  108. return it.Addr().Is6()
  109. })
  110. if deprecatedAddressUsed {
  111. deprecated.Report(ctx, deprecated.OptionTUNAddressX)
  112. }
  113. //nolint:staticcheck
  114. if options.GSO {
  115. deprecated.Report(ctx, deprecated.OptionTUNGSO)
  116. }
  117. tunMTU := options.MTU
  118. if tunMTU == 0 {
  119. tunMTU = 9000
  120. }
  121. var udpTimeout time.Duration
  122. if options.UDPTimeout != 0 {
  123. udpTimeout = time.Duration(options.UDPTimeout)
  124. } else {
  125. udpTimeout = C.UDPTimeout
  126. }
  127. var err error
  128. includeUID := uidToRange(options.IncludeUID)
  129. if len(options.IncludeUIDRange) > 0 {
  130. includeUID, err = parseRange(includeUID, options.IncludeUIDRange)
  131. if err != nil {
  132. return nil, E.Cause(err, "parse include_uid_range")
  133. }
  134. }
  135. excludeUID := uidToRange(options.ExcludeUID)
  136. if len(options.ExcludeUIDRange) > 0 {
  137. excludeUID, err = parseRange(excludeUID, options.ExcludeUIDRange)
  138. if err != nil {
  139. return nil, E.Cause(err, "parse exclude_uid_range")
  140. }
  141. }
  142. tableIndex := options.IPRoute2TableIndex
  143. if tableIndex == 0 {
  144. tableIndex = tun.DefaultIPRoute2TableIndex
  145. }
  146. ruleIndex := options.IPRoute2RuleIndex
  147. if ruleIndex == 0 {
  148. ruleIndex = tun.DefaultIPRoute2RuleIndex
  149. }
  150. inputMark := uint32(options.AutoRedirectInputMark)
  151. if inputMark == 0 {
  152. inputMark = tun.DefaultAutoRedirectInputMark
  153. }
  154. outputMark := uint32(options.AutoRedirectOutputMark)
  155. if outputMark == 0 {
  156. outputMark = tun.DefaultAutoRedirectOutputMark
  157. }
  158. networkManager := service.FromContext[adapter.NetworkManager](ctx)
  159. inbound := &Inbound{
  160. tag: tag,
  161. ctx: ctx,
  162. router: router,
  163. networkManager: networkManager,
  164. logger: logger,
  165. inboundOptions: options.InboundOptions,
  166. tunOptions: tun.Options{
  167. Name: options.InterfaceName,
  168. MTU: tunMTU,
  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: networkManager.InterfaceMonitor(),
  189. },
  190. udpTimeout: udpTimeout,
  191. stack: options.Stack,
  192. platformInterface: service.FromContext[platform.Interface](ctx),
  193. platformOptions: common.PtrValueOrDefault(options.Platform),
  194. }
  195. for _, routeAddressSet := range options.RouteAddressSet {
  196. ruleSet, loaded := router.RuleSet(routeAddressSet)
  197. if !loaded {
  198. return nil, E.New("parse route_address_set: rule-set not found: ", routeAddressSet)
  199. }
  200. ruleSet.IncRef()
  201. inbound.routeRuleSet = append(inbound.routeRuleSet, ruleSet)
  202. }
  203. for _, routeExcludeAddressSet := range options.RouteExcludeAddressSet {
  204. ruleSet, loaded := router.RuleSet(routeExcludeAddressSet)
  205. if !loaded {
  206. return nil, E.New("parse route_exclude_address_set: rule-set not found: ", routeExcludeAddressSet)
  207. }
  208. ruleSet.IncRef()
  209. inbound.routeExcludeRuleSet = append(inbound.routeExcludeRuleSet, ruleSet)
  210. }
  211. if options.AutoRedirect {
  212. if !options.AutoRoute {
  213. return nil, E.New("`auto_route` is required by `auto_redirect`")
  214. }
  215. disableNFTables, dErr := strconv.ParseBool(os.Getenv("DISABLE_NFTABLES"))
  216. inbound.autoRedirect, err = tun.NewAutoRedirect(tun.AutoRedirectOptions{
  217. TunOptions: &inbound.tunOptions,
  218. Context: ctx,
  219. Handler: (*autoRedirectHandler)(inbound),
  220. Logger: logger,
  221. NetworkMonitor: networkManager.NetworkMonitor(),
  222. InterfaceFinder: networkManager.InterfaceFinder(),
  223. TableName: "sing-box",
  224. DisableNFTables: dErr == nil && disableNFTables,
  225. RouteAddressSet: &inbound.routeAddressSet,
  226. RouteExcludeAddressSet: &inbound.routeExcludeAddressSet,
  227. })
  228. if err != nil {
  229. return nil, E.Cause(err, "initialize auto-redirect")
  230. }
  231. if !C.IsAndroid && (len(inbound.routeRuleSet) > 0 || len(inbound.routeExcludeRuleSet) > 0) {
  232. inbound.tunOptions.AutoRedirectMarkMode = true
  233. err = networkManager.RegisterAutoRedirectOutputMark(inbound.tunOptions.AutoRedirectOutputMark)
  234. if err != nil {
  235. return nil, err
  236. }
  237. }
  238. }
  239. return inbound, nil
  240. }
  241. func uidToRange(uidList badoption.Listable[uint32]) []ranges.Range[uint32] {
  242. return common.Map(uidList, func(uid uint32) ranges.Range[uint32] {
  243. return ranges.NewSingle(uid)
  244. })
  245. }
  246. func parseRange(uidRanges []ranges.Range[uint32], rangeList []string) ([]ranges.Range[uint32], error) {
  247. for _, uidRange := range rangeList {
  248. if !strings.Contains(uidRange, ":") {
  249. return nil, E.New("missing ':' in range: ", uidRange)
  250. }
  251. subIndex := strings.Index(uidRange, ":")
  252. if subIndex == 0 {
  253. return nil, E.New("missing range start: ", uidRange)
  254. } else if subIndex == len(uidRange)-1 {
  255. return nil, E.New("missing range end: ", uidRange)
  256. }
  257. var start, end uint64
  258. var err error
  259. start, err = strconv.ParseUint(uidRange[:subIndex], 0, 32)
  260. if err != nil {
  261. return nil, E.Cause(err, "parse range start")
  262. }
  263. end, err = strconv.ParseUint(uidRange[subIndex+1:], 0, 32)
  264. if err != nil {
  265. return nil, E.Cause(err, "parse range end")
  266. }
  267. uidRanges = append(uidRanges, ranges.New(uint32(start), uint32(end)))
  268. }
  269. return uidRanges, nil
  270. }
  271. func (t *Inbound) Type() string {
  272. return C.TypeTun
  273. }
  274. func (t *Inbound) Tag() string {
  275. return t.tag
  276. }
  277. func (t *Inbound) Start(stage adapter.StartStage) error {
  278. switch stage {
  279. case adapter.StartStateStart:
  280. if C.IsAndroid && t.platformInterface == nil {
  281. t.tunOptions.BuildAndroidRules(t.networkManager.PackageManager())
  282. }
  283. if t.tunOptions.Name == "" {
  284. t.tunOptions.Name = tun.CalculateInterfaceName("")
  285. }
  286. if t.platformInterface == nil {
  287. t.routeAddressSet = common.FlatMap(t.routeRuleSet, adapter.RuleSet.ExtractIPSet)
  288. for _, routeRuleSet := range t.routeRuleSet {
  289. ipSets := routeRuleSet.ExtractIPSet()
  290. if len(ipSets) == 0 {
  291. t.logger.Warn("route_address_set: no destination IP CIDR rules found in rule-set: ", routeRuleSet.Name())
  292. }
  293. routeRuleSet.DecRef()
  294. t.routeAddressSet = append(t.routeAddressSet, ipSets...)
  295. if t.autoRedirect != nil {
  296. t.routeRuleSetCallback = append(t.routeRuleSetCallback, routeRuleSet.RegisterCallback(t.updateRouteAddressSet))
  297. }
  298. }
  299. t.routeExcludeAddressSet = common.FlatMap(t.routeExcludeRuleSet, adapter.RuleSet.ExtractIPSet)
  300. for _, routeExcludeRuleSet := range t.routeExcludeRuleSet {
  301. ipSets := routeExcludeRuleSet.ExtractIPSet()
  302. if len(ipSets) == 0 {
  303. t.logger.Warn("route_address_set: no destination IP CIDR rules found in rule-set: ", routeExcludeRuleSet.Name())
  304. }
  305. routeExcludeRuleSet.DecRef()
  306. t.routeExcludeAddressSet = append(t.routeExcludeAddressSet, ipSets...)
  307. if t.autoRedirect != nil {
  308. t.routeExcludeRuleSetCallback = append(t.routeExcludeRuleSetCallback, routeExcludeRuleSet.RegisterCallback(t.updateRouteAddressSet))
  309. }
  310. }
  311. }
  312. var (
  313. tunInterface tun.Tun
  314. err error
  315. )
  316. monitor := taskmonitor.New(t.logger, C.StartTimeout)
  317. tunOptions := t.tunOptions
  318. if t.autoRedirect == nil && !(runtime.GOOS == "android" && t.platformInterface != nil) {
  319. for _, ipSet := range t.routeAddressSet {
  320. for _, prefix := range ipSet.Prefixes() {
  321. if prefix.Addr().Is4() {
  322. tunOptions.Inet4RouteAddress = append(tunOptions.Inet4RouteAddress, prefix)
  323. } else {
  324. tunOptions.Inet6RouteAddress = append(tunOptions.Inet6RouteAddress, prefix)
  325. }
  326. }
  327. }
  328. for _, ipSet := range t.routeExcludeAddressSet {
  329. for _, prefix := range ipSet.Prefixes() {
  330. if prefix.Addr().Is4() {
  331. tunOptions.Inet4RouteExcludeAddress = append(tunOptions.Inet4RouteExcludeAddress, prefix)
  332. } else {
  333. tunOptions.Inet6RouteExcludeAddress = append(tunOptions.Inet6RouteExcludeAddress, prefix)
  334. }
  335. }
  336. }
  337. }
  338. monitor.Start("open interface")
  339. if t.platformInterface != nil {
  340. tunInterface, err = t.platformInterface.OpenTun(&tunOptions, t.platformOptions)
  341. } else {
  342. tunInterface, err = tun.New(tunOptions)
  343. }
  344. monitor.Finish()
  345. t.tunOptions.Name = tunOptions.Name
  346. if err != nil {
  347. return E.Cause(err, "configure tun interface")
  348. }
  349. t.logger.Trace("creating stack")
  350. t.tunIf = tunInterface
  351. var (
  352. forwarderBindInterface bool
  353. includeAllNetworks bool
  354. )
  355. if t.platformInterface != nil {
  356. forwarderBindInterface = true
  357. includeAllNetworks = t.platformInterface.IncludeAllNetworks()
  358. }
  359. tunStack, err := tun.NewStack(t.stack, tun.StackOptions{
  360. Context: t.ctx,
  361. Tun: tunInterface,
  362. TunOptions: t.tunOptions,
  363. UDPTimeout: t.udpTimeout,
  364. Handler: t,
  365. Logger: t.logger,
  366. ForwarderBindInterface: forwarderBindInterface,
  367. InterfaceFinder: t.networkManager.InterfaceFinder(),
  368. IncludeAllNetworks: includeAllNetworks,
  369. })
  370. if err != nil {
  371. return err
  372. }
  373. t.tunStack = tunStack
  374. t.logger.Info("started at ", t.tunOptions.Name)
  375. case adapter.StartStatePostStart:
  376. monitor := taskmonitor.New(t.logger, C.StartTimeout)
  377. monitor.Start("starting tun stack")
  378. err := t.tunStack.Start()
  379. monitor.Finish()
  380. if err != nil {
  381. return E.Cause(err, "starting tun stack")
  382. }
  383. monitor.Start("starting tun interface")
  384. err = t.tunIf.Start()
  385. monitor.Finish()
  386. if err != nil {
  387. return E.Cause(err, "starting TUN interface")
  388. }
  389. if t.autoRedirect != nil {
  390. monitor.Start("initialize auto-redirect")
  391. err := t.autoRedirect.Start()
  392. monitor.Finish()
  393. if err != nil {
  394. return E.Cause(err, "auto-redirect")
  395. }
  396. }
  397. t.routeAddressSet = nil
  398. t.routeExcludeAddressSet = nil
  399. }
  400. return nil
  401. }
  402. func (t *Inbound) updateRouteAddressSet(it adapter.RuleSet) {
  403. t.routeAddressSet = common.FlatMap(t.routeRuleSet, adapter.RuleSet.ExtractIPSet)
  404. t.routeExcludeAddressSet = common.FlatMap(t.routeExcludeRuleSet, adapter.RuleSet.ExtractIPSet)
  405. t.autoRedirect.UpdateRouteAddressSet()
  406. t.routeAddressSet = nil
  407. t.routeExcludeAddressSet = nil
  408. }
  409. func (t *Inbound) Close() error {
  410. return common.Close(
  411. t.tunStack,
  412. t.tunIf,
  413. t.autoRedirect,
  414. )
  415. }
  416. func (t *Inbound) PrepareConnection(network string, source M.Socksaddr, destination M.Socksaddr, routeContext tun.DirectRouteContext) (tun.DirectRouteDestination, error) {
  417. routeDestination, err := t.router.PreMatch(adapter.InboundContext{
  418. Inbound: t.tag,
  419. InboundType: C.TypeTun,
  420. Network: network,
  421. Source: source,
  422. Destination: destination,
  423. InboundOptions: t.inboundOptions,
  424. }, routeContext)
  425. if err != nil {
  426. if !E.IsMulti(err, tun.ErrDrop, syscall.ECONNREFUSED) {
  427. t.logger.Warn(err)
  428. }
  429. }
  430. return routeDestination, err
  431. }
  432. func (t *Inbound) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  433. ctx = log.ContextWithNewID(ctx)
  434. var metadata adapter.InboundContext
  435. metadata.Inbound = t.tag
  436. metadata.InboundType = C.TypeTun
  437. metadata.Source = source
  438. metadata.Destination = destination
  439. //nolint:staticcheck
  440. metadata.InboundOptions = t.inboundOptions
  441. t.logger.InfoContext(ctx, "inbound connection from ", metadata.Source)
  442. t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  443. t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  444. }
  445. func (t *Inbound) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  446. ctx = log.ContextWithNewID(ctx)
  447. var metadata adapter.InboundContext
  448. metadata.Inbound = t.tag
  449. metadata.InboundType = C.TypeTun
  450. metadata.Source = source
  451. metadata.Destination = destination
  452. //nolint:staticcheck
  453. metadata.InboundOptions = t.inboundOptions
  454. t.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source)
  455. t.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
  456. t.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  457. }
  458. type autoRedirectHandler Inbound
  459. func (t *autoRedirectHandler) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  460. ctx = log.ContextWithNewID(ctx)
  461. var metadata adapter.InboundContext
  462. metadata.Inbound = t.tag
  463. metadata.InboundType = C.TypeTun
  464. metadata.Source = source
  465. metadata.Destination = destination
  466. //nolint:staticcheck
  467. metadata.InboundOptions = t.inboundOptions
  468. t.logger.InfoContext(ctx, "inbound redirect connection from ", metadata.Source)
  469. t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  470. t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  471. }