1
0

router_geo_resources.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. package route
  2. import (
  3. "context"
  4. "io"
  5. "net"
  6. "net/http"
  7. "os"
  8. "path/filepath"
  9. "time"
  10. "github.com/sagernet/sing-box/adapter"
  11. "github.com/sagernet/sing-box/common/geoip"
  12. "github.com/sagernet/sing-box/common/geosite"
  13. C "github.com/sagernet/sing-box/constant"
  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. "github.com/sagernet/sing/common/rw"
  19. "github.com/sagernet/sing/service/filemanager"
  20. )
  21. func (r *Router) GeoIPReader() *geoip.Reader {
  22. return r.geoIPReader
  23. }
  24. func (r *Router) LoadGeosite(code string) (adapter.Rule, error) {
  25. rule, cached := r.geositeCache[code]
  26. if cached {
  27. return rule, nil
  28. }
  29. items, err := r.geositeReader.Read(code)
  30. if err != nil {
  31. return nil, err
  32. }
  33. rule, err = NewDefaultRule(r, nil, geosite.Compile(items))
  34. if err != nil {
  35. return nil, err
  36. }
  37. r.geositeCache[code] = rule
  38. return rule, nil
  39. }
  40. func (r *Router) prepareGeoIPDatabase() error {
  41. var geoPath string
  42. if r.geoIPOptions.Path != "" {
  43. geoPath = r.geoIPOptions.Path
  44. } else {
  45. geoPath = "geoip.db"
  46. if foundPath, loaded := C.FindPath(geoPath); loaded {
  47. geoPath = foundPath
  48. }
  49. }
  50. if !rw.FileExists(geoPath) {
  51. geoPath = filemanager.BasePath(r.ctx, geoPath)
  52. }
  53. if stat, err := os.Stat(geoPath); err == nil {
  54. if stat.IsDir() {
  55. return E.New("geoip path is a directory: ", geoPath)
  56. }
  57. if stat.Size() == 0 {
  58. os.Remove(geoPath)
  59. }
  60. }
  61. if !rw.FileExists(geoPath) {
  62. r.logger.Warn("geoip database not exists: ", geoPath)
  63. var err error
  64. for attempts := 0; attempts < 3; attempts++ {
  65. err = r.downloadGeoIPDatabase(geoPath)
  66. if err == nil {
  67. break
  68. }
  69. r.logger.Error("download geoip database: ", err)
  70. os.Remove(geoPath)
  71. // time.Sleep(10 * time.Second)
  72. }
  73. if err != nil {
  74. return err
  75. }
  76. }
  77. geoReader, codes, err := geoip.Open(geoPath)
  78. if err != nil {
  79. return E.Cause(err, "open geoip database")
  80. }
  81. r.logger.Info("loaded geoip database: ", len(codes), " codes")
  82. r.geoIPReader = geoReader
  83. return nil
  84. }
  85. func (r *Router) prepareGeositeDatabase() error {
  86. var geoPath string
  87. if r.geositeOptions.Path != "" {
  88. geoPath = r.geositeOptions.Path
  89. } else {
  90. geoPath = "geosite.db"
  91. if foundPath, loaded := C.FindPath(geoPath); loaded {
  92. geoPath = foundPath
  93. }
  94. }
  95. if !rw.FileExists(geoPath) {
  96. geoPath = filemanager.BasePath(r.ctx, geoPath)
  97. }
  98. if stat, err := os.Stat(geoPath); err == nil {
  99. if stat.IsDir() {
  100. return E.New("geoip path is a directory: ", geoPath)
  101. }
  102. if stat.Size() == 0 {
  103. os.Remove(geoPath)
  104. }
  105. }
  106. if !rw.FileExists(geoPath) {
  107. r.logger.Warn("geosite database not exists: ", geoPath)
  108. var err error
  109. for attempts := 0; attempts < 3; attempts++ {
  110. err = r.downloadGeositeDatabase(geoPath)
  111. if err == nil {
  112. break
  113. }
  114. r.logger.Error("download geosite database: ", err)
  115. os.Remove(geoPath)
  116. }
  117. if err != nil {
  118. return err
  119. }
  120. }
  121. geoReader, codes, err := geosite.Open(geoPath)
  122. if err == nil {
  123. r.logger.Info("loaded geosite database: ", len(codes), " codes")
  124. r.geositeReader = geoReader
  125. } else {
  126. return E.Cause(err, "open geosite database")
  127. }
  128. return nil
  129. }
  130. func (r *Router) downloadGeoIPDatabase(savePath string) error {
  131. var downloadURL string
  132. if r.geoIPOptions.DownloadURL != "" {
  133. downloadURL = r.geoIPOptions.DownloadURL
  134. } else {
  135. downloadURL = "https://github.com/SagerNet/sing-geoip/releases/latest/download/geoip.db"
  136. }
  137. r.logger.Info("downloading geoip database")
  138. var detour adapter.Outbound
  139. if r.geoIPOptions.DownloadDetour != "" {
  140. outbound, loaded := r.Outbound(r.geoIPOptions.DownloadDetour)
  141. if !loaded {
  142. return E.New("detour outbound not found: ", r.geoIPOptions.DownloadDetour)
  143. }
  144. detour = outbound
  145. } else {
  146. detour = r.defaultOutboundForConnection
  147. }
  148. if parentDir := filepath.Dir(savePath); parentDir != "" {
  149. filemanager.MkdirAll(r.ctx, parentDir, 0o755)
  150. }
  151. httpClient := &http.Client{
  152. Transport: &http.Transport{
  153. ForceAttemptHTTP2: true,
  154. TLSHandshakeTimeout: 5 * time.Second,
  155. DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
  156. return detour.DialContext(ctx, network, M.ParseSocksaddr(addr))
  157. },
  158. },
  159. }
  160. defer httpClient.CloseIdleConnections()
  161. request, err := http.NewRequest("GET", downloadURL, nil)
  162. if err != nil {
  163. return err
  164. }
  165. response, err := httpClient.Do(request.WithContext(r.ctx))
  166. if err != nil {
  167. return err
  168. }
  169. defer response.Body.Close()
  170. saveFile, err := filemanager.Create(r.ctx, savePath)
  171. if err != nil {
  172. return E.Cause(err, "open output file: ", downloadURL)
  173. }
  174. _, err = io.Copy(saveFile, response.Body)
  175. saveFile.Close()
  176. if err != nil {
  177. filemanager.Remove(r.ctx, savePath)
  178. }
  179. return err
  180. }
  181. func (r *Router) downloadGeositeDatabase(savePath string) error {
  182. var downloadURL string
  183. if r.geositeOptions.DownloadURL != "" {
  184. downloadURL = r.geositeOptions.DownloadURL
  185. } else {
  186. downloadURL = "https://github.com/SagerNet/sing-geosite/releases/latest/download/geosite.db"
  187. }
  188. r.logger.Info("downloading geosite database")
  189. var detour adapter.Outbound
  190. if r.geositeOptions.DownloadDetour != "" {
  191. outbound, loaded := r.Outbound(r.geositeOptions.DownloadDetour)
  192. if !loaded {
  193. return E.New("detour outbound not found: ", r.geositeOptions.DownloadDetour)
  194. }
  195. detour = outbound
  196. } else {
  197. detour = r.defaultOutboundForConnection
  198. }
  199. if parentDir := filepath.Dir(savePath); parentDir != "" {
  200. filemanager.MkdirAll(r.ctx, parentDir, 0o755)
  201. }
  202. httpClient := &http.Client{
  203. Transport: &http.Transport{
  204. ForceAttemptHTTP2: true,
  205. TLSHandshakeTimeout: 5 * time.Second,
  206. DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
  207. return detour.DialContext(ctx, network, M.ParseSocksaddr(addr))
  208. },
  209. },
  210. }
  211. defer httpClient.CloseIdleConnections()
  212. request, err := http.NewRequest("GET", downloadURL, nil)
  213. if err != nil {
  214. return err
  215. }
  216. response, err := httpClient.Do(request.WithContext(r.ctx))
  217. if err != nil {
  218. return err
  219. }
  220. defer response.Body.Close()
  221. saveFile, err := filemanager.Create(r.ctx, savePath)
  222. if err != nil {
  223. return E.Cause(err, "open output file: ", downloadURL)
  224. }
  225. _, err = io.Copy(saveFile, response.Body)
  226. saveFile.Close()
  227. if err != nil {
  228. filemanager.Remove(r.ctx, savePath)
  229. }
  230. return err
  231. }
  232. func hasRule(rules []option.Rule, cond func(rule option.DefaultRule) bool) bool {
  233. for _, rule := range rules {
  234. switch rule.Type {
  235. case C.RuleTypeDefault:
  236. if cond(rule.DefaultOptions) {
  237. return true
  238. }
  239. case C.RuleTypeLogical:
  240. if hasRule(rule.LogicalOptions.Rules, cond) {
  241. return true
  242. }
  243. }
  244. }
  245. return false
  246. }
  247. func hasDNSRule(rules []option.DNSRule, cond func(rule option.DefaultDNSRule) bool) bool {
  248. for _, rule := range rules {
  249. switch rule.Type {
  250. case C.RuleTypeDefault:
  251. if cond(rule.DefaultOptions) {
  252. return true
  253. }
  254. case C.RuleTypeLogical:
  255. if hasDNSRule(rule.LogicalOptions.Rules, cond) {
  256. return true
  257. }
  258. }
  259. }
  260. return false
  261. }
  262. func isGeoIPRule(rule option.DefaultRule) bool {
  263. return len(rule.SourceGeoIP) > 0 && common.Any(rule.SourceGeoIP, notPrivateNode) || len(rule.GeoIP) > 0 && common.Any(rule.GeoIP, notPrivateNode)
  264. }
  265. func isGeoIPDNSRule(rule option.DefaultDNSRule) bool {
  266. return len(rule.SourceGeoIP) > 0 && common.Any(rule.SourceGeoIP, notPrivateNode)
  267. }
  268. func isGeositeRule(rule option.DefaultRule) bool {
  269. return len(rule.Geosite) > 0
  270. }
  271. func isGeositeDNSRule(rule option.DefaultDNSRule) bool {
  272. return len(rule.Geosite) > 0
  273. }
  274. func isProcessRule(rule option.DefaultRule) bool {
  275. return len(rule.ProcessName) > 0 || len(rule.ProcessPath) > 0 || len(rule.PackageName) > 0 || len(rule.User) > 0 || len(rule.UserID) > 0
  276. }
  277. func isProcessDNSRule(rule option.DefaultDNSRule) bool {
  278. return len(rule.ProcessName) > 0 || len(rule.ProcessPath) > 0 || len(rule.PackageName) > 0 || len(rule.User) > 0 || len(rule.UserID) > 0
  279. }
  280. func notPrivateNode(code string) bool {
  281. return code != "private"
  282. }
  283. func isWIFIRule(rule option.DefaultRule) bool {
  284. return len(rule.WIFISSID) > 0 || len(rule.WIFIBSSID) > 0
  285. }
  286. func isWIFIDNSRule(rule option.DefaultDNSRule) bool {
  287. return len(rule.WIFISSID) > 0 || len(rule.WIFIBSSID) > 0
  288. }