feat: search for assets in XDG directories (#393)

This commit is contained in:
Nick Cao authored and GitHub committed 2022-01-30 12:42:39 +08:00
1 parent 4a09c580b3
commit 7a79683ad4
18 files changed
+156 -101

No files matched your search

+1 -1
View File
@@ -34,7 +34,7 @@ func ConnectionReport(arg []string) (report string) {
)
// get version of v2ray-core
ver, err := where.GetV2rayServiceVersion()
_, ver, err := where.GetV2rayServiceVersion()
if err != nil {
lines = append(lines, fmt.Sprintf("failed to get version of v2ray-core: %v", err))
return
+1 -1
View File
@@ -7,7 +7,7 @@ import (
)
func CouldUseFakeDns() bool {
ver, err := where.GetV2rayServiceVersion()
_, ver, err := where.GetV2rayServiceVersion()
if err != nil {
ver = "0.0.0"
}
@@ -7,7 +7,6 @@ import (
"github.com/v2rayA/v2ray-lib/router/routercommon"
"github.com/v2rayA/v2rayA/core/v2ray/asset"
"os"
"path"
"regexp"
"sync"
)
@@ -23,9 +22,12 @@ func GetWhitelistCn(externDomains []*routercommon.Domain) (wlDomains *strmatcher
if whitelistCn.domainMatcher != nil {
return whitelistCn.domainMatcher, nil
}
dir := asset.GetV2rayLocationAsset()
datpath, err := asset.GetV2rayLocationAsset("geosite.dat")
if err != nil {
return nil, err
}
var siteList routercommon.GeoSiteList
b, err := os.ReadFile(path.Join(dir, "geosite.dat"))
b, err := os.ReadFile(datpath)
if err != nil {
return nil, fmt.Errorf("GetWhitelistCn: %w", err)
}
+87 -58
View File
@@ -1,86 +1,122 @@
package asset
import (
"errors"
"github.com/adrg/xdg"
"github.com/muhammadmuzzammil1998/jsonc"
"github.com/v2rayA/v2rayA/common"
"github.com/v2rayA/v2rayA/common/files"
"github.com/v2rayA/v2rayA/conf"
"github.com/v2rayA/v2rayA/core/v2ray/where"
"github.com/v2rayA/v2rayA/pkg/util/log"
"io/fs"
"os"
"path"
"path/filepath"
"runtime"
"time"
)
func GetV2rayLocationAsset() (s string) {
var candidates = []string{
"/usr/local/share/v2ray",
"/usr/share/v2ray",
"/opt/share/v2ray",
"/usr/local/share/xray",
"/usr/share/xray",
"/opt/share/xray",
func GetV2rayLocationAssetOverride() string {
if runtime.GOOS != "windows" {
return filepath.Join(xdg.RuntimeDir, "v2raya")
} else {
return conf.GetEnvironmentConfig().Config
}
var is bool
if ver, err := where.GetV2rayServiceVersion(); err == nil {
if is, err = common.VersionGreaterEqual(ver, "4.27.1"); is {
for _, c := range candidates {
if _, err := os.Stat(c); os.IsNotExist(err) {
continue
}
if _, err := os.Stat(path.Join(c, "geoip.dat")); os.IsNotExist(err) {
continue
}
s = c
break
}
}
}
if s == "" {
// set as v2rayA config directory
s = conf.GetEnvironmentConfig().Config
}
return
}
func IsGFWListExists() bool {
_, err := os.Stat(path.Join(GetV2rayLocationAsset(), "LoyalsoldierSite.dat"))
func GetV2rayLocationAsset(filename string) (string, error) {
variant, _, err := where.GetV2rayServiceVersion()
if err != nil {
return false
variant = where.Unknown
}
return true
}
func IsGeoipExists() bool {
_, err := os.Stat(path.Join(GetV2rayLocationAsset(), "geoip.dat"))
if err != nil {
return false
var location string
var folder string
switch variant {
case where.V2ray:
location = "V2RAY_LOCATION_ASSET"
folder = "v2ray"
case where.Xray:
location = "XRAY_LOCATION_ASSET"
folder = "xray"
default:
location = "V2RAY_LOCATION_ASSET"
folder = "v2ray"
}
location = os.Getenv(location)
// check if V2RAY_LOCATION_ASSET is set
if location != "" {
// add V2RAY_LOCATION_ASSET to search path
searchPaths := []string{
filepath.Join(location, filename),
}
// additional paths for non windows platforms
if runtime.GOOS != "windows" {
searchPaths = append(
searchPaths,
filepath.Join("/usr/local/share", folder, filename),
filepath.Join("/usr/share", folder, filename),
)
}
for _, searchPath := range searchPaths {
if _, err = os.Stat(searchPath); err != nil && errors.Is(err, fs.ErrNotExist) {
continue
}
// return the first path that exists
return searchPath, nil
}
// or download asset into V2RAY_LOCATION_ASSET
return searchPaths[0], nil
} else {
if runtime.GOOS != "windows" {
// search XDG data directories on non windows platform
// symlink all assets into XDG_RUNTIME_DIR
relpath := filepath.Join(folder, filename)
fullpath, err := xdg.SearchDataFile(relpath)
if err != nil {
fullpath, err = xdg.DataFile(relpath)
if err != nil {
return "", err
}
}
runtimepath, err := xdg.RuntimeFile(filepath.Join("v2raya", filename))
if err != nil {
return "", err
}
os.Remove(runtimepath)
err = os.Symlink(fullpath, runtimepath)
if err != nil {
return "", err
}
return fullpath, err
} else {
// fallback to the old behavior of using only config dir on windows
return filepath.Join(conf.GetEnvironmentConfig().Config, filename), nil
}
}
return true
}
func IsGeoipOnlyCnPrivateExists() bool {
_, err := os.Stat(path.Join(GetV2rayLocationAsset(), "geoip-only-cn-private.dat"))
func DoesV2rayAssetExist(filename string) bool {
fullpath, err := GetV2rayLocationAsset(filename)
if err != nil {
return false
}
return true
}
func IsGeositeExists() bool {
_, err := os.Stat(path.Join(GetV2rayLocationAsset(), "geosite.dat"))
_, err = os.Stat(fullpath)
if err != nil {
return false
}
return true
}
func GetGFWListModTime() (time.Time, error) {
return files.GetFileModTime(path.Join(GetV2rayLocationAsset(), "LoyalsoldierSite.dat"))
fullpath, err := GetV2rayLocationAsset("LoyalsoldierSite.dat")
if err != nil {
return time.Now(), err
}
return files.GetFileModTime(fullpath)
}
func IsCustomExists() bool {
_, err := os.Stat(path.Join(GetV2rayLocationAsset(), "custom.dat"))
if err != nil {
return false
}
return true
return DoesV2rayAssetExist("custom.dat")
}
func GetConfigBytes() (b []byte, err error) {
@@ -100,10 +136,3 @@ func GetV2rayConfigPath() (p string) {
func GetV2rayConfigDirPath() (p string) {
return conf.GetEnvironmentConfig().V2rayConfigDirectory
}
func LoyalsoldierSiteDatExists() bool {
if info, err := os.Stat(filepath.Join(GetV2rayLocationAsset(), "LoyalsoldierSite.dat")); err == nil && !info.IsDir() {
return true
}
return false
}
+4 -3
View File
@@ -6,13 +6,14 @@ import (
gopeed2 "github.com/v2rayA/v2rayA/pkg/util/gopeed"
"github.com/v2rayA/v2rayA/pkg/util/log"
"os"
"path/filepath"
"strings"
)
func UpdateLocalGeoIP() (err error) {
assetDir := asset.GetV2rayLocationAsset()
pathSiteDat := filepath.Join(assetDir, "geoip.dat")
pathSiteDat, err := asset.GetV2rayLocationAsset("geoip.dat")
if err != nil {
return err
}
if err = gopeed2.Down(&gopeed2.Request{
Method: "GET",
URL: "https://hubmirror.v2raya.org/v2fly/geoip/releases/latest/download/geoip.dat",
+4 -3
View File
@@ -6,13 +6,14 @@ import (
gopeed2 "github.com/v2rayA/v2rayA/pkg/util/gopeed"
"github.com/v2rayA/v2rayA/pkg/util/log"
"os"
"path/filepath"
"strings"
)
func UpdateLocalGeoSite() (err error) {
assetDir := asset.GetV2rayLocationAsset()
pathSiteDat := filepath.Join(assetDir, "geosite.dat")
pathSiteDat, err := asset.GetV2rayLocationAsset("geosite.dat")
if err != nil {
return err
}
if err = gopeed2.Down(&gopeed2.Request{
Method: "GET",
URL: "https://hubmirror.v2raya.org/v2fly/domain-list-community/releases/latest/download/dlc.dat",
+5 -4
View File
@@ -15,7 +15,6 @@ import (
"io"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
@@ -69,7 +68,7 @@ func IsGFWListUpdate() (update bool, remoteTime time.Time, err error) {
return
}
remoteTime = gfwlist.UpdateTime
if !asset.IsGFWListExists() {
if !asset.DoesV2rayAssetExist("LoyalsoldierSite.dat") {
//本地文件不存在,那远端必定比本地新
return false, remoteTime, nil
}
@@ -117,8 +116,10 @@ func UpdateLocalGFWList() (localGFWListVersionAfterUpdate string, err error) {
if err != nil {
return
}
assetDir := asset.GetV2rayLocationAsset()
pathSiteDat := filepath.Join(assetDir, "LoyalsoldierSite.dat")
pathSiteDat, err := asset.GetV2rayLocationAsset("LoyalsoldierSite.dat")
if err != nil {
return "", err
}
u := fmt.Sprintf(`https://hubmirror.v2raya.org/v2rayA/dist-v2ray-rules-dat/raw/%v/geosite.dat`, gfwlist.Tag)
if err = gopeed2.Down(&gopeed2.Request{
Method: "GET",
+7 -4
View File
@@ -198,10 +198,13 @@ func StartCoreProcess(ctx context.Context) (*os.Process, error) {
arguments = append(arguments, "--confdir="+confdir)
}
log.Debug(strings.Join(arguments, " "))
assetDir := asset.GetV2rayLocationAsset()
env := append(os.Environ(),
"V2RAY_LOCATION_ASSET="+assetDir,
"XRAY_LOCATION_ASSET="+assetDir,
assetDir := asset.GetV2rayLocationAssetOverride()
env := append(
[]string{
"V2RAY_LOCATION_ASSET="+assetDir,
"XRAY_LOCATION_ASSET="+assetDir,
},
os.Environ()...,
)
if service.CheckMemconservativeSupported() == nil {
memstat, err := mem.VirtualMemory()
+1 -1
View File
@@ -49,7 +49,7 @@ func (m *CoreProcessManager) beforeStart(t *Template) (err error) {
return fmt.Errorf("Please sync datetime first. Your datetime is %v, and the correct datetime is %v", time.Now().Local().Format(ntp.DisplayFormat), t.Local().Format(ntp.DisplayFormat))
}
if (t.Setting.Transparent == configure.TransparentGfwlist || t.Setting.RulePortMode == configure.GfwlistMode) && !asset.IsGFWListExists() {
if (t.Setting.Transparent == configure.TransparentGfwlist || t.Setting.RulePortMode == configure.GfwlistMode) && !asset.DoesV2rayAssetExist("LoyalsoldierSite.dat") {
return fmt.Errorf("cannot find GFWList files. update GFWList and try again")
}
+3 -3
View File
@@ -11,10 +11,10 @@ import (
)
func IsV2rayServiceValid() bool {
if !asset.IsGeoipExists() || !asset.IsGeositeExists() {
if !asset.DoesV2rayAssetExist("geoip.dat") || !asset.DoesV2rayAssetExist("geosite.dat") {
return false
}
ver, err := where.GetV2rayServiceVersion()
_, ver, err := where.GetV2rayServiceVersion()
return err == nil && ver != ""
}
@@ -39,7 +39,7 @@ func CheckAndProbeTProxy() (err error) {
}
func isVersionSatisfied(version string, mustV2rayCore bool) error {
ver, err := where.GetV2rayServiceVersion()
_, ver, err := where.GetV2rayServiceVersion()
if err != nil {
return fmt.Errorf("failed to get the version of v2ray-core")
}
+6 -6
View File
@@ -511,7 +511,7 @@ func (t *Template) AppendRoutingRuleByMode(mode configure.RulePortMode, inbounds
switch mode {
case configure.WhitelistMode:
// foreign domains with intranet IP should be proxied first rather than directly connected
if asset.LoyalsoldierSiteDatExists() {
if asset.DoesV2rayAssetExist("LoyalsoldierSite.dat") {
t.Routing.Rules = append(t.Routing.Rules,
coreObj.RoutingRule{
Type: "field",
@@ -549,7 +549,7 @@ func (t *Template) AppendRoutingRuleByMode(mode configure.RulePortMode, inbounds
},
)
case configure.GfwlistMode:
if asset.LoyalsoldierSiteDatExists() {
if asset.DoesV2rayAssetExist("LoyalsoldierSite.dat") {
t.Routing.Rules = append(t.Routing.Rules,
coreObj.RoutingRule{
Type: "field",
@@ -1088,7 +1088,7 @@ func (t *Template) updatePrivateRouting() {
}
func (t *Template) optimizeGeoipMemoryOccupation() {
if asset.IsGeoipOnlyCnPrivateExists() {
if asset.DoesV2rayAssetExist("geoip-only-cn-private.dat") {
for i := range t.Routing.Rules {
for j := range t.Routing.Rules[i].IP {
switch t.Routing.Rules[i].IP[j] {
@@ -1470,7 +1470,7 @@ func NewTemplate(serverInfos []serverInfo, setting *configure.Setting) (t *Templ
if err != nil {
return nil, fmt.Errorf("error occurs while reading template json, please check whether templateJson variable is correct json format")
}
tmplJson.CoreVersion, _ = where.GetV2rayServiceVersion()
_, tmplJson.CoreVersion, _ = where.GetV2rayServiceVersion()
t = &tmplJson
t.Setting = setting
// log
@@ -1694,7 +1694,7 @@ func WriteV2rayConfig(content []byte) (err error) {
func NewEmptyTemplate(setting *configure.Setting) (t *Template) {
t = new(Template)
t.CoreVersion, _ = where.GetV2rayServiceVersion()
_, t.CoreVersion, _ = where.GetV2rayServiceVersion()
if setting != nil {
setting.FillEmpty()
} else {
@@ -1719,7 +1719,7 @@ func (t *Template) checkAndSetMark(o *coreObj.OutboundObject, mark int) {
func (t *Template) InsertMappingOutbound(o serverObj.ServerObj, inboundPort string, udpSupport bool, pluginPort int, protocol string) (err error) {
if t.CoreVersion == "" {
t.CoreVersion, _ = where.GetV2rayServiceVersion()
_, t.CoreVersion, _ = where.GetV2rayServiceVersion()
}
c, err := o.Configuration(serverObj.PriorInfo{
CoreVersion: t.CoreVersion,
+21 -6
View File
@@ -12,35 +12,50 @@ import (
"time"
)
type Variant int64
const (
Unknown Variant = iota
V2ray
Xray
)
var NotFoundErr = fmt.Errorf("not found")
var ServiceNameList = []string{"v2ray", "xray"}
var v2rayVersion struct {
variant Variant
version string
lastUpdate time.Time
mu sync.Mutex
}
/* get the version of v2ray-core without 'v' like 4.23.1 */
func GetV2rayServiceVersion() (ver string, err error) {
func GetV2rayServiceVersion() (variant Variant, ver string, err error) {
// cache for 10 seconds
v2rayVersion.mu.Lock()
defer v2rayVersion.mu.Unlock()
if time.Since(v2rayVersion.lastUpdate) < 10*time.Second {
return v2rayVersion.version, nil
return v2rayVersion.variant, v2rayVersion.version, nil
}
v2rayPath, err := GetV2rayBinPath()
if err != nil || len(v2rayPath) <= 0 {
return "", fmt.Errorf("cannot find v2ray executable binary")
return Unknown, "", fmt.Errorf("cannot find v2ray executable binary")
}
out, err := exec.Command(v2rayPath, "-version").Output()
var fields []string
if fields = strings.Fields(strings.TrimSpace(string(out))); len(fields) < 2 {
return "", fmt.Errorf("cannot parse version of v2ray")
return Unknown, "", fmt.Errorf("cannot parse version of v2ray")
}
ver = fields[1]
if strings.ToUpper(fields[0]) != "V2RAY" {
ver = "UnknownClient"
switch strings.ToUpper(fields[0]) {
case "V2RAY":
variant = V2ray
case "XRAY":
variant = Xray
default:
variant = Unknown
}
v2rayVersion.variant = variant
v2rayVersion.version = ver
v2rayVersion.lastUpdate = time.Now()
return
+2 -1
View File
@@ -3,6 +3,7 @@ module github.com/v2rayA/v2rayA
go 1.17
require (
github.com/adrg/xdg v0.4.0
github.com/beevik/ntp v0.3.0
github.com/boltdb/bolt v1.3.1
github.com/devfeel/mapper v0.7.5
@@ -30,7 +31,7 @@ require (
github.com/v2rayA/v2ray-lib v0.0.0-20211227083129-d4f59fbf62b8
github.com/vearutop/statigz v1.1.7
golang.org/x/net v0.0.0-20210903162142-ad29c8ab022f
golang.org/x/sys v0.0.0-20211013075003-97ac67df715c
golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359
google.golang.org/grpc v1.40.0
)
+4 -1
View File
@@ -4,6 +4,8 @@ github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc=
github.com/adrg/xdg v0.4.0 h1:RzRqFcjH4nE5C6oTAxhBtoE2IRyjBSa62SCbyPidvls=
github.com/adrg/xdg v0.4.0/go.mod h1:N6ag73EX4wyxeaoeHctc1mas01KZgsj5tYiAIwqJE/E=
github.com/andybalholm/brotli v1.0.4 h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qY3JY=
github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
@@ -293,8 +295,9 @@ golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210816074244-15123e1e1f71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211013075003-97ac67df715c h1:taxlMj0D/1sOAuv/CbSD+MMDof2vbyPTqz5FNYKpXt8=
golang.org/x/sys v0.0.0-20211013075003-97ac67df715c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359 h1:2B5p2L5IfGiD7+b9BOoRMC6DgObAVZV+Fsp050NqXik=
golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+2 -3
View File
@@ -239,13 +239,13 @@ func initConfigure() {
//首先确定v2ray是否存在
if _, err := where.GetV2rayBinPath(); err == nil {
//检查geoip、geosite是否存在
if !asset.IsGeoipExists() {
if !asset.DoesV2rayAssetExist("geoip.dat") {
err := dat.UpdateLocalGeoIP()
if err != nil {
log.Fatal("%v", err)
}
}
if !asset.IsGeositeExists() {
if !asset.DoesV2rayAssetExist("geosite.dat") {
err = dat.UpdateLocalGeoSite()
if err != nil {
log.Fatal("%v", err)
@@ -255,7 +255,6 @@ func initConfigure() {
}
func hello() {
log.Alert("V2RayLocationAsset is %v", asset.GetV2rayLocationAsset())
v2rayPath, _ := where.GetV2rayBinPath()
log.Alert("V2Ray binary is %v", v2rayPath)
wd, _ := os.Getwd()
+1 -1
View File
@@ -15,7 +15,7 @@ func GetVersion(ctx *gin.Context) {
var vlessValid int
var lite int
ver, err := where.GetV2rayServiceVersion()
_, ver, err := where.GetV2rayServiceVersion()
if err == nil {
if ok, _ := common.VersionGreaterEqual(ver, "4.27.0"); ok {
// 1: vless
+1 -1
View File
@@ -60,7 +60,7 @@ func Disconnect(which configure.Which, clearOutbound bool) (err error) {
func checkAssetsExist(setting *configure.Setting) error {
//FIXME: non-fully check
if setting.RulePortMode == configure.GfwlistMode || setting.Transparent == configure.TransparentGfwlist {
if !asset.LoyalsoldierSiteDatExists() {
if !asset.DoesV2rayAssetExist("LoyalsoldierSite.dat") {
return fmt.Errorf("GFWList file not exists. Try updating GFWList please")
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ func GetSetting() *configure.Setting {
}
func UpdateSetting(setting *configure.Setting) (err error) {
if (setting.Transparent == configure.TransparentGfwlist || setting.RulePortMode == configure.GfwlistMode) && !asset.IsGFWListExists() {
if (setting.Transparent == configure.TransparentGfwlist || setting.RulePortMode == configure.GfwlistMode) && !asset.DoesV2rayAssetExist("LoyalsoldierSite.dat") {
return fmt.Errorf("cannot find GFWList files. update GFWList and try again")
}
if setting.IpForward != ipforward.IsIpForwardOn() {