2021-11-17 16:03:47 +08:00
|
|
|
|
package geodata
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"github.com/Dreamacro/clash/component/geodata/router"
|
2022-03-15 22:25:33 +08:00
|
|
|
|
C "github.com/Dreamacro/clash/constant"
|
2022-02-04 23:33:36 +08:00
|
|
|
|
"strings"
|
2021-11-17 16:03:47 +08:00
|
|
|
|
)
|
|
|
|
|
|
2022-02-05 00:51:06 +08:00
|
|
|
|
var geoLoaderName = "memconservative"
|
|
|
|
|
|
|
|
|
|
// geoLoaderName = "standard"
|
|
|
|
|
|
|
|
|
|
func LoaderName() string {
|
|
|
|
|
return geoLoaderName
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func SetLoader(newLoader string) {
|
2022-04-11 13:23:59 +08:00
|
|
|
|
if newLoader == "memc" {
|
|
|
|
|
newLoader = "memconservative"
|
|
|
|
|
}
|
2022-02-05 00:51:06 +08:00
|
|
|
|
geoLoaderName = newLoader
|
|
|
|
|
}
|
|
|
|
|
|
2022-03-15 22:25:33 +08:00
|
|
|
|
func Verify(name string) bool {
|
|
|
|
|
switch name {
|
|
|
|
|
case C.GeositeName:
|
|
|
|
|
_, _, err := LoadGeoSiteMatcher("CN")
|
|
|
|
|
return err == nil
|
|
|
|
|
case C.GeoipName:
|
|
|
|
|
_, _, err := LoadGeoIPMatcher("CN")
|
|
|
|
|
return err == nil
|
|
|
|
|
default:
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-17 16:03:47 +08:00
|
|
|
|
func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error) {
|
|
|
|
|
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, 0, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
domains, err := geoLoader.LoadGeoSite(countryCode)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, 0, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
linear: linear algorithm
|
|
|
|
|
matcher, err := router.NewDomainMatcher(domains)
|
|
|
|
|
mph:minimal perfect hash algorithm
|
|
|
|
|
*/
|
|
|
|
|
matcher, err := router.NewMphMatcherGroup(domains)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, 0, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return matcher, len(domains), nil
|
|
|
|
|
}
|
2022-02-04 23:33:36 +08:00
|
|
|
|
|
|
|
|
|
func LoadGeoIPMatcher(country string) (*router.GeoIPMatcher, int, error) {
|
|
|
|
|
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, 0, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
records, err := geoLoader.LoadGeoIP(strings.ReplaceAll(country, "!", ""))
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, 0, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
geoIP := &router.GeoIP{
|
|
|
|
|
CountryCode: country,
|
|
|
|
|
Cidr: records,
|
|
|
|
|
ReverseMatch: strings.Contains(country, "!"),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
matcher, err := router.NewGeoIPMatcher(geoIP)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, 0, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return matcher, len(records), nil
|
|
|
|
|
}
|