fix: repair known bugs in docker mode

This commit is contained in:
mzz2017 committed 2019-11-04 06:44:18 +08:00
1 parent b825e457b5
commit 5b0002e5da
22 files changed
+622 -365

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
FROM golang
RUN go get github.com/codegangsta/gin
RUN apt-get update
RUN apt-get install -y psmisc ca-certificates
WORKDIR /service
ENTRYPOINT gin -p 2017 -i run
+13 -13
View File
@@ -63,18 +63,8 @@ V2RayA是V2Ray的一个Web客户端。
cd V2RayA
docker-compose up -d
```
2. (文档待完善)用docker拉取镜像部署service,在[Web-GUI](https://v2raya.mzz.pub)使用(或手动部署Web-GUI)。
```bash
# TODO
docker pull v2ray/official
docker run -d -p 20170-20172:20170-20172 --restart=always v2ray/official
docker pull mzz2017/v2raya
docker run -d -p 2017:2017 --restart=always mzz2017/v2raya
```
3. 不使用docker
2. 不使用docker
```bash
git clone https://github.com/mzz2017/V2RayA.git
@@ -82,7 +72,7 @@ V2RayA是V2Ray的一个Web客户端。
sudo go run -mod=vendor main.go
```
或直接使用[Releases](https://github.com/mzz2017/V2RayA/releases)。注意,该方法不支持windows,其他系统请使用sudo运行。
或直接使用[Releases](https://github.com/mzz2017/V2RayA/releases)。注意,该方法不支持windows。
默认使用的四个端口分别为:
@@ -98,7 +88,7 @@ V2RayA是V2Ray的一个Web客户端。
### 在不同运行环境下程序表现将不同
由于docker容器对systemd的限制性,在docker中将采用pid共享进程命名空间,volumes共享存储空间,更新配置后通过结束进程触发v2ray容器的重启来更新配置,以无inbounds的配置代替断开连接,这是一种曲折的折中方案。
由于docker容器对systemd的限制性,在docker中将采用pid共享进程命名空间,volumes共享存储空间,更新配置后通过结束进程触发v2ray容器的重启来更新配置,以无inbounds的配置代替断开连接,这是一种折中方案,不影响正常使用。
在宿主环境下以sudo权限运行将不受此限制。
@@ -110,6 +100,16 @@ V2RayA是V2Ray的一个Web客户端。
不要将本项目用于不合法用途,作者仅将该项目用于学习研究和内网穿透的用途。
# 在docker环境中开发
```bash
docker-compose -f docker-compose.dev.yml up
```
gin会监测文件改动并热重载,见[codegangsta/gin](https://github.com/codegangsta/gin)。
# 感谢
[jiangxufeng/v2rayL](https://github.com/jiangxufeng/v2rayL)
+27
View File
@@ -0,0 +1,27 @@
version: "3"
services:
backend:
restart: always
build:
context: .
dockerfile: Dockerfile.dev
ports:
- 2017:2017
volumes:
- shared-data:/etc/v2ray
- ./service:/service
v2ray:
restart: always
image: "v2ray/official"
pid: service:backend
environment:
- V2RAY_LOCATION_ASSET=/etc/v2ray
ports:
- 20170-20172:20170-20172
volumes:
- shared-data:/etc/v2ray
entrypoint: sh -c "cp -rfu /usr/bin/v2ray/*.dat /etc/v2ray && v2ray -config=/etc/v2ray/config.json"
volumes:
shared-data:
+3 -2
View File
@@ -12,12 +12,13 @@ services:
restart: always
image: "v2ray/official"
pid: service:backend
environment:
- V2RAY_LOCATION_ASSET=/etc/v2ray
ports:
- 20170-20172:20170-20172
volumes:
- shared-data:/etc/v2ray
command: cp -r /usr/bin/v2ray/* /etc/v2ray/
entrypoint: v2ray -config=/etc/v2ray/config.json
entrypoint: sh -c "cp -rfu /usr/bin/v2ray/*.dat /etc/v2ray && v2ray -config=/etc/v2ray/config.json"
volumes:
shared-data:
+15 -17
View File
@@ -1,23 +1,21 @@
module.exports = {
root: true,
root: true,
env: {
node: true
},
env: {
node: true
},
extends: ["plugin:vue/essential", "@vue/prettier"],
rules: {
'no-console': 'off',
'no-debugger': 'off'
},
rules: {
'no-console': 'off',
'no-debugger': 'off'
},
parserOptions: {
parser: 'babel-eslint'
},
parserOptions: {
parser: 'babel-eslint'
},
'extends': [
'plugin:vue/recommended',
'@vue/prettier'
]
'extends': [
'plugin:vue/recommended',
'@vue/prettier'
]
};
+281 -264
View File
@@ -1,160 +1,164 @@
<template>
<div id="app">
<b-navbar ref="navs" fixed-top shadow type="is-light">
<template slot="brand">
<b-navbar-item href="/">
<img src="./assets/logo.png" alt="V2RayA" class="logo no-select" />
</b-navbar-item>
</template>
<template slot="start">
<b-navbar-item tag="div">
V2Ray状态:<b-tag
id="statusTag"
:type="statusMap[runningState.running]"
@mouseenter.native="handleOnStatusMouseEnter"
@mouseleave.native="handleOnStatusMouseLeave"
@click.native="handleClickStatus"
>{{
coverStatusText ? coverStatusText : runningState.running
}}</b-tag
>
</b-navbar-item>
</template>
<div id="app">
<b-navbar ref="navs" fixed-top shadow type="is-light">
<template slot="brand">
<b-navbar-item href="/">
<img src="./assets/logo.png" alt="V2RayA" class="logo no-select"/>
</b-navbar-item>
</template>
<template slot="start">
<b-navbar-item tag="div">
V2Ray状态:
<b-tag
id="statusTag"
:type="statusMap[runningState.running]"
@mouseenter.native="handleOnStatusMouseEnter"
@mouseleave.native="handleOnStatusMouseLeave"
@click.native="handleClickStatus"
>{{
coverStatusText ? coverStatusText : runningState.running
}}
</b-tag
>
</b-navbar-item>
</template>
<template slot="end">
<!-- <b-navbar-item tag="router-link" to="/node" :active="nav === 'node'">-->
<!-- <i class="iconfont icon-cloud" style="font-size: 1.4em"></i>-->
<!-- 节点-->
<!-- </b-navbar-item>-->
<b-navbar-item tag="a" @click.native="handleClickSetting">
<i class="iconfont icon-setting" style="font-size: 1.25em"></i>
设置
</b-navbar-item>
<b-navbar-item tag="a" @click.native="handleClickAbout">
<i class="iconfont icon-heart" style="font-size: 1.25em"></i>
关于
</b-navbar-item>
<b-dropdown
position="is-bottom-left"
aria-role="menu"
style="margin-right:10px"
class="menudropdown"
>
<a slot="trigger" class="navbar-item" role="button">
<span class="no-select">mzz2017</span>
<i
class="iconfont icon-caret-down"
style="position: relative; top: 1px; left:2px"
></i>
</a>
<template slot="end">
<!-- <b-navbar-item tag="router-link" to="/node" :active="nav === 'node'">-->
<!-- <i class="iconfont icon-cloud" style="font-size: 1.4em"></i>-->
<!-- 节点-->
<!-- </b-navbar-item>-->
<b-navbar-item tag="a" @click.native="handleClickSetting">
<i class="iconfont icon-setting" style="font-size: 1.25em"></i>
设置
</b-navbar-item>
<b-navbar-item tag="a" @click.native="handleClickAbout">
<i class="iconfont icon-heart" style="font-size: 1.25em"></i>
关于
</b-navbar-item>
<b-dropdown
position="is-bottom-left"
aria-role="menu"
style="margin-right:10px"
class="menudropdown"
>
<a slot="trigger" class="navbar-item" role="button">
<span class="no-select">mzz2017</span>
<i
class="iconfont icon-caret-down"
style="position: relative; top: 1px; left:2px"
></i>
</a>
<b-dropdown-item custom aria-role="menuitem">
Logged as <b>mzz2017</b>
</b-dropdown-item>
<hr class="dropdown-divider" />
<b-dropdown-item
value="logout"
aria-role="menuitem"
class="no-select"
>
<i
class="iconfont icon-logout"
style="position: relative;top:1px;"
></i>
Logout
</b-dropdown-item>
</b-dropdown>
</template>
</b-navbar>
<node v-model="runningState" />
</div>
<b-dropdown-item custom aria-role="menuitem">
Logged as <b>mzz2017</b>
</b-dropdown-item>
<hr class="dropdown-divider"/>
<b-dropdown-item
value="logout"
aria-role="menuitem"
class="no-select"
>
<i
class="iconfont icon-logout"
style="position: relative;top:1px;"
></i>
Logout
</b-dropdown-item>
</b-dropdown>
</template>
</b-navbar>
<node v-model="runningState"/>
</div>
</template>
<script>
import CONST from "@/assets/js/const";
import ModalSetting from "@/components/ModalSetting";
import node from "@/components/node";
import CONST from "@/assets/js/const";
import ModalSetting from "@/components/ModalSetting";
import node from "@/components/node";
export default {
components: { node },
data() {
return {
statusMap: {
[CONST.INSPECTING_RUNNING]: "is-light",
[CONST.NOT_RUNNING]: "is-danger",
[CONST.IS_RUNNING]: "is-success"
},
coverStatusText: "",
runningState: {
running: CONST.INSPECTING_RUNNING,
connectedServer: null,
lastConnectedServer: null
}
};
},
created() {
this.$axios({
url: apiRoot + "/version"
})
.then(res => {
if (res.data.code === "SUCCESS") {
this.$buefy.toast.open({
message: `V2RayA服务端正在运行于${
res.data.data.isInDocker ? "Docker环境中" : "本地"
},Version: ${res.data.data.version}`,
type: "is-dark",
position: "is-top",
duration: 3000
});
}
})
.catch(err => {
if (err.message === "Network Error") {
console.log("todo", Object.assign({}, err)); //TODO
this.$buefy.snackbar.open({
message: "未检测到本地V2RayA服务端,请确认服务端是否监听2017端口",
type: "is-warning",
position: "is-top",
actionText: "查看帮助",
duration: 60000,
onAction: () => {
window.open(
"https://github.com/mzz2017/V2RayA#%E4%BD%BF%E7%94%A8",
"_blank"
);
}
});
}
});
},
methods: {
handleOnStatusMouseEnter() {
if (this.runningState.running === CONST.IS_RUNNING) {
this.coverStatusText = " 关闭 ";
} else if (this.runningState.running === CONST.NOT_RUNNING) {
this.coverStatusText = " 启动 ";
}
},
handleOnStatusMouseLeave() {
this.coverStatusText = "";
},
handleClickSetting() {
this.$buefy.modal.open({
parent: this,
component: ModalSetting,
hasModalCard: true,
canCancel: false
});
},
handleClickAbout() {
this.$buefy.modal.open({
content: `
export default {
components: {node},
data() {
return {
statusMap: {
[CONST.INSPECTING_RUNNING]: "is-light",
[CONST.NOT_RUNNING]: "is-danger",
[CONST.IS_RUNNING]: "is-success"
},
coverStatusText: "",
runningState: {
running: CONST.INSPECTING_RUNNING,
connectedServer: null,
lastConnectedServer: null
}
};
},
created() {
this.$axios({
url: apiRoot + "/version"
})
.then(res => {
if (res.data.code === "SUCCESS") {
this.$buefy.toast.open({
message: `V2RayA服务端正在运行于${
res.data.data.isInDocker ? "Docker环境中" : "本地"
},Version: ${res.data.data.version}`,
type: "is-dark",
position: "is-top",
duration: 3000
});
}
})
.catch(err => {
if (err.message === "Network Error") {
console.log("todo", Object.assign({}, err)); //TODO
this.$buefy.snackbar.open({
message: "未检测到本地V2RayA服务端,请确认服务端是否监听2017端口",
type: "is-warning",
position: "is-top",
actionText: "查看帮助",
duration: 60000,
onAction: () => {
window.open(
"https://github.com/mzz2017/V2RayA#%E4%BD%BF%E7%94%A8",
"_blank"
);
}
});
}
});
},
methods: {
handleOnStatusMouseEnter() {
if (this.runningState.running === CONST.IS_RUNNING) {
this.coverStatusText = " 关闭 ";
} else if (this.runningState.running === CONST.NOT_RUNNING) {
this.coverStatusText = " 启动 ";
}
},
handleOnStatusMouseLeave() {
this.coverStatusText = "";
},
handleClickSetting() {
this.$buefy.modal.open({
parent: this,
component: ModalSetting,
hasModalCard: true,
canCancel: false
});
},
handleClickAbout() {
this.$buefy.modal.open({
width: 640,
content: `
<div class="modal-card" style="margin:auto">
<header class="modal-card-head">
<p class="modal-card-title">mzz2017 / V2RayA</p>
</header>
<section class="modal-card-body lazy">
<p>V2RayA是V2Ray的一个Web客户端,前端使用Vue.js构建,后端使用Golang构建。</p>
<p style="font-size:0.85em;text-indent:1em;color:rgba(0,0,0,0.6)">默认端口:</p>
<p style="font-size:0.85em;text-indent:1em;color:rgba(0,0,0,0.6)">2017: V2RayA后端端口</p>
<p style="font-size:0.85em;text-indent:1em;color:rgba(0,0,0,0.6)">20170: SOCKS协议</p>
<p style="font-size:0.85em;text-indent:1em;color:rgba(0,0,0,0.6)">20171: HTTP协议</p>
@@ -172,133 +176,146 @@ export default {
</footer>
</div>
`
});
},
handleClickStatus() {
if (this.runningState.running === CONST.NOT_RUNNING) {
this.$axios({
url: apiRoot + "/v2ray",
method: "post"
}).then(res => {
if (res.data.code === "SUCCESS") {
Object.assign(this.runningState, {
running: CONST.IS_RUNNING,
connectedServer: res.data.data.connectedServer,
lastConnectedServer: null
});
} else {
this.$buefy.toast.open({
message: res.data.message,
type: "is-warning",
position: "is-top"
});
}
});
} else if (this.runningState.running === CONST.IS_RUNNING) {
this.$axios({
url: apiRoot + "/v2ray",
method: "delete"
}).then(res => {
if (res.data.code === "SUCCESS") {
Object.assign(this.runningState, {
running: CONST.NOT_RUNNING,
connectedServer: null,
lastConnectedServer: res.data.data.lastConnectedServer
});
console.log(this.runningState);
} else {
this.$buefy.toast.open({
message: res.data.message,
type: "is-warning",
position: "is-top"
});
}
});
}
}
}
};
});
},
handleClickStatus() {
if (this.runningState.running === CONST.NOT_RUNNING) {
this.$axios({
url: apiRoot + "/v2ray",
method: "post"
}).then(res => {
if (res.data.code === "SUCCESS") {
Object.assign(this.runningState, {
running: CONST.IS_RUNNING,
connectedServer: res.data.data.connectedServer,
lastConnectedServer: null
});
} else {
this.$buefy.toast.open({
message: res.data.message,
type: "is-warning",
position: "is-top"
});
}
});
} else if (this.runningState.running === CONST.IS_RUNNING) {
this.$axios({
url: apiRoot + "/v2ray",
method: "delete"
}).then(res => {
if (res.data.code === "SUCCESS") {
Object.assign(this.runningState, {
running: CONST.NOT_RUNNING,
connectedServer: null,
lastConnectedServer: res.data.data.lastConnectedServer
});
console.log(this.runningState);
} else {
this.$buefy.toast.open({
message: res.data.message,
type: "is-warning",
position: "is-top"
});
}
});
}
}
}
};
</script>
<style>
@import "https://at.alicdn.com/t/font_1467288_0g54ffvhenqu.css";
@import "https://at.alicdn.com/t/font_1467288_0g54ffvhenqu.css";
</style>
<style lang="scss" scoped>
#app {
margin: 0;
}
.menucontainer {
padding: 20px;
}
.logo {
min-height: 2.5rem;
}
.navbar-item .iconfont {
margin-right: 0.15em;
}
#statusTag:hover {
cursor: pointer;
}
#app {
margin: 0;
}
.menucontainer {
padding: 20px;
}
.logo {
min-height: 2.5rem;
}
.navbar-item .iconfont {
margin-right: 0.15em;
}
#statusTag:hover {
cursor: pointer;
}
</style>
<style lang="scss">
html {
&::-webkit-scrollbar {
// 去掉讨厌的滚动条
display: none;
}
#app {
height: calc(100vh - 3.25rem);
overflow-y: auto;
overflow-scrolling: touch;
-webkit-overflow-scrolling: touch;
}
}
@media screen and (max-width: 1023px) {
.dropdown.is-mobile-modal .dropdown-menu {
// 修复modal模糊问题
left: 0 !important;
right: 0 !important;
margin: auto;
transform: unset !important;
}
}
.dropdown-item:focus {
// 不要丑丑的outline
outline: none !important;
}
.no-select {
user-select: none;
-webkit-user-drag: none;
}
.menudropdown .dropdown-item {
font-size: 0.8em;
}
.leave-right {
margin-right: 0.6rem;
}
.lazy {
p {
margin: 0.5em 0;
}
}
a.navbar-item:focus,
a.navbar-item:focus-within,
a.navbar-item:hover,
a.navbar-item.is-active,
.navbar-link:focus,
.navbar-link:focus-within,
.navbar-link:hover,
.navbar-link.is-active,
.is-link,
a {
$success: #506da4;
color: $success;
}
.icon-loading_ico-copy {
font-size: 2.5rem;
color: rgba(0, 0, 0, 0.45);
animation: loading-rotate 2s infinite linear;
}
html {
&::-webkit-scrollbar {
// 去掉讨厌的滚动条
display: none;
}
#app {
height: calc(100vh - 3.25rem);
overflow-y: auto;
overflow-scrolling: touch;
-webkit-overflow-scrolling: touch;
}
}
@media screen and (max-width: 1023px) {
.dropdown.is-mobile-modal .dropdown-menu {
// 修复modal模糊问题
left: 0 !important;
right: 0 !important;
margin: auto;
transform: unset !important;
}
}
.dropdown-item:focus {
// 不要丑丑的outline
outline: none !important;
}
.no-select {
user-select: none;
-webkit-user-drag: none;
}
.menudropdown .dropdown-item {
font-size: 0.8em;
}
.leave-right {
margin-right: 0.6rem;
}
.lazy {
p {
margin: 0.5em 0;
}
}
a.navbar-item:focus,
a.navbar-item:focus-within,
a.navbar-item:hover,
a.navbar-item.is-active,
.navbar-link:focus,
.navbar-link:focus-within,
.navbar-link:hover,
.navbar-link.is-active,
.is-link,
a {
$success: #506da4;
color: $success;
}
.icon-loading_ico-copy {
font-size: 2.5rem;
color: rgba(0, 0, 0, 0.45);
animation: loading-rotate 2s infinite linear;
}
</style>
+3 -1
View File
@@ -1,3 +1,5 @@
main.test.go
V2RayA*
.tr
.tr
tmp
gin-bin
+1 -1
View File
@@ -12,6 +12,7 @@ func GetTouchRaw() touch.TouchRaw {
if tr == nil {
tr = new(touch.TouchRaw)
tr.Lock()
defer tr.Unlock()
_ = tr.ReadFromFile(GetServiceConfig().ConfigPath)
if tr.Subscriptions == nil {
tr.Subscriptions = make([]touch.SubscriptionRaw, 0)
@@ -22,7 +23,6 @@ func GetTouchRaw() touch.TouchRaw {
if tr.Setting == nil {
tr.Setting = touch.NewSetting()
}
tr.Unlock()
}
return *deepcopy.Copy(tr).(*touch.TouchRaw)
}
+48 -1
View File
@@ -1,3 +1,50 @@
package global
var IsInDocker bool
import (
"V2RayA/models/v2ray"
"os/exec"
)
var ServiceControlMode v2ray.ServiceControlMode
var V2RAY_LOCATION_ASSET string
func getV2rayLocationAsset() (s string) {
switch ServiceControlMode {
case v2ray.Docker:
return "/etc/v2ray"
case v2ray.Systemctl, v2ray.Service:
var (
p string
out []byte
err error
)
if ServiceControlMode == v2ray.Systemctl {
out, err = exec.Command("sh", "-c", "systemctl status v2ray|grep Loaded|awk '{print $3}'").Output()
if err != nil {
p = `/usr/lib/systemd/system/v2ray.service`
}
} else {
out, err = exec.Command("sh", "-c", "systemctl v2ray status|grep Loaded|awk '{print $3}'").Output()
if err != nil {
p = `/lib/systemd/system/v2ray.service`
}
}
sout := string(out)
p = sout[1 : len(sout)-1]
out, err = exec.Command("sh", "-c", "cat "+p+"|grep Environment=V2RAY_LOCATION_ASSET").Output()
if err != nil {
return
}
s = string(out)
s = s[len("Environment=V2RAY_LOCATION_ASSET="):]
}
if s == "" {
s = "/etc/v2ray"
}
return
}
func init() {
ServiceControlMode = v2ray.NewServiceControlMode()
V2RAY_LOCATION_ASSET = getV2rayLocationAsset()
}
+16 -7
View File
@@ -3,6 +3,7 @@ package handlers
import (
"V2RayA/global"
"V2RayA/models/touch"
"V2RayA/models/v2ray"
"V2RayA/tools"
"errors"
"github.com/gin-gonic/gin"
@@ -24,7 +25,7 @@ func PostConnection(ctx *gin.Context) {
return
}
//根据找到的Server更新V2Ray服务的配置
err = tools.UpdateV2RayConfig(&tsr.VmessInfo)
err = tools.UpdateV2RayConfigAndRestart(&tsr.VmessInfo)
if err != nil {
tools.ResponseError(ctx, err)
return
@@ -55,12 +56,7 @@ func DeleteConnection(ctx *gin.Context) {
tr.Lock() //写操作加锁
defer tr.Unlock()
tr.SetDisConnect()
err := tr.WriteToFile()
if err != nil {
tools.ResponseError(ctx, err)
return
}
err = tools.StopV2rayService()
err := tools.StopV2rayService()
if err != nil {
tools.ResponseError(ctx, err)
return
@@ -70,6 +66,19 @@ func DeleteConnection(ctx *gin.Context) {
tools.ResponseError(ctx, err)
return
}
err = tr.WriteToFile()
if err != nil {
tools.ResponseError(ctx, err)
return
}
global.SetTouchRaw(&tr)
//docker模式下清空inbounds来代表断开连接
if global.ServiceControlMode == v2ray.Docker {
err = tools.PretendToStopV2rayService()
if err != nil {
tools.ResponseError(ctx, err)
return
}
}
tools.ResponseSuccess(ctx, gin.H{"lastConnectedServer": cs})
}
+24 -3
View File
@@ -6,11 +6,13 @@ import (
"V2RayA/tools"
"errors"
"github.com/gin-gonic/gin"
"os"
)
func GetSetting(ctx *gin.Context) {
tr := global.GetTouchRaw()
tr.Lock()
defer tr.Unlock()
s := tr.Setting
if s == nil {
s = touch.NewSetting()
@@ -30,7 +32,6 @@ func GetSetting(ctx *gin.Context) {
tools.ResponseError(ctx, err)
return
}
tr.Unlock()
tools.ResponseSuccess(ctx, gin.H{
"setting": s,
"localGFWListVersion": localGFWListVersion,
@@ -47,10 +48,22 @@ func PutSetting(ctx *gin.Context) {
}
//TODO: 检查参数合法性
//TODO: 确保SiteDAT文件存在!
switch data.PacMode {
case touch.GfwlistMode:
if _, err := os.Stat("/etc/v2ray/h2y.dat"); err != nil {
tools.ResponseError(ctx, errors.New("未发现GFWList文件,请更新GFWList后再试"))
return
}
case touch.CustomMode:
if _, err := os.Stat("/etc/v2ray/custom.dat"); err != nil {
tools.ResponseError(ctx, errors.New("未发现custom.dat文件,功能正在开发"))
return
}
}
tr := global.GetTouchRaw()
tr.Lock()
defer tr.Unlock()
tr.Setting = &data
global.SetTouchRaw(&tr)
err = tr.WriteToFile()
@@ -58,6 +71,14 @@ func PutSetting(ctx *gin.Context) {
tools.ResponseError(ctx, err)
return
}
tr.Unlock()
//重写配置并重启连接,使得对PAC的修改立即生效
if tr.ConnectedServer != nil {
tsr, _ := tr.LocateServer(tr.ConnectedServer)
err = tools.UpdateV2RayConfigAndRestart(&tsr.VmessInfo)
if err != nil {
tools.ResponseError(ctx, err)
return
}
}
tools.ResponseSuccess(ctx, nil)
}
+19 -2
View File
@@ -3,6 +3,7 @@ package handlers
import (
"V2RayA/global"
"V2RayA/models/touch"
"V2RayA/models/v2ray"
"V2RayA/tools"
"errors"
"github.com/gin-gonic/gin"
@@ -45,7 +46,7 @@ func DeleteTouch(ctx *gin.Context) {
touches := data.GetTouches()
tr.Lock() //写操作需要上锁
defer tr.Unlock()
disconnect := func() {
disconnect := func() (err error) {
tr.SetDisConnect()
err = tools.StopV2rayService()
if err != nil {
@@ -57,6 +58,19 @@ func DeleteTouch(ctx *gin.Context) {
tools.ResponseError(ctx, err)
return
}
//docker模式下清空inbounds来代表断开连接
if global.ServiceControlMode == v2ray.Docker {
err = tools.PretendToStopV2rayService()
if err != nil {
tools.ResponseError(ctx, err)
return
}
err = tools.RestartV2rayService()
if err != nil {
return
}
}
return
}
for _, v := range touches {
ind := v.ID - 1
@@ -64,7 +78,10 @@ func DeleteTouch(ctx *gin.Context) {
case touch.SubscriptionType: //这里删的是某个订阅
//检查现在连接的结点是否在该订阅中,是的话断开连接
if tr.ConnectedServer != nil && tr.ConnectedServer.TYPE == touch.SubscriptionServerType && tr.ConnectedServer.Sub == ind {
disconnect()
err = disconnect()
if err != nil {
return
}
}
tr.Subscriptions = append(tr.Subscriptions[:ind], tr.Subscriptions[ind+1:]...)
case touch.ServerType:
+5
View File
@@ -2,6 +2,7 @@ package handlers
import (
"V2RayA/global"
"V2RayA/models/v2ray"
"V2RayA/tools"
"errors"
"github.com/gin-gonic/gin"
@@ -27,6 +28,10 @@ func PostV2ray(ctx *gin.Context) {
}
func DeleteV2ray(ctx *gin.Context) {
if global.ServiceControlMode == v2ray.Docker {
tools.ResponseError(ctx, errors.New("Docker模式下无法关闭V2Ray,但可以断开节点连接"))
return
}
err := tools.StopV2rayService()
if err != nil {
tools.ResponseError(ctx, err)
+2 -1
View File
@@ -2,6 +2,7 @@ package handlers
import (
"V2RayA/global"
"V2RayA/models/v2ray"
"V2RayA/tools"
"github.com/gin-gonic/gin"
)
@@ -9,7 +10,7 @@ import (
func Version(ctx *gin.Context) {
tools.ResponseSuccess(ctx, gin.H{
"version": "v0.2",
"isInDocker": global.IsInDocker,
"isInDocker": global.ServiceControlMode == v2ray.Docker,
})
}
+6 -8
View File
@@ -2,6 +2,7 @@ package main
import (
"V2RayA/global"
"V2RayA/models/v2ray"
"V2RayA/router"
"V2RayA/tools"
"fmt"
@@ -9,7 +10,6 @@ import (
"github.com/gookit/color"
"log"
"os"
"os/exec"
"runtime"
)
@@ -25,17 +25,17 @@ func main() {
fmt.Println("请以sudo或root权限执行本程序")
return
}
_, err := exec.Command("ls", "/.dockerenv").Output()
if err != nil {
color.Red.Println("V2RAY_LOCATION_ASSET is:", global.V2RAY_LOCATION_ASSET)
if global.ServiceControlMode != v2ray.Docker {
wd, _ := os.Getwd()
color.Red.Println("Working directory is:", wd)
color.Red.Println("Service working directory is:", wd)
conf := global.GetServiceConfig()
color.Red.Println("Configuration file is at:", conf.ConfigPath)
color.Red.Println("Service listen: "+conf.Address+":"+conf.Port+",", "GUI demo: https://v2raya.mzz.pub")
color.Red.Println("Service listen: http://"+conf.Address+":"+conf.Port+",", "GUI demo: https://v2raya.mzz.pub")
//如果V2Ray正在运行,而配置文件中没有记录当前连接的节点是谁,就关掉V2Ray
if tools.IsV2RayRunning() && global.GetTouchRaw().ConnectedServer == nil {
err = tools.StopV2rayService()
err := tools.StopV2rayService()
if err != nil {
log.Fatal(err)
}
@@ -44,9 +44,7 @@ func main() {
log.Fatal(err)
}
}
} else {
global.IsInDocker = true
fmt.Println("V2RayA is running in Docker. Compatibility mode starts up.") //TODO
}
router.Run()
+1 -1
View File
@@ -18,7 +18,7 @@ type TouchRaw struct {
Subscriptions []SubscriptionRaw `json:"subscriptions"`
mutex sync.Mutex `json:"-"`
ConnectedServer *WhichTouch `json:"connectedServer"` //冗余一个信息,方便查找
Setting *Setting `json:"setting"`
Setting *Setting `json:"setting"`
}
type Setting struct {
@@ -0,0 +1,32 @@
package v2ray
import (
"os/exec"
"strings"
)
type ServiceControlMode int
const (
Systemctl = ServiceControlMode(iota)
Service
Common
Docker
)
func NewServiceControlMode() (mode ServiceControlMode) {
if _, err := exec.Command("ls", "/.dockerenv").Output(); err == nil {
mode = Docker
return
}
if out, err := exec.Command("sh", "-c", "type -p systemctl").Output(); strings.Contains(string(out), "systemctl") && err == nil {
mode = Systemctl
return
}
if out, err := exec.Command("sh", "-c", "type -p service").Output(); strings.Contains(string(out), "service") && err == nil {
mode = Service
return
}
mode = Common
return
}
+6
View File
@@ -0,0 +1,6 @@
package v2ray
type v2ray struct{}
+3
View File
@@ -16,6 +16,9 @@ func Run() {
corsConfig := cors.DefaultConfig()
corsConfig.AllowAllOrigins = true
engine.Use(cors.New(corsConfig))
engine.GET("/", func(ctx *gin.Context) {
ctx.String(200, `这里是V2RayA服务端,请配合前端GUI使用,方法:https://github.com/mzz2017/V2RayA/blob/master/README.md`)
})
g := engine.Group("api")
{
g.GET("version", handlers.Version)
+27 -2
View File
@@ -3,9 +3,12 @@ package tools
import (
"V2RayA/global"
"V2RayA/models/touch"
"V2RayA/models/v2ray"
"V2RayA/proxyWithHttp"
"net/http"
"net/url"
"os/exec"
"strings"
)
func GetHttpClientWithProxy(proxyURL string) (client *http.Client, err error) {
@@ -24,11 +27,33 @@ func GetHttpClientWithProxy(proxyURL string) (client *http.Client, err error) {
}
func GetHttpClientWithV2RayAProxy() (client *http.Client, err error) {
return GetHttpClientWithProxy("socks5://localhost:20170")
host := "localhost"
//是否在docker环境
if global.ServiceControlMode == v2ray.Docker {
//连接网关,即宿主机的端口,失败则用同网络下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 GetHttpClientWithProxy("socks5://" + host + ":20170")
}
func GetHttpClientWithV2RayAPac() (client *http.Client, err error) {
return GetHttpClientWithProxy("http://localhost:20172")
host := "localhost"
//是否在docker环境
if global.ServiceControlMode == v2ray.Docker {
//连接网关,即宿主机的端口,失败则用同网络下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 GetHttpClientWithProxy("http://" + host + ":20172")
}
func GetHttpClientAutomatically() (c *http.Client, err error) {
+8 -1
View File
@@ -2,6 +2,8 @@ package tools
import (
"github.com/PuerkitoBio/goquery"
"github.com/pkg/errors"
"log"
"net/http"
"time"
)
@@ -16,6 +18,11 @@ func GetRemoteGFWListUpdateTime(c *http.Client) (t time.Time, err error) {
return
}
defer resp.Body.Close()
timeRaw, _ := doc.Find("relative-time").First().Attr("datetime")
timeRaw, ok := doc.Find("relative-time").First().Attr("datetime")
if !ok {
log.Println(doc.Html())
return time.Time{}, errors.New("获取最新GFWList版本失败")
}
log.Println("timeraw", timeRaw)
return time.Parse(time.RFC3339, timeRaw)
}
+75 -41
View File
@@ -2,27 +2,46 @@ package tools
import (
"V2RayA/global"
"V2RayA/models/v2ray"
"V2RayA/models/v2rayTmpl"
"V2RayA/models/vmessInfo"
"encoding/json"
"errors"
"io/ioutil"
"log"
"os"
"os/exec"
"strings"
"time"
)
func RestartV2rayService() (err error) {
if global.IsInDocker {
switch global.ServiceControlMode {
case v2ray.Docker:
_, err = exec.Command("sh", "-c", "killall -9 v2ray").CombinedOutput()
return
}
_, err = exec.Command("sh", "-c", "service v2ray restart").CombinedOutput()
if err != nil {
log.Println(1, err)
//8秒等待v2ray启动
startTime := time.Now()
for {
if time.Now().Sub(startTime) > 8*time.Second {
return errors.New("请勿在Docker模式下频繁更换配置,请等待一段时间后再试")
}
<-time.After(200 * time.Millisecond)
if IsV2RayRunning() {
return nil
}
}
case v2ray.Service:
_, err = exec.Command("sh", "-c", "service v2ray restart").CombinedOutput()
case v2ray.Systemctl:
_, err = exec.Command("sh", "-c", "systemctl restart v2ray").Output()
case v2ray.Common:
_, _ = exec.Command("sh", "-c", "killall -9 v2ray").CombinedOutput()
_, err = exec.Command("sh", "-c", "v2ray --config=/etc/v2ray/config.json").CombinedOutput()
}
if err != nil {
if global.ServiceControlMode == v2ray.Docker {
log.Println("建议检查killall命令是否可用")
}
return
}
if !IsV2RayRunning() {
@@ -31,18 +50,16 @@ func RestartV2rayService() (err error) {
return
}
func StopV2rayService() (err error) { //TODO: 在stop的地方替换config,并在启动时还原
if global.IsInDocker {
return nil //docker中无法stop service
}
out, err := exec.Command("sh", "-c", "service v2ray stop").CombinedOutput()
if err != nil {
log.Println(2, string(out), err)
_, err = exec.Command("sh", "-c", "systemctl stop v2ray").CombinedOutput()
}
if err != nil {
log.Println(2, string(out), err)
func StopV2rayService() (err error) {
switch global.ServiceControlMode {
case v2ray.Docker: //docker中无需stop service
return nil
case v2ray.Common:
_, err = exec.Command("sh", "-c", "killall -9 v2ray").CombinedOutput()
case v2ray.Service:
_, err = exec.Command("sh", "-c", "service v2ray stop").CombinedOutput()
case v2ray.Systemctl:
_, err = exec.Command("sh", "-c", "systemctl stop v2ray").CombinedOutput()
}
if IsV2RayRunning() {
return errors.New("v2ray停止失败")
@@ -51,24 +68,22 @@ func StopV2rayService() (err error) { //TODO: 在stop的地方替换config,并
}
func EnableV2rayService() (err error) {
if global.IsInDocker {
return nil //docker中无需enable service
}
_, err = exec.Command("sh", "-c", "update-rc.d v2ray enable").CombinedOutput()
if err != nil {
log.Println(3, err)
switch global.ServiceControlMode {
case v2ray.Docker, v2ray.Common: //docker, common中无需enable service
case v2ray.Service:
_, err = exec.Command("sh", "-c", "update-rc.d v2ray enable").CombinedOutput()
case v2ray.Systemctl:
_, err = exec.Command("sh", "-c", "systemctl enable v2ray").Output()
}
return
}
func DisableV2rayService() (err error) {
if global.IsInDocker {
return nil //docker中无需disable service
}
_, err = exec.Command("sh", "-c", "update-rc.d v2ray disable").CombinedOutput()
if err != nil {
log.Println(4, err)
switch global.ServiceControlMode {
case v2ray.Docker, v2ray.Common: //docker, common中无需disable service
case v2ray.Service:
_, err = exec.Command("sh", "-c", "update-rc.d v2ray disable").CombinedOutput()
case v2ray.Systemctl:
_, err = exec.Command("sh", "-c", "systemctl disable v2ray").Output()
}
return
@@ -79,21 +94,24 @@ func WriteV2rayConfig(content []byte) (err error) {
}
func IsV2RayRunning() bool {
if global.IsInDocker {
out, err := exec.Command("sh", "-c", "ps|grep v2ray").CombinedOutput()
switch global.ServiceControlMode {
case v2ray.Docker, v2ray.Common:
out, err := exec.Command("sh", "-c", "ps -ef|grep v2ray").CombinedOutput()
return err == nil && strings.Contains(string(out), "v2ray -config=")
case v2ray.Service:
out, err := exec.Command("sh", "-c", "service v2ray status|head -n 5|grep running").CombinedOutput()
if err != nil || strings.Contains(string(out), "not running") {
return false
}
case v2ray.Systemctl:
out, err := exec.Command("sh", "-c", "systemctl status v2ray|head -n 5|grep running").Output()
return err == nil && len(out) > 0
}
out, err := exec.Command("sh", "-c", "service v2ray status|head -n 5|grep running").CombinedOutput()
if strings.Contains(string(out), "not running") {
return false
}
if err != nil {
log.Println(5, string(out), err)
out, err = exec.Command("sh", "-c", "systemctl status v2ray|head -n 5|grep running").Output()
}
return err == nil && len(out) > 0
return true
}
func UpdateV2RayConfig(vmessInfo *vmessInfo.VmessInfo) (err error) {
/*更新v2ray配置并重启*/
func UpdateV2RayConfigAndRestart(vmessInfo *vmessInfo.VmessInfo) (err error) {
//读配置,转换为v2ray配置并写入
tmpl := v2rayTmpl.NewTemplate()
err = tmpl.FillWithVmessInfo(*vmessInfo)
@@ -106,3 +124,19 @@ func UpdateV2RayConfig(vmessInfo *vmessInfo.VmessInfo) (err error) {
}
return RestartV2rayService()
}
/*清空inbounds规则来假停v2ray, 不重启服务*/
func PretendToStopV2rayService() (err error) {
tmplJson := v2rayTmpl.Template{}
b, err := ioutil.ReadFile("/etc/v2ray/config.json")
if err != nil {
return
}
err = json.Unmarshal(b, &tmplJson)
if err != nil {
return
}
tmplJson.Inbounds = make([]v2rayTmpl.Inbound, 0)
b, _ = json.Marshal(tmplJson)
return WriteV2rayConfig(b)
}