router.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. package route
  2. import (
  3. "context"
  4. "io"
  5. "net"
  6. "net/http"
  7. "os"
  8. "path/filepath"
  9. "time"
  10. "github.com/oschwald/geoip2-golang"
  11. "github.com/sagernet/sing-box/adapter"
  12. C "github.com/sagernet/sing-box/constant"
  13. "github.com/sagernet/sing-box/log"
  14. "github.com/sagernet/sing-box/option"
  15. "github.com/sagernet/sing/common"
  16. E "github.com/sagernet/sing/common/exceptions"
  17. M "github.com/sagernet/sing/common/metadata"
  18. N "github.com/sagernet/sing/common/network"
  19. )
  20. var _ adapter.Router = (*Router)(nil)
  21. type Router struct {
  22. ctx context.Context
  23. logger log.Logger
  24. defaultOutbound adapter.Outbound
  25. outboundByTag map[string]adapter.Outbound
  26. rules []adapter.Rule
  27. needGeoDatabase bool
  28. geoOptions option.GeoIPOptions
  29. geoReader *geoip2.Reader
  30. }
  31. func NewRouter(ctx context.Context, logger log.Logger, options option.RouteOptions) (*Router, error) {
  32. router := &Router{
  33. ctx: ctx,
  34. logger: logger.WithPrefix("router: "),
  35. outboundByTag: make(map[string]adapter.Outbound),
  36. rules: make([]adapter.Rule, 0, len(options.Rules)),
  37. needGeoDatabase: hasGeoRule(options.Rules),
  38. geoOptions: common.PtrValueOrDefault(options.GeoIP),
  39. }
  40. for i, ruleOptions := range options.Rules {
  41. rule, err := NewRule(router, logger, ruleOptions)
  42. if err != nil {
  43. return nil, E.Cause(err, "parse rule[", i, "]")
  44. }
  45. router.rules = append(router.rules, rule)
  46. }
  47. return router, nil
  48. }
  49. func hasGeoRule(rules []option.Rule) bool {
  50. for _, rule := range rules {
  51. if rule.DefaultOptions != nil {
  52. if isGeoRule(common.PtrValueOrDefault(rule.DefaultOptions)) {
  53. return true
  54. }
  55. } else if rule.LogicalOptions != nil {
  56. for _, subRule := range rule.LogicalOptions.Rules {
  57. if isGeoRule(subRule) {
  58. return true
  59. }
  60. }
  61. }
  62. }
  63. return false
  64. }
  65. func isGeoRule(rule option.DefaultRule) bool {
  66. return len(rule.SourceGeoIP) > 0 && common.Any(rule.SourceGeoIP, notPrivateNode) || len(rule.GeoIP) > 0 && common.Any(rule.GeoIP, notPrivateNode)
  67. }
  68. func notPrivateNode(code string) bool {
  69. return code == "private"
  70. }
  71. func (r *Router) UpdateOutbounds(outbounds []adapter.Outbound) {
  72. var defaultOutbound adapter.Outbound
  73. outboundByTag := make(map[string]adapter.Outbound)
  74. if len(outbounds) > 0 {
  75. defaultOutbound = outbounds[0]
  76. }
  77. for _, outbound := range outbounds {
  78. outboundByTag[outbound.Tag()] = outbound
  79. }
  80. r.defaultOutbound = defaultOutbound
  81. r.outboundByTag = outboundByTag
  82. }
  83. func (r *Router) Start() error {
  84. if r.needGeoDatabase {
  85. go r.prepareGeoIPDatabase()
  86. }
  87. return nil
  88. }
  89. func (r *Router) Close() error {
  90. return common.Close(
  91. common.PtrOrNil(r.geoReader),
  92. )
  93. }
  94. func (r *Router) GeoIPReader() *geoip2.Reader {
  95. return r.geoReader
  96. }
  97. func (r *Router) prepareGeoIPDatabase() {
  98. var geoPath string
  99. if r.geoOptions.Path != "" {
  100. geoPath = r.geoOptions.Path
  101. } else {
  102. geoPath = "Country.mmdb"
  103. }
  104. geoPath, loaded := C.Find(geoPath)
  105. if !loaded {
  106. r.logger.Warn("geoip database not exists: ", geoPath)
  107. var err error
  108. for attempts := 0; attempts < 3; attempts++ {
  109. err = r.downloadGeoIPDatabase(geoPath)
  110. if err == nil {
  111. break
  112. }
  113. r.logger.Error("download geoip database: ", err)
  114. os.Remove(geoPath)
  115. time.Sleep(10 * time.Second)
  116. }
  117. if err != nil {
  118. return
  119. }
  120. }
  121. geoReader, err := geoip2.Open(geoPath)
  122. if err == nil {
  123. r.logger.Info("loaded geoip database")
  124. r.geoReader = geoReader
  125. } else {
  126. r.logger.Error("open geoip database: ", err)
  127. return
  128. }
  129. }
  130. func (r *Router) downloadGeoIPDatabase(savePath string) error {
  131. var downloadURL string
  132. if r.geoOptions.DownloadURL != "" {
  133. downloadURL = r.geoOptions.DownloadURL
  134. } else {
  135. downloadURL = "https://cdn.jsdelivr.net/gh/Dreamacro/maxmind-geoip@release/Country.mmdb"
  136. }
  137. r.logger.Info("downloading geoip database")
  138. var detour adapter.Outbound
  139. if r.geoOptions.DownloadDetour != "" {
  140. outbound, loaded := r.Outbound(r.geoOptions.DownloadDetour)
  141. if !loaded {
  142. return E.New("detour outbound not found: ", r.geoOptions.DownloadDetour)
  143. }
  144. detour = outbound
  145. } else {
  146. detour = r.defaultOutbound
  147. }
  148. if parentDir := filepath.Dir(savePath); parentDir != "" {
  149. os.MkdirAll(parentDir, 0o755)
  150. }
  151. saveFile, err := os.OpenFile(savePath, os.O_CREATE|os.O_WRONLY, 0o644)
  152. if err != nil {
  153. return E.Cause(err, "open output file: ", downloadURL)
  154. }
  155. defer saveFile.Close()
  156. httpClient := &http.Client{
  157. Timeout: 5 * time.Second,
  158. Transport: &http.Transport{
  159. ForceAttemptHTTP2: true,
  160. TLSHandshakeTimeout: 5 * time.Second,
  161. DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
  162. return detour.DialContext(ctx, network, M.ParseSocksaddr(addr))
  163. },
  164. },
  165. }
  166. response, err := httpClient.Get(downloadURL)
  167. if err != nil {
  168. return err
  169. }
  170. defer response.Body.Close()
  171. _, err = io.Copy(saveFile, response.Body)
  172. return err
  173. }
  174. func (r *Router) DefaultOutbound() adapter.Outbound {
  175. if r.defaultOutbound == nil {
  176. panic("missing default outbound")
  177. }
  178. return r.defaultOutbound
  179. }
  180. func (r *Router) Outbound(tag string) (adapter.Outbound, bool) {
  181. outbound, loaded := r.outboundByTag[tag]
  182. return outbound, loaded
  183. }
  184. func (r *Router) RouteConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  185. return r.match(ctx, metadata).NewConnection(ctx, conn, metadata.Destination)
  186. }
  187. func (r *Router) RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  188. return r.match(ctx, metadata).NewPacketConnection(ctx, conn, metadata.Destination)
  189. }
  190. func (r *Router) match(ctx context.Context, metadata adapter.InboundContext) adapter.Outbound {
  191. for i, rule := range r.rules {
  192. if rule.Match(&metadata) {
  193. detour := rule.Outbound()
  194. r.logger.WithContext(ctx).Info("match [", i, "]", rule.String(), " => ", detour)
  195. if outbound, loaded := r.Outbound(detour); loaded {
  196. return outbound
  197. }
  198. r.logger.WithContext(ctx).Error("outbound not found: ", detour)
  199. }
  200. }
  201. r.logger.WithContext(ctx).Info("no match")
  202. return r.defaultOutbound
  203. }