standard.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package standard
  2. import (
  3. "github.com/v2fly/v2ray-core/v4/app/router/routercommon"
  4. "strings"
  5. "google.golang.org/protobuf/proto"
  6. "github.com/v2fly/v2ray-core/v4/common/platform/filesystem"
  7. "github.com/v2fly/v2ray-core/v4/infra/conf/geodata"
  8. )
  9. //go:generate go run github.com/v2fly/v2ray-core/v4/common/errors/errorgen
  10. func loadIP(filename, country string) ([]*routercommon.CIDR, error) {
  11. geoipBytes, err := filesystem.ReadAsset(filename)
  12. if err != nil {
  13. return nil, newError("failed to open file: ", filename).Base(err)
  14. }
  15. var geoipList routercommon.GeoIPList
  16. if err := proto.Unmarshal(geoipBytes, &geoipList); err != nil {
  17. return nil, err
  18. }
  19. for _, geoip := range geoipList.Entry {
  20. if strings.EqualFold(geoip.CountryCode, country) {
  21. return geoip.Cidr, nil
  22. }
  23. }
  24. return nil, newError("country not found in ", filename, ": ", country)
  25. }
  26. func loadSite(filename, list string) ([]*routercommon.Domain, error) {
  27. geositeBytes, err := filesystem.ReadAsset(filename)
  28. if err != nil {
  29. return nil, newError("failed to open file: ", filename).Base(err)
  30. }
  31. var geositeList routercommon.GeoSiteList
  32. if err := proto.Unmarshal(geositeBytes, &geositeList); err != nil {
  33. return nil, err
  34. }
  35. for _, site := range geositeList.Entry {
  36. if strings.EqualFold(site.CountryCode, list) {
  37. return site.Domain, nil
  38. }
  39. }
  40. return nil, newError("list not found in ", filename, ": ", list)
  41. }
  42. type standardLoader struct{}
  43. func (d standardLoader) LoadSite(filename, list string) ([]*routercommon.Domain, error) {
  44. return loadSite(filename, list)
  45. }
  46. func (d standardLoader) LoadIP(filename, country string) ([]*routercommon.CIDR, error) {
  47. return loadIP(filename, country)
  48. }
  49. func init() {
  50. geodata.RegisterGeoDataLoaderImplementationCreator("standard", func() geodata.LoaderImplementation {
  51. return standardLoader{}
  52. })
  53. }