github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/infra/conf/geodata/standard/standard.go (about)

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