router.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. package route
  2. import (
  3. "context"
  4. "net"
  5. "net/netip"
  6. "net/url"
  7. "os"
  8. "os/user"
  9. "strings"
  10. "time"
  11. "github.com/sagernet/sing-box/adapter"
  12. "github.com/sagernet/sing-box/common/dialer"
  13. "github.com/sagernet/sing-box/common/geoip"
  14. "github.com/sagernet/sing-box/common/geosite"
  15. "github.com/sagernet/sing-box/common/mux"
  16. "github.com/sagernet/sing-box/common/process"
  17. "github.com/sagernet/sing-box/common/sniff"
  18. "github.com/sagernet/sing-box/common/warning"
  19. C "github.com/sagernet/sing-box/constant"
  20. "github.com/sagernet/sing-box/experimental/libbox/platform"
  21. "github.com/sagernet/sing-box/log"
  22. "github.com/sagernet/sing-box/ntp"
  23. "github.com/sagernet/sing-box/option"
  24. "github.com/sagernet/sing-dns"
  25. "github.com/sagernet/sing-tun"
  26. "github.com/sagernet/sing-vmess"
  27. "github.com/sagernet/sing/common"
  28. "github.com/sagernet/sing/common/buf"
  29. "github.com/sagernet/sing/common/bufio"
  30. "github.com/sagernet/sing/common/control"
  31. E "github.com/sagernet/sing/common/exceptions"
  32. F "github.com/sagernet/sing/common/format"
  33. M "github.com/sagernet/sing/common/metadata"
  34. N "github.com/sagernet/sing/common/network"
  35. "github.com/sagernet/sing/common/uot"
  36. )
  37. var warnDefaultInterfaceOnUnsupportedPlatform = warning.New(
  38. func() bool {
  39. return !(C.IsLinux || C.IsWindows || C.IsDarwin)
  40. },
  41. "route option `default_mark` is only supported on Linux and Windows",
  42. )
  43. var warnDefaultMarkOnNonLinux = warning.New(
  44. func() bool {
  45. return !C.IsLinux
  46. },
  47. "route option `default_mark` is only supported on Linux",
  48. )
  49. var warnFindProcessOnUnsupportedPlatform = warning.New(
  50. func() bool {
  51. return !(C.IsLinux || C.IsWindows || C.IsDarwin)
  52. },
  53. "route option `find_process` is only supported on Linux, Windows, and macOS",
  54. )
  55. var _ adapter.Router = (*Router)(nil)
  56. type Router struct {
  57. ctx context.Context
  58. logger log.ContextLogger
  59. dnsLogger log.ContextLogger
  60. inboundByTag map[string]adapter.Inbound
  61. outbounds []adapter.Outbound
  62. outboundByTag map[string]adapter.Outbound
  63. rules []adapter.Rule
  64. ipRules []adapter.IPRule
  65. defaultDetour string
  66. defaultOutboundForConnection adapter.Outbound
  67. defaultOutboundForPacketConnection adapter.Outbound
  68. needGeoIPDatabase bool
  69. needGeositeDatabase bool
  70. geoIPOptions option.GeoIPOptions
  71. geositeOptions option.GeositeOptions
  72. geoIPReader *geoip.Reader
  73. geositeReader *geosite.Reader
  74. geositeCache map[string]adapter.Rule
  75. dnsClient *dns.Client
  76. defaultDomainStrategy dns.DomainStrategy
  77. dnsRules []adapter.DNSRule
  78. defaultTransport dns.Transport
  79. transports []dns.Transport
  80. transportMap map[string]dns.Transport
  81. transportDomainStrategy map[dns.Transport]dns.DomainStrategy
  82. interfaceFinder myInterfaceFinder
  83. autoDetectInterface bool
  84. defaultInterface string
  85. defaultMark int
  86. networkMonitor tun.NetworkUpdateMonitor
  87. interfaceMonitor tun.DefaultInterfaceMonitor
  88. packageManager tun.PackageManager
  89. processSearcher process.Searcher
  90. timeService adapter.TimeService
  91. clashServer adapter.ClashServer
  92. v2rayServer adapter.V2RayServer
  93. platformInterface platform.Interface
  94. }
  95. func NewRouter(
  96. ctx context.Context,
  97. logFactory log.Factory,
  98. options option.RouteOptions,
  99. dnsOptions option.DNSOptions,
  100. ntpOptions option.NTPOptions,
  101. inbounds []option.Inbound,
  102. platformInterface platform.Interface,
  103. ) (*Router, error) {
  104. if options.DefaultInterface != "" {
  105. warnDefaultInterfaceOnUnsupportedPlatform.Check()
  106. }
  107. if options.DefaultMark != 0 {
  108. warnDefaultMarkOnNonLinux.Check()
  109. }
  110. if options.FindProcess {
  111. warnFindProcessOnUnsupportedPlatform.Check()
  112. }
  113. router := &Router{
  114. ctx: ctx,
  115. logger: logFactory.NewLogger("router"),
  116. dnsLogger: logFactory.NewLogger("dns"),
  117. outboundByTag: make(map[string]adapter.Outbound),
  118. rules: make([]adapter.Rule, 0, len(options.Rules)),
  119. ipRules: make([]adapter.IPRule, 0, len(options.IPRules)),
  120. dnsRules: make([]adapter.DNSRule, 0, len(dnsOptions.Rules)),
  121. needGeoIPDatabase: hasRule(options.Rules, isGeoIPRule) || hasDNSRule(dnsOptions.Rules, isGeoIPDNSRule),
  122. needGeositeDatabase: hasRule(options.Rules, isGeositeRule) || hasDNSRule(dnsOptions.Rules, isGeositeDNSRule),
  123. geoIPOptions: common.PtrValueOrDefault(options.GeoIP),
  124. geositeOptions: common.PtrValueOrDefault(options.Geosite),
  125. geositeCache: make(map[string]adapter.Rule),
  126. defaultDetour: options.Final,
  127. defaultDomainStrategy: dns.DomainStrategy(dnsOptions.Strategy),
  128. autoDetectInterface: options.AutoDetectInterface,
  129. defaultInterface: options.DefaultInterface,
  130. defaultMark: options.DefaultMark,
  131. platformInterface: platformInterface,
  132. }
  133. router.dnsClient = dns.NewClient(dnsOptions.DNSClientOptions.DisableCache, dnsOptions.DNSClientOptions.DisableExpire, router.dnsLogger)
  134. for i, ruleOptions := range options.Rules {
  135. routeRule, err := NewRule(router, router.logger, ruleOptions)
  136. if err != nil {
  137. return nil, E.Cause(err, "parse rule[", i, "]")
  138. }
  139. router.rules = append(router.rules, routeRule)
  140. }
  141. for i, ipRuleOptions := range options.IPRules {
  142. ipRule, err := NewIPRule(router, router.logger, ipRuleOptions)
  143. if err != nil {
  144. return nil, E.Cause(err, "parse ip rule[", i, "]")
  145. }
  146. router.ipRules = append(router.ipRules, ipRule)
  147. }
  148. for i, dnsRuleOptions := range dnsOptions.Rules {
  149. dnsRule, err := NewDNSRule(router, router.logger, dnsRuleOptions)
  150. if err != nil {
  151. return nil, E.Cause(err, "parse dns rule[", i, "]")
  152. }
  153. router.dnsRules = append(router.dnsRules, dnsRule)
  154. }
  155. transports := make([]dns.Transport, len(dnsOptions.Servers))
  156. dummyTransportMap := make(map[string]dns.Transport)
  157. transportMap := make(map[string]dns.Transport)
  158. transportTags := make([]string, len(dnsOptions.Servers))
  159. transportTagMap := make(map[string]bool)
  160. transportDomainStrategy := make(map[dns.Transport]dns.DomainStrategy)
  161. for i, server := range dnsOptions.Servers {
  162. var tag string
  163. if server.Tag != "" {
  164. tag = server.Tag
  165. } else {
  166. tag = F.ToString(i)
  167. }
  168. if transportTagMap[tag] {
  169. return nil, E.New("duplicate dns server tag: ", tag)
  170. }
  171. transportTags[i] = tag
  172. transportTagMap[tag] = true
  173. }
  174. ctx = adapter.ContextWithRouter(ctx, router)
  175. for {
  176. lastLen := len(dummyTransportMap)
  177. for i, server := range dnsOptions.Servers {
  178. tag := transportTags[i]
  179. if _, exists := dummyTransportMap[tag]; exists {
  180. continue
  181. }
  182. var detour N.Dialer
  183. if server.Detour == "" {
  184. detour = dialer.NewRouter(router)
  185. } else {
  186. detour = dialer.NewDetour(router, server.Detour)
  187. }
  188. switch server.Address {
  189. case "local":
  190. default:
  191. serverURL, _ := url.Parse(server.Address)
  192. var serverAddress string
  193. if serverURL != nil {
  194. serverAddress = serverURL.Hostname()
  195. }
  196. if serverAddress == "" {
  197. serverAddress = server.Address
  198. }
  199. _, notIpAddress := netip.ParseAddr(serverAddress)
  200. if server.AddressResolver != "" {
  201. if !transportTagMap[server.AddressResolver] {
  202. return nil, E.New("parse dns server[", tag, "]: address resolver not found: ", server.AddressResolver)
  203. }
  204. if upstream, exists := dummyTransportMap[server.AddressResolver]; exists {
  205. detour = dns.NewDialerWrapper(detour, router.dnsClient, upstream, dns.DomainStrategy(server.AddressStrategy), time.Duration(server.AddressFallbackDelay))
  206. } else {
  207. continue
  208. }
  209. } else if notIpAddress != nil {
  210. switch serverURL.Scheme {
  211. case "rcode", "dhcp":
  212. default:
  213. return nil, E.New("parse dns server[", tag, "]: missing address_resolver")
  214. }
  215. }
  216. }
  217. transport, err := dns.CreateTransport(ctx, logFactory.NewLogger(F.ToString("dns/transport[", tag, "]")), detour, server.Address)
  218. if err != nil {
  219. return nil, E.Cause(err, "parse dns server[", tag, "]")
  220. }
  221. transports[i] = transport
  222. dummyTransportMap[tag] = transport
  223. if server.Tag != "" {
  224. transportMap[server.Tag] = transport
  225. }
  226. strategy := dns.DomainStrategy(server.Strategy)
  227. if strategy != dns.DomainStrategyAsIS {
  228. transportDomainStrategy[transport] = strategy
  229. }
  230. }
  231. if len(transports) == len(dummyTransportMap) {
  232. break
  233. }
  234. if lastLen != len(dummyTransportMap) {
  235. continue
  236. }
  237. unresolvedTags := common.MapIndexed(common.FilterIndexed(dnsOptions.Servers, func(index int, server option.DNSServerOptions) bool {
  238. _, exists := dummyTransportMap[transportTags[index]]
  239. return !exists
  240. }), func(index int, server option.DNSServerOptions) string {
  241. return transportTags[index]
  242. })
  243. if len(unresolvedTags) == 0 {
  244. panic(F.ToString("unexpected unresolved dns servers: ", len(transports), " ", len(dummyTransportMap), " ", len(transportMap)))
  245. }
  246. return nil, E.New("found circular reference in dns servers: ", strings.Join(unresolvedTags, " "))
  247. }
  248. var defaultTransport dns.Transport
  249. if dnsOptions.Final != "" {
  250. defaultTransport = dummyTransportMap[dnsOptions.Final]
  251. if defaultTransport == nil {
  252. return nil, E.New("default dns server not found: ", dnsOptions.Final)
  253. }
  254. }
  255. if defaultTransport == nil {
  256. if len(transports) == 0 {
  257. transports = append(transports, dns.NewLocalTransport(N.SystemDialer))
  258. }
  259. defaultTransport = transports[0]
  260. }
  261. router.defaultTransport = defaultTransport
  262. router.transports = transports
  263. router.transportMap = transportMap
  264. router.transportDomainStrategy = transportDomainStrategy
  265. needInterfaceMonitor := platformInterface == nil && (options.AutoDetectInterface || common.Any(inbounds, func(inbound option.Inbound) bool {
  266. return inbound.HTTPOptions.SetSystemProxy || inbound.MixedOptions.SetSystemProxy || inbound.TunOptions.AutoRoute
  267. }))
  268. if needInterfaceMonitor {
  269. networkMonitor, err := tun.NewNetworkUpdateMonitor(router)
  270. if err == nil {
  271. router.networkMonitor = networkMonitor
  272. networkMonitor.RegisterCallback(router.interfaceFinder.update)
  273. }
  274. }
  275. if router.networkMonitor != nil && needInterfaceMonitor {
  276. interfaceMonitor, err := tun.NewDefaultInterfaceMonitor(router.networkMonitor, tun.DefaultInterfaceMonitorOptions{
  277. OverrideAndroidVPN: options.OverrideAndroidVPN,
  278. })
  279. if err != nil {
  280. return nil, E.New("auto_detect_interface unsupported on current platform")
  281. }
  282. interfaceMonitor.RegisterCallback(router.notifyNetworkUpdate)
  283. router.interfaceMonitor = interfaceMonitor
  284. }
  285. needFindProcess := hasRule(options.Rules, isProcessRule) || hasDNSRule(dnsOptions.Rules, isProcessDNSRule) || options.FindProcess
  286. needPackageManager := C.IsAndroid && platformInterface == nil && (needFindProcess || common.Any(inbounds, func(inbound option.Inbound) bool {
  287. return len(inbound.TunOptions.IncludePackage) > 0 || len(inbound.TunOptions.ExcludePackage) > 0
  288. }))
  289. if needPackageManager {
  290. packageManager, err := tun.NewPackageManager(router)
  291. if err != nil {
  292. return nil, E.Cause(err, "create package manager")
  293. }
  294. router.packageManager = packageManager
  295. }
  296. if needFindProcess {
  297. if platformInterface != nil {
  298. router.processSearcher = platformInterface
  299. } else {
  300. searcher, err := process.NewSearcher(process.Config{
  301. Logger: logFactory.NewLogger("router/process"),
  302. PackageManager: router.packageManager,
  303. })
  304. if err != nil {
  305. if err != os.ErrInvalid {
  306. router.logger.Warn(E.Cause(err, "create process searcher"))
  307. }
  308. } else {
  309. router.processSearcher = searcher
  310. }
  311. }
  312. }
  313. if ntpOptions.Enabled {
  314. router.timeService = ntp.NewService(ctx, router, logFactory.NewLogger("ntp"), ntpOptions)
  315. }
  316. return router, nil
  317. }
  318. func (r *Router) Initialize(inbounds []adapter.Inbound, outbounds []adapter.Outbound, defaultOutbound func() adapter.Outbound) error {
  319. inboundByTag := make(map[string]adapter.Inbound)
  320. for _, inbound := range inbounds {
  321. inboundByTag[inbound.Tag()] = inbound
  322. }
  323. outboundByTag := make(map[string]adapter.Outbound)
  324. for _, detour := range outbounds {
  325. outboundByTag[detour.Tag()] = detour
  326. }
  327. var defaultOutboundForConnection adapter.Outbound
  328. var defaultOutboundForPacketConnection adapter.Outbound
  329. if r.defaultDetour != "" {
  330. detour, loaded := outboundByTag[r.defaultDetour]
  331. if !loaded {
  332. return E.New("default detour not found: ", r.defaultDetour)
  333. }
  334. if common.Contains(detour.Network(), N.NetworkTCP) {
  335. defaultOutboundForConnection = detour
  336. }
  337. if common.Contains(detour.Network(), N.NetworkUDP) {
  338. defaultOutboundForPacketConnection = detour
  339. }
  340. }
  341. var index, packetIndex int
  342. if defaultOutboundForConnection == nil {
  343. for i, detour := range outbounds {
  344. if common.Contains(detour.Network(), N.NetworkTCP) {
  345. index = i
  346. defaultOutboundForConnection = detour
  347. break
  348. }
  349. }
  350. }
  351. if defaultOutboundForPacketConnection == nil {
  352. for i, detour := range outbounds {
  353. if common.Contains(detour.Network(), N.NetworkUDP) {
  354. packetIndex = i
  355. defaultOutboundForPacketConnection = detour
  356. break
  357. }
  358. }
  359. }
  360. if defaultOutboundForConnection == nil || defaultOutboundForPacketConnection == nil {
  361. detour := defaultOutbound()
  362. if defaultOutboundForConnection == nil {
  363. defaultOutboundForConnection = detour
  364. }
  365. if defaultOutboundForPacketConnection == nil {
  366. defaultOutboundForPacketConnection = detour
  367. }
  368. outbounds = append(outbounds, detour)
  369. outboundByTag[detour.Tag()] = detour
  370. }
  371. if defaultOutboundForConnection != defaultOutboundForPacketConnection {
  372. var description string
  373. if defaultOutboundForConnection.Tag() != "" {
  374. description = defaultOutboundForConnection.Tag()
  375. } else {
  376. description = F.ToString(index)
  377. }
  378. var packetDescription string
  379. if defaultOutboundForPacketConnection.Tag() != "" {
  380. packetDescription = defaultOutboundForPacketConnection.Tag()
  381. } else {
  382. packetDescription = F.ToString(packetIndex)
  383. }
  384. r.logger.Info("using ", defaultOutboundForConnection.Type(), "[", description, "] as default outbound for connection")
  385. r.logger.Info("using ", defaultOutboundForPacketConnection.Type(), "[", packetDescription, "] as default outbound for packet connection")
  386. }
  387. r.inboundByTag = inboundByTag
  388. r.outbounds = outbounds
  389. r.defaultOutboundForConnection = defaultOutboundForConnection
  390. r.defaultOutboundForPacketConnection = defaultOutboundForPacketConnection
  391. r.outboundByTag = outboundByTag
  392. for i, rule := range r.rules {
  393. if _, loaded := outboundByTag[rule.Outbound()]; !loaded {
  394. return E.New("outbound not found for rule[", i, "]: ", rule.Outbound())
  395. }
  396. }
  397. return nil
  398. }
  399. func (r *Router) Outbounds() []adapter.Outbound {
  400. return r.outbounds
  401. }
  402. func (r *Router) Start() error {
  403. if r.needGeoIPDatabase {
  404. err := r.prepareGeoIPDatabase()
  405. if err != nil {
  406. return err
  407. }
  408. }
  409. if r.needGeositeDatabase {
  410. err := r.prepareGeositeDatabase()
  411. if err != nil {
  412. return err
  413. }
  414. }
  415. if r.interfaceMonitor != nil {
  416. err := r.interfaceMonitor.Start()
  417. if err != nil {
  418. return err
  419. }
  420. }
  421. if r.networkMonitor != nil {
  422. err := r.networkMonitor.Start()
  423. if err != nil {
  424. return err
  425. }
  426. }
  427. if r.packageManager != nil {
  428. err := r.packageManager.Start()
  429. if err != nil {
  430. return err
  431. }
  432. }
  433. if r.needGeositeDatabase {
  434. for _, rule := range r.rules {
  435. err := rule.UpdateGeosite()
  436. if err != nil {
  437. r.logger.Error("failed to initialize geosite: ", err)
  438. }
  439. }
  440. for _, rule := range r.dnsRules {
  441. err := rule.UpdateGeosite()
  442. if err != nil {
  443. r.logger.Error("failed to initialize geosite: ", err)
  444. }
  445. }
  446. err := common.Close(r.geositeReader)
  447. if err != nil {
  448. return err
  449. }
  450. r.geositeCache = nil
  451. r.geositeReader = nil
  452. }
  453. for i, rule := range r.rules {
  454. err := rule.Start()
  455. if err != nil {
  456. return E.Cause(err, "initialize rule[", i, "]")
  457. }
  458. }
  459. for i, rule := range r.dnsRules {
  460. err := rule.Start()
  461. if err != nil {
  462. return E.Cause(err, "initialize DNS rule[", i, "]")
  463. }
  464. }
  465. for i, transport := range r.transports {
  466. err := transport.Start()
  467. if err != nil {
  468. return E.Cause(err, "initialize DNS server[", i, "]")
  469. }
  470. }
  471. if r.timeService != nil {
  472. err := r.timeService.Start()
  473. if err != nil {
  474. return E.Cause(err, "initialize time service")
  475. }
  476. }
  477. return nil
  478. }
  479. func (r *Router) Close() error {
  480. for _, rule := range r.rules {
  481. err := rule.Close()
  482. if err != nil {
  483. return err
  484. }
  485. }
  486. for _, rule := range r.dnsRules {
  487. err := rule.Close()
  488. if err != nil {
  489. return err
  490. }
  491. }
  492. for _, transport := range r.transports {
  493. err := transport.Close()
  494. if err != nil {
  495. return err
  496. }
  497. }
  498. return common.Close(
  499. common.PtrOrNil(r.geoIPReader),
  500. r.interfaceMonitor,
  501. r.networkMonitor,
  502. r.packageManager,
  503. r.timeService,
  504. )
  505. }
  506. func (r *Router) Outbound(tag string) (adapter.Outbound, bool) {
  507. outbound, loaded := r.outboundByTag[tag]
  508. return outbound, loaded
  509. }
  510. func (r *Router) DefaultOutbound(network string) adapter.Outbound {
  511. if network == N.NetworkTCP {
  512. return r.defaultOutboundForConnection
  513. } else {
  514. return r.defaultOutboundForPacketConnection
  515. }
  516. }
  517. func (r *Router) RouteConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  518. if metadata.InboundDetour != "" {
  519. if metadata.LastInbound == metadata.InboundDetour {
  520. return E.New("routing loop on detour: ", metadata.InboundDetour)
  521. }
  522. detour := r.inboundByTag[metadata.InboundDetour]
  523. if detour == nil {
  524. return E.New("inbound detour not found: ", metadata.InboundDetour)
  525. }
  526. injectable, isInjectable := detour.(adapter.InjectableInbound)
  527. if !isInjectable {
  528. return E.New("inbound detour is not injectable: ", metadata.InboundDetour)
  529. }
  530. if !common.Contains(injectable.Network(), N.NetworkTCP) {
  531. return E.New("inject: TCP unsupported")
  532. }
  533. metadata.LastInbound = metadata.Inbound
  534. metadata.Inbound = metadata.InboundDetour
  535. metadata.InboundDetour = ""
  536. err := injectable.NewConnection(ctx, conn, metadata)
  537. if err != nil {
  538. return E.Cause(err, "inject ", detour.Tag())
  539. }
  540. return nil
  541. }
  542. metadata.Network = N.NetworkTCP
  543. switch metadata.Destination.Fqdn {
  544. case mux.Destination.Fqdn:
  545. r.logger.InfoContext(ctx, "inbound multiplex connection")
  546. return mux.NewConnection(ctx, r, r, r.logger, conn, metadata)
  547. case vmess.MuxDestination.Fqdn:
  548. r.logger.InfoContext(ctx, "inbound legacy multiplex connection")
  549. return vmess.HandleMuxConnection(ctx, conn, adapter.NewUpstreamHandler(metadata, r.RouteConnection, r.RoutePacketConnection, r))
  550. case uot.MagicAddress:
  551. request, err := uot.ReadRequest(conn)
  552. if err != nil {
  553. return E.Cause(err, "read UoT request")
  554. }
  555. if request.IsConnect {
  556. r.logger.InfoContext(ctx, "inbound UoT connect connection to ", request.Destination)
  557. } else {
  558. r.logger.InfoContext(ctx, "inbound UoT connection to ", request.Destination)
  559. }
  560. metadata.Domain = metadata.Destination.Fqdn
  561. metadata.Destination = request.Destination
  562. return r.RoutePacketConnection(ctx, uot.NewConn(conn, *request), metadata)
  563. case uot.LegacyMagicAddress:
  564. r.logger.InfoContext(ctx, "inbound legacy UoT connection")
  565. metadata.Domain = metadata.Destination.Fqdn
  566. metadata.Destination = M.Socksaddr{Addr: netip.IPv4Unspecified()}
  567. return r.RoutePacketConnection(ctx, uot.NewConn(conn, uot.Request{}), metadata)
  568. }
  569. if metadata.InboundOptions.SniffEnabled {
  570. buffer := buf.NewPacket()
  571. buffer.FullReset()
  572. sniffMetadata, _ := sniff.PeekStream(ctx, conn, buffer, time.Duration(metadata.InboundOptions.SniffTimeout), sniff.StreamDomainNameQuery, sniff.TLSClientHello, sniff.HTTPHost)
  573. if sniffMetadata != nil {
  574. metadata.Protocol = sniffMetadata.Protocol
  575. metadata.Domain = sniffMetadata.Domain
  576. if metadata.InboundOptions.SniffOverrideDestination && M.IsDomainName(metadata.Domain) {
  577. metadata.Destination = M.Socksaddr{
  578. Fqdn: metadata.Domain,
  579. Port: metadata.Destination.Port,
  580. }
  581. }
  582. if metadata.Domain != "" {
  583. r.logger.DebugContext(ctx, "sniffed protocol: ", metadata.Protocol, ", domain: ", metadata.Domain)
  584. } else {
  585. r.logger.DebugContext(ctx, "sniffed protocol: ", metadata.Protocol)
  586. }
  587. }
  588. if !buffer.IsEmpty() {
  589. conn = bufio.NewCachedConn(conn, buffer)
  590. } else {
  591. buffer.Release()
  592. }
  593. }
  594. if metadata.Destination.IsFqdn() && dns.DomainStrategy(metadata.InboundOptions.DomainStrategy) != dns.DomainStrategyAsIS {
  595. addresses, err := r.Lookup(adapter.WithContext(ctx, &metadata), metadata.Destination.Fqdn, dns.DomainStrategy(metadata.InboundOptions.DomainStrategy))
  596. if err != nil {
  597. return err
  598. }
  599. metadata.DestinationAddresses = addresses
  600. r.dnsLogger.DebugContext(ctx, "resolved [", strings.Join(F.MapToString(metadata.DestinationAddresses), " "), "]")
  601. }
  602. matchedRule, detour := r.match(ctx, &metadata, r.defaultOutboundForConnection)
  603. if !common.Contains(detour.Network(), N.NetworkTCP) {
  604. conn.Close()
  605. return E.New("missing supported outbound, closing connection")
  606. }
  607. if r.clashServer != nil {
  608. trackerConn, tracker := r.clashServer.RoutedConnection(ctx, conn, metadata, matchedRule)
  609. defer tracker.Leave()
  610. conn = trackerConn
  611. }
  612. if r.v2rayServer != nil {
  613. if statsService := r.v2rayServer.StatsService(); statsService != nil {
  614. conn = statsService.RoutedConnection(metadata.Inbound, detour.Tag(), metadata.User, conn)
  615. }
  616. }
  617. return detour.NewConnection(ctx, conn, metadata)
  618. }
  619. func (r *Router) RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  620. if metadata.InboundDetour != "" {
  621. if metadata.LastInbound == metadata.InboundDetour {
  622. return E.New("routing loop on detour: ", metadata.InboundDetour)
  623. }
  624. detour := r.inboundByTag[metadata.InboundDetour]
  625. if detour == nil {
  626. return E.New("inbound detour not found: ", metadata.InboundDetour)
  627. }
  628. injectable, isInjectable := detour.(adapter.InjectableInbound)
  629. if !isInjectable {
  630. return E.New("inbound detour is not injectable: ", metadata.InboundDetour)
  631. }
  632. if !common.Contains(injectable.Network(), N.NetworkUDP) {
  633. return E.New("inject: UDP unsupported")
  634. }
  635. metadata.LastInbound = metadata.Inbound
  636. metadata.Inbound = metadata.InboundDetour
  637. metadata.InboundDetour = ""
  638. err := injectable.NewPacketConnection(ctx, conn, metadata)
  639. if err != nil {
  640. return E.Cause(err, "inject ", detour.Tag())
  641. }
  642. return nil
  643. }
  644. metadata.Network = N.NetworkUDP
  645. if metadata.InboundOptions.SniffEnabled {
  646. buffer := buf.NewPacket()
  647. buffer.FullReset()
  648. destination, err := conn.ReadPacket(buffer)
  649. if err != nil {
  650. buffer.Release()
  651. return err
  652. }
  653. sniffMetadata, _ := sniff.PeekPacket(ctx, buffer.Bytes(), sniff.DomainNameQuery, sniff.QUICClientHello, sniff.STUNMessage)
  654. if sniffMetadata != nil {
  655. metadata.Protocol = sniffMetadata.Protocol
  656. metadata.Domain = sniffMetadata.Domain
  657. if metadata.InboundOptions.SniffOverrideDestination && M.IsDomainName(metadata.Domain) {
  658. metadata.Destination = M.Socksaddr{
  659. Fqdn: metadata.Domain,
  660. Port: metadata.Destination.Port,
  661. }
  662. }
  663. if metadata.Domain != "" {
  664. r.logger.DebugContext(ctx, "sniffed packet protocol: ", metadata.Protocol, ", domain: ", metadata.Domain)
  665. } else {
  666. r.logger.DebugContext(ctx, "sniffed packet protocol: ", metadata.Protocol)
  667. }
  668. }
  669. conn = bufio.NewCachedPacketConn(conn, buffer, destination)
  670. }
  671. if metadata.Destination.IsFqdn() && dns.DomainStrategy(metadata.InboundOptions.DomainStrategy) != dns.DomainStrategyAsIS {
  672. addresses, err := r.Lookup(adapter.WithContext(ctx, &metadata), metadata.Destination.Fqdn, dns.DomainStrategy(metadata.InboundOptions.DomainStrategy))
  673. if err != nil {
  674. return err
  675. }
  676. metadata.DestinationAddresses = addresses
  677. r.dnsLogger.DebugContext(ctx, "resolved [", strings.Join(F.MapToString(metadata.DestinationAddresses), " "), "]")
  678. }
  679. matchedRule, detour := r.match(ctx, &metadata, r.defaultOutboundForPacketConnection)
  680. if !common.Contains(detour.Network(), N.NetworkUDP) {
  681. conn.Close()
  682. return E.New("missing supported outbound, closing packet connection")
  683. }
  684. if r.clashServer != nil {
  685. trackerConn, tracker := r.clashServer.RoutedPacketConnection(ctx, conn, metadata, matchedRule)
  686. defer tracker.Leave()
  687. conn = trackerConn
  688. }
  689. if r.v2rayServer != nil {
  690. if statsService := r.v2rayServer.StatsService(); statsService != nil {
  691. conn = statsService.RoutedPacketConnection(metadata.Inbound, detour.Tag(), metadata.User, conn)
  692. }
  693. }
  694. return detour.NewPacketConnection(ctx, conn, metadata)
  695. }
  696. func (r *Router) match(ctx context.Context, metadata *adapter.InboundContext, defaultOutbound adapter.Outbound) (adapter.Rule, adapter.Outbound) {
  697. if r.processSearcher != nil {
  698. var originDestination netip.AddrPort
  699. if metadata.OriginDestination.IsValid() {
  700. originDestination = metadata.OriginDestination.AddrPort()
  701. } else if metadata.Destination.IsIP() {
  702. originDestination = metadata.Destination.AddrPort()
  703. }
  704. processInfo, err := process.FindProcessInfo(r.processSearcher, ctx, metadata.Network, metadata.Source.AddrPort(), originDestination)
  705. if err != nil {
  706. r.logger.InfoContext(ctx, "failed to search process: ", err)
  707. } else {
  708. if processInfo.ProcessPath != "" {
  709. r.logger.InfoContext(ctx, "found process path: ", processInfo.ProcessPath)
  710. } else if processInfo.PackageName != "" {
  711. r.logger.InfoContext(ctx, "found package name: ", processInfo.PackageName)
  712. } else if processInfo.UserId != -1 {
  713. if /*needUserName &&*/ true {
  714. osUser, _ := user.LookupId(F.ToString(processInfo.UserId))
  715. if osUser != nil {
  716. processInfo.User = osUser.Username
  717. }
  718. }
  719. if processInfo.User != "" {
  720. r.logger.InfoContext(ctx, "found user: ", processInfo.User)
  721. } else {
  722. r.logger.InfoContext(ctx, "found user id: ", processInfo.UserId)
  723. }
  724. }
  725. metadata.ProcessInfo = processInfo
  726. }
  727. }
  728. for i, rule := range r.rules {
  729. if rule.Match(metadata) {
  730. detour := rule.Outbound()
  731. r.logger.DebugContext(ctx, "match[", i, "] ", rule.String(), " => ", detour)
  732. if outbound, loaded := r.Outbound(detour); loaded {
  733. return rule, outbound
  734. }
  735. r.logger.ErrorContext(ctx, "outbound not found: ", detour)
  736. }
  737. }
  738. return nil, defaultOutbound
  739. }
  740. func (r *Router) InterfaceFinder() control.InterfaceFinder {
  741. return &r.interfaceFinder
  742. }
  743. func (r *Router) AutoDetectInterface() bool {
  744. return r.autoDetectInterface
  745. }
  746. func (r *Router) AutoDetectInterfaceFunc() control.Func {
  747. if r.platformInterface != nil {
  748. return r.platformInterface.AutoDetectInterfaceControl()
  749. } else {
  750. return control.BindToInterfaceFunc(r.InterfaceFinder(), func(network string, address string) (interfaceName string, interfaceIndex int) {
  751. remoteAddr := M.ParseSocksaddr(address).Addr
  752. if C.IsLinux {
  753. return r.InterfaceMonitor().DefaultInterfaceName(remoteAddr), -1
  754. } else {
  755. return "", r.InterfaceMonitor().DefaultInterfaceIndex(remoteAddr)
  756. }
  757. })
  758. }
  759. }
  760. func (r *Router) DefaultInterface() string {
  761. return r.defaultInterface
  762. }
  763. func (r *Router) DefaultMark() int {
  764. return r.defaultMark
  765. }
  766. func (r *Router) Rules() []adapter.Rule {
  767. return r.rules
  768. }
  769. func (r *Router) IPRules() []adapter.IPRule {
  770. return r.ipRules
  771. }
  772. func (r *Router) NetworkMonitor() tun.NetworkUpdateMonitor {
  773. return r.networkMonitor
  774. }
  775. func (r *Router) InterfaceMonitor() tun.DefaultInterfaceMonitor {
  776. return r.interfaceMonitor
  777. }
  778. func (r *Router) PackageManager() tun.PackageManager {
  779. return r.packageManager
  780. }
  781. func (r *Router) TimeFunc() func() time.Time {
  782. if r.timeService == nil {
  783. return nil
  784. }
  785. return r.timeService.TimeFunc()
  786. }
  787. func (r *Router) ClashServer() adapter.ClashServer {
  788. return r.clashServer
  789. }
  790. func (r *Router) SetClashServer(server adapter.ClashServer) {
  791. r.clashServer = server
  792. }
  793. func (r *Router) V2RayServer() adapter.V2RayServer {
  794. return r.v2rayServer
  795. }
  796. func (r *Router) SetV2RayServer(server adapter.V2RayServer) {
  797. r.v2rayServer = server
  798. }
  799. func (r *Router) OnPackagesUpdated(packages int, sharedUsers int) {
  800. r.logger.Info("updated packages list: ", packages, " packages, ", sharedUsers, " shared users")
  801. }
  802. func (r *Router) NewError(ctx context.Context, err error) {
  803. common.Close(err)
  804. if E.IsClosedOrCanceled(err) {
  805. r.logger.DebugContext(ctx, "connection closed: ", err)
  806. return
  807. }
  808. r.logger.ErrorContext(ctx, err)
  809. }
  810. func (r *Router) notifyNetworkUpdate(int) error {
  811. if C.IsAndroid {
  812. var vpnStatus string
  813. if r.interfaceMonitor.AndroidVPNEnabled() {
  814. vpnStatus = "enabled"
  815. } else {
  816. vpnStatus = "disabled"
  817. }
  818. r.logger.Info("updated default interface ", r.interfaceMonitor.DefaultInterfaceName(netip.IPv4Unspecified()), ", index ", r.interfaceMonitor.DefaultInterfaceIndex(netip.IPv4Unspecified()), ", vpn ", vpnStatus)
  819. } else {
  820. r.logger.Info("updated default interface ", r.interfaceMonitor.DefaultInterfaceName(netip.IPv4Unspecified()), ", index ", r.interfaceMonitor.DefaultInterfaceIndex(netip.IPv4Unspecified()))
  821. }
  822. for _, outbound := range r.outbounds {
  823. listener, isListener := outbound.(adapter.InterfaceUpdateListener)
  824. if isListener {
  825. err := listener.InterfaceUpdated()
  826. if err != nil {
  827. return err
  828. }
  829. }
  830. }
  831. return nil
  832. }