From d34ba11db980743583fdeb9ea9740cfee11268f0 Mon Sep 17 00:00:00 2001 From: mzz2017 Date: Wed, 23 Dec 2020 20:06:21 +0800 Subject: [PATCH] refactor/feat: universal mode by default; try using xray first but v2ray recommended. support param --v2ray-confdir #122 support param --v2ray-bin v2rayA will not control v2ray by systemd but subprocess way --- service/common/httpClient/httpClient.go | 17 ++- service/common/netTools/ipaddress.go | 10 -- service/common/tools.go | 12 +- service/controller/portWhiteList.go | 8 +- service/controller/v2ray.go | 2 +- service/core/dnsPoison/handle.go | 2 +- service/core/touch/touch.go | 3 +- service/core/v2ray/asset/asset.go | 58 ++----- service/core/v2ray/status.go | 167 ++++----------------- service/core/v2ray/transparent.go | 8 +- service/core/v2ray/v2rayService.go | 117 +-------------- service/core/v2ray/v2rayTmpl.go | 6 +- service/core/v2ray/where/where.go | 94 +++++++++--- service/db/configure/which.go | 2 +- service/extra/proxy/ssr/ssr.go | 20 ++- service/global/environmentConfig.go | 20 +-- service/global/systemServiceControlMode.go | 26 +--- service/main.go | 1 - service/plugin/simpleobfs/simpleobfs.go | 3 +- service/pre.go | 112 ++++++-------- service/router/index.go | 3 +- service/service/connect.go | 4 - service/service/ports.go | 7 +- 23 files changed, 236 insertions(+), 466 deletions(-) diff --git a/service/common/httpClient/httpClient.go b/service/common/httpClient/httpClient.go index bc7ad0f1..629842a4 100644 --- a/service/common/httpClient/httpClient.go +++ b/service/common/httpClient/httpClient.go @@ -1,14 +1,15 @@ package httpClient import ( + "fmt" + "github.com/v2rayA/v2rayA/common" + "github.com/v2rayA/v2rayA/core/v2ray" + "github.com/v2rayA/v2rayA/db/configure" + "github.com/v2rayA/v2rayA/extra/proxyWithHttp" "net/http" "net/url" "os/exec" "strings" - "github.com/v2rayA/v2rayA/common" - "github.com/v2rayA/v2rayA/core/v2ray" - "github.com/v2rayA/v2rayA/extra/proxyWithHttp" - "github.com/v2rayA/v2rayA/db/configure" ) func GetHttpClientWithProxy(proxyURL string) (client *http.Client, err error) { @@ -31,12 +32,12 @@ func GetHttpClientWithv2rayAProxy() (client *http.Client, err error) { host := "127.0.0.1" //是否在docker环境 if common.IsInDocker() { - //连接网关,即宿主机的端口,失败则用同网络下v2ray容器的 + //连接网关,即宿主机的端口 out, err := exec.Command("sh", "-c", "ip route list default|head -n 1|awk '{print $3}'").Output() if err == nil { host = strings.TrimSpace(string(out)) } else { - host = "v2ray" + return nil, fmt.Errorf("failed to get gateway: %v", err) } } return GetHttpClientWithProxy("socks5://" + host + ":20170") @@ -46,12 +47,12 @@ func GetHttpClientWithv2rayAPac() (client *http.Client, err error) { host := "127.0.0.1" //是否在docker环境 if common.IsInDocker() { - //连接网关,即宿主机的端口,失败则用同网络下v2ray容器的 + //连接网关,即宿主机的端口 out, err := exec.Command("sh", "-c", "ip route|grep default|awk '{print $3}'").Output() if err == nil { host = strings.TrimSpace(string(out)) } else { - host = "v2ray" + return nil, fmt.Errorf("failed to get gateway: %v", err) } } return GetHttpClientWithProxy("http://" + host + ":20172") diff --git a/service/common/netTools/ipaddress.go b/service/common/netTools/ipaddress.go index 3ec8a22e..cdad90ae 100644 --- a/service/common/netTools/ipaddress.go +++ b/service/common/netTools/ipaddress.go @@ -69,13 +69,3 @@ func IsIntranet4(ipv4 *[4]byte) bool { func IsJokernet4(ipv4 *[4]byte) bool { return trieJokernet.Match(ipv4ToBin(ipv4)) != "" } - -func ParseAddress(address string) (ip string, port string) { - p := strings.LastIndex(address, ":") - if p == -1 { - return - } - port = address[p+1:] - ip = address[:p] - return -} diff --git a/service/common/tools.go b/service/common/tools.go index 85312892..ba73672f 100644 --- a/service/common/tools.go +++ b/service/common/tools.go @@ -1,6 +1,7 @@ package common import ( + "github.com/mzz2017/go-engine/src/common" "net/url" "os" "strconv" @@ -49,10 +50,17 @@ func VersionMustGreaterEqual(v1, v2 string) (is bool) { /* return if v1 is after v2 */ func VersionGreaterEqual(v1, v2 string) (is bool, err error) { - if v1 == "debug" || v1 == "unstable" { + if v1 == "UnknownClient" { return true, nil } - if v2 == "debug" || v2 == "unstable" { + if v2 == "UnknownClient" { + return false, nil + } + var HighPriority = []string{"debug", "unstable"} + if common.ArrayContainString(HighPriority, v1) { + return true, nil + } + if common.ArrayContainString(HighPriority, v2) { return false, nil } v1 = strings.TrimPrefix(v1, "v") diff --git a/service/controller/portWhiteList.go b/service/controller/portWhiteList.go index 6c30df09..96332b50 100644 --- a/service/controller/portWhiteList.go +++ b/service/controller/portWhiteList.go @@ -2,13 +2,13 @@ package controller import ( "github.com/gin-gonic/gin" - "strconv" - "strings" "github.com/v2rayA/v2rayA/common" "github.com/v2rayA/v2rayA/core/v2ray" - "github.com/v2rayA/v2rayA/global" "github.com/v2rayA/v2rayA/db/configure" + "github.com/v2rayA/v2rayA/global" "github.com/v2rayA/v2rayA/service" + "net" + "strconv" ) func GetPortWhiteList(ctx *gin.Context) { @@ -44,7 +44,7 @@ func PostPortWhiteList(ctx *gin.Context) { return } p := service.GetPortsDefault() - listenPort := strings.Split(global.GetEnvironmentConfig().Address, ":")[1] + _, listenPort, _ := net.SplitHostPort(global.GetEnvironmentConfig().Address) wpl := configure.PortWhiteList{ TCP: []string{"1:1023", data.RequestPort, listenPort, strconv.Itoa(p.Http), strconv.Itoa(p.HttpWithPac), strconv.Itoa(p.Socks5)}, UDP: []string{"1:1023", strconv.Itoa(p.Socks5)}, diff --git a/service/controller/v2ray.go b/service/controller/v2ray.go index bd8512c1..948655ee 100644 --- a/service/controller/v2ray.go +++ b/service/controller/v2ray.go @@ -27,7 +27,7 @@ func PostV2ray(ctx *gin.Context) { } func DeleteV2ray(ctx *gin.Context) { - err := v2ray.StopAndDisableV2rayService() + err := v2ray.StopV2rayService() if err != nil { common.ResponseError(ctx, logError(err)) return diff --git a/service/core/dnsPoison/handle.go b/service/core/dnsPoison/handle.go index c5c293ae..d4c4285d 100644 --- a/service/core/dnsPoison/handle.go +++ b/service/core/dnsPoison/handle.go @@ -242,7 +242,7 @@ func (interfaceHandle *handle) poison(m *dnsmessage.Message, lAddr, lPort, rAddr go func(m *dnsmessage.Message) { packed, _ := m.Pack() lport, _ := strconv.Atoi(lPort.String()) - conn, err := newDialer(lAddr.String(), uint32(lport), 30*time.Second).Dial("udp", rAddr.String()+":"+rPort.String()) + conn, err := newDialer(lAddr.String(), uint32(lport), 30*time.Second).Dial("udp", net.JoinHostPort(rAddr.String(), rPort.String())) if err != nil { return } diff --git a/service/core/touch/touch.go b/service/core/touch/touch.go index 05fe2e51..81f45b08 100644 --- a/service/core/touch/touch.go +++ b/service/core/touch/touch.go @@ -3,6 +3,7 @@ package touch import ( "fmt" "github.com/v2rayA/v2rayA/db/configure" + "net" "net/url" "strings" "time" @@ -80,7 +81,7 @@ func serverRawsToServers(rss []configure.ServerRaw) (ts []TouchServer) { if v.VmessInfo.Port == "" { address = v.VmessInfo.Add } else { - address = v.VmessInfo.Add + ":" + v.VmessInfo.Port + address = net.JoinHostPort(v.VmessInfo.Add, v.VmessInfo.Port) } ts[i] = TouchServer{ ID: i + 1, diff --git a/service/core/v2ray/asset/asset.go b/service/core/v2ray/asset/asset.go index af71f40b..1ed8a7e6 100644 --- a/service/core/v2ray/asset/asset.go +++ b/service/core/v2ray/asset/asset.go @@ -40,7 +40,7 @@ func GetV2rayLocationAsset() (s string) { var err error if s == "" { //fine, guess one - var candidates = []string{`/usr/local/share/v2ray`, `/usr/share/v2ray`} + var candidates = []string{`/usr/local/share/xray`, `/usr/share/xray`, `/usr/local/share/v2ray`, `/usr/share/v2ray`} var ver string var is bool if ver, err = where.GetV2rayServiceVersion(); err == nil { @@ -56,10 +56,11 @@ func GetV2rayLocationAsset() (s string) { } if s == "" { //maybe v2ray working directory - s, err = where.GetV2rayWorkingDir() + v2rayPath, err := where.GetV2rayBinPath() if err != nil { s = "/etc/v2ray" } + s = path.Dir(v2rayPath) } } else { //save the result if not by guess @@ -68,23 +69,6 @@ func GetV2rayLocationAsset() (s string) { return } -func GetV2ctlDir() (string, error) { - d, err := where.GetV2rayWorkingDir() - if err == nil { - _, err := os.Stat(d + "/v2ctl") - if err != nil { - return "", err - } - return d, nil - } - out, err := exec.Command("sh", "-c", "which v2ctl").Output() - if err != nil { - err = newError(string(out)).Base(err) - return "", err - } - return path.Dir(strings.TrimSpace(string(out))), nil -} - func IsGFWListExists() bool { _, err := os.Stat(GetV2rayLocationAsset() + "/LoyalsoldierSite.dat") if err != nil { @@ -118,7 +102,7 @@ func IsCustomExists() bool { } func GetConfigBytes() (b []byte, err error) { - b, err = ioutil.ReadFile(GetConfigPath()) + b, err = ioutil.ReadFile(GetV2rayConfigPath()) if err != nil { log.Println(err) return @@ -127,34 +111,12 @@ func GetConfigBytes() (b []byte, err error) { return } -func GetConfigPath() (p string) { - p = "/etc/v2ray/config.json" - switch global.ServiceControlMode { - case global.SystemctlMode, global.ServiceMode: - //从systemd的启动参数里找 - pa, _ := where.GetV2rayServiceFilePath() - out, e := exec.Command("sh", "-c", "cat "+pa+"|grep ExecStart=").CombinedOutput() - if e != nil { - return - } - pa = strings.TrimSpace(string(out))[len("ExecStart="):] - indexConfigBegin := strings.Index(pa, "-config") - if indexConfigBegin == -1 { - return - } - indexConfigBegin += len("-config") + 1 - indexConfigEnd := strings.Index(pa[indexConfigBegin:], " ") - if indexConfigEnd == -1 { - indexConfigEnd = len(pa) - } else { - indexConfigEnd += indexConfigBegin - } - p = pa[indexConfigBegin:indexConfigEnd] - case global.UniversalMode: - p = GetV2rayLocationAsset() + "/config.json" - default: - } - return +func GetV2rayConfigPath() (p string) { + return path.Join(global.GetEnvironmentConfig().Config, "config.json") +} + +func GetV2rayConfigDirPath() (p string) { + return global.GetEnvironmentConfig().V2rayConfigDirectory } var whitelistCn struct { diff --git a/service/core/v2ray/status.go b/service/core/v2ray/status.go index aa2f86de..b626020c 100644 --- a/service/core/v2ray/status.go +++ b/service/core/v2ray/status.go @@ -1,9 +1,6 @@ package v2ray import ( - "bytes" - "fmt" - netstat2 "github.com/cakturk/go-netstat/netstat" "github.com/json-iterator/go" "github.com/v2rayA/v2rayA/common/netTools/netstat" "github.com/v2rayA/v2rayA/common/ntp" @@ -16,89 +13,13 @@ import ( "github.com/v2rayA/v2rayA/plugin" "log" "os" - "os/exec" - "regexp" - "strconv" + "path" "strings" "time" ) -func IsV2RayProcessExists() bool { - out, err := exec.Command("sh", "-c", "ps -e -o args").CombinedOutput() - if err != nil || (strings.Contains(string(out), "invalid option") && strings.Contains(strings.ToLower(string(out)), "busybox")) { - out, err = exec.Command("sh", "-c", "ps|awk '{print $4,$5}'").CombinedOutput() - } - if err == nil { - //模拟grep -E - regex := regexp.MustCompile(`\bv2ray\b`) - lines := bytes.Split(out, []byte{'\n'}) - for _, line := range lines { - if regex.Match(line) && !bytes.Contains(line, []byte("-version")) { - return true - } - } - } - return false -} - func IsV2RayRunning() bool { - switch global.ServiceControlMode { - case global.UniversalMode: - return IsV2RayProcessExists() - case global.ServiceMode: - out, err := exec.Command("sh", "-c", "service v2ray status|grep running").CombinedOutput() - if err != nil || strings.Contains(string(out), "not running") { - return false - } - case global.SystemctlMode: - out, err := exec.Command("sh", "-c", "systemctl status v2ray|grep Active|grep running").Output() - return err == nil && len(out) > 0 - } - return true -} - -func testprint() string { - var buffer strings.Builder - e, _ := netstat2.TCPSocks(func(entry *netstat2.SockTabEntry) bool { - return true - }) - e2, _ := netstat2.TCP6Socks(func(entry *netstat2.SockTabEntry) bool { - return true - }) - buffer.WriteString(fmt.Sprintf("%-6v%-25v%-25v%-15v%-6v%-9v%v\n", "Proto", "Local Address", "Foreign Address", "State", "User", "Inode", "PID/Program name")) - for _, v := range e { - var pstr string - if v.Process != nil { - pstr = v.Process.String() - } - buffer.WriteString(fmt.Sprintf( - "%-6v%-25v%-25v%-15v%-6v%-9v%v\n", - "tcp", - v.LocalAddr.IP.String()+"/"+strconv.Itoa(int(v.LocalAddr.Port)), - v.RemoteAddr.IP.String()+"/"+strconv.Itoa(int(v.RemoteAddr.Port)), - v.State.String(), - v.UID, - "", - pstr, - )) - } - for _, v := range e2 { - var pstr string - if v.Process != nil { - pstr = v.Process.String() - } - buffer.WriteString(fmt.Sprintf( - "%-6v%-25v%-25v%-15v%-6v%-9v%v\n", - "tcp6", - v.LocalAddr.IP.String()+"/"+strconv.Itoa(int(v.LocalAddr.Port)), - v.RemoteAddr.IP.String()+"/"+strconv.Itoa(int(v.RemoteAddr.Port)), - v.State.String(), - v.UID, - "", - pstr, - )) - } - return buffer.String() + return global.V2RayPID != nil } func RestartV2rayService() (err error) { @@ -110,39 +31,36 @@ func RestartV2rayService() (err error) { return newError("cannot find GFWList files. update GFWList and try again") } //关闭transparentProxy,防止v2ray在启动DOH时需要解析域名 - var out []byte - switch global.ServiceControlMode { - case global.ServiceMode: - out, err = exec.Command("sh", "-c", "service v2ray restart").CombinedOutput() - if err != nil { - err = newError(string(out)).Base(err) - } - case global.SystemctlMode: - out, err = exec.Command("sh", "-c", "systemctl restart v2ray").Output() - if err != nil { - err = newError(string(out)).Base(err) - } - case global.UniversalMode: - _ = killV2ray() - v2wd, _ := where.GetV2rayWorkingDir() - v2ctlDir, _ := asset.GetV2ctlDir() - log.Println(v2wd+"/v2ray", "--config="+asset.GetConfigPath(), v2ctlDir) - global.V2RayPID, err = os.StartProcess(v2wd+"/v2ray", []string{v2wd + "/v2ray", "--config=" + asset.GetConfigPath()}, &os.ProcAttr{ - Dir: v2ctlDir, //防止找不到v2ctl - Env: os.Environ(), - //Files: []*os.File{ - // os.Stdin, - // os.Stdout, - // os.Stderr, - //}, - }) - if err != nil { - err = newError(string(out)).Base(err) - } - } + _ = killV2ray() + v2rayBinPath, err := where.GetV2rayBinPath() if err != nil { return } + dir := path.Dir(v2rayBinPath) + var params = []string{ + v2rayBinPath, + "--config=" + asset.GetV2rayConfigPath(), + } + if confdir := asset.GetV2rayConfigDirPath(); confdir != "" { + params = append(params, "--confdir="+confdir) + } + log.Println(strings.Join(params, " ")) + global.V2RayPID, err = os.StartProcess(v2rayBinPath, params, &os.ProcAttr{ + Dir: dir, //防止找不到v2ctl + Env: append(os.Environ(), "V2RAY_LOCATION_ASSET="+asset.GetV2rayLocationAsset()), + Files: []*os.File{ + os.Stderr, + os.Stdout, + }, + }) + if err != nil { + return newError().Base(err) + } + defer func() { + if err != nil && global.V2RayPID != nil { + _ = killV2ray() + } + }() //如果inbounds中开放端口,检测端口是否已就绪 tmplJson := NewTemplate() var b []byte @@ -175,7 +93,7 @@ func RestartV2rayService() (err error) { for { if bPortOpen { var is bool - is, err = netstat.IsProcessListenPort("v2ray", port) + is, err = netstat.IsProcessListenPort(path.Base(v2rayBinPath), port) if err != nil { return } @@ -322,28 +240,5 @@ func StopV2rayService() (err error) { err = newError(msg) } }() - var out []byte - switch global.ServiceControlMode { - case global.UniversalMode: - return killV2ray() - case global.ServiceMode: - out, err = exec.Command("sh", "-c", "service v2ray stop").CombinedOutput() - if err != nil { - err = newError(string(out)).Base(err) - } - case global.SystemctlMode: - out, err = exec.Command("sh", "-c", "systemctl stop v2ray").CombinedOutput() - if err != nil { - err = newError(string(out)).Base(err) - } - } - return -} - -func StopAndDisableV2rayService() (err error) { - err = StopV2rayService() - if err != nil { - return - } - return DisableV2rayService() + return killV2ray() } diff --git a/service/core/v2ray/transparent.go b/service/core/v2ray/transparent.go index 0cccb165..d2b8820a 100644 --- a/service/core/v2ray/transparent.go +++ b/service/core/v2ray/transparent.go @@ -7,11 +7,13 @@ import ( "github.com/v2rayA/v2rayA/common/netTools/ports" "github.com/v2rayA/v2rayA/core/dnsPoison/entity" "github.com/v2rayA/v2rayA/core/iptables" + "github.com/v2rayA/v2rayA/core/v2ray/where" "github.com/v2rayA/v2rayA/db/configure" "github.com/v2rayA/v2rayA/global" "io/ioutil" "log" "os" + "path" "strings" "time" ) @@ -130,6 +132,10 @@ func nextPortsGroup(ports []string, groupSize int) (group []string, remain []str } func CheckAndSetupTransparentProxy(checkRunning bool) (err error) { + v2rayPath, err := where.GetV2rayBinPath() + if err != nil { + return + } setting := configure.GetSettingNotNil() preprocess := func(c *iptables.SetupCommands) { commands := string(*c) @@ -187,7 +193,7 @@ func CheckAndSetupTransparentProxy(checkRunning bool) (err error) { } if o { p, e := s.Process() - if e == nil && p.Name != "v2ray" { + if e == nil && p.Name != path.Base(v2rayPath) { err = newError("transparent proxy cannot be set up, port 32345 is occupied by ", p.Name) return } diff --git a/service/core/v2ray/v2rayService.go b/service/core/v2ray/v2rayService.go index 464d34b5..8cf6719f 100644 --- a/service/core/v2ray/v2rayService.go +++ b/service/core/v2ray/v2rayService.go @@ -5,132 +5,24 @@ import ( "github.com/v2rayA/v2rayA/common" "github.com/v2rayA/v2rayA/core/v2ray/asset" "github.com/v2rayA/v2rayA/core/v2ray/where" - "github.com/v2rayA/v2rayA/global" - "io/ioutil" - "os" "os/exec" "strings" ) -func EnableV2rayService() (err error) { - var out []byte - switch global.ServiceControlMode { - case global.UniversalMode: //docker, universal中无需enable service - case global.ServiceMode: - out, err = exec.Command("sh", "-c", "update-rc.d v2ray enable").CombinedOutput() - if err != nil { - err = newError(string(out)).Base(err) - } - case global.SystemctlMode: - out, err = exec.Command("sh", "-c", "systemctl enable v2ray").CombinedOutput() - if err != nil { - err = newError(string(out)).Base(err) - } - } - return -} - -func DisableV2rayService() (err error) { - var out []byte - switch global.ServiceControlMode { - case global.UniversalMode: //docker, universal中无需disable service - case global.ServiceMode: - out, err = exec.Command("sh", "-c", "update-rc.d v2ray disable").CombinedOutput() - if err != nil { - err = newError(string(out)).Base(err) - } - case global.SystemctlMode: - out, err = exec.Command("sh", "-c", "systemctl disable v2ray").CombinedOutput() - if err != nil { - err = newError(string(out)).Base(err) - } - } - return -} - -func OptimizeServiceFile() (err error) { - if global.ServiceControlMode != global.SystemctlMode && global.ServiceControlMode != global.ServiceMode { - return - } - p, err := where.GetV2rayServiceFilePath() - if err != nil { - return - } - b, err := ioutil.ReadFile(p) - if err != nil { - return - } - s := string(b) - if strings.Contains(s, "LimitNPROC=500") && - strings.Contains(s, "LimitNOFILE=1000000") && - strings.Contains(s, "CapabilityBoundingSet=CAP_NET_BIND_SERVICE CAP_NET_RAW CAP_NET_ADMIN") { - return - } - lines := strings.Split(s, "\n") - for i := len(lines) - 1; i >= 0; i-- { - if strings.HasPrefix(lines[i], "LimitNPROC=") || - strings.HasPrefix(lines[i], "LimitNOFILE=") || - strings.HasPrefix(lines[i], "CapabilityBoundingSet=") { - lines = append(lines[:i], lines[i+1:]...) - } - } - for i, line := range lines { - if strings.ToLower(line) == "[service]" { - s = strings.Join(lines[:i+1], "\n") - s += "\n" - s += "LimitNPROC=500\n" - s += "LimitNOFILE=1000000\n" - s += "CapabilityBoundingSet=CAP_NET_BIND_SERVICE CAP_NET_RAW CAP_NET_ADMIN\n" - s += strings.Join(lines[i+1:], "\n") - break - } - } - err = ioutil.WriteFile(p, []byte(s), os.ModeAppend) - if err != nil { - return - } - if global.ServiceControlMode == global.SystemctlMode { - _, _ = exec.Command("sh", "-c", "systemctl daemon-reload").Output() - } - if IsV2RayRunning() { - err = RestartV2rayService() - } - return -} - func IsV2rayServiceValid() bool { - switch global.ServiceControlMode { - case global.SystemctlMode: - out, err := exec.Command("sh", "-c", "systemctl list-unit-files|grep v2ray.service").Output() - return err == nil && len(bytes.TrimSpace(out)) > 0 - case global.ServiceMode: - out, err := exec.Command("sh", "-c", "service v2ray status|grep not-found").Output() - return err == nil && len(bytes.TrimSpace(out)) == 0 - case global.UniversalMode: - if !asset.IsGeoipExists() || !asset.IsGeositeExists() { - return false - } - out, err := exec.Command("sh", "-c", "which v2ray").Output() - return err == nil && len(bytes.TrimSpace(out)) > 0 + if !asset.IsGeoipExists() || !asset.IsGeositeExists() { + return false } - return false + ver, err := where.GetV2rayServiceVersion() + return err == nil && ver != "" } - - func IfTProxyModLoaded() bool { out, err := exec.Command("sh", "-c", "lsmod|grep xt_TPROXY").Output() return err == nil && len(bytes.TrimSpace(out)) > 0 } func CheckAndProbeTProxy() (err error) { - ver, err := where.GetV2rayServiceVersion() - if err != nil { - return newError("failed to get the version of v2ray-core").Base(err) - } - if greaterEqual, err := common.VersionGreaterEqual(ver, "4.19.1"); err != nil || !greaterEqual { - return newError("the version of v2ray-core (" + ver + ") is lower than 4.19.1") - } if !IfTProxyModLoaded() && !common.IsInDocker() { //docker下无法判断 var out []byte out, err = exec.Command("sh", "-c", "modprobe xt_TPROXY").CombinedOutput() @@ -157,4 +49,3 @@ func CheckDohSupported(ver string) (err error) { } return } - diff --git a/service/core/v2ray/v2rayTmpl.go b/service/core/v2ray/v2rayTmpl.go index 5a81ca85..790e5d5d 100644 --- a/service/core/v2ray/v2rayTmpl.go +++ b/service/core/v2ray/v2rayTmpl.go @@ -18,6 +18,7 @@ import ( "net" "net/url" "os" + "path" "regexp" "strconv" "strings" @@ -1182,7 +1183,8 @@ func (t *Template) CheckInboundPortsOccupied() (occupied bool, port string, pnam st = append(st, strconv.Itoa(in.Port)+":tcp") } } - occupied, socket, err := ports.IsPortOccupiedWithWhitelist(st, map[string]struct{}{"v2ray": {}}) + v2rayPath, _ := where.GetV2rayBinPath() + occupied, socket, err := ports.IsPortOccupiedWithWhitelist(st, map[string]struct{}{path.Base(v2rayPath): {}}) if err != nil { return true, "unknown", err.Error() } @@ -1200,7 +1202,7 @@ func (t *Template) ToConfigBytes() []byte { } func WriteV2rayConfig(content []byte) (err error) { - err = ioutil.WriteFile(asset.GetConfigPath(), content, os.FileMode(0600)) + err = ioutil.WriteFile(asset.GetV2rayConfigPath(), content, os.FileMode(0600)) if err != nil { return newError("WriteV2rayConfig").Base(err) } diff --git a/service/core/v2ray/where/where.go b/service/core/v2ray/where/where.go index ac9cc6a7..aa2ec1fb 100644 --- a/service/core/v2ray/where/where.go +++ b/service/core/v2ray/where/where.go @@ -4,27 +4,36 @@ import ( "fmt" "github.com/v2rayA/v2rayA/global" "os/exec" - "path" "strings" ) -func GetV2rayServiceFilePath() (path string, err error) { - var out []byte +var NotFoundErr = fmt.Errorf("not found") +var ServiceNameList = []string{"xray", "v2ray"} +func GetV2rayServiceFilePath() (path string, err error) { + for _, target := range ServiceNameList { + if path, err = getV2rayServiceFilePath(target); err == nil { + return + } + } + return +} +func getV2rayServiceFilePath(target string) (path string, err error) { + var out []byte if global.ServiceControlMode == global.SystemctlMode { - out, err = exec.Command("sh", "-c", "systemctl status v2ray|grep /v2ray.service").CombinedOutput() + out, err = exec.Command("sh", "-c", "systemctl status "+target+"|grep /"+target+".service").CombinedOutput() if err != nil { err = newError(strings.TrimSpace(string(out))) if !strings.Contains(string(out), "not be found") { - path = `/usr/lib/systemd/system/v2ray.service` + path = `/usr/lib/systemd/system/` + target + `.service` return } } } else if global.ServiceControlMode == global.ServiceMode { - out, err = exec.Command("sh", "-c", "service v2ray status|grep /v2ray.service").CombinedOutput() + out, err = exec.Command("sh", "-c", "service "+target+" status|grep /"+target+".service").CombinedOutput() if err != nil || strings.TrimSpace(string(out)) == "(Reason:" { if !strings.Contains(string(out), "not be found") { - path = `/lib/systemd/system/v2ray.service` + path = `/lib/systemd/system/` + target + `.service` return } if err != nil { @@ -40,41 +49,76 @@ func GetV2rayServiceFilePath() (path string, err error) { } sout := string(out) l := strings.Index(sout, "/") - r := strings.Index(sout, "/v2ray.service") + r := strings.Index(sout, "/"+target+".service") if l < 0 || r < 0 { - err = newError("fail: getV2rayServiceFilePath") + err = newError("failure: getV2rayServiceFilePath") return } - path = sout[l : r+len("/v2ray.service")] + path = sout[l : r+len("/"+target+".service")] return } + /* get the version of v2ray-core without 'v' like 4.23.1 */ func GetV2rayServiceVersion() (ver string, err error) { - dir, err := GetV2rayWorkingDir() - if err != nil || len(dir) <= 0 { + v2rayPath, err := GetV2rayBinPath() + if err != nil || len(v2rayPath) <= 0 { return "", newError("cannot find v2ray executable binary") } - out, err := exec.Command("sh", "-c", fmt.Sprintf("%v/v2ray -version|awk '{print $2}'|awk 'NR==1'", dir)).Output() - return strings.TrimSpace(string(out)), err + out, err := exec.Command("sh", "-c", fmt.Sprintf("%v -version", v2rayPath)).Output() + var fields []string + if fields = strings.Fields(strings.TrimSpace(string(out))); len(fields) < 2 { + return "", newError("cannot parse version of v2ray") + } + ver = fields[1] + if strings.ToUpper(fields[0]) != "V2RAY" { + ver = "UnknownClient" + } + return } -func GetV2rayWorkingDir() (string, error) { +func GetV2rayBinPath() (string, error) { + v2rayBinPath := global.GetEnvironmentConfig().V2rayBin + if v2rayBinPath == "" { + return getV2rayBinPathAnyway() + } + return v2rayBinPath, nil +} + +func getV2rayBinPathAnyway() (path string, err error) { + for _, target := range ServiceNameList { + if path, err = getV2rayBinPath(target); err == nil { + return + } + } + return +} + +func getV2rayBinPath(target string) (string, error) { + var pa string switch global.ServiceControlMode { case global.SystemctlMode, global.ServiceMode: //从systemd的启动参数里找 - p, _ := GetV2rayServiceFilePath() + p, err := getV2rayServiceFilePath(target) + if err != nil { + return "", err + } out, err := exec.Command("sh", "-c", "cat "+p+"|grep ExecStart=").CombinedOutput() if err != nil { return "", newError(string(out)).Base(err) } arr := strings.SplitN(strings.TrimSpace(string(out)), " ", 2) - return path.Dir(strings.TrimPrefix(arr[0], "ExecStart=")), nil - case global.UniversalMode: - //从环境变量里找 - out, err := exec.Command("sh", "-c", "which v2ray").CombinedOutput() - if err == nil { - return path.Dir(strings.TrimSpace(string(out))), nil - } + pa = strings.TrimPrefix(arr[0], "ExecStart=") } - return "", newError("not found") -} \ No newline at end of file + if pa == "" { + //从环境变量里找 + out, err := exec.Command("sh", "-c", "which "+target).CombinedOutput() + if err != nil { + return "", NotFoundErr + } + pa = strings.TrimSpace(string(out)) + } + if pa == "" { + return "", NotFoundErr + } + return pa, nil +} diff --git a/service/db/configure/which.go b/service/db/configure/which.go index 333ec9ef..36af99de 100644 --- a/service/db/configure/which.go +++ b/service/db/configure/which.go @@ -123,7 +123,7 @@ func (w *Which) Ping(timeout time.Duration) (err error) { host = hosts[0] } t := time.Now() - conn, e := net.DialTimeout("tcp", host+":"+tsr.VmessInfo.Port, timeout) + conn, e := net.DialTimeout("tcp", net.JoinHostPort(host, tsr.VmessInfo.Port), timeout) if e == nil || (strings.Contains(e.Error(), "refuse")) { if e == nil { _ = conn.Close() diff --git a/service/extra/proxy/ssr/ssr.go b/service/extra/proxy/ssr/ssr.go index 57b7ba60..cfd704db 100644 --- a/service/extra/proxy/ssr/ssr.go +++ b/service/extra/proxy/ssr/ssr.go @@ -2,18 +2,16 @@ package ssr import ( shadowsocksr "github.com/mzz2017/shadowsocksR" + "github.com/mzz2017/shadowsocksR/obfs" + "github.com/mzz2017/shadowsocksR/protocol" "github.com/mzz2017/shadowsocksR/ssr" "github.com/mzz2017/shadowsocksR/streamCipher" + "github.com/nadoo/glider/common/socks" + "github.com/v2rayA/v2rayA/extra/proxy" + "log" "net" "net/url" "strconv" - "strings" - - "github.com/mzz2017/shadowsocksR/obfs" - "github.com/mzz2017/shadowsocksR/protocol" - "github.com/v2rayA/v2rayA/extra/proxy" - "github.com/nadoo/glider/common/socks" - "log" ) // SSR struct. @@ -102,8 +100,8 @@ func (s *SSR) Dial(network, addr string) (net.Conn, error) { } // should initialize obfs/protocol now - rs := strings.Split(ssrconn.RemoteAddr().String(), ":") - port, _ := strconv.Atoi(rs[1]) + h, p, _ := net.SplitHostPort(ssrconn.RemoteAddr().String()) + port, _ := strconv.Atoi(p) ssrconn.IObfs = obfs.NewObfs(s.Obfs) if ssrconn.IObfs == nil { @@ -111,7 +109,7 @@ func (s *SSR) Dial(network, addr string) (net.Conn, error) { } obfsServerInfo := &ssr.ServerInfo{ - Host: rs[0], + Host: h, Port: uint16(port), TcpMss: 1460, Param: s.ObfsParam, @@ -124,7 +122,7 @@ func (s *SSR) Dial(network, addr string) (net.Conn, error) { } protocolServerInfo := &ssr.ServerInfo{ - Host: rs[0], + Host: h, Port: uint16(port), TcpMss: 1460, Param: s.ProtocolParam, diff --git a/service/global/environmentConfig.go b/service/global/environmentConfig.go index 753b8ea8..9ba2eba4 100644 --- a/service/global/environmentConfig.go +++ b/service/global/environmentConfig.go @@ -11,14 +11,16 @@ import ( ) type Params struct { - Address string `id:"address" short:"a" default:"0.0.0.0:2017" desc:"Listening address"` - Config string `id:"config" short:"c" default:"/etc/v2raya" desc:"v2rayA configure directory"` - WebDir string `id:"webdir" default:"/etc/v2raya/web" desc:"v2rayA web files directory"` - Mode string `id:"mode" short:"m" desc:"Options: systemctl, service, universal. Auto-detect if not set"` - PluginListenPort int `short:"s" default:"32346" desc:"Plugin outbound port"` - PassCheckRoot bool `desc:"Skip privilege checking. Use it only when you cannot start v2raya but confirm you have root privilege"` - ResetPassword bool `id:"reset-password"` - ShowVersion bool `id:"version"` + Address string `id:"address" short:"a" default:"0.0.0.0:2017" desc:"Listening address"` + Config string `id:"config" short:"c" default:"/etc/v2raya" desc:"v2rayA configure directory"` + V2rayBin string `id:"v2ray-bin" desc:"Executable v2ray binary path. Auto-detect if put it empty."` + V2rayConfigDirectory string `id:"v2ray-confdir" desc:"Additional v2ray config directory, files in it will be combined with config generated by v2rayA"` + WebDir string `id:"webdir" default:"/etc/v2raya/web" desc:"v2rayA web files directory"` + Mode string `id:"mode" short:"m" desc:"(deprecated) Options: systemctl, service, universal. Auto-detect if not set"` + PluginListenPort int `short:"s" default:"32346" desc:"Plugin outbound port"` + PassCheckRoot bool `desc:"Skip privilege checking. Use it only when you cannot start v2raya but confirm you have root privilege"` + ResetPassword bool `id:"reset-password"` + ShowVersion bool `id:"version"` } var params Params @@ -26,7 +28,7 @@ var params Params var dontLoadConfig bool func initFunc() { - defer SetServiceControlMode(params.Mode) + defer SetServiceControlMode() if dontLoadConfig { return } diff --git a/service/global/systemServiceControlMode.go b/service/global/systemServiceControlMode.go index f3013386..e02cb661 100644 --- a/service/global/systemServiceControlMode.go +++ b/service/global/systemServiceControlMode.go @@ -13,25 +13,13 @@ const ( UniversalMode ) -func SetServiceControlMode(modeString string) (mode SystemServiceControlMode) { - defer func() { - ServiceControlMode = mode - }() - switch modeString { - case "systemctl": +func SetServiceControlMode() (mode SystemServiceControlMode) { + // The behaviour of this function has changed after v1.1.4 + if out, err := exec.Command("sh", "-c", "which systemctl").Output(); err == nil && strings.Contains(string(out), "systemctl") { return SystemctlMode - case "service": - return ServiceMode - case "universal", "common": - return UniversalMode - default: - //自动检测 - if out, err := exec.Command("sh", "-c", "which systemctl").Output(); err == nil && strings.Contains(string(out), "systemctl") { - return SystemctlMode - } - if out, err := exec.Command("sh", "-c", "which service").Output(); err == nil && strings.Contains(string(out), "service") { - return ServiceMode - } - return UniversalMode } + if out, err := exec.Command("sh", "-c", "which service").Output(); err == nil && strings.Contains(string(out), "service") { + return ServiceMode + } + return UniversalMode } diff --git a/service/main.go b/service/main.go index 066e5afb..d189fb1c 100644 --- a/service/main.go +++ b/service/main.go @@ -15,7 +15,6 @@ func main() { checkEnvironment() checkTProxySupportability() initConfigure() - checkConnection() go checkUpdate() hello() if err := run(); err != nil { diff --git a/service/plugin/simpleobfs/simpleobfs.go b/service/plugin/simpleobfs/simpleobfs.go index 8a60a003..5939f51c 100644 --- a/service/plugin/simpleobfs/simpleobfs.go +++ b/service/plugin/simpleobfs/simpleobfs.go @@ -9,6 +9,7 @@ import ( "github.com/v2rayA/v2rayA/extra/proxy/simpleobfs" "github.com/v2rayA/v2rayA/plugin" "log" + "net" "net/url" ) @@ -66,7 +67,7 @@ func (so *SimpleObfs) Serve(localPort int, v vmessInfo.VmessInfo) (err error) { return } p, _ := simpleobfs.NewProxy(s) - return so.s.Serve(p, "tcp->"+v.Add+":"+v.Port) + return so.s.Serve(p, "tcp->"+net.JoinHostPort(v.Add, v.Port)) } func (so *SimpleObfs) Close() error { diff --git a/service/pre.go b/service/pre.go index d0ea9cad..f20173b7 100644 --- a/service/pre.go +++ b/service/pre.go @@ -1,10 +1,12 @@ package main import ( + "errors" "fmt" "github.com/gookit/color" jsoniter "github.com/json-iterator/go" jsonIteratorExtra "github.com/json-iterator/go/extra" + "github.com/tidwall/gjson" "github.com/v2rayA/v2rayA/common/netTools/ports" "github.com/v2rayA/v2rayA/core/ipforward" "github.com/v2rayA/v2rayA/core/iptables" @@ -18,7 +20,6 @@ import ( "github.com/v2rayA/v2rayA/global" "github.com/v2rayA/v2rayA/router" "github.com/v2rayA/v2rayA/service" - "github.com/tidwall/gjson" "io/ioutil" "log" "net" @@ -32,7 +33,6 @@ import ( "sync" "syscall" "time" - "v2ray.com/core/common/errors" ) func checkEnvironment() { @@ -155,14 +155,6 @@ func initConfigure() { initDBValue() } } - - //配置文件描述符上限 - if global.ServiceControlMode == global.ServiceMode || global.ServiceControlMode == global.SystemctlMode { - err := v2ray.OptimizeServiceFile() - if err != nil { - log.Println(err) - } - } //配置ip转发 setting := configure.GetSettingNotNil() if setting.Transparent != configure.TransparentClose { @@ -170,68 +162,62 @@ func initConfigure() { _ = ipforward.WriteIpForward(setting.IpForward) } } - //检查geoip、geosite是否存在 - if !asset.IsGeoipExists() || !asset.IsGeositeExists() { - dld := func(repo, filename, localname string) (err error) { - color.Red.Println("installing " + filename) - p := asset.GetV2rayLocationAsset() + "/" + filename - resp, err := http.Get("https://api.github.com/repos/" + repo + "/tags") - if err != nil { - return - } - defer resp.Body.Close() - b, err := ioutil.ReadAll(resp.Body) - if err != nil { - return - } - tag := gjson.GetBytes(b, "0.name").String() - u := fmt.Sprintf("https://cdn.jsdelivr.net/gh/%v@%v/%v", repo, tag, filename) - err = gopeed.Down(&gopeed.Request{ - Method: "GET", - URL: u, - }, p) - if err != nil { - return errors.New("download<" + p + ">: " + err.Error()) - } - err = os.Chmod(p, os.FileMode(0755)) - if err != nil { - return errors.New("chmod: " + err.Error()) - } - os.Rename(p, asset.GetV2rayLocationAsset()+"/"+localname) - return - } - err := dld("v2rayA/dist-geoip", "geoip.dat", "geoip.dat") - if err != nil { - log.Println(err) - } - err = dld("v2rayA/dist-domain-list-community", "dlc.dat", "geosite.dat") - if err != nil { - log.Println(err) - } - } //检查config.json是否存在 - if _, err := os.Stat(asset.GetConfigPath()); err != nil { + if _, err := os.Stat(asset.GetV2rayConfigPath()); err != nil { //不存在就建一个。多数情况发生于docker模式挂载volume时覆盖了/etc/v2ray t := v2ray.NewTemplate() _ = v2ray.WriteV2rayConfig(t.ToConfigBytes()) } -} -func checkConnection() { - //如果V2Ray正在运行,而配置文件中没有记录当前连接的节点是谁,就关掉V2Ray - if v2ray.IsV2RayRunning() && configure.GetConnectedServer() == nil { - err := v2ray.StopAndDisableV2rayService() - if err != nil { - log.Fatal(err) + //首先确定v2ray是否存在 + if _, err := where.GetV2rayBinPath(); err == nil { + //检查geoip、geosite是否存在 + if !asset.IsGeoipExists() || !asset.IsGeositeExists() { + dld := func(repo, filename, localname string) (err error) { + color.Red.Println("installing " + filename) + p := asset.GetV2rayLocationAsset() + "/" + filename + resp, err := http.Get("https://api.github.com/repos/" + repo + "/tags") + if err != nil { + return + } + defer resp.Body.Close() + b, err := ioutil.ReadAll(resp.Body) + if err != nil { + return + } + tag := gjson.GetBytes(b, "0.name").String() + u := fmt.Sprintf("https://cdn.jsdelivr.net/gh/%v@%v/%v", repo, tag, filename) + err = gopeed.Down(&gopeed.Request{ + Method: "GET", + URL: u, + }, p) + if err != nil { + return errors.New("download<" + p + ">: " + err.Error()) + } + err = os.Chmod(p, os.FileMode(0755)) + if err != nil { + return errors.New("chmod: " + err.Error()) + } + os.Rename(p, asset.GetV2rayLocationAsset()+"/"+localname) + return + } + err := dld("v2rayA/dist-geoip", "geoip.dat", "geoip.dat") + if err != nil { + log.Println(err) + } + err = dld("v2rayA/dist-domain-list-community", "dlc.dat", "geosite.dat") + if err != nil { + log.Println(err) + } } } } func hello() { color.Red.Println("V2RayLocationAsset is", asset.GetV2rayLocationAsset()) - wd, _ := where.GetV2rayWorkingDir() - color.Red.Println("V2Ray binary is at", wd+"/v2ray") - wd, _ = os.Getwd() + v2rayPath, _ := where.GetV2rayBinPath() + color.Red.Println("V2Ray binary is", v2rayPath) + wd, _ := os.Getwd() color.Red.Println("v2rayA working directory is", wd) color.Red.Println("Version:", global.Version) color.Red.Println("Starting...") @@ -311,11 +297,9 @@ func checkUpdate() { func run() (err error) { //判别需要启动v2ray吗 - if configure.GetConnectedServer() != nil { - _ = v2ray.RestartV2rayService() + if w := configure.GetConnectedServer(); w != nil { + _ = service.Connect(w) } - //刷新配置以刷新透明代理、ssr server - err = v2ray.UpdateV2RayConfig(nil) if err != nil { w := configure.GetConnectedServer() log.Println(err, ", which:", w) diff --git a/service/router/index.go b/service/router/index.go index 967e0040..64b7b889 100644 --- a/service/router/index.go +++ b/service/router/index.go @@ -6,7 +6,6 @@ import ( "github.com/gookit/color" "github.com/v2rayA/v2rayA/common" "github.com/v2rayA/v2rayA/common/jwt" - "github.com/v2rayA/v2rayA/common/netTools" "github.com/v2rayA/v2rayA/controller" "github.com/v2rayA/v2rayA/db/configure" "github.com/v2rayA/v2rayA/global" @@ -43,7 +42,7 @@ func ServeGUI(engine *gin.Engine) { app := global.GetEnvironmentConfig() - ip, port := netTools.ParseAddress(app.Address) + ip, port, _ := net.SplitHostPort(app.Address) addrs, err := net.InterfaceAddrs() if net.ParseIP(ip).IsUnspecified() && err == nil { for _, addr := range addrs { diff --git a/service/service/connect.go b/service/service/connect.go index c0162850..f8ed8290 100644 --- a/service/service/connect.go +++ b/service/service/connect.go @@ -14,10 +14,6 @@ func Disconnect() (err error) { if err != nil { return } - err = v2ray.DisableV2rayService() - if err != nil { - return - } err = configure.ClearConnected() if err != nil { return diff --git a/service/service/ports.go b/service/service/ports.go index 0fb66c4c..9b674c53 100644 --- a/service/service/ports.go +++ b/service/service/ports.go @@ -1,11 +1,13 @@ package service import ( + "fmt" "github.com/v2rayA/v2rayA/common/netTools/netstat" ports2 "github.com/v2rayA/v2rayA/common/netTools/ports" "github.com/v2rayA/v2rayA/core/v2ray" + "github.com/v2rayA/v2rayA/core/v2ray/where" "github.com/v2rayA/v2rayA/db/configure" - "fmt" + "path" "strconv" ) @@ -67,7 +69,8 @@ func SetPorts(ports *configure.Ports) (err error) { return } process, err := v.Process() - if err == nil && process.Name != "v2ray" { + v2rayPath, _ := where.GetV2rayBinPath() + if err == nil && process.Name != path.Base(v2rayPath) { return newError(fmt.Sprintf("port %v is occupied by %v", v.LocalAddress.Port, process.Name)) } }