router.go 34 KB

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