Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5bf590784b | ||
|
|
743369214b | ||
|
|
fb948cc346 | ||
|
|
e4dddc69c2 | ||
|
|
1049079428 | ||
|
|
7e6d8aef19 | ||
|
|
fb6b5b0b16 |
@@ -1,27 +0,0 @@
|
||||
name: Android
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
release:
|
||||
types: [published]
|
||||
branches: [ master ]
|
||||
|
||||
jobs:
|
||||
|
||||
build_android:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v2
|
||||
- name: Build
|
||||
run: |
|
||||
chmod +x build.android.sh
|
||||
docker run --rm -i -w /app -v $(pwd):/app -e ANDROID_HOME=/usr/local/android_sdk -e GOPROXY=direct fyneio/fyne-cross:android-latest /app/build.android.sh
|
||||
- name: Upload
|
||||
uses: softprops/action-gh-release@v1
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
with:
|
||||
files: |
|
||||
android_client.apk
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -1,55 +0,0 @@
|
||||
name: Docker
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
release:
|
||||
types: [published]
|
||||
# branches: [ master ]
|
||||
tags: [v*]
|
||||
|
||||
jobs:
|
||||
build_docker:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v2
|
||||
- name: Set env
|
||||
run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v1
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v1
|
||||
- name: Cache Docker layers
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: /tmp/.buildx-cache
|
||||
key: ${{ runner.os }}-buildx-${{ github.sha }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-buildx-
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
- name: Build and push nps
|
||||
uses: docker/build-push-action@v2
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile.nps
|
||||
platforms: linux/amd64,linux/arm,linux/arm64
|
||||
push: true
|
||||
tags: |
|
||||
${{ secrets.DOCKERHUB_USERNAME }}/nps:latest
|
||||
${{ secrets.DOCKERHUB_USERNAME }}/nps:${{ env.RELEASE_VERSION }}
|
||||
- name: Build and push npc
|
||||
uses: docker/build-push-action@v2
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile.npc
|
||||
platforms: linux/amd64,linux/arm,linux/arm64
|
||||
push: true
|
||||
tags: |
|
||||
${{ secrets.DOCKERHUB_USERNAME }}/npc:latest
|
||||
${{ secrets.DOCKERHUB_USERNAME }}/npc:${{ env.RELEASE_VERSION }}
|
||||
@@ -1,75 +0,0 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
release:
|
||||
types: [published]
|
||||
branches: [ master ]
|
||||
|
||||
jobs:
|
||||
|
||||
build_assets:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
- name: Set up Go 1.x
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.22
|
||||
id: go
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v2
|
||||
- name: Get dependencies
|
||||
run: |
|
||||
go get -v -t -d ./...
|
||||
if [ -f Gopkg.toml ]; then
|
||||
curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
|
||||
dep ensure
|
||||
fi
|
||||
- name: Build
|
||||
run: |
|
||||
chmod +x build.assets.sh
|
||||
./build.assets.sh
|
||||
- name: Upload
|
||||
uses: softprops/action-gh-release@v1
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
with:
|
||||
files: |
|
||||
freebsd_386_client.tar.gz
|
||||
freebsd_386_server.tar.gz
|
||||
freebsd_amd64_client.tar.gz
|
||||
freebsd_amd64_server.tar.gz
|
||||
freebsd_arm_client.tar.gz
|
||||
freebsd_arm_server.tar.gz
|
||||
linux_386_client.tar.gz
|
||||
linux_386_server.tar.gz
|
||||
linux_amd64_client.tar.gz
|
||||
linux_amd64_server.tar.gz
|
||||
linux_arm64_client.tar.gz
|
||||
linux_arm64_server.tar.gz
|
||||
linux_arm_v5_client.tar.gz
|
||||
linux_arm_v6_client.tar.gz
|
||||
linux_arm_v7_client.tar.gz
|
||||
linux_arm_v5_server.tar.gz
|
||||
linux_arm_v6_server.tar.gz
|
||||
linux_arm_v7_server.tar.gz
|
||||
linux_mips64le_client.tar.gz
|
||||
linux_mips64le_server.tar.gz
|
||||
linux_mips64_client.tar.gz
|
||||
linux_mips64_server.tar.gz
|
||||
linux_mipsle_client.tar.gz
|
||||
linux_mipsle_server.tar.gz
|
||||
linux_mips_client.tar.gz
|
||||
linux_mips_server.tar.gz
|
||||
darwin_amd64_client.tar.gz
|
||||
darwin_amd64_server.tar.gz
|
||||
darwin_arm64_client.tar.gz
|
||||
darwin_arm64_server.tar.gz
|
||||
windows_386_client.tar.gz
|
||||
windows_386_server.tar.gz
|
||||
windows_amd64_client.tar.gz
|
||||
windows_amd64_server.tar.gz
|
||||
npc_sdk.tar.gz
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -0,0 +1,163 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
branches: [ master ]
|
||||
|
||||
jobs:
|
||||
|
||||
build_assets:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
- name: Set up Go 1.x
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.15
|
||||
id: go
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v2
|
||||
- name: Get dependencies
|
||||
run: |
|
||||
go get -v -t -d ./...
|
||||
if [ -f Gopkg.toml ]; then
|
||||
curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
|
||||
dep ensure
|
||||
fi
|
||||
- name: Build
|
||||
run: |
|
||||
chmod +x build.assets.sh
|
||||
./build.assets.sh
|
||||
- name: Upload
|
||||
uses: softprops/action-gh-release@v1
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
with:
|
||||
files: |
|
||||
freebsd_386_client.tar.gz
|
||||
freebsd_386_server.tar.gz
|
||||
freebsd_amd64_client.tar.gz
|
||||
freebsd_amd64_server.tar.gz
|
||||
freebsd_arm_client.tar.gz
|
||||
freebsd_arm_server.tar.gz
|
||||
linux_386_client.tar.gz
|
||||
linux_386_server.tar.gz
|
||||
linux_amd64_client.tar.gz
|
||||
linux_amd64_server.tar.gz
|
||||
linux_arm64_client.tar.gz
|
||||
linux_arm64_server.tar.gz
|
||||
linux_arm_v5_client.tar.gz
|
||||
linux_arm_v6_client.tar.gz
|
||||
linux_arm_v7_client.tar.gz
|
||||
linux_arm_v5_server.tar.gz
|
||||
linux_arm_v6_server.tar.gz
|
||||
linux_arm_v7_server.tar.gz
|
||||
linux_mips64le_client.tar.gz
|
||||
linux_mips64le_server.tar.gz
|
||||
linux_mips64_client.tar.gz
|
||||
linux_mips64_server.tar.gz
|
||||
linux_mipsle_client.tar.gz
|
||||
linux_mipsle_server.tar.gz
|
||||
linux_mips_client.tar.gz
|
||||
linux_mips_server.tar.gz
|
||||
darwin_amd64_client.tar.gz
|
||||
darwin_amd64_server.tar.gz
|
||||
windows_386_client.tar.gz
|
||||
windows_386_server.tar.gz
|
||||
windows_amd64_client.tar.gz
|
||||
windows_amd64_server.tar.gz
|
||||
npc_sdk.tar.gz
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
build_android:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v2
|
||||
- name: Build
|
||||
run: |
|
||||
chmod +x build.android.sh
|
||||
docker run --rm -i -w /app -v $(pwd):/app -e ANDROID_HOME=/usr/local/android_sdk -e GOPROXY=direct fyneio/fyne-cross:android-latest /app/build.android.sh
|
||||
- name: Upload
|
||||
uses: softprops/action-gh-release@v1
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
with:
|
||||
files: |
|
||||
android_client.apk
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
build_spk:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v2
|
||||
- name: Set env
|
||||
run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV
|
||||
- name: Build
|
||||
run: |
|
||||
git clone https://github.com/cnlh/spksrc.git ~/spksrc
|
||||
mkdir ~/spksrc/nps && cp -rf ./* ~/spksrc/nps/
|
||||
docker run -id --name spksrc --env VERSION=${{ env.RELEASE_VERSION }} -e GOPROXY=direct -v ~/spksrc:/spksrc synocommunity/spksrc /bin/bash
|
||||
docker exec spksrc /bin/bash -c 'cd /spksrc && make setup && cd /spksrc/spk/npc && make'
|
||||
cp ~/spksrc/packages/npc_noarch-all_${{ env.RELEASE_VERSION }}-1.spk ./npc_syno.spk
|
||||
- name: Upload
|
||||
uses: softprops/action-gh-release@v1
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
with:
|
||||
files: |
|
||||
npc_syno.spk
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
build_docker:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v2
|
||||
- name: Set env
|
||||
run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v1
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v1
|
||||
- name: Cache Docker layers
|
||||
uses: actions/cache@v2
|
||||
with:
|
||||
path: /tmp/.buildx-cache
|
||||
key: ${{ runner.os }}-buildx-${{ github.sha }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-buildx-
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
- name: Build and push nps
|
||||
uses: docker/build-push-action@v2
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile.nps
|
||||
platforms: linux/amd64,linux/arm,linux/arm64
|
||||
push: true
|
||||
tags: |
|
||||
${{ secrets.DOCKERHUB_USERNAME }}/nps:latest
|
||||
${{ secrets.DOCKERHUB_USERNAME }}/nps:${{ env.RELEASE_VERSION }}
|
||||
- name: Build and push npc
|
||||
uses: docker/build-push-action@v2
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile.npc
|
||||
platforms: linux/amd64,linux/arm,linux/arm64
|
||||
push: true
|
||||
tags: |
|
||||
${{ secrets.DOCKERHUB_USERNAME }}/npc:latest
|
||||
${{ secrets.DOCKERHUB_USERNAME }}/npc:${{ env.RELEASE_VERSION }}
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.24 as builder
|
||||
FROM golang:1.15 as builder
|
||||
ARG GOPROXY=direct
|
||||
WORKDIR /go/src/ehang.io/nps
|
||||
COPY . .
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
FROM golang:1.24 as builder
|
||||
FROM golang:1.15 as builder
|
||||
ARG GOPROXY=direct
|
||||
WORKDIR /go/src/ehang.io/nps
|
||||
COPY . .
|
||||
RUN go get -d -v ./...
|
||||
RUN go get -d -v ./...
|
||||
RUN CGO_ENABLED=0 go build -ldflags="-w -s -extldflags -static" ./cmd/nps/nps.go
|
||||
|
||||
FROM scratch
|
||||
COPY --from=builder /go/src/ehang.io/nps/nps /
|
||||
COPY --from=builder /go/src/ehang.io/nps/web /web
|
||||
VOLUME /conf
|
||||
CMD ["/nps"]
|
||||
CMD ["/nps", "service"]
|
||||
@@ -1,199 +1,86 @@
|
||||
|
||||
# NPS
|
||||
 
|
||||
[](https://gitter.im/cnlh-nps/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
|
||||

|
||||

|
||||
|
||||
[新特性文档](https://dqg9t9eulqq.feishu.cn/wiki/FmVVwDcEGiTZxekYJl5ccuFanlg?from=from_copylink)
|
||||
[README](https://github.com/ehang-io/nps/blob/master/README.md)|[中文文档](https://github.com/ehang-io/nps/blob/master/README_zh.md)
|
||||
|
||||
# 说明
|
||||
由于nps已经停更多年,存留了不少bug和未完善的功能。
|
||||
|
||||
此版本基于 nps 0.26.10的基础上二次开发而来。
|
||||
|
||||
***DockerHub***: [NPS](https://hub.docker.com/r/yisier1/nps) [NPC](https://hub.docker.com/r/yisier1/npc)
|
||||
|
||||
***宝塔面板***:[宝塔面板 Docker](docs/bt.md)
|
||||
|
||||
# 交流群
|
||||
聊天灌水QQ群:619833483(2000人群),770569342
|
||||
|
||||
# 免费NPS节点
|
||||
https://natnps.com/
|
||||
免费NPS内网穿透节点,长期免费,6M带宽,3条隧道,欢迎来嫖,自行注册账号。
|
||||
|
||||
# 特价云服务器
|
||||
国内BGP,游戏开服,2核 2G 15M上行 25元/月,[专属连接,首月5折](https://www.rainyun.com/MjY0MzY1_)
|
||||
|
||||
# 提示
|
||||
强烈推荐使用无配置文件模式启动客户端(删除掉npc.exe 目录下的`conf`文件夹即可),所有数据应该在服务端保存和配置,而客户端只做连接转发。客户端配置文件对小白极不友好,配置繁琐,容易出错。
|
||||
0.26.21 版本后的客户端,无需再通过命令行方式启动、安装、卸载客户端,直接双击运行,按照提示输入指令即可完成,非常方便。
|
||||
NPS is a lightweight, high-performance, powerful **intranet penetration** proxy server, with a powerful web management terminal.
|
||||
|
||||
|
||||
# 更新日志
|
||||
- 2025-12-06 v0.26.28
|
||||
-【全局参数】页面新增`服务地址`配置项,用于客户端命令地址显示、隧道访问地址显示 [293](https://github.com/yisier/nps/issues/293)
|
||||
-【IP授权功能优化】,通过穿透的端口去提交 IP 认证,感谢 [Aqamoe](https://github.com/Aqamoe) 的建议 [291](https://github.com/yisier/nps/issues/291)
|
||||
-【重构限速器实现】提升性能和准确性
|
||||

|
||||
|
||||
## Feature
|
||||
|
||||
- Comprehensive protocol support, compatible with almost all commonly used protocols, such as tcp, udp, http(s), socks5, p2p, http proxy ...
|
||||
- Full platform compatibility (linux, windows, macos, Synology, etc.), support installation as a system service simply.
|
||||
- Comprehensive control, both client and server control are allowed.
|
||||
- Https integration, support to convert backend proxy and web services to https, and support multiple certificates.
|
||||
- Just simple configuration on web ui can complete most requirements.
|
||||
- Complete information display, such as traffic, system information, real-time bandwidth, client version, etc.
|
||||
- Powerful extension functions, everything is available (cache, compression, encryption, traffic limit, bandwidth limit, port reuse, etc.)
|
||||
- Domain name resolution has functions such as custom headers, 404 page configuration, host modification, site protection, URL routing, and pan-resolution.
|
||||
- Multi-user and user registration support on server.
|
||||
|
||||
**Didn't find the feature you want? It doesn't matter, click [Enter the document](https://ehang-io.github.io/nps/) to find it!**
|
||||
|
||||
## Quick start
|
||||
|
||||
### Installation
|
||||
|
||||
> [releases](https://github.com/ehang-io/nps/releases)
|
||||
|
||||
Download the corresponding system version, the server and client are separate.
|
||||
|
||||
### Server start
|
||||
|
||||
After downloading the server compressed package, unzip it, and then enter the unzipped folder.
|
||||
|
||||
- execute installation command
|
||||
|
||||
For linux、darwin ```sudo ./nps install```
|
||||
|
||||
For windows, run cmd as administrator and enter the installation directory ```nps.exe install```
|
||||
|
||||
- default ports
|
||||
|
||||
The default configuration file of nps use 80,443,8080,8024 ports
|
||||
|
||||
80 and 443 ports for host mode default ports
|
||||
|
||||
8080 for web management access port
|
||||
|
||||
8024 for net bridge port, to communicate between server and client
|
||||
|
||||
- start up
|
||||
|
||||
For linux、darwin ```sudo nps start```
|
||||
|
||||
For windows, run cmd as administrator and enter the program directory ```nps.exe start```
|
||||
|
||||
```After installation, the windows configuration file is located at C:\Program Files\nps, linux or darwin is located at /etc/nps```
|
||||
|
||||
**If you don't find it started successfully, you can check the log (Windows log files are located in the current running directory, linux and darwin are located in /var/log/nps.log).**
|
||||
|
||||
- Access server IP:web service port (default is 8080).
|
||||
- Login with username and password (default is admin/123, must be modified when officially used).
|
||||
- Create a client.
|
||||
|
||||
### Client connection
|
||||
- Click the + sign in front of the client in web management and copy the startup command.
|
||||
- Execute the startup command, Linux can be executed directly, Windows will replace ./npc with npc.exe and execute it with cmd.
|
||||
|
||||
|
||||
- 2025-11-05 v0.26.27
|
||||
新增:
|
||||
- 1.客户端新增【IP白名单】,可通过两种方式添加IP:
|
||||
- 方式1️⃣:在【客户端】新建/修改页面,配置IP授权密码,不在IP白名单的外网访问将被跳转到 IP 授权页面,输入正确的授权密码,即可完成添加 IP。
|
||||
- 方式2️⃣:在【客户端】新建/修改页面,直接添加IP到白名单中。
|
||||

|
||||
- 2.客户端配置移除【压缩】和【加密】功能,此功能会显著提高内存和CPU占用率,"利大于弊"。
|
||||
- 3.客户端默认不再提供配置文件,***强烈推荐使用无配置文件模式启动客户端***
|
||||
If you need to register to the system service, you can check [Register to the system service](https://ehang-io.github.io/nps/#/use?id=注册到系统服务)
|
||||
|
||||
### Configuration
|
||||
- After the client connects, configure the corresponding penetration service in the web.
|
||||
- For more advanced usage, see [Complete Documentation](https://ehang-io.github.io/nps/)
|
||||
|
||||
- 2025-08-15 v0.26.26
|
||||
修复:
|
||||
- windows注册服务 使用tls无法连接 [269](https://github.com/yisier/nps/issues/269)
|
||||
- 域名解析自动HTTPS逻辑bug [273](https://github.com/yisier/nps/issues/273)
|
||||
|
||||
|
||||
- 2025-05-28 v0.26.25
|
||||
新增:
|
||||
- nps增加`nps(.exe) -server` 命令,用于管理NPS服务,安装和卸载服务在 Linux 下需要有 sudo 权限,Windows 下需要有管理员权限。
|
||||

|
||||
- 增加【TLS快捷启动命令】,可用于在tls模式下,快速启动客户端。 [257](https://github.com/yisier/nps/issues/257)
|
||||
|
||||
|
||||
- 2025-04-16 v0.26.24
|
||||
新增:
|
||||
- 隧道支持复制功能,在隧道页面增加复制按钮,除了端口号为随机生成外,其他参数全部拷贝。[251](https://github.com/yisier/nps/issues/251)
|
||||
|
||||
修复:
|
||||
- 私密代理连接时服务端会报错退出,[250](https://github.com/yisier/nps/issues/250)
|
||||
|
||||
|
||||
|
||||
- 2025-04-11 v0.26.23
|
||||
新增:
|
||||
- TCP 隧道支持 Proxy Protocol 协议来传递经过请求的真实 IP。
|
||||
|
||||
修复:
|
||||
- 客户端较多时,协程增长过快,感谢 [@huanglei288766](https://github.com/yisier/nps/pull/244) 的PR
|
||||
|
||||
|
||||
- 2025-01-23 v0.26.22
|
||||
优化:
|
||||
- 客户端注册系统服务时,(新版客户端注册方式,非 install 命令) 将按照 `npc-[vkey].log` 格式保存日志,每个客户端VKEY单独一个日志文件,windows 日志位于 `npc.exe` 同级目录下,linux 位于 `/var/log/`目录。
|
||||
- 域名模式,HTTPS证书支持上传文件和文件路径,系统将自动识别路径还是证书内容。 [#175](https://github.com/yisier/nps/issues/175)
|
||||
|
||||
修复:
|
||||
- ipv6地址显示不全 [#237](https://github.com/yisier/nps/issues/237)
|
||||
|
||||
|
||||
- 2025-01-07 v0.26.21
|
||||
新增:
|
||||
- 客户端列表页面新增【快捷启动命令】,此命令为连接地址+链接秘钥的base64编码,方便一键启动、一键安装客户端。
|
||||
- 域名解析和隧道列表增加访问地址,可以点击隧道链接,直接网页打开。 [#234](https://github.com/yisier/nps/issues/234)
|
||||
|
||||
优化:
|
||||
- 修改vkey生成方式,由16位缩短至10位,截取uuid前10位,避免重复。
|
||||
- 优化客户端启动方式,当npc文件目录下无配置文件时,可直接双击运行客户端,输入命令完成启动、安装、卸载客户端,直接启动和安装服务时需要输入【快捷启动命令】,卸载服务、启动服务、停止服务时,只需输入隧道秘钥【vkey】即可。安装服务以 nps-client-vkey 方式命名 ,实现注册多个服务。
|
||||

|
||||
|
||||
|
||||
**注意**
|
||||
强烈推荐使用无配置文件模式启动客户端,所有数据应该在服务端保存和配置,而客户端只做连接转发。客户端配置文件对小白极不友好,配置繁琐,容易出错。
|
||||
|
||||
- 2024-11-07 v0.26.20
|
||||
新增:
|
||||
- 客户端增加创建时间
|
||||
|
||||
修复:
|
||||
- 客户端限速单位不统一 [#185](https://github.com/yisier/nps/issues/185)
|
||||
- 增加从下拉选择客户端,隧道列表排序,新增编辑后不会刷新界面 [#183](https://github.com/yisier/nps/issues/183)
|
||||
- 隧道数量限制无法统计域名映射 [#209](https://github.com/yisier/nps/issues/209)
|
||||
|
||||
|
||||
- 2024-06-01 v0.26.19
|
||||
- golang 版本升级到 1.22.
|
||||
- 增加自动https,自动将http 重定向(301)到 https.
|
||||
- 客户端命令行方式启动支持多个隧道ID,使用逗号拼接,示例:`npc -server=xxx:8024 -vkey=ytkpyr0er676m0r7,iwnbjfbvygvzyzzt` .
|
||||
- 移除 nps.conf 参数 `https_just_proxy` , 调整 https 处理逻辑,如果上传了 https 证书,则由nps负责SSL (此方式可以获取真实IP),
|
||||
否则走端口转发模式(使用本地证书,nps 获取不到真实IP), 如下图所示。
|
||||

|
||||
|
||||
|
||||
|
||||
- 2024-02-27 v0.26.18
|
||||
***新增***:nps.conf 新增 `tls_bridge_port=8025` 参数,当 `tls_enable=true` 时,nps 会监听8025端口,作为 tls 的连接端口。
|
||||
客户端可以选择连接 tls 端口或者非 tls 端口: `npc.exe -server=xxx:8024 -vkey=xxx` 或 `npc.exe -server=xxx:8025 -vkey=xxx -tls_enable=true`
|
||||
|
||||
|
||||
- 2024-01-31 v0.26.17
|
||||
***说明***:考虑到 npc 历史版本客户端众多,版本号不同旧版本客户端无法连接,为了兼容,仓库版本号将继续沿用 0.26.xx
|
||||
|
||||
|
||||
- 2024-01-02 v0.27.01 (已作废,功能移动到v0.26.17 版本)
|
||||
***新增***:tls 流量加密,(客户端忽略证书校验,谨慎使用,客户端与服务端需要同时开启,或同时关闭),使用方式:
|
||||
服务端:nps.conf `tls_enable=true`;
|
||||
客户端:npc.conf `tls_enable=true` 或者 `npc.exe -server=xxx -vkey=xxx -tls_enable=true`
|
||||
|
||||
|
||||
- 2023-06-01 v0.26.16
|
||||
***修复***:https 流量不统计 Bug 修复。
|
||||
***新增***:新增全局黑名单IP,用于防止被肉鸡扫描端口或被恶意攻击。
|
||||
***新增***:新增客户端上次在线时间。
|
||||
|
||||
|
||||
- 2023-02-24 v0.26.15
|
||||
***修复***:更新程序 url 更改到当前仓库中
|
||||
***修复***:nps 在外部路径启动时找不到配置文件
|
||||
***新增***:增加 nps 启动参数,`-conf_path=D:\test\nps`,可用于加载指定nps配置文件和web文件目录。
|
||||
***window 使用示例:***
|
||||
直接启动:`nps.exe -conf_path=D:\test\nps`
|
||||
安装:`nps.exe install -conf_path=D:\test\nps`
|
||||
安装启动:`nps.exe start`
|
||||
|
||||
***linux 使用示例:***
|
||||
直接启动:`./nps -conf_path=/app/nps`
|
||||
安装:`./nps install -conf_path=/app/nps`
|
||||
安装启动:`nps start -conf_path=/app/nps`
|
||||
|
||||
|
||||
|
||||
- 2022-12-30 v0.26.14
|
||||
***修复***:API 鉴权漏洞修复
|
||||
|
||||
|
||||
- 2022-12-19
|
||||
***修复***:某些场景下丢包导致服务端意外退出
|
||||
***优化***:新增隧道时,不指定服务端口时,将自动生成端口号
|
||||
***优化***:API返回ID, `/client/add/, /index/addhost/,/index/add/ `
|
||||
***优化***:域名解析、隧道页面,增加[唯一验证密钥],方便搜查
|
||||
|
||||
|
||||
- 2022-10-30
|
||||
***新增***:在管理面板中新增客户端时,可以配置多个黑名单IP,用于防止被肉鸡扫描端口或被恶意攻击。
|
||||
***优化***:0.26.12 版本还原了注册系统功能,使用方式和以前一样。无论是否注册了系统服务,直接执行 nps 时只会读取当前目录下的配置文件。
|
||||
|
||||
|
||||
- 2022-10-27
|
||||
***新增***:在管理面板登录时开启验证码校验,开启方式:nps.conf `open_captcha=true`,感谢 [@dongFangTuring](https://github.com/dongFangTuring) 提供的PR
|
||||
|
||||
|
||||
- 2022-10-24:
|
||||
***修复***:HTTP协议支持WebSocket(稳定性待测试)
|
||||
|
||||
|
||||
- 2022-10-21:
|
||||
***修复***:HTTP协议下实时统计流量,能够精准的限制住流量(上下行对等)
|
||||
***优化***:删除HTTP隧道时,客户端已用流量不再清空
|
||||
|
||||
|
||||
- 2022-10-19:
|
||||
***BUG***:在TCP协议下,流量统计有问题,只有当连接断开时才会统计流量。例如,限制客户端流量20m,当传输100m的文件时,也能传输成功。
|
||||
***修复***:TCP协议下实时统计流量,能够精准的限制住流量(上下行对等)
|
||||
***优化***:删除TCP隧道时,客户端已用流量不再清空
|
||||

|
||||
|
||||
|
||||
- 2022-09-14:
|
||||
修改NPS工作目录为当前可执行文件目录(即配置文件和nps可执行文件放在同一目录下,直接执行nps文件即可),去除注册系统服务,启动、停止、升级等命令
|
||||
|
||||
|
||||
|
||||
|
||||
# 捐赠
|
||||

|
||||
## Contribution
|
||||
- If you encounter a bug, you can submit it to the dev branch directly.
|
||||
- If you encounter a problem, you can feedback through the issue.
|
||||
- The project is under development, and there is still a lot of room for improvement. If you can contribute code, please submit PR to the dev branch.
|
||||
- If there is feedback on new features, you can feedback via issues or qq group.
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
_ "crypto/tls"
|
||||
"ehang.io/nps/lib/nps_mux"
|
||||
"ehang.io/nps-mux"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -25,8 +23,6 @@ import (
|
||||
"github.com/astaxie/beego/logs"
|
||||
)
|
||||
|
||||
var ServerTlsEnable bool = false
|
||||
|
||||
type Client struct {
|
||||
tunnel *nps_mux.Mux
|
||||
signal *conn.Conn
|
||||
@@ -80,42 +76,20 @@ func (s *Bridge) StartTunnel() error {
|
||||
s.cliProcess(conn.NewConn(c))
|
||||
})
|
||||
} else {
|
||||
|
||||
go func() {
|
||||
listener, err := connection.GetBridgeListener(s.tunnelType)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
return
|
||||
}
|
||||
conn.Accept(listener, func(c net.Conn) {
|
||||
s.cliProcess(conn.NewConn(c))
|
||||
})
|
||||
}()
|
||||
|
||||
// tls
|
||||
if ServerTlsEnable {
|
||||
go func() {
|
||||
// 监听TLS 端口
|
||||
tlsBridgePort := beego.AppConfig.DefaultInt("tls_bridge_port", 8025)
|
||||
|
||||
logs.Info("tls server start, the bridge type is %s, the tls bridge port is %d", "tcp", tlsBridgePort)
|
||||
tlsListener, tlsErr := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP(beego.AppConfig.String("bridge_ip")), tlsBridgePort, ""})
|
||||
if tlsErr != nil {
|
||||
logs.Error(tlsErr)
|
||||
os.Exit(0)
|
||||
return
|
||||
}
|
||||
conn.Accept(tlsListener, func(c net.Conn) {
|
||||
s.cliProcess(conn.NewConn(tls.Server(c, &tls.Config{Certificates: []tls.Certificate{crypt.GetCert()}})))
|
||||
})
|
||||
}()
|
||||
listener, err := connection.GetBridgeListener(s.tunnelType)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
return err
|
||||
}
|
||||
conn.Accept(listener, func(c net.Conn) {
|
||||
s.cliProcess(conn.NewConn(c))
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// get health information form client
|
||||
//get health information form client
|
||||
func (s *Bridge) GetHealthFromClient(id int, c *conn.Conn) {
|
||||
for {
|
||||
if info, status, err := c.GetHealthInfo(); err != nil {
|
||||
@@ -180,7 +154,7 @@ func (s *Bridge) GetHealthFromClient(id int, c *conn.Conn) {
|
||||
s.DelClient(id)
|
||||
}
|
||||
|
||||
// 验证失败,返回错误验证flag,并且关闭连接
|
||||
//验证失败,返回错误验证flag,并且关闭连接
|
||||
func (s *Bridge) verifyError(c *conn.Conn) {
|
||||
c.Write([]byte(common.VERIFY_EER))
|
||||
}
|
||||
@@ -197,9 +171,9 @@ func (s *Bridge) cliProcess(c *conn.Conn) {
|
||||
}
|
||||
//version check
|
||||
if b, err := c.GetShortLenContent(); err != nil || string(b) != version.GetVersion() {
|
||||
//logs.Info("The client %s version does not match", c.Conn.RemoteAddr())
|
||||
//c.Close()
|
||||
//return
|
||||
logs.Info("The client %s version does not match", c.Conn.RemoteAddr())
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
//version get
|
||||
var vs []byte
|
||||
@@ -250,7 +224,7 @@ func (s *Bridge) DelClient(id int) {
|
||||
}
|
||||
}
|
||||
|
||||
// use different
|
||||
//use different
|
||||
func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int, vs string) {
|
||||
isPub := file.GetDb().IsPubClient(id)
|
||||
switch typeVal {
|
||||
@@ -329,7 +303,7 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int, vs string) {
|
||||
return
|
||||
}
|
||||
|
||||
// register ip
|
||||
//register ip
|
||||
func (s *Bridge) register(c *conn.Conn) {
|
||||
var hour int32
|
||||
if err := binary.Read(c, binary.LittleEndian, &hour); err == nil {
|
||||
@@ -413,7 +387,7 @@ func (s *Bridge) ping() {
|
||||
}
|
||||
}
|
||||
|
||||
// get config and add task from client config
|
||||
//get config and add task from client config
|
||||
func (s *Bridge) getConfig(c *conn.Conn, isPub bool, client *file.Client) {
|
||||
var fail bool
|
||||
loop:
|
||||
|
||||
@@ -8,80 +8,75 @@ tar -czvf npc_sdk.tar.gz npc_sdk.dll npc_sdk.so npc_sdk.h
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
|
||||
tar -czvf linux_amd64_client.tar.gz npc
|
||||
tar -czvf linux_amd64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
|
||||
tar -czvf linux_386_client.tar.gz npc
|
||||
tar -czvf linux_386_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
|
||||
tar -czvf freebsd_386_client.tar.gz npc
|
||||
tar -czvf freebsd_386_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
|
||||
tar -czvf freebsd_amd64_client.tar.gz npc
|
||||
tar -czvf freebsd_amd64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
|
||||
tar -czvf freebsd_arm_client.tar.gz npc
|
||||
tar -czvf freebsd_arm_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
|
||||
tar -czvf linux_arm_v7_client.tar.gz npc
|
||||
tar -czvf linux_arm_v7_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
|
||||
tar -czvf linux_arm_v6_client.tar.gz npc
|
||||
tar -czvf linux_arm_v6_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
|
||||
tar -czvf linux_arm_v5_client.tar.gz npc
|
||||
tar -czvf linux_arm_v5_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
|
||||
tar -czvf linux_arm64_client.tar.gz npc
|
||||
tar -czvf linux_arm64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
|
||||
tar -czvf linux_mips64_client.tar.gz npc
|
||||
tar -czvf linux_mips64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
|
||||
tar -czvf linux_mips64le_client.tar.gz npc
|
||||
tar -czvf linux_mips64le_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
|
||||
tar -czvf linux_mipsle_client.tar.gz npc
|
||||
tar -czvf linux_mipsle_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mips go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
|
||||
tar -czvf linux_mips_client.tar.gz npc
|
||||
tar -czvf linux_mips_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
|
||||
tar -czvf windows_386_client.tar.gz npc.exe
|
||||
tar -czvf windows_386_client.tar.gz npc.exe conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
|
||||
tar -czvf windows_amd64_client.tar.gz npc.exe
|
||||
tar -czvf windows_amd64_client.tar.gz npc.exe conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
|
||||
tar -czvf darwin_amd64_client.tar.gz npc
|
||||
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
|
||||
tar -czvf darwin_arm64_client.tar.gz npc
|
||||
|
||||
tar -czvf darwin_amd64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
|
||||
@@ -151,12 +146,6 @@ CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "-s -w -extldflags -sta
|
||||
tar -czvf darwin_amd64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
|
||||
tar -czvf darwin_arm64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
|
||||
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
|
||||
tar -czvf windows_amd64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps.exe
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
SET VERSION=100.26.10
|
||||
SET GOPROXY=direct
|
||||
|
||||
SET CGO_ENABLED=0
|
||||
SET GOOS=linux
|
||||
SET GOARCH=amd64
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_amd64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
tar -czvf linux_amd64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
|
||||
|
||||
|
||||
SET GOARCH=386
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_386_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
tar -czvf linux_386_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
|
||||
|
||||
|
||||
SET GOARCH=arm
|
||||
SET GOARM=7
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_arm_v7_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
tar -czvf linux_arm_v7_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
|
||||
|
||||
|
||||
SET GOARM=6
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_arm_v6_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
tar -czvf linux_arm_v6_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
|
||||
|
||||
|
||||
SET GOARM=5
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_arm_v5_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
tar -czvf linux_arm_v5_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
|
||||
|
||||
|
||||
SET GOARCH=arm64
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_arm64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
tar -czvf linux_arm64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
|
||||
|
||||
|
||||
SET GOARCH=mips64
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_mips64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
tar -czvf linux_mips64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
|
||||
|
||||
|
||||
SET GOARCH=mips64le
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_mips64le_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
tar -czvf linux_mips64le_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
|
||||
|
||||
|
||||
SET GOARCH=mipsle
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_mipsle_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
tar -czvf linux_mipsle_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
|
||||
|
||||
|
||||
SET GOARCH=mips
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_mips_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
tar -czvf linux_mips_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
|
||||
|
||||
|
||||
SET GOOS=freebsd
|
||||
SET GOARCH=386
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf freebsd_386_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
tar -czvf freebsd_386_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
|
||||
|
||||
|
||||
SET GOARCH=amd64
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf freebsd_amd64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
tar -czvf freebsd_amd64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
|
||||
|
||||
|
||||
SET GOARCH=arm
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf freebsd_arm_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
tar -czvf freebsd_arm_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
|
||||
|
||||
|
||||
SET GOOS=windows
|
||||
SET GOARCH=386
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf windows_386_client.tar.gz npc.exe conf/npc.conf conf/multi_account.conf
|
||||
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
tar -czvf windows_386_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps.exe
|
||||
|
||||
|
||||
SET GOARCH=amd64
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf windows_amd64_client.tar.gz npc.exe conf/npc.conf conf/multi_account.conf
|
||||
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
tar -czvf windows_amd64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps.exe
|
||||
|
||||
|
||||
SET GOOS=darwin
|
||||
SET GOARCH=amd64
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf darwin_amd64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
tar -czvf darwin_amd64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
|
||||
|
||||
|
||||
SET GOARCH=arm64
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf darwin_arm64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
tar -czvf darwin_arm64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
|
||||
@@ -1,5 +1,5 @@
|
||||
#/bash/sh
|
||||
export VERSION=0.26.28
|
||||
export VERSION=100.26.10
|
||||
export GOPROXY=direct
|
||||
|
||||
sudo apt-get update
|
||||
@@ -13,71 +13,71 @@ tar -xvf upx-3.95-amd64_linux.tar.xz
|
||||
cp upx-3.95-amd64_linux/upx ./
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_amd64_client.tar.gz npc
|
||||
tar -czvf linux_amd64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_386_client.tar.gz npc
|
||||
tar -czvf linux_386_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf freebsd_386_client.tar.gz npc
|
||||
tar -czvf freebsd_386_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf freebsd_amd64_client.tar.gz npc
|
||||
tar -czvf freebsd_amd64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf freebsd_arm_client.tar.gz npc
|
||||
tar -czvf freebsd_arm_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_arm_v7_client.tar.gz npc
|
||||
tar -czvf linux_arm_v7_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_arm_v6_client.tar.gz npc
|
||||
tar -czvf linux_arm_v6_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_arm_v5_client.tar.gz npc
|
||||
tar -czvf linux_arm_v5_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_arm64_client.tar.gz npc
|
||||
tar -czvf linux_arm64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_mips64_client.tar.gz npc
|
||||
tar -czvf linux_mips64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_mips64le_client.tar.gz npc
|
||||
tar -czvf linux_mips64le_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_mipsle_client.tar.gz npc
|
||||
tar -czvf linux_mipsle_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mips go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf linux_mips_client.tar.gz npc
|
||||
tar -czvf linux_mips_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf windows_386_client.tar.gz npc.exe
|
||||
tar -czvf windows_386_client.tar.gz npc.exe conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf windows_amd64_client.tar.gz npc.exe
|
||||
tar -czvf windows_amd64_client.tar.gz npc.exe conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf darwin_amd64_client.tar.gz npc
|
||||
tar -czvf darwin_amd64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
|
||||
tar -czvf darwin_arm64_client.tar.gz npc
|
||||
tar -czvf darwin_arm64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
|
||||
|
||||
@@ -3,12 +3,10 @@ package client
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"ehang.io/nps/lib/nps_mux"
|
||||
"github.com/pires/go-proxyproto"
|
||||
"ehang.io/nps-mux"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -35,7 +33,7 @@ type TRPClient struct {
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
// new client
|
||||
//new client
|
||||
func NewRPClient(svraddr string, vKey string, bridgeConnType string, proxyUrl string, cnf *config.Config, disconnectTime int) *TRPClient {
|
||||
return &TRPClient{
|
||||
svrAddr: svraddr,
|
||||
@@ -52,7 +50,7 @@ func NewRPClient(svraddr string, vKey string, bridgeConnType string, proxyUrl st
|
||||
var NowStatus int
|
||||
var CloseClient bool
|
||||
|
||||
// start
|
||||
//start
|
||||
func (s *TRPClient) Start() {
|
||||
CloseClient = false
|
||||
retry:
|
||||
@@ -86,7 +84,7 @@ retry:
|
||||
s.handleMain()
|
||||
}
|
||||
|
||||
// handle main connection
|
||||
//handle main connection
|
||||
func (s *TRPClient) handleMain() {
|
||||
for {
|
||||
flags, err := s.signal.ReadFlag()
|
||||
@@ -153,7 +151,7 @@ func (s *TRPClient) newUdpConn(localAddr, rAddr string, md5Password string) {
|
||||
}
|
||||
}
|
||||
|
||||
// pmux tunnel
|
||||
//pmux tunnel
|
||||
func (s *TRPClient) newChan() {
|
||||
tunnel, err := NewConn(s.bridgeConnType, s.vKey, s.svrAddr, common.WORK_CHAN, s.proxyUrl)
|
||||
if err != nil {
|
||||
@@ -199,11 +197,7 @@ func (s *TRPClient) handleChan(src net.Conn) {
|
||||
targetConn.Close()
|
||||
break
|
||||
} else {
|
||||
remoteAddr := strings.TrimSpace(r.Header.Get("X-Forwarded-For"))
|
||||
if len(remoteAddr) == 0 {
|
||||
remoteAddr = r.RemoteAddr
|
||||
}
|
||||
logs.Trace("http request, method %s, host %s, url %s, remote address %s", r.Method, r.Host, r.URL.Path, remoteAddr)
|
||||
logs.Trace("http request, method %s, host %s, url %s, remote address %s", r.Method, r.Host, r.URL.Path, r.RemoteAddr)
|
||||
r.Write(targetConn)
|
||||
}
|
||||
}
|
||||
@@ -220,48 +214,7 @@ func (s *TRPClient) handleChan(src net.Conn) {
|
||||
src.Close()
|
||||
} else {
|
||||
logs.Trace("new %s connection with the goal of %s, remote address:%s", lk.ConnType, lk.Host, lk.RemoteAddr)
|
||||
|
||||
if lk.ProtoVersion == "V1" || lk.ProtoVersion == "V2" {
|
||||
var addr = targetConn.RemoteAddr()
|
||||
if lk.RemoteAddr != "" {
|
||||
s := strings.Split(lk.RemoteAddr, ":")[1]
|
||||
port, _ := strconv.Atoi(s)
|
||||
addr = &net.TCPAddr{
|
||||
IP: net.ParseIP(strings.Split(lk.RemoteAddr, ":")[0]),
|
||||
Port: port,
|
||||
}
|
||||
}
|
||||
|
||||
var version byte
|
||||
|
||||
if lk.ProtoVersion == "V1" {
|
||||
version = 1
|
||||
} else if lk.ProtoVersion == "V2" {
|
||||
version = 2
|
||||
}
|
||||
|
||||
transportProtocol := proxyproto.TCPv4
|
||||
if strings.Contains(addr.String(), ".") {
|
||||
transportProtocol = proxyproto.TCPv4
|
||||
} else {
|
||||
transportProtocol = proxyproto.TCPv6
|
||||
}
|
||||
|
||||
header := &proxyproto.Header{
|
||||
Command: proxyproto.PROXY,
|
||||
SourceAddr: addr,
|
||||
DestinationAddr: targetConn.RemoteAddr(),
|
||||
Version: version,
|
||||
TransportProtocol: transportProtocol,
|
||||
}
|
||||
|
||||
_, err2 := header.WriteTo(targetConn)
|
||||
if err2 != nil {
|
||||
logs.Error(err2)
|
||||
}
|
||||
}
|
||||
|
||||
conn.CopyWaitGroup(src, targetConn, lk.Crypt, lk.Compress, nil, nil, false, nil, nil)
|
||||
conn.CopyWaitGroup(src, targetConn, lk.Crypt, lk.Compress, nil, nil, false, nil)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ package client
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
@@ -30,16 +29,6 @@ import (
|
||||
"golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
var tlsEnable1 = false
|
||||
|
||||
func SetTlsEnable(tlsEnable11 bool) {
|
||||
tlsEnable1 = tlsEnable11
|
||||
}
|
||||
|
||||
func GetTlsEnable() bool {
|
||||
return tlsEnable1
|
||||
}
|
||||
|
||||
func GetTaskStatus(path string) {
|
||||
cnf, err := config.NewConfig(path)
|
||||
if err != nil {
|
||||
@@ -107,8 +96,6 @@ func StartFromFile(path string) {
|
||||
}
|
||||
logs.Info("Loading configuration file %s successfully", path)
|
||||
|
||||
SetTlsEnable(cnf.CommonConfig.TlsEnable)
|
||||
logs.Info("the version of client is %s, the core version of client is %s,tls enable is %t", version.VERSION, version.GetVersion(), GetTlsEnable())
|
||||
re:
|
||||
if first || cnf.CommonConfig.AutoReconnection {
|
||||
if !first {
|
||||
@@ -215,32 +202,7 @@ func NewConn(tp string, vkey string, server string, connType string, proxyUrl st
|
||||
connection, err = NewHttpProxyConn(u, server)
|
||||
}
|
||||
} else {
|
||||
if GetTlsEnable() {
|
||||
//tls 流量加密
|
||||
conf := &tls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
}
|
||||
connection, err = tls.Dial("tcp", server, conf)
|
||||
} else {
|
||||
connection, err = net.Dial("tcp", server)
|
||||
}
|
||||
|
||||
//header := &proxyproto.Header{
|
||||
// Version: 1,
|
||||
// Command: proxyproto.PROXY,
|
||||
// TransportProtocol: proxyproto.TCPv4,
|
||||
// SourceAddr: &net.TCPAddr{
|
||||
// IP: net.ParseIP("10.1.1.1"),
|
||||
// Port: 1000,
|
||||
// },
|
||||
// DestinationAddr: &net.TCPAddr{
|
||||
// IP: net.ParseIP("20.2.2.2"),
|
||||
// Port: 2000,
|
||||
// },
|
||||
//}
|
||||
//
|
||||
//_, err = header.WriteTo(connection)
|
||||
//_, err = io.WriteString(connection, "HELO")
|
||||
connection, err = net.Dial("tcp", server)
|
||||
}
|
||||
} else {
|
||||
sess, err = kcp.DialWithOptions(server, nil, 10, 3)
|
||||
@@ -270,8 +232,8 @@ func NewConn(tp string, vkey string, server string, connType string, proxyUrl st
|
||||
return nil, err
|
||||
}
|
||||
if crypt.Md5(version.GetVersion()) != string(b) {
|
||||
//logs.Error("The client does not match the server version. The current core version of the client is", version.GetVersion())
|
||||
//return nil, err
|
||||
logs.Error("The client does not match the server version. The current core version of the client is", version.GetVersion())
|
||||
return nil, err
|
||||
}
|
||||
if _, err := c.Write([]byte(common.Getverifyval(vkey))); err != nil {
|
||||
return nil, err
|
||||
@@ -289,7 +251,7 @@ func NewConn(tp string, vkey string, server string, connType string, proxyUrl st
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// http proxy connection
|
||||
//http proxy connection
|
||||
func NewHttpProxyConn(url *url.URL, remoteAddr string) (net.Conn, error) {
|
||||
req, err := http.NewRequest("CONNECT", "http://"+remoteAddr, nil)
|
||||
if err != nil {
|
||||
@@ -316,7 +278,7 @@ func NewHttpProxyConn(url *url.URL, remoteAddr string) (net.Conn, error) {
|
||||
return proxyConn, nil
|
||||
}
|
||||
|
||||
// get a basic auth string
|
||||
//get a basic auth string
|
||||
func basicAuth(username, password string) string {
|
||||
auth := username + ":" + password
|
||||
return base64.StdEncoding.EncodeToString([]byte(auth))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"ehang.io/nps/lib/nps_mux"
|
||||
"ehang.io/nps-mux"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
@@ -161,7 +161,7 @@ func handleSecret(localTcpConn net.Conn, config *config.CommonConfig, l *config.
|
||||
logs.Error("Local connection server failed ", err.Error())
|
||||
return
|
||||
}
|
||||
conn.CopyWaitGroup(remoteConn.Conn, localTcpConn, false, false, nil, nil, false, nil, nil)
|
||||
conn.CopyWaitGroup(remoteConn.Conn, localTcpConn, false, false, nil, nil, false, nil)
|
||||
}
|
||||
|
||||
func handleP2PVisitor(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
|
||||
@@ -172,13 +172,13 @@ func handleP2PVisitor(localTcpConn net.Conn, config *config.CommonConfig, l *con
|
||||
}
|
||||
logs.Trace("start trying to connect with the server")
|
||||
//TODO just support compress now because there is not tls file in client packages
|
||||
link := conn.NewLink(common.CONN_TCP, l.Target, false, config.Client.Cnf.Compress, localTcpConn.LocalAddr().String(), false, "")
|
||||
link := conn.NewLink(common.CONN_TCP, l.Target, false, config.Client.Cnf.Compress, localTcpConn.LocalAddr().String(), false)
|
||||
if target, err := p2pNetBridge.SendLinkInfo(0, link, nil); err != nil {
|
||||
logs.Error(err)
|
||||
udpConnStatus = false
|
||||
return
|
||||
} else {
|
||||
conn.CopyWaitGroup(target, localTcpConn, false, config.Client.Cnf.Compress, nil, nil, false, nil, nil)
|
||||
conn.CopyWaitGroup(target, localTcpConn, false, config.Client.Cnf.Compress, nil, nil, false, nil)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,27 +1,23 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"ehang.io/nps/lib/crypt"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"ehang.io/nps/client"
|
||||
"ehang.io/nps/lib/common"
|
||||
"ehang.io/nps/lib/config"
|
||||
"ehang.io/nps/lib/file"
|
||||
"ehang.io/nps/lib/install"
|
||||
"ehang.io/nps/lib/version"
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/ccding/go-stun/stun"
|
||||
"github.com/fatih/color"
|
||||
"github.com/kardianos/service"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -43,7 +39,6 @@ var (
|
||||
stunAddr = flag.String("stun_addr", "stun.stunprotocol.org:3478", "stun server address (eg:stun.stunprotocol.org:3478)")
|
||||
ver = flag.Bool("version", false, "show current version")
|
||||
disconnectTime = flag.Int("disconnect_timeout", 60, "not receiving check packet times, until timeout will disconnect the client")
|
||||
tlsEnable = flag.Bool("tls_enable", false, "enable tls")
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -120,7 +115,6 @@ func main() {
|
||||
return
|
||||
case "nat":
|
||||
c := stun.NewClient()
|
||||
flag.CommandLine.Parse(os.Args[2:])
|
||||
c.SetServerAddr(*stunAddr)
|
||||
nat, host, err := c.Discover()
|
||||
if err != nil || host == nil {
|
||||
@@ -234,321 +228,19 @@ func run() {
|
||||
if *verifyKey == "" {
|
||||
*verifyKey, _ = env["NPC_SERVER_VKEY"]
|
||||
}
|
||||
logs.Info("the version of client is %s, the core version of client is %s", version.VERSION, version.GetVersion())
|
||||
if *verifyKey != "" && *serverAddr != "" && *configPath == "" {
|
||||
client.SetTlsEnable(*tlsEnable)
|
||||
logs.Info("the version of client is %s, the core version of client is %s,tls enable is %t", version.VERSION, version.GetVersion(), client.GetTlsEnable())
|
||||
|
||||
vkeys := strings.Split(*verifyKey, `,`)
|
||||
for _, key := range vkeys {
|
||||
key := key
|
||||
go func() {
|
||||
for {
|
||||
logs.Info("start vkey:" + key)
|
||||
client.NewRPClient(*serverAddr, key, *connType, *proxyUrl, nil, *disconnectTime).Start()
|
||||
logs.Info("Client closed! It will be reconnected in five seconds")
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
go func() {
|
||||
for {
|
||||
client.NewRPClient(*serverAddr, *verifyKey, *connType, *proxyUrl, nil, *disconnectTime).Start()
|
||||
logs.Info("Client closed! It will be reconnected in five seconds")
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
if *configPath == "" {
|
||||
*configPath = common.GetConfigPath()
|
||||
}
|
||||
|
||||
// 判断路径下是否有配置文件
|
||||
if common.FileExists(*configPath) {
|
||||
logs.Info("配置文件模式启动")
|
||||
go client.StartFromFile(*configPath)
|
||||
} else {
|
||||
// 无配置文件模式双击运行
|
||||
printSlogan()
|
||||
inputCmd()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func printSlogan() {
|
||||
green := color.New(color.FgGreen).SprintFunc()
|
||||
// 第一次输入,如果输入 1,2,3,4 则需要输入秘钥,否则
|
||||
|
||||
fmt.Printf("%s", green(""))
|
||||
|
||||
fmt.Printf("\033[32;0m###########################################################\n")
|
||||
fmt.Printf("\033[32;0m# \033[31mNPS内网穿透客户端\033[0m #\n")
|
||||
fmt.Printf("\033[32;0m# #\n")
|
||||
fmt.Printf("\033[32;0m#\033[32m 地址:\033[31;0mhttps://github.com/yisier/nps\033[0m #\n")
|
||||
fmt.Printf("\033[32;0m#\033[32m 提示:\033[32;0m1、涉及到系统服务的需要以管理员身份运行\033[0m\033[32;0m #\n")
|
||||
fmt.Printf("\033[32;0m#\033[32m \033[32;0m2、直接启动或[注册系统服务]需要使用[快捷启动命令]\033[0m\033[32;0m #\n")
|
||||
fmt.Printf("\033[32;0m#\033[32m \033[32;0m3、其他命令如卸载/启动/停止只需要输入[vkey]\033[0m\033[32;0m #\n")
|
||||
fmt.Printf("\033[32;0m###########################################################\n")
|
||||
fmt.Printf("\033[0m") // 重置颜色
|
||||
|
||||
fmt.Printf("\n")
|
||||
|
||||
fmt.Printf("\u001B[32m输入[1]\u001B[0m - 注册系统服务\n")
|
||||
fmt.Printf("\u001B[32m输入[2]\u001B[0m - 卸载系统服务\n")
|
||||
fmt.Printf("---------------------\n")
|
||||
fmt.Printf("\u001B[32m输入[3]\u001B[0m - 启动系统服务\n")
|
||||
fmt.Printf("\u001B[32m输入[4]\u001B[0m - 停止系统服务\n")
|
||||
fmt.Printf("---------------------\n")
|
||||
fmt.Printf("\u001B[32m输入[0]\u001B[0m - 退出\n")
|
||||
fmt.Printf("---------------------\n")
|
||||
fmt.Printf("直接输入[快捷启动命令]则是启动隧道,多个[快捷启动命令]用英文逗号拼接\n")
|
||||
fmt.Printf("\n")
|
||||
}
|
||||
|
||||
func inputCmd() {
|
||||
|
||||
var flag string
|
||||
fmt.Printf("请输入:")
|
||||
|
||||
stdin := bufio.NewReader(os.Stdin)
|
||||
_, err := fmt.Fscanln(stdin, &flag)
|
||||
if err != nil {
|
||||
fmt.Println("输入有误")
|
||||
} else {
|
||||
if flag == "0" {
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
flag := strings.Replace(flag, " ", "", -1)
|
||||
|
||||
// 如果输入不等于 1,2,3,4,则启动隧道
|
||||
if flag != "1" && flag != "2" && flag != "3" && flag != "4" {
|
||||
|
||||
vkeys := strings.Split(flag, `,`)
|
||||
var cmdArray []string
|
||||
|
||||
for _, key := range vkeys {
|
||||
startCmd, err := crypt.Base64Decoding(key)
|
||||
if err != nil {
|
||||
fmt.Println("快捷启动命令解析失败")
|
||||
inputCmd()
|
||||
return
|
||||
}
|
||||
|
||||
cmdArray = append(cmdArray, startCmd)
|
||||
}
|
||||
|
||||
for _, item := range cmdArray {
|
||||
startNpcServer(item)
|
||||
}
|
||||
|
||||
} else {
|
||||
systemService(flag)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func startNpcServer(startCmd string) {
|
||||
var serAddr string
|
||||
var vkey string
|
||||
var tls string
|
||||
array := strings.Fields(startCmd)
|
||||
serAddr = array[0]
|
||||
vkey = array[1]
|
||||
if len(array) > 2 {
|
||||
tls = array[2]
|
||||
}
|
||||
go func() {
|
||||
for {
|
||||
if tls == "-tls_enable=true" || len(array) > 2 {
|
||||
client.SetTlsEnable(true)
|
||||
logs.Info("start cmd:-server=" + serAddr + " -vkey=" + vkey + " " + tls)
|
||||
logs.Info("the version of client is %s, the core version of client is %s,tls enable is %t", version.VERSION, version.GetVersion(), client.GetTlsEnable())
|
||||
} else {
|
||||
client.SetTlsEnable(false)
|
||||
logs.Info("start cmd:-server=" + serAddr + " -vkey=" + vkey)
|
||||
logs.Info("the version of client is %s, the core version of client is %s", version.VERSION, version.GetVersion())
|
||||
}
|
||||
|
||||
client.NewRPClient(serAddr, vkey, *connType, *proxyUrl, nil, *disconnectTime).Start()
|
||||
logs.Info("Client closed! It will be reconnected in five seconds")
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func systemService(flag string) {
|
||||
|
||||
if flag == "1" {
|
||||
fmt.Printf("请输入[快捷启动命令],多个[快捷启动命令]用英文逗号拼接:")
|
||||
} else {
|
||||
fmt.Printf("请输入[VKEY],多个[VKEY]用英文逗号拼接:")
|
||||
}
|
||||
|
||||
var vkey string
|
||||
stdin := bufio.NewReader(os.Stdin)
|
||||
_, err := fmt.Fscanln(stdin, &vkey)
|
||||
|
||||
if err != nil {
|
||||
fmt.Println("输入错误,请重试")
|
||||
systemService(flag)
|
||||
return
|
||||
} else {
|
||||
if vkey == "0" {
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
vkey = strings.Replace(vkey, " ", "", -1)
|
||||
|
||||
vkeys := strings.Split(vkey, `,`)
|
||||
|
||||
if flag == "1" {
|
||||
var cmdArray []string
|
||||
for _, key := range vkeys {
|
||||
startCmd, err := crypt.Base64Decoding(key)
|
||||
if err != nil {
|
||||
fmt.Println("快捷启动命令解析失败")
|
||||
systemService(flag)
|
||||
return
|
||||
}
|
||||
cmdArray = append(cmdArray, startCmd)
|
||||
}
|
||||
|
||||
for _, item := range cmdArray {
|
||||
array := strings.Fields(item)
|
||||
// tls
|
||||
if len(array) > 2 {
|
||||
systemPro(flag, array[0], array[1], true)
|
||||
} else {
|
||||
systemPro(flag, array[0], array[1], false)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for _, key := range vkeys {
|
||||
systemPro(flag, "", key, false)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
inputCmd()
|
||||
return
|
||||
}
|
||||
|
||||
func systemPro(flag string, serAddr string, vkey string, tls bool) {
|
||||
// init service
|
||||
prg := &npc{
|
||||
exit: make(chan struct{}),
|
||||
}
|
||||
options := make(service.KeyValue)
|
||||
svcConfig := &service.Config{
|
||||
Name: "nps-client-" + vkey,
|
||||
DisplayName: "nps-client-" + vkey,
|
||||
Description: "NPS内网穿透客户端,支持tcp、udp流量转发,支持内网http代理,地址:https://github.com/yisier/nps",
|
||||
Option: options,
|
||||
}
|
||||
s, _ := service.New(prg, svcConfig)
|
||||
|
||||
switch flag {
|
||||
case "1":
|
||||
svcConfig.Arguments = append(svcConfig.Arguments, "-server="+serAddr)
|
||||
svcConfig.Arguments = append(svcConfig.Arguments, "-vkey="+vkey)
|
||||
if tls {
|
||||
svcConfig.Arguments = append(svcConfig.Arguments, "-tls_enable=true")
|
||||
}
|
||||
svcConfig.Arguments = append(svcConfig.Arguments, "-debug=false")
|
||||
|
||||
*logPath = common.GetNpcLogPath()
|
||||
if common.IsWindows() {
|
||||
*logPath = strings.Replace(*logPath, "\\", "\\\\", -1)
|
||||
}
|
||||
|
||||
*logPath = strings.Replace(*logPath, "npc.log", "npc-"+vkey+".log", -1)
|
||||
svcConfig.Arguments = append(svcConfig.Arguments, "-log_path="+*logPath)
|
||||
|
||||
logs.NewLogger()
|
||||
logs.Reset()
|
||||
logs.EnableFuncCallDepth(true)
|
||||
logs.SetLogFuncCallDepth(3)
|
||||
logs.SetLogger(logs.AdapterFile, `{"level":`+*logLevel+`,"filename":"`+*logPath+`","daily":false,"maxlines":100000,"color":true}`)
|
||||
|
||||
install.InstallNpc()
|
||||
err := service.Control(s, "install")
|
||||
if err != nil {
|
||||
fmt.Println("隧道["+vkey+"]安装到系统服务失败", err)
|
||||
return
|
||||
} else {
|
||||
fmt.Println("隧道[" + vkey + "]已经安装到系统")
|
||||
}
|
||||
if service.Platform() == "unix-systemv" {
|
||||
logs.Info("unix-systemv service")
|
||||
confPath := "/etc/init.d/" + svcConfig.Name
|
||||
os.Symlink(confPath, "/etc/rc.d/S90"+svcConfig.Name)
|
||||
os.Symlink(confPath, "/etc/rc.d/K02"+svcConfig.Name)
|
||||
}
|
||||
|
||||
err2 := service.Control(s, "start")
|
||||
if err2 != nil {
|
||||
fmt.Println("隧道["+vkey+"]启动服务失败", err2)
|
||||
} else {
|
||||
fmt.Println("隧道[" + vkey + "]服务已启动")
|
||||
}
|
||||
|
||||
return
|
||||
case "2":
|
||||
// 卸载系统服务
|
||||
err := service.Control(s, "stop")
|
||||
if err != nil {
|
||||
fmt.Println("隧道["+vkey+"]服务停止失败", err)
|
||||
} else {
|
||||
fmt.Println("隧道[" + vkey + "]服务已停止")
|
||||
}
|
||||
|
||||
err = service.Control(s, "uninstall")
|
||||
if err != nil {
|
||||
fmt.Println("隧道["+vkey+"]服务卸载失败", err)
|
||||
}
|
||||
if service.Platform() == "unix-systemv" {
|
||||
fmt.Println("unix-systemv service")
|
||||
os.Remove("/etc/rc.d/S90" + svcConfig.Name)
|
||||
os.Remove("/etc/rc.d/K02" + svcConfig.Name)
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
fmt.Println("隧道[" + vkey + "]服务已卸载成功")
|
||||
}
|
||||
|
||||
return
|
||||
|
||||
case "3":
|
||||
//启动系统服务
|
||||
if service.Platform() == "unix-systemv" {
|
||||
logs.Info("unix-systemv service")
|
||||
cmd := exec.Command("/etc/init.d/"+svcConfig.Name, "start")
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
err := service.Control(s, "start")
|
||||
if err != nil {
|
||||
fmt.Println("隧道["+vkey+"]服务启动失败", err)
|
||||
} else {
|
||||
fmt.Println("隧道[" + vkey + "]服务启动成功")
|
||||
}
|
||||
|
||||
return
|
||||
case "4":
|
||||
if service.Platform() == "unix-systemv" {
|
||||
logs.Info("unix-systemv service")
|
||||
cmd := exec.Command("/etc/init.d/"+svcConfig.Name, "stop")
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
err := service.Control(s, "stop")
|
||||
if err != nil {
|
||||
fmt.Println("隧道["+vkey+"]服务停止失败", err)
|
||||
} else {
|
||||
fmt.Println("隧道[" + vkey + "]服务停止成功")
|
||||
}
|
||||
|
||||
return
|
||||
go client.StartFromFile(*configPath)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,31 +1,26 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"ehang.io/nps/bridge"
|
||||
"ehang.io/nps/lib/daemon"
|
||||
"ehang.io/nps/server"
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/fatih/color"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"ehang.io/nps/lib/file"
|
||||
"ehang.io/nps/lib/install"
|
||||
"ehang.io/nps/lib/version"
|
||||
"ehang.io/nps/server"
|
||||
"ehang.io/nps/server/connection"
|
||||
"ehang.io/nps/server/tool"
|
||||
"ehang.io/nps/web/routers"
|
||||
|
||||
"ehang.io/nps/lib/common"
|
||||
"ehang.io/nps/lib/crypt"
|
||||
"ehang.io/nps/lib/daemon"
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/astaxie/beego/logs"
|
||||
|
||||
@@ -33,49 +28,20 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
level string
|
||||
ver = flag.Bool("version", false, "show current version")
|
||||
confPath = flag.String("conf_path", "", "set current confPath")
|
||||
serverCmd = flag.Bool("server", false, "NPS管理脚本")
|
||||
npsLogPath = flag.String("log_path", "", "nps log path")
|
||||
level string
|
||||
ver = flag.Bool("version", false, "show current version")
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
debug.SetMaxThreads(1000000)
|
||||
|
||||
flag.Parse()
|
||||
// init log
|
||||
if *ver {
|
||||
common.PrintVersion()
|
||||
return
|
||||
}
|
||||
if *serverCmd {
|
||||
printSlogan()
|
||||
inputCmd()
|
||||
return
|
||||
}
|
||||
|
||||
var logPath string
|
||||
// *confPath why get null value ?
|
||||
for _, v := range os.Args[1:] {
|
||||
switch v {
|
||||
case "install", "start", "stop", "uninstall", "restart":
|
||||
continue
|
||||
}
|
||||
if strings.Contains(v, "-conf_path=") {
|
||||
common.ConfPath = strings.Replace(v, "-conf_path=", "", -1)
|
||||
}
|
||||
|
||||
if strings.Contains(v, "-log_path=") {
|
||||
logPath = strings.Replace(v, "-log_path=", "", -1)
|
||||
}
|
||||
}
|
||||
|
||||
if err := beego.LoadAppConfig("ini", filepath.Join(common.GetRunPath(), "conf", "nps.conf")); err != nil {
|
||||
log.Fatalln("load config file error", err.Error())
|
||||
}
|
||||
|
||||
common.InitPProfFromFile()
|
||||
if level = beego.AppConfig.String("log_level"); level == "" {
|
||||
level = "7"
|
||||
@@ -83,17 +49,13 @@ func main() {
|
||||
logs.Reset()
|
||||
logs.EnableFuncCallDepth(true)
|
||||
logs.SetLogFuncCallDepth(3)
|
||||
|
||||
logPath := beego.AppConfig.String("log_path")
|
||||
if logPath == "" {
|
||||
logPath := beego.AppConfig.String("log_path")
|
||||
if logPath == "" {
|
||||
logPath = common.GetLogPath()
|
||||
}
|
||||
if common.IsWindows() {
|
||||
logPath = strings.Replace(logPath, "\\", "\\\\", -1)
|
||||
}
|
||||
logPath = common.GetLogPath()
|
||||
}
|
||||
if common.IsWindows() {
|
||||
logPath = strings.Replace(logPath, "\\", "\\\\", -1)
|
||||
}
|
||||
|
||||
// init service
|
||||
options := make(service.KeyValue)
|
||||
svcConfig := &service.Config{
|
||||
@@ -102,17 +64,6 @@ func main() {
|
||||
Description: "一款轻量级、功能强大的内网穿透代理服务器。支持tcp、udp流量转发,支持内网http代理、内网socks5代理,同时支持snappy压缩、站点保护、加密传输、多路复用、header修改等。支持web图形化管理,集成多用户模式。",
|
||||
Option: options,
|
||||
}
|
||||
|
||||
bridge.ServerTlsEnable = beego.AppConfig.DefaultBool("tls_enable", false)
|
||||
|
||||
for _, v := range os.Args[1:] {
|
||||
switch v {
|
||||
case "install", "start", "stop", "uninstall", "restart":
|
||||
continue
|
||||
}
|
||||
svcConfig.Arguments = append(svcConfig.Arguments, v)
|
||||
}
|
||||
|
||||
svcConfig.Arguments = append(svcConfig.Arguments, "service")
|
||||
if len(os.Args) > 1 && os.Args[1] == "service" {
|
||||
_ = logs.SetLogger(logs.AdapterFile, `{"level":`+level+`,"filename":"`+logPath+`","daily":false,"maxlines":100000,"color":true}`)
|
||||
@@ -138,7 +89,6 @@ func main() {
|
||||
wg.Wait()
|
||||
return
|
||||
}
|
||||
|
||||
if len(os.Args) > 1 && os.Args[1] != "service" {
|
||||
switch os.Args[1] {
|
||||
case "reload":
|
||||
@@ -196,192 +146,12 @@ func main() {
|
||||
case "update":
|
||||
install.UpdateNps()
|
||||
return
|
||||
//default:
|
||||
// logs.Error("command is not support")
|
||||
// return
|
||||
}
|
||||
}
|
||||
|
||||
_ = s.Run()
|
||||
}
|
||||
|
||||
func printSlogan() {
|
||||
green := color.New(color.FgGreen).SprintFunc()
|
||||
// 第一次输入,如果输入 1,2,3,4 则需要输入秘钥,否则
|
||||
|
||||
fmt.Printf("%s", green(""))
|
||||
|
||||
fmt.Printf("\033[32;0m欢迎使用 NPS 管理脚本 \n")
|
||||
fmt.Printf("\033[0m") // 重置颜色
|
||||
|
||||
fmt.Printf("\n")
|
||||
|
||||
fmt.Printf("\u001B[32m输入[1]\u001B[0m - 安装 NPS\n")
|
||||
fmt.Printf("\u001B[32m输入[2]\u001B[0m - 卸载 NPS\n")
|
||||
fmt.Printf("\u001B[32m输入[3]\u001B[0m - 更新 NPS\n")
|
||||
fmt.Printf("---------------------\n")
|
||||
fmt.Printf("\u001B[32m输入[4]\u001B[0m - 查看状态\n")
|
||||
fmt.Printf("---------------------\n")
|
||||
fmt.Printf("\u001B[32m输入[5]\u001B[0m - 启动 NPS\n")
|
||||
fmt.Printf("\u001B[32m输入[6]\u001B[0m - 停止 NPS\n")
|
||||
fmt.Printf("\u001B[32m输入[7]\u001B[0m - 重启 NPS\n")
|
||||
fmt.Printf("---------------------\n")
|
||||
fmt.Printf("\u001B[32m输入[0]\u001B[0m - 退出脚本\n")
|
||||
fmt.Printf("---------------------\n")
|
||||
fmt.Printf("\n")
|
||||
|
||||
}
|
||||
|
||||
func inputCmd() {
|
||||
var flag string
|
||||
fmt.Printf("请输入[0-7]:")
|
||||
|
||||
stdin := bufio.NewReader(os.Stdin)
|
||||
_, err := fmt.Fscanln(stdin, &flag)
|
||||
if err != nil {
|
||||
fmt.Println("输入有误")
|
||||
} else {
|
||||
if flag == "0" {
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
// init service
|
||||
|
||||
prg := &nps{
|
||||
exit: make(chan struct{}),
|
||||
}
|
||||
options := make(service.KeyValue)
|
||||
svcConfig := &service.Config{
|
||||
Name: "Nps",
|
||||
DisplayName: "nps内网穿透代理服务器",
|
||||
Description: "一款轻量级、功能强大的内网穿透代理服务器。支持tcp、udp流量转发,支持内网http代理、内网socks5代理,同时支持snappy压缩、站点保护、加密传输、多路复用、header修改等。支持web图形化管理,集成多用户模式。",
|
||||
Option: options,
|
||||
}
|
||||
s, _ := service.New(prg, svcConfig)
|
||||
|
||||
switch flag {
|
||||
case "1":
|
||||
// uninstall before
|
||||
_ = service.Control(s, "stop")
|
||||
_ = service.Control(s, "uninstall")
|
||||
binPath := install.InstallNpsToCurrentDir()
|
||||
|
||||
beego.LoadAppConfig("ini", filepath.Join(common.GetAppPath(), "conf", "nps.conf"))
|
||||
|
||||
logPath := filepath.Join(common.GetAppPath(), "nps.log")
|
||||
if common.IsWindows() {
|
||||
logPath = strings.Replace(logPath, "\\", "\\\\", -1)
|
||||
}
|
||||
svcConfig.Arguments = append(svcConfig.Arguments, "service")
|
||||
svcConfig.Arguments = append(svcConfig.Arguments, "-conf_path="+common.GetAppPath())
|
||||
svcConfig.Arguments = append(svcConfig.Arguments, "-log_path="+logPath)
|
||||
|
||||
fmt.Println("日志文件路径为:", logPath)
|
||||
|
||||
svcConfig.Executable = binPath
|
||||
s, err := service.New(prg, svcConfig)
|
||||
|
||||
if service.Platform() == "unix-systemv" {
|
||||
logs.Info("unix-systemv service")
|
||||
confPath := "/etc/init.d/" + svcConfig.Name
|
||||
os.Symlink(confPath, "/etc/rc.d/S90"+svcConfig.Name)
|
||||
os.Symlink(confPath, "/etc/rc.d/K02"+svcConfig.Name)
|
||||
}
|
||||
|
||||
err = service.Control(s, "install")
|
||||
if err != nil {
|
||||
logs.Error("Valid actions: %q\n%s", service.ControlAction, err.Error())
|
||||
} else {
|
||||
fmt.Println("NPS服务安装成功")
|
||||
}
|
||||
|
||||
err = service.Control(s, "start")
|
||||
if err != nil {
|
||||
fmt.Println("启动NPS服务失败", err)
|
||||
} else {
|
||||
fmt.Println("NPS服务已启动,管理面板访问地址:127.0.0.1:" + beego.AppConfig.String("web_port"))
|
||||
}
|
||||
|
||||
break
|
||||
case "2":
|
||||
// 卸载系统服务
|
||||
err := service.Control(s, "stop")
|
||||
if err != nil {
|
||||
fmt.Println("NPS服务停止失败", err)
|
||||
} else {
|
||||
fmt.Println("NPS服务已停止")
|
||||
}
|
||||
|
||||
err = service.Control(s, "uninstall")
|
||||
if err != nil {
|
||||
logs.Error("NPS服务卸载失败")
|
||||
}
|
||||
if service.Platform() == "unix-systemv" {
|
||||
logs.Info("unix-systemv service")
|
||||
os.Remove("/etc/rc.d/S90" + svcConfig.Name)
|
||||
os.Remove("/etc/rc.d/K02" + svcConfig.Name)
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
fmt.Println("NPS服务已卸载成功")
|
||||
}
|
||||
break
|
||||
case "3":
|
||||
install.UpdateNpsNew()
|
||||
default:
|
||||
logs.Error("command is not support")
|
||||
return
|
||||
case "4":
|
||||
// 查看状态
|
||||
var statusMsg = ""
|
||||
status, err := s.Status()
|
||||
if err != nil {
|
||||
statusMsg = "\u001B[31m未运行\u001B[0m"
|
||||
} else {
|
||||
if status == 1 {
|
||||
statusMsg = "\u001B[32m运行中\u001B[0m"
|
||||
} else {
|
||||
statusMsg = "\u001B[31m未运行\u001B[0m"
|
||||
}
|
||||
}
|
||||
fmt.Println("NPS服务状态:" + statusMsg)
|
||||
break
|
||||
case "5":
|
||||
// 启动 NPS
|
||||
err := service.Control(s, "start")
|
||||
if err != nil {
|
||||
fmt.Println("NPS服务启动失败", err)
|
||||
} else {
|
||||
fmt.Println("NPS服务启动成功")
|
||||
}
|
||||
|
||||
break
|
||||
case "6":
|
||||
// 停止 NPS
|
||||
err := service.Control(s, "stop")
|
||||
if err != nil {
|
||||
fmt.Println("NPS服务停止失败", err)
|
||||
} else {
|
||||
fmt.Println("NPS服务停止成功")
|
||||
}
|
||||
|
||||
break
|
||||
case "7":
|
||||
// 重启 NPS
|
||||
err := service.Control(s, "restart")
|
||||
if err != nil {
|
||||
fmt.Println("NPS服务重启失败", err)
|
||||
} else {
|
||||
fmt.Println("NPS服务重启成功")
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
inputCmd()
|
||||
}
|
||||
|
||||
func installNps() {
|
||||
|
||||
_ = s.Run()
|
||||
}
|
||||
|
||||
type nps struct {
|
||||
@@ -429,10 +199,7 @@ func run() {
|
||||
logs.Error("Getting bridge_port error", err)
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
logs.Info("日志路径:" + *npsLogPath)
|
||||
logs.Info("the config path is:" + common.GetRunPath())
|
||||
logs.Info("the version of server is %s ,allow client core version to be %s,tls enable is %t", version.VERSION, version.GetVersion(), bridge.ServerTlsEnable)
|
||||
logs.Info("the version of server is %s ,allow client core version to be %s", version.VERSION, version.GetVersion())
|
||||
connection.InitConnectionService()
|
||||
//crypt.InitTls(filepath.Join(common.GetRunPath(), "conf", "server.pem"), filepath.Join(common.GetRunPath(), "conf", "server.key"))
|
||||
crypt.InitTls()
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
{"Cnf":{"U":"","P":"","Compress":false,"Crypt":false},"Id":34,"VerifyKey":"a1efa114df","Addr":"127.0.0.1","Remark":"","Status":true,"IsConnect":false,"RateLimit":0,"Flow":{"ExportFlow":0,"InletFlow":0,"FlowLimit":0},"Rate":{"NowRate":0},"NoStore":false,"NoDisplay":false,"MaxConn":0,"NowConn":0,"WebUserName":"","WebPassword":"","ConfigConnAllow":true,"MaxTunnelNum":0,"Version":"0.26.20","BlackIpList":[""],"CreateTime":"2025-01-03 17:07:37","LastOnlineTime":"2025-01-07 11:12:00"}
|
||||
*#*
|
||||
@@ -14,7 +14,6 @@ crypt=true
|
||||
compress=true
|
||||
#pprof_addr=0.0.0.0:9999
|
||||
disconnect_timeout=60
|
||||
tls_enable=true
|
||||
|
||||
[health_check_test1]
|
||||
health_check_timeout=1
|
||||
|
||||
@@ -22,11 +22,11 @@ public_vkey=123
|
||||
|
||||
#Traffic data persistence interval(minute)
|
||||
#Ignorance means no persistence
|
||||
flow_store_interval=1
|
||||
#flow_store_interval=1
|
||||
|
||||
# log level LevelEmergency->0 LevelAlert->1 LevelCritical->2 LevelError->3 LevelWarning->4 LevelNotice->5 LevelInformational->6 LevelDebug->7
|
||||
log_level=6
|
||||
log_path=nps.log
|
||||
log_level=7
|
||||
#log_path=nps.log
|
||||
|
||||
#Whether to restrict IP access, true or false or ignore
|
||||
#ip_limit=true
|
||||
@@ -39,7 +39,7 @@ log_path=nps.log
|
||||
web_host=a.o.com
|
||||
web_username=admin
|
||||
web_password=123
|
||||
web_port = 8081
|
||||
web_port = 8080
|
||||
web_ip=0.0.0.0
|
||||
web_base_url=
|
||||
web_open_ssl=false
|
||||
@@ -51,9 +51,7 @@ web_key_file=conf/server.key
|
||||
#Web API unauthenticated IP address(the len of auth_crypt_key must be 16)
|
||||
#Remove comments if needed
|
||||
#auth_key=test
|
||||
auth_key=123
|
||||
#获取服务端authKey时的aes加密密钥,16位
|
||||
auth_crypt_key =213
|
||||
auth_crypt_key =1234567812345678
|
||||
|
||||
#allow_ports=9001-9009,10001,11000-12000
|
||||
|
||||
@@ -62,29 +60,22 @@ allow_user_login=false
|
||||
allow_user_register=false
|
||||
allow_user_change_username=false
|
||||
|
||||
#extension
|
||||
#流量限制
|
||||
allow_flow_limit=true
|
||||
#带宽限制
|
||||
allow_rate_limit=true
|
||||
#客户端最大隧道数限制
|
||||
allow_tunnel_num_limit=true
|
||||
allow_local_proxy=false
|
||||
#客户端最大连接数
|
||||
allow_connection_num_limit=true
|
||||
#每个隧道监听不同的服务端端口
|
||||
allow_multi_ip=true
|
||||
system_info_display=true
|
||||
|
||||
#获取用户真实ip
|
||||
http_add_origin_header=true
|
||||
#extension
|
||||
allow_flow_limit=false
|
||||
allow_rate_limit=false
|
||||
allow_tunnel_num_limit=false
|
||||
allow_local_proxy=false
|
||||
allow_connection_num_limit=false
|
||||
allow_multi_ip=false
|
||||
system_info_display=false
|
||||
|
||||
#cache
|
||||
http_cache=false
|
||||
http_cache_length=100
|
||||
|
||||
#get origin ip
|
||||
#http_add_origin_header=false
|
||||
http_add_origin_header=false
|
||||
|
||||
#pprof debug options
|
||||
#pprof_ip=0.0.0.0
|
||||
@@ -92,11 +83,3 @@ http_cache_length=100
|
||||
|
||||
#client disconnect timeout
|
||||
disconnect_timeout=60
|
||||
|
||||
#管理面板开启验证码校验
|
||||
open_captcha=false
|
||||
|
||||
|
||||
# 是否开启tls
|
||||
tls_enable=true
|
||||
tls_bridge_port=8025
|
||||
@@ -1,6 +1,6 @@
|
||||

|
||||
|
||||
# NPS <small>0.26.10</small>
|
||||
# NPS <small>100.26.10</small>
|
||||
|
||||
> 一款轻量级、高性能、功能强大的内网穿透代理服务器
|
||||
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
# 🐳 宝塔面板 (一键部署)
|
||||
|
||||
> 安装宝塔面板,前往宝塔面板官网,选择对应的脚本下载安装,推荐宝塔版本 9.2.0+
|
||||
|
||||

|
||||
|
||||
# 安装宝塔面板
|
||||
1. 安装宝塔面板,前往 [宝塔面板官网](https://www.bt.cn/new/download.html) 进行安装,选择正式版脚本安装。
|
||||
|
||||
2. 登录面板,点击左侧 **Docker** 进入 `Docker 管理`。
|
||||
|
||||
3. 如提示未安装 Docker / Docker Compose, 可根据上方引导安装。
|
||||
|
||||
|
||||
# 安装NPS服务端
|
||||
1. 在宝塔面板左侧` Docker 菜单`,进入 **应用商城**,搜索 `NPS`,找到 `NPS 服务端` 并点击 **安装**。
|
||||
|
||||
2. 配置NPS,进入安装目录,修改 `conf/nps.conf` 即可(修改后记得重启容器),服务端参数配置详见 [配置文件说明](https://ehang-io.github.io/nps/#/server_config)
|
||||

|
||||
|
||||
|
||||
|
||||
**注意**:NPS 默认的`WEB端口`为`80,443`, 如果端口被占用,请修改 `nps.conf` 中的 `http_proxy_port`,`https_proxy_port` 为其他端口。
|
||||
web管理端口默认为`8081`,服务端启动后,输入:`ip:8081` 即可访问。
|
||||
|
||||
|
||||
|
||||
# 安装NPS客户端
|
||||
1. 在宝塔面板左侧` Docker 菜单`,进入 **应用商城**,搜索 `NPS`,找到 `NPS 客户端` 并点击 **安装**。
|
||||
|
||||
2. 客户端配置有两种方式,1. [无配置文件模式](https://ehang-io.github.io/nps/#/use?id=%e6%97%a0%e9%85%8d%e7%bd%ae%e6%96%87%e4%bb%b6%e6%a8%a1%e5%bc%8f)(推荐),2. [配置文件模式](https://ehang-io.github.io/nps/#/use?id=%e9%85%8d%e7%bd%ae%e6%96%87%e4%bb%b6%e6%a8%a1%e5%bc%8f)。
|
||||
|
||||
- **无配置文件模式**:点击安装后,输入`服务地址`、`连接密钥`,即可启动客户端。`连接方式`和`开启TLS`参数,为了避免意外错误,不建议修改。如果需要配置多个客户端,直接安装多个即可(注意名字不要重复)。
|
||||
|
||||
- **配置文件模式**: `服务地址`、`连接密钥`不需要填写,直接点击 **安装** ,然后在`安装目录`下找到 `conf/npc.conf`,修改配置文件,再重启容器即可。客户端参数配置详见 [配置文件说明](https://ehang-io.github.io/nps/#/use?id=%e9%85%8d%e7%bd%ae%e6%96%87%e4%bb%b6%e6%a8%a1%e5%bc%8f)。
|
||||
|
||||
**注意**:强烈推荐使用无配置文件模式,所有数据应该在服务端保存和配置,而客户端只做连接转发。客户端配置文件对小白极不友好,配置繁琐,容易出错。
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
```
|
||||
命令行模式启动客户端
|
||||
从v0.26.10开始,此函数会阻塞,直到客户端退出返回,请自行管理是否重连
|
||||
从v100.26.10开始,此函数会阻塞,直到客户端退出返回,请自行管理是否重连
|
||||
p0->连接地址
|
||||
p1->vkey
|
||||
p2->连接类型(tcp or udp)
|
||||
|
||||
@@ -53,8 +53,8 @@ npc-update.exe update
|
||||
server_addr=1.1.1.1:8024
|
||||
conn_type=tcp
|
||||
vkey=123
|
||||
username=111
|
||||
password=222
|
||||
basic_username=111
|
||||
basic_password=222
|
||||
compress=true
|
||||
crypt=true
|
||||
rate_limit=10000
|
||||
@@ -68,8 +68,8 @@ max_conn=10
|
||||
server_addr | 服务端ip/域名:port
|
||||
conn_type | 与服务端通信模式(tcp或kcp)
|
||||
vkey|服务端配置文件中的密钥(非web)
|
||||
username|socks5或http(s)密码保护用户名(可忽略)
|
||||
password|socks5或http(s)密码保护密码(可忽略)
|
||||
basic_username|socks5或http(s)密码保护用户名(可忽略)
|
||||
basic_password|socks5或http(s)密码保护密码(可忽略)
|
||||
compress|是否压缩传输(true或false或忽略)
|
||||
crypt|是否加密传输(true或false或忽略)
|
||||
rate_limit|速度限制,可忽略
|
||||
@@ -159,7 +159,7 @@ multi_account=multi_account.conf
|
||||
---|---
|
||||
mode | socks5
|
||||
server_port | 在服务端的代理端口
|
||||
multi_account | socks5多账号配置文件(可选),配置后使用basic_username和basic_password无法通过认证
|
||||
multi_account | socks5多账号配置文件(可选),配置后使用basic_username和basic_password无法通过认证 <br> multi_account.conf要与可执行文件npc同一目录,或者npc.conf里面写相对路径,conf/multi_account.conf
|
||||
#### 私密代理模式
|
||||
|
||||
```ini
|
||||
|
||||
@@ -1,69 +1,35 @@
|
||||
module ehang.io/nps
|
||||
|
||||
go 1.24.0
|
||||
|
||||
toolchain go1.24.9
|
||||
go 1.15
|
||||
|
||||
require (
|
||||
ehang.io/nps-mux v0.0.0-20210407130203-4afa0c10c992
|
||||
fyne.io/fyne/v2 v2.0.2
|
||||
github.com/astaxie/beego v1.12.0
|
||||
github.com/bradfitz/iter v0.0.0-20191230175014-e8f45d346db8 // indirect
|
||||
github.com/c4milo/unpackit v0.0.0-20170704181138-4ed373e9ef1c
|
||||
github.com/ccding/go-stun v0.0.0-20180726100737-be486d185f3d
|
||||
github.com/fatih/color v1.18.0
|
||||
github.com/golang/snappy v0.0.3
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/kardianos/service v1.2.0
|
||||
github.com/panjf2000/ants/v2 v2.4.2
|
||||
github.com/pires/go-proxyproto v0.8.0
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/shirou/gopsutil/v3 v3.23.10
|
||||
github.com/xtaci/kcp-go v5.4.20+incompatible
|
||||
golang.org/x/net v0.23.0
|
||||
golang.org/x/time v0.14.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bradfitz/iter v0.0.0-20191230175014-e8f45d346db8 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/dchest/captcha v0.0.0-20200903113550-03f5f0333e1f
|
||||
github.com/dsnet/compress v0.0.1 // indirect
|
||||
github.com/fredbi/uri v0.0.0-20181227131451-3dcfdacbaaf3 // indirect
|
||||
github.com/fsnotify/fsnotify v1.4.9 // indirect
|
||||
github.com/fyne-io/mobile v0.1.3-0.20210318200029-09e9c4e13a8f // indirect
|
||||
github.com/go-gl/gl v0.0.0-20190320180904-bf2b1f2f34d7 // indirect
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20210311203641-62640a716d48 // indirect
|
||||
github.com/go-ole/go-ole v1.2.6 // indirect
|
||||
github.com/godbus/dbus/v5 v5.0.3 // indirect
|
||||
github.com/goki/freetype v0.0.0-20181231101311-fa8a33aabaff // indirect
|
||||
github.com/golang/snappy v0.0.3
|
||||
github.com/hooklift/assert v0.0.0-20170704181755-9d1defd6d214 // indirect
|
||||
github.com/klauspost/compress v1.4.1 // indirect
|
||||
github.com/kardianos/service v1.2.0
|
||||
github.com/klauspost/cpuid v1.3.1 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.0.6 // indirect
|
||||
github.com/klauspost/pgzip v1.2.1 // indirect
|
||||
github.com/klauspost/reedsolomon v1.9.12 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
|
||||
github.com/panjf2000/ants/v2 v2.4.2
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect
|
||||
github.com/shoenig/go-m1cpu v0.1.6 // indirect
|
||||
github.com/srwiley/oksvg v0.0.0-20200311192757-870daf9aa564 // indirect
|
||||
github.com/srwiley/rasterx v0.0.0-20200120212402-85cb7272f5e9 // indirect
|
||||
github.com/stretchr/testify v1.8.4 // indirect
|
||||
github.com/shirou/gopsutil/v3 v3.21.3
|
||||
github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161 // indirect
|
||||
github.com/templexxx/xor v0.0.0-20191217153810-f85b25db303b // indirect
|
||||
github.com/tjfoc/gmsm v1.4.0 // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.12 // indirect
|
||||
github.com/tklauser/numcpus v0.6.1 // indirect
|
||||
github.com/ulikunitz/xz v0.5.6 // indirect
|
||||
github.com/xtaci/kcp-go v5.4.20+incompatible
|
||||
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.3 // indirect
|
||||
golang.org/x/crypto v0.21.0 // indirect
|
||||
golang.org/x/image v0.0.0-20200430140353-33d19683fad8 // indirect
|
||||
golang.org/x/sys v0.25.0 // indirect
|
||||
golang.org/x/text v0.14.0 // indirect
|
||||
gopkg.in/yaml.v2 v2.2.8 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 // indirect
|
||||
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4
|
||||
golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57 // indirect
|
||||
)
|
||||
|
||||
replace github.com/astaxie/beego => github.com/exfly/beego v1.12.0-export-init
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
ehang.io/nps-mux v0.0.0-20210407130203-4afa0c10c992 h1:LvlcB+8JveSBprHnva0g+OyLwAH8CRxEwtWzTe6ocoE=
|
||||
ehang.io/nps-mux v0.0.0-20210407130203-4afa0c10c992/go.mod h1:v54y/8ICChiM/aVUuKxGIcWwjm4HGNRyyAwbgLBoMbI=
|
||||
fyne.io/fyne/v2 v2.0.2 h1:6pDvFuCmL1odyT/fPI+2L54hMJW1Zt9Dno41HmLInRs=
|
||||
fyne.io/fyne/v2 v2.0.2/go.mod h1:3+FYmLJVgeb8EvTPJ5YzZeo7LkAq4bbuY3Zrir6xHbg=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=
|
||||
github.com/Kodeworks/golang-image-ico v0.0.0-20141118225523-73f0f4cfade9/go.mod h1:7uhhqiBaR4CpN0k9rMjOtjpcfGd6DG2m04zQxKnWQ0I=
|
||||
github.com/OwnLocal/goes v1.0.0/go.mod h1:8rIFjBGTue3lCU0wplczcUgt9Gxgrkkrw7etMIcn8TM=
|
||||
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d h1:G0m3OIz70MZUWq3EgK3CesDbo8upS2Vm9/P3FtgI+Jk=
|
||||
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg=
|
||||
github.com/akavel/rsrc v0.8.0/go.mod h1:uLoCtb9J+EyAqh+26kdrTgmzRBFPGOolLWKpdxkKq+c=
|
||||
github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ=
|
||||
github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU=
|
||||
@@ -27,6 +31,8 @@ github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGii
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dchest/captcha v0.0.0-20200903113550-03f5f0333e1f h1:q/DpyjJjZs94bziQ7YkBmIlpqbVP7yw179rnzoNVX1M=
|
||||
github.com/dchest/captcha v0.0.0-20200903113550-03f5f0333e1f/go.mod h1:QGrK8vMWWHQYQ3QU9bw9Y9OPNfxccGzfb41qjvVeXtY=
|
||||
github.com/dsnet/compress v0.0.1 h1:PlZu0n3Tuv04TzpfPbrnI0HW/YwodEXDS+oPKahKF0Q=
|
||||
github.com/dsnet/compress v0.0.1/go.mod h1:Aw8dCMJ7RioblQeTqt88akK31OvO8Dhf5JflhBbQEHo=
|
||||
github.com/dsnet/golib v0.0.0-20171103203638-1ea166775780/go.mod h1:Lj+Z9rebOhdfkVLjJ8T6VcRQv3SXugXy999NBtR9aFY=
|
||||
@@ -38,8 +44,6 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m
|
||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||
github.com/exfly/beego v1.12.0-export-init h1:VQNYKdXhAwZGUaFmQv8Aj921O3rQJZRIF8xeGrhsjrI=
|
||||
github.com/exfly/beego v1.12.0-export-init/go.mod h1:fysx+LZNZKnvh4GED/xND7jWtjCR6HzydR2Hh2Im57o=
|
||||
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
|
||||
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
|
||||
github.com/fredbi/uri v0.0.0-20181227131451-3dcfdacbaaf3 h1:FDqhDm7pcsLhhWl1QtD8vlzI4mm59llRvNzrFg6/LAA=
|
||||
github.com/fredbi/uri v0.0.0-20181227131451-3dcfdacbaaf3/go.mod h1:CzM2G82Q9BDUvMTGHnXf/6OExw/Dz2ivDj48nVg7Lg8=
|
||||
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
|
||||
@@ -50,8 +54,8 @@ github.com/go-gl/gl v0.0.0-20190320180904-bf2b1f2f34d7 h1:SCYMcCJ89LjRGwEa0tRluN
|
||||
github.com/go-gl/gl v0.0.0-20190320180904-bf2b1f2f34d7/go.mod h1:482civXOzJJCPzJ4ZOX/pwvXBWSnzD4OKMdH4ClKGbk=
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20210311203641-62640a716d48 h1:QrUfZrT8n72FUuiABt4tbu8PwDnOPAbnj3Mql1UhdRI=
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20210311203641-62640a716d48/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
|
||||
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
||||
github.com/go-ole/go-ole v1.2.4 h1:nNBDSCOigTSiarFpYE9J/KtEA1IOW4CNeqT9TQDqCxI=
|
||||
github.com/go-ole/go-ole v1.2.4/go.mod h1:XCwSNxSkXRo4vlyPy93sltvi/qJq0jqQhjqQNIwKuxM=
|
||||
github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
|
||||
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
|
||||
github.com/godbus/dbus/v5 v5.0.3 h1:ZqHaoEF7TBzh4jzPmqVhE/5A1z9of6orkAe5uHoAeME=
|
||||
@@ -78,12 +82,6 @@ github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5a
|
||||
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hooklift/assert v0.0.0-20170704181755-9d1defd6d214 h1:WgfvpuKg42WVLkxNwzfFraXkTXPK36bMqXvMFN67clI=
|
||||
github.com/hooklift/assert v0.0.0-20170704181755-9d1defd6d214/go.mod h1:kj6hFWqfwSjFjLnYW5PK1DoxZ4O0uapwHRmd9jhln4E=
|
||||
github.com/jackmordaunt/icns v0.0.0-20181231085925-4f16af745526/go.mod h1:UQkeMHVoNcyXYq9otUupF7/h/2tmHlhrS2zw7ZVvUqc=
|
||||
@@ -107,13 +105,6 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
|
||||
github.com/lucor/goinfo v0.0.0-20200401173949-526b5363a13a/go.mod h1:ORP3/rB5IsulLEBwQZCJyyV6niqmI7P4EWSmkug+1Ng=
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4=
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=
|
||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
|
||||
@@ -121,24 +112,16 @@ github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLA
|
||||
github.com/panjf2000/ants/v2 v2.4.2 h1:kesjjo8JipN3vNNg1XaiXaeSs6xJweBTgenkBtsrHf8=
|
||||
github.com/panjf2000/ants/v2 v2.4.2/go.mod h1:f6F0NZVFsGCp5A7QW/Zj/m92atWwOkY0OIhFxRNFr4A=
|
||||
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
|
||||
github.com/pires/go-proxyproto v0.8.0 h1:5unRmEAPbHXHuLjDg01CxJWf91cw3lKHc/0xzKpXEe0=
|
||||
github.com/pires/go-proxyproto v0.8.0/go.mod h1:iknsfgnH8EkjrMeMyvfKByp9TiBZCKZM0jx2xmKqnVY=
|
||||
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw=
|
||||
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
|
||||
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo=
|
||||
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg=
|
||||
github.com/shirou/gopsutil/v3 v3.23.10 h1:/N42opWlYzegYaVkWejXWJpbzKv2JDy3mrgGzKsh9hM=
|
||||
github.com/shirou/gopsutil/v3 v3.23.10/go.mod h1:JIE26kpucQi+innVlAUnIEOSBhBUkirr5b44yr55+WE=
|
||||
github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM=
|
||||
github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ=
|
||||
github.com/shoenig/test v0.6.4 h1:kVTaSd7WLz5WZ2IaoM0RSzRsUD+m8wRR+5qvntpn4LU=
|
||||
github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k=
|
||||
github.com/shirou/gopsutil/v3 v3.21.3 h1:wgcdAHZS2H6qy4JFewVTtqfiYxFzCeEJod/mLztdPG8=
|
||||
github.com/shirou/gopsutil/v3 v3.21.3/go.mod h1:ghfMypLDrFSWN2c9cDYFLHyynQ+QUht0cv/18ZqVczw=
|
||||
github.com/siddontang/go v0.0.0-20180604090527-bdc77568d726/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw=
|
||||
github.com/siddontang/ledisdb v0.0.0-20181029004158-becf5f38d373/go.mod h1:mF1DpOSOUiJRMR+FDqaqu3EBqrybQtrDDszLUZ6oxPg=
|
||||
github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA=
|
||||
@@ -150,15 +133,11 @@ github.com/srwiley/rasterx v0.0.0-20200120212402-85cb7272f5e9 h1:m59mIOBO4kfcNCE
|
||||
github.com/srwiley/rasterx v0.0.0-20200120212402-85cb7272f5e9/go.mod h1:mvWM0+15UqyrFKqdRjY6LuAVJR0HOVhJlEgZ5JWtSWU=
|
||||
github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0=
|
||||
github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161 h1:89CEmDvlq/F7SJEOqkIdNDGJXrQIhuIx9D2DBXjavSU=
|
||||
github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161/go.mod h1:wM7WEvslTq+iOEAMDLSzhVuOt5BRZ05WirO+b09GHQU=
|
||||
@@ -166,10 +145,10 @@ github.com/templexxx/xor v0.0.0-20191217153810-f85b25db303b h1:fj5tQ8acgNUr6O8LE
|
||||
github.com/templexxx/xor v0.0.0-20191217153810-f85b25db303b/go.mod h1:5XA7W9S6mni3h5uvOC75dA3m9CCCaS83lltmc0ukdi4=
|
||||
github.com/tjfoc/gmsm v1.4.0 h1:8nbaiZG+iVdh+fXVw0DZoZZa7a4TGm3Qab+xdrdzj8s=
|
||||
github.com/tjfoc/gmsm v1.4.0/go.mod h1:j4INPkHWMrhJb38G+J6W4Tw0AbuN8Thu3PbdVYhVcTE=
|
||||
github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU=
|
||||
github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI=
|
||||
github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk=
|
||||
github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY=
|
||||
github.com/tklauser/go-sysconf v0.3.4 h1:HT8SVixZd3IzLdfs/xlpq0jeSfTX57g1v6wB1EuzV7M=
|
||||
github.com/tklauser/go-sysconf v0.3.4/go.mod h1:Cl2c8ZRWfHD5IrfHo9VN+FX9kCFjIOyVklgXycLB6ek=
|
||||
github.com/tklauser/numcpus v0.2.1 h1:ct88eFm+Q7m2ZfXJdan1xYoXKlmwsfP+k88q05KvlZc=
|
||||
github.com/tklauser/numcpus v0.2.1/go.mod h1:9aU+wOc6WjUIZEwWMP62PL/41d65P+iks1gBkr4QyP8=
|
||||
github.com/ulikunitz/xz v0.5.6 h1:jGHAfXawEGZQ3blwU5wnWKQJvAraT7Ftq9EXjnXYgt8=
|
||||
github.com/ulikunitz/xz v0.5.6/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8=
|
||||
github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc=
|
||||
@@ -178,15 +157,13 @@ github.com/xtaci/kcp-go v5.4.20+incompatible/go.mod h1:bN6vIwHQbfHaHtFpEssmWsN45
|
||||
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae h1:J0GxkO96kL4WF+AIT3M4mfUVinOCPgf2uUWYFUzN0sM=
|
||||
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae/go.mod h1:gXtu8J62kEgmN++bm9BVICuT/e8yiLI2KFobd/TRFsE=
|
||||
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yusufpapurcu/wmi v1.2.3 h1:E1ctvB7uKFMOJw3fdOW32DwGE9I7t++CRUEMKvFoFiw=
|
||||
github.com/yusufpapurcu/wmi v1.2.3/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
|
||||
golang.org/x/crypto v0.0.0-20181127143415-eb0de9b17e85/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA=
|
||||
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
|
||||
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 h1:It14KIkyBFYkHkwZ7k45minvA9aorojkyjGk9KJ5B/w=
|
||||
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
golang.org/x/image v0.0.0-20200430140353-33d19683fad8 h1:6WW6V3x1P/jokJBpRQYUJnMHRP6isStQwCozxnU7XQw=
|
||||
@@ -205,8 +182,9 @@ golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLL
|
||||
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
|
||||
golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs=
|
||||
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 h1:4nGaVu0QrbjT/AK2PRLuQfQuh6DJve+pELhqTdAj3x0=
|
||||
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
@@ -215,27 +193,21 @@ golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJ
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200720211630-cb9d2d5c5666/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
|
||||
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210217105451-b926d437f341/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57 h1:F5Gozwx4I1xtr/sr/8CFbb57iKi3297KFs0QDbGN60A=
|
||||
golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
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=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
|
||||
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
|
||||
@@ -269,8 +241,7 @@ gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
|
||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="org.nps.client"
|
||||
android:versionCode="1"
|
||||
android:versionName="0.26.10">
|
||||
android:versionName="100.26.10">
|
||||
|
||||
<application android:label="Npc" android:debuggable="true">
|
||||
<activity android:name="org.golang.app.GoNativeActivity"
|
||||
|
||||
|
Before Width: | Height: | Size: 156 KiB |
|
Before Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 72 KiB |
|
Before Width: | Height: | Size: 119 KiB |
|
Before Width: | Height: | Size: 132 KiB |
|
Before Width: | Height: | Size: 34 KiB |
|
Before Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 166 KiB |
|
Before Width: | Height: | Size: 23 KiB |
|
Before Width: | Height: | Size: 26 KiB |
|
Before Width: | Height: | Size: 61 KiB |
@@ -34,8 +34,5 @@ WWW-Authenticate: Basic realm="easyProxy"
|
||||
401 Unauthorized`
|
||||
ConnectionFailBytes = `HTTP/1.1 404 Not Found
|
||||
|
||||
`
|
||||
Unauthorized = `HTTP/1.1 401 Unauthorized
|
||||
|
||||
`
|
||||
)
|
||||
|
||||
@@ -6,50 +6,29 @@ import (
|
||||
"runtime"
|
||||
)
|
||||
|
||||
var ConfPath string
|
||||
|
||||
// Get the currently selected configuration file directory
|
||||
// For non-Windows systems, select the /etc/nps as config directory if exist, or select ./
|
||||
// windows system, select the C:\Program Files\nps as config directory if exist, or select ./
|
||||
//Get the currently selected configuration file directory
|
||||
//For non-Windows systems, select the /etc/nps as config directory if exist, or select ./
|
||||
//windows system, select the C:\Program Files\nps as config directory if exist, or select ./
|
||||
func GetRunPath() string {
|
||||
if ConfPath != "" {
|
||||
return ConfPath
|
||||
}
|
||||
|
||||
var path string
|
||||
if len(os.Args) == 1 {
|
||||
if !IsWindows() {
|
||||
dir, _ := filepath.Abs(filepath.Dir(os.Args[0])) //返回
|
||||
return dir + "/"
|
||||
} else {
|
||||
return "./"
|
||||
}
|
||||
} else {
|
||||
if path = GetInstallPath(); !FileExists(path) {
|
||||
return GetAppPath()
|
||||
}
|
||||
if path = GetInstallPath(); !FileExists(path) {
|
||||
return GetAppPath()
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// Different systems get different installation paths
|
||||
//Different systems get different installation paths
|
||||
func GetInstallPath() string {
|
||||
var path string
|
||||
|
||||
if ConfPath != "" {
|
||||
return ConfPath
|
||||
}
|
||||
|
||||
if IsWindows() {
|
||||
path = `C:\Program Files\nps`
|
||||
} else {
|
||||
path = "/etc/nps"
|
||||
}
|
||||
|
||||
return path
|
||||
}
|
||||
|
||||
// Get the absolute path to the running directory
|
||||
//Get the absolute path to the running directory
|
||||
func GetAppPath() string {
|
||||
if path, err := filepath.Abs(filepath.Dir(os.Args[0])); err == nil {
|
||||
return path
|
||||
@@ -57,7 +36,7 @@ func GetAppPath() string {
|
||||
return os.Args[0]
|
||||
}
|
||||
|
||||
// Determine whether the current system is a Windows system?
|
||||
//Determine whether the current system is a Windows system?
|
||||
func IsWindows() bool {
|
||||
if runtime.GOOS == "windows" {
|
||||
return true
|
||||
@@ -65,7 +44,7 @@ func IsWindows() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// interface log file path
|
||||
//interface log file path
|
||||
func GetLogPath() string {
|
||||
var path string
|
||||
if IsWindows() {
|
||||
@@ -76,13 +55,7 @@ func GetLogPath() string {
|
||||
return path
|
||||
}
|
||||
|
||||
func GetLogPathCurrentPath() string {
|
||||
var path string
|
||||
path = filepath.Join(GetAppPath(), "nps.log")
|
||||
return path
|
||||
}
|
||||
|
||||
// interface npc log file path
|
||||
//interface npc log file path
|
||||
func GetNpcLogPath() string {
|
||||
var path string
|
||||
if IsWindows() {
|
||||
@@ -93,7 +66,7 @@ func GetNpcLogPath() string {
|
||||
return path
|
||||
}
|
||||
|
||||
// interface pid file path
|
||||
//interface pid file path
|
||||
func GetTmpPath() string {
|
||||
var path string
|
||||
if IsWindows() {
|
||||
@@ -104,7 +77,7 @@ func GetTmpPath() string {
|
||||
return path
|
||||
}
|
||||
|
||||
// config file path
|
||||
//config file path
|
||||
func GetConfigPath() string {
|
||||
var path string
|
||||
if IsWindows() {
|
||||
|
||||
@@ -7,8 +7,6 @@ import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/astaxie/beego/logs"
|
||||
"html/template"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
@@ -16,7 +14,6 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -24,7 +21,7 @@ import (
|
||||
"ehang.io/nps/lib/crypt"
|
||||
)
|
||||
|
||||
// Get the corresponding IP address through domain name
|
||||
//Get the corresponding IP address through domain name
|
||||
func GetHostByName(hostname string) string {
|
||||
if !DomainCheck(hostname) {
|
||||
return hostname
|
||||
@@ -40,7 +37,7 @@ func GetHostByName(hostname string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Check the legality of domain
|
||||
//Check the legality of domain
|
||||
func DomainCheck(domain string) bool {
|
||||
var match bool
|
||||
IsLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}(/)"
|
||||
@@ -52,7 +49,7 @@ func DomainCheck(domain string) bool {
|
||||
return match
|
||||
}
|
||||
|
||||
// Check if the Request request is validated
|
||||
//Check if the Request request is validated
|
||||
func CheckAuth(r *http.Request, user, passwd string) bool {
|
||||
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
|
||||
if len(s) != 2 {
|
||||
@@ -74,7 +71,7 @@ func CheckAuth(r *http.Request, user, passwd string) bool {
|
||||
return pair[0] == user && pair[1] == passwd
|
||||
}
|
||||
|
||||
// get bool by str
|
||||
//get bool by str
|
||||
func GetBoolByStr(s string) bool {
|
||||
switch s {
|
||||
case "1", "true":
|
||||
@@ -83,7 +80,7 @@ func GetBoolByStr(s string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// get str by bool
|
||||
//get str by bool
|
||||
func GetStrByBool(b bool) string {
|
||||
if b {
|
||||
return "1"
|
||||
@@ -91,19 +88,19 @@ func GetStrByBool(b bool) string {
|
||||
return "0"
|
||||
}
|
||||
|
||||
// int
|
||||
//int
|
||||
func GetIntNoErrByStr(str string) int {
|
||||
i, _ := strconv.Atoi(strings.TrimSpace(str))
|
||||
return i
|
||||
}
|
||||
|
||||
// Get verify value
|
||||
//Get verify value
|
||||
func Getverifyval(vkey string) string {
|
||||
return crypt.Md5(vkey)
|
||||
}
|
||||
|
||||
// Change headers and host of request
|
||||
func ChangeHostAndHeader(r *http.Request, host string, header string, addr string) {
|
||||
//Change headers and host of request
|
||||
func ChangeHostAndHeader(r *http.Request, host string, header string, addr string, addOrigin bool) {
|
||||
if host != "" {
|
||||
r.Host = host
|
||||
}
|
||||
@@ -120,17 +117,13 @@ func ChangeHostAndHeader(r *http.Request, host string, header string, addr strin
|
||||
if prior, ok := r.Header["X-Forwarded-For"]; ok {
|
||||
addr = strings.Join(prior, ", ") + ", " + addr
|
||||
}
|
||||
|
||||
addOrigin, _ := beego.AppConfig.Bool("http_add_origin_header")
|
||||
|
||||
if addOrigin {
|
||||
logs.Debug("set X-Forwarded-For X-Real-IP = " + addr)
|
||||
r.Header.Set("X-Forwarded-For", addr)
|
||||
r.Header.Set("X-Real-IP", addr)
|
||||
}
|
||||
}
|
||||
|
||||
// Read file content by file path
|
||||
//Read file content by file path
|
||||
func ReadAllFromFile(filePath string) ([]byte, error) {
|
||||
f, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
@@ -150,7 +143,7 @@ func FileExists(name string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Judge whether the TCP port can open normally
|
||||
//Judge whether the TCP port can open normally
|
||||
func TestTcpPort(port int) bool {
|
||||
l, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), port, ""})
|
||||
defer func() {
|
||||
@@ -164,7 +157,7 @@ func TestTcpPort(port int) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Judge whether the UDP port can open normally
|
||||
//Judge whether the UDP port can open normally
|
||||
func TestUdpPort(port int) bool {
|
||||
l, err := net.ListenUDP("udp", &net.UDPAddr{net.ParseIP("0.0.0.0"), port, ""})
|
||||
defer func() {
|
||||
@@ -178,9 +171,9 @@ func TestUdpPort(port int) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Write length and individual byte data
|
||||
// Length prevents sticking
|
||||
// # Characters are used to separate data
|
||||
//Write length and individual byte data
|
||||
//Length prevents sticking
|
||||
//# Characters are used to separate data
|
||||
func BinaryWrite(raw *bytes.Buffer, v ...string) {
|
||||
b := GetWriteStr(v...)
|
||||
binary.Write(raw, binary.LittleEndian, int32(len(b)))
|
||||
@@ -199,7 +192,7 @@ func GetWriteStr(v ...string) []byte {
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
// inArray str interface
|
||||
//inArray str interface
|
||||
func InStrArr(arr []string, val string) bool {
|
||||
for _, v := range arr {
|
||||
if v == val {
|
||||
@@ -209,7 +202,7 @@ func InStrArr(arr []string, val string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// inArray int interface
|
||||
//inArray int interface
|
||||
func InIntArr(arr []int, val int) bool {
|
||||
for _, v := range arr {
|
||||
if v == val {
|
||||
@@ -219,7 +212,7 @@ func InIntArr(arr []int, val int) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// format ports str to a int array
|
||||
//format ports str to a int array
|
||||
func GetPorts(p string) []int {
|
||||
var ps []int
|
||||
arr := strings.Split(p, ",")
|
||||
@@ -243,7 +236,7 @@ func GetPorts(p string) []int {
|
||||
return ps
|
||||
}
|
||||
|
||||
// is the string a port
|
||||
//is the string a port
|
||||
func IsPort(p string) bool {
|
||||
pi, err := strconv.Atoi(p)
|
||||
if err != nil {
|
||||
@@ -255,7 +248,7 @@ func IsPort(p string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// if the s is just a port,return 127.0.0.1:s
|
||||
//if the s is just a port,return 127.0.0.1:s
|
||||
func FormatAddress(s string) string {
|
||||
if strings.Contains(s, ":") {
|
||||
return s
|
||||
@@ -263,21 +256,13 @@ func FormatAddress(s string) string {
|
||||
return "127.0.0.1:" + s
|
||||
}
|
||||
|
||||
// get address from the complete address
|
||||
//get address from the complete address
|
||||
func GetIpByAddr(addr string) string {
|
||||
// 如果是 IPv6 地址,可能的格式为[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:8080或[2001:0db8:85a3:0000:0000:8a2e:0370:7334]
|
||||
// IPv4 地址,可能的格式为192.168.1.1:80或192.168.1.1
|
||||
// 截取地址
|
||||
if strings.Contains(addr, "[") {
|
||||
addr = strings.Split(addr, "[")[1]
|
||||
addr = strings.Split(addr, "]")[0]
|
||||
} else {
|
||||
addr = strings.Split(addr, ":")[0]
|
||||
}
|
||||
return addr
|
||||
arr := strings.Split(addr, ":")
|
||||
return arr[0]
|
||||
}
|
||||
|
||||
// get port from the complete address
|
||||
//get port from the complete address
|
||||
func GetPortByAddr(addr string) int {
|
||||
arr := strings.Split(addr, ":")
|
||||
if len(arr) < 2 {
|
||||
@@ -290,37 +275,6 @@ func GetPortByAddr(addr string) int {
|
||||
return p
|
||||
}
|
||||
|
||||
func in(target string, str_array []string) bool {
|
||||
sort.Strings(str_array)
|
||||
index := sort.SearchStrings(str_array, target)
|
||||
if index < len(str_array) && str_array[index] == target {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// 判断访问地址是否在黑名单内
|
||||
func IsBlackIp(ipPort, vkey string, blackIpList []string) bool {
|
||||
ip := GetIpByAddr(ipPort)
|
||||
if in(ip, blackIpList) {
|
||||
logs.Error("IP地址[" + ip + "]在隧道[" + vkey + "]黑名单列表内")
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// 判断访问地址是否在白名单内
|
||||
func IsAuthIp(ipPort, vkey string, authIpList []string) bool {
|
||||
ip := GetIpByAddr(ipPort)
|
||||
|
||||
if in(ip, authIpList) {
|
||||
return false
|
||||
}
|
||||
logs.Error("IP地址[" + ip + "]不在隧道[" + vkey + "]白名单列表内")
|
||||
return true
|
||||
}
|
||||
|
||||
func CopyBuffer(dst io.Writer, src io.Reader, label ...string) (written int64, err error) {
|
||||
buf := CopyBuff.Get()
|
||||
defer CopyBuff.Put(buf)
|
||||
@@ -351,7 +305,7 @@ func CopyBuffer(dst io.Writer, src io.Reader, label ...string) (written int64, e
|
||||
return written, err
|
||||
}
|
||||
|
||||
// send this ip forget to get a local udp port
|
||||
//send this ip forget to get a local udp port
|
||||
func GetLocalUdpAddr() (net.Conn, error) {
|
||||
tmpConn, err := net.Dial("udp", "114.114.114.114:53")
|
||||
if err != nil {
|
||||
@@ -360,7 +314,7 @@ func GetLocalUdpAddr() (net.Conn, error) {
|
||||
return tmpConn, tmpConn.Close()
|
||||
}
|
||||
|
||||
// parse template
|
||||
//parse template
|
||||
func ParseStr(str string) (string, error) {
|
||||
tmp := template.New("npc")
|
||||
var err error
|
||||
@@ -374,7 +328,7 @@ func ParseStr(str string) (string, error) {
|
||||
return w.String(), nil
|
||||
}
|
||||
|
||||
// get env
|
||||
//get env
|
||||
func GetEnvMap() map[string]string {
|
||||
m := make(map[string]string)
|
||||
environ := os.Environ()
|
||||
@@ -387,7 +341,7 @@ func GetEnvMap() map[string]string {
|
||||
return m
|
||||
}
|
||||
|
||||
// throw the empty element of the string array
|
||||
//throw the empty element of the string array
|
||||
func TrimArr(arr []string) []string {
|
||||
newArr := make([]string, 0)
|
||||
for _, v := range arr {
|
||||
@@ -398,6 +352,7 @@ func TrimArr(arr []string) []string {
|
||||
return newArr
|
||||
}
|
||||
|
||||
//
|
||||
func IsArrContains(arr []string, val string) bool {
|
||||
if arr == nil {
|
||||
return false
|
||||
@@ -410,7 +365,7 @@ func IsArrContains(arr []string, val string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// remove value from string array
|
||||
//remove value from string array
|
||||
func RemoveArrVal(arr []string, val string) []string {
|
||||
for k, v := range arr {
|
||||
if v == val {
|
||||
@@ -421,7 +376,7 @@ func RemoveArrVal(arr []string, val string) []string {
|
||||
return arr
|
||||
}
|
||||
|
||||
// convert bytes to num
|
||||
//convert bytes to num
|
||||
func BytesToNum(b []byte) int {
|
||||
var str string
|
||||
for i := 0; i < len(b); i++ {
|
||||
@@ -431,7 +386,7 @@ func BytesToNum(b []byte) int {
|
||||
return int(x)
|
||||
}
|
||||
|
||||
// get the length of the sync map
|
||||
//get the length of the sync map
|
||||
func GeSynctMapLen(m sync.Map) int {
|
||||
var c int
|
||||
m.Range(func(key, value interface{}) bool {
|
||||
|
||||
@@ -15,7 +15,6 @@ type CommonConfig struct {
|
||||
VKey string
|
||||
Tp string //bridgeType kcp or tcp
|
||||
AutoReconnection bool
|
||||
TlsEnable bool
|
||||
ProxyUrl string
|
||||
Client *file.Client
|
||||
DisconnectTime int
|
||||
@@ -151,8 +150,6 @@ func dealCommon(s string) *CommonConfig {
|
||||
common.InitPProfFromArg(item[1])
|
||||
case "disconnect_timeout":
|
||||
c.DisconnectTime = common.GetIntNoErrByStr(item[1])
|
||||
case "tls_enable":
|
||||
c.TlsEnable = common.GetBoolByStr(item[1])
|
||||
}
|
||||
}
|
||||
return c
|
||||
|
||||
@@ -373,8 +373,7 @@ func SetUdpSession(sess *kcp.UDPSession) {
|
||||
}
|
||||
|
||||
//conn1 mux conn
|
||||
func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Rate,
|
||||
flow *file.Flow, isServer bool, rb []byte, task *file.Tunnel) {
|
||||
func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Rate, flow *file.Flow, isServer bool, rb []byte) {
|
||||
//var in, out int64
|
||||
//var wg sync.WaitGroup
|
||||
connHandle := GetConn(conn1, crypt, snappy, rate, isServer)
|
||||
@@ -397,7 +396,7 @@ func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Ra
|
||||
//}
|
||||
wg := new(sync.WaitGroup)
|
||||
wg.Add(1)
|
||||
err := goroutine.CopyConnsPool.Invoke(goroutine.NewConns(connHandle, conn2, flow, wg, task))
|
||||
err := goroutine.CopyConnsPool.Invoke(goroutine.NewConns(connHandle, conn2, flow, wg))
|
||||
wg.Wait()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
|
||||
@@ -15,14 +15,13 @@ func NewSecret(p string, conn *Conn) *Secret {
|
||||
}
|
||||
|
||||
type Link struct {
|
||||
ConnType string //连接类型
|
||||
Host string //目标
|
||||
Crypt bool //加密
|
||||
Compress bool
|
||||
LocalProxy bool
|
||||
RemoteAddr string
|
||||
ProtoVersion string
|
||||
Option Options
|
||||
ConnType string //连接类型
|
||||
Host string //目标
|
||||
Crypt bool //加密
|
||||
Compress bool
|
||||
LocalProxy bool
|
||||
RemoteAddr string
|
||||
Option Options
|
||||
}
|
||||
|
||||
type Option func(*Options)
|
||||
@@ -33,18 +32,17 @@ type Options struct {
|
||||
|
||||
var defaultTimeOut = time.Second * 5
|
||||
|
||||
func NewLink(connType string, host string, crypt bool, compress bool, remoteAddr string, localProxy bool, protoVersion string, opts ...Option) *Link {
|
||||
func NewLink(connType string, host string, crypt bool, compress bool, remoteAddr string, localProxy bool, opts ...Option) *Link {
|
||||
options := newOptions(opts...)
|
||||
|
||||
return &Link{
|
||||
RemoteAddr: remoteAddr,
|
||||
ConnType: connType,
|
||||
Host: host,
|
||||
Crypt: crypt,
|
||||
Compress: compress,
|
||||
LocalProxy: localProxy,
|
||||
ProtoVersion: protoVersion,
|
||||
Option: options,
|
||||
RemoteAddr: remoteAddr,
|
||||
ConnType: connType,
|
||||
Host: host,
|
||||
Crypt: crypt,
|
||||
Compress: compress,
|
||||
LocalProxy: localProxy,
|
||||
Option: options,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,16 +5,13 @@ import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"math/rand"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// en
|
||||
//en
|
||||
func AesEncrypt(origData, key []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
@@ -28,7 +25,7 @@ func AesEncrypt(origData, key []byte) ([]byte, error) {
|
||||
return crypted, nil
|
||||
}
|
||||
|
||||
// de
|
||||
//de
|
||||
func AesDecrypt(crypted, key []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
@@ -42,14 +39,14 @@ func AesDecrypt(crypted, key []byte) ([]byte, error) {
|
||||
return origData, err
|
||||
}
|
||||
|
||||
// Completion when the length is insufficient
|
||||
//Completion when the length is insufficient
|
||||
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
|
||||
padding := blockSize - len(ciphertext)%blockSize
|
||||
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
|
||||
return append(ciphertext, padtext...)
|
||||
}
|
||||
|
||||
// Remove excess
|
||||
//Remove excess
|
||||
func PKCS5UnPadding(origData []byte) (error, []byte) {
|
||||
length := len(origData)
|
||||
unpadding := int(origData[length-1])
|
||||
@@ -59,14 +56,14 @@ func PKCS5UnPadding(origData []byte) (error, []byte) {
|
||||
return nil, origData[:(length - unpadding)]
|
||||
}
|
||||
|
||||
// Generate 32-bit MD5 strings
|
||||
//Generate 32-bit MD5 strings
|
||||
func Md5(s string) string {
|
||||
h := md5.New()
|
||||
h.Write([]byte(s))
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
// Generating Random Verification Key
|
||||
//Generating Random Verification Key
|
||||
func GetRandomString(l int) string {
|
||||
str := "0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
bytes := []byte(str)
|
||||
@@ -77,32 +74,3 @@ func GetRandomString(l int) string {
|
||||
}
|
||||
return string(result)
|
||||
}
|
||||
|
||||
func GetVkey() string {
|
||||
// 生成UUID
|
||||
u, _ := uuid.NewRandom()
|
||||
// 将UUID转换为字符串
|
||||
uuidStr := u.String()
|
||||
uuidStr = strings.ReplaceAll(uuidStr, "-", "")
|
||||
// 截取前10位
|
||||
return uuidStr[:10]
|
||||
}
|
||||
|
||||
func Base64Decoding(encodedString string) (string, error) {
|
||||
decodedBytes, err := base64.StdEncoding.DecodeString(encodedString)
|
||||
if err != nil {
|
||||
// 处理解码错误
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 将解码后的字节数组转换为字符串
|
||||
decodedString := string(decodedBytes)
|
||||
|
||||
// 如果startCmd开头不包含"nps ",则报错
|
||||
if len(decodedString) < 4 || !(decodedString[0:4] == "nps ") {
|
||||
return "", errors.New("快捷启动命令错误,请检查")
|
||||
}
|
||||
|
||||
return decodedString[4:], nil
|
||||
|
||||
}
|
||||
|
||||
@@ -30,10 +30,6 @@ func InitTls() {
|
||||
}
|
||||
}
|
||||
|
||||
func GetCert() tls.Certificate {
|
||||
return cert
|
||||
}
|
||||
|
||||
func NewTlsServerConn(conn net.Conn) net.Conn {
|
||||
var err error
|
||||
if err != nil {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
@@ -23,14 +22,13 @@ var (
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
// init csv from file
|
||||
//init csv from file
|
||||
func GetDb() *DbUtils {
|
||||
once.Do(func() {
|
||||
jsonDb := NewJsonDb(common.GetRunPath())
|
||||
jsonDb.LoadClientFromJsonFile()
|
||||
jsonDb.LoadTaskFromJsonFile()
|
||||
jsonDb.LoadHostFromJsonFile()
|
||||
jsonDb.LoadGlobalFromJsonFile()
|
||||
Db = &DbUtils{JsonDb: jsonDb}
|
||||
})
|
||||
return Db
|
||||
@@ -117,19 +115,13 @@ func (s *DbUtils) UpdateTask(t *Tunnel) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *DbUtils) SaveGlobal(t *Glob) error {
|
||||
s.JsonDb.Global = t
|
||||
s.JsonDb.StoreGlobalToJsonFile()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *DbUtils) DelTask(id int) error {
|
||||
s.JsonDb.Tasks.Delete(id)
|
||||
s.JsonDb.StoreTasksToJsonFile()
|
||||
return nil
|
||||
}
|
||||
|
||||
// md5 password
|
||||
//md5 password
|
||||
func (s *DbUtils) GetTaskByMd5Password(p string) (t *Tunnel) {
|
||||
s.JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
if crypt.Md5(value.(*Tunnel).Password) == p {
|
||||
@@ -189,7 +181,7 @@ func (s *DbUtils) GetHost(start, length int, id int, search string) ([]*Host, in
|
||||
for _, key := range keys {
|
||||
if value, ok := s.JsonDb.Hosts.Load(key); ok {
|
||||
v := value.(*Host)
|
||||
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.Host, search) || strings.Contains(v.Remark, search) || strings.Contains(v.Client.VerifyKey, search)) {
|
||||
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.Host, search) || strings.Contains(v.Remark, search)) {
|
||||
continue
|
||||
}
|
||||
if id == 0 || v.Client.Id == id {
|
||||
@@ -219,10 +211,10 @@ func (s *DbUtils) NewClient(c *Client) error {
|
||||
reset:
|
||||
if c.VerifyKey == "" || isNotSet {
|
||||
isNotSet = true
|
||||
c.VerifyKey = crypt.GetVkey()
|
||||
c.VerifyKey = crypt.GetRandomString(16)
|
||||
}
|
||||
if c.RateLimit == 0 {
|
||||
c.Rate = rate.NewRate((2 << 23) * 1024)
|
||||
c.Rate = rate.NewRate(int64(2 << 23))
|
||||
} else if c.Rate == nil {
|
||||
c.Rate = rate.NewRate(int64(c.RateLimit * 1024))
|
||||
}
|
||||
@@ -273,7 +265,7 @@ func (s *DbUtils) VerifyUserName(username string, id int) (res bool) {
|
||||
func (s *DbUtils) UpdateClient(t *Client) error {
|
||||
s.JsonDb.Clients.Store(t.Id, t)
|
||||
if t.RateLimit == 0 {
|
||||
t.Rate = rate.NewRate(0)
|
||||
t.Rate = rate.NewRate(int64(2 << 23))
|
||||
t.Rate.Start()
|
||||
}
|
||||
return nil
|
||||
@@ -296,10 +288,6 @@ func (s *DbUtils) GetClient(id int) (c *Client, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (s *DbUtils) GetGlobal() (c *Glob) {
|
||||
return s.JsonDb.Global
|
||||
}
|
||||
|
||||
func (s *DbUtils) GetClientIdByVkey(vkey string) (id int, err error) {
|
||||
var exist bool
|
||||
s.JsonDb.Clients.Range(func(key, value interface{}) bool {
|
||||
@@ -318,24 +306,6 @@ func (s *DbUtils) GetClientIdByVkey(vkey string) (id int, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (s *DbUtils) GetClientByVkey(vkey string) (c *Client, err error) {
|
||||
var exist bool
|
||||
s.JsonDb.Clients.Range(func(key, value interface{}) bool {
|
||||
v := value.(*Client)
|
||||
if fmt.Sprintf("%x", md5.Sum([]byte(v.VerifyKey))) == vkey {
|
||||
exist = true
|
||||
c = v
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
if exist {
|
||||
return
|
||||
}
|
||||
err = errors.New("未找到客户端")
|
||||
return
|
||||
}
|
||||
|
||||
func (s *DbUtils) GetHostById(id int) (h *Host, err error) {
|
||||
if v, ok := s.JsonDb.Hosts.Load(id); ok {
|
||||
h = v.(*Host)
|
||||
@@ -345,7 +315,7 @@ func (s *DbUtils) GetHostById(id int) (h *Host, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// get key by host from x
|
||||
//get key by host from x
|
||||
func (s *DbUtils) GetInfoByHost(host string, r *http.Request) (h *Host, err error) {
|
||||
var hosts []*Host
|
||||
//Handling Ported Access
|
||||
|
||||
@@ -20,7 +20,6 @@ func NewJsonDb(runPath string) *JsonDb {
|
||||
TaskFilePath: filepath.Join(runPath, "conf", "tasks.json"),
|
||||
HostFilePath: filepath.Join(runPath, "conf", "hosts.json"),
|
||||
ClientFilePath: filepath.Join(runPath, "conf", "clients.json"),
|
||||
GlobalFilePath: filepath.Join(runPath, "conf", "global.json"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +28,6 @@ type JsonDb struct {
|
||||
Hosts sync.Map
|
||||
HostsTmp sync.Map
|
||||
Clients sync.Map
|
||||
Global *Glob
|
||||
RunPath string
|
||||
ClientIncreaseId int32 //client increased id
|
||||
TaskIncreaseId int32 //task increased id
|
||||
@@ -37,7 +35,6 @@ type JsonDb struct {
|
||||
TaskFilePath string //task file path
|
||||
HostFilePath string //host file path
|
||||
ClientFilePath string //client file path
|
||||
GlobalFilePath string //global file path
|
||||
}
|
||||
|
||||
func (s *JsonDb) LoadTaskFromJsonFile() {
|
||||
@@ -66,7 +63,7 @@ func (s *JsonDb) LoadClientFromJsonFile() {
|
||||
if post.RateLimit > 0 {
|
||||
post.Rate = rate.NewRate(int64(post.RateLimit * 1024))
|
||||
} else {
|
||||
post.Rate = rate.NewRate((2 << 23) * 1024)
|
||||
post.Rate = rate.NewRate(int64(2 << 23))
|
||||
}
|
||||
post.Rate.Start()
|
||||
post.NowConn = 0
|
||||
@@ -94,16 +91,6 @@ func (s *JsonDb) LoadHostFromJsonFile() {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *JsonDb) LoadGlobalFromJsonFile() {
|
||||
loadSyncMapFromFileWithSingleJson(s.GlobalFilePath, func(v string) {
|
||||
post := new(Glob)
|
||||
if json.Unmarshal([]byte(v), &post) != nil {
|
||||
return
|
||||
}
|
||||
s.Global = post
|
||||
})
|
||||
}
|
||||
|
||||
func (s *JsonDb) GetClient(id int) (c *Client, err error) {
|
||||
if v, ok := s.Clients.Load(id); ok {
|
||||
c = v.(*Client)
|
||||
@@ -137,14 +124,6 @@ func (s *JsonDb) StoreClientsToJsonFile() {
|
||||
clientLock.Unlock()
|
||||
}
|
||||
|
||||
var globalLock sync.Mutex
|
||||
|
||||
func (s *JsonDb) StoreGlobalToJsonFile() {
|
||||
globalLock.Lock()
|
||||
storeGlobalToFile(s.Global, s.GlobalFilePath)
|
||||
globalLock.Unlock()
|
||||
}
|
||||
|
||||
func (s *JsonDb) GetClientId() int32 {
|
||||
return atomic.AddInt32(&s.ClientIncreaseId, 1)
|
||||
}
|
||||
@@ -167,19 +146,6 @@ func loadSyncMapFromFile(filePath string, f func(value string)) {
|
||||
}
|
||||
}
|
||||
|
||||
func loadSyncMapFromFileWithSingleJson(filePath string, f func(value string)) {
|
||||
if !common.FileExists(filePath) {
|
||||
return
|
||||
}
|
||||
|
||||
b, err := common.ReadAllFromFile(filePath)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
f(string(b))
|
||||
}
|
||||
|
||||
func storeSyncMapToFile(m sync.Map, filePath string) {
|
||||
file, err := os.Create(filePath + ".tmp")
|
||||
// first create a temporary file to store
|
||||
@@ -208,9 +174,6 @@ func storeSyncMapToFile(m sync.Map, filePath string) {
|
||||
return true
|
||||
}
|
||||
b, err = json.Marshal(obj)
|
||||
//case *Glob:
|
||||
// obj := value.(*Glob)
|
||||
// b, err = json.Marshal(obj)
|
||||
default:
|
||||
return true
|
||||
}
|
||||
@@ -236,25 +199,3 @@ func storeSyncMapToFile(m sync.Map, filePath string) {
|
||||
}
|
||||
// replace the file, maybe provides atomic operation
|
||||
}
|
||||
|
||||
func storeGlobalToFile(m *Glob, filePath string) {
|
||||
file, err := os.Create(filePath + ".tmp")
|
||||
// first create a temporary file to store
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
var b []byte
|
||||
b, err = json.Marshal(m)
|
||||
_, err = file.Write(b)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
_ = file.Sync()
|
||||
_ = file.Close()
|
||||
// must close file first, then rename it
|
||||
err = os.Rename(filePath+".tmp", filePath)
|
||||
if err != nil {
|
||||
logs.Error(err, "store to file err, data will lost")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,12 +51,6 @@ type Client struct {
|
||||
ConfigConnAllow bool //is allow connected by config file
|
||||
MaxTunnelNum int
|
||||
Version string
|
||||
BlackIpList []string
|
||||
CreateTime string
|
||||
LastOnlineTime string
|
||||
IpWhite bool // 是否启用ip白名单
|
||||
IpWhitePass string // ip授权密码
|
||||
IpWhiteList []string // ip白名单
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
@@ -114,14 +108,6 @@ func (s *Client) GetTunnelNum() (num int) {
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
GetDb().JsonDb.Hosts.Range(func(key, value interface{}) bool {
|
||||
v := value.(*Host)
|
||||
if v.Client.Id == s.Id {
|
||||
num++
|
||||
}
|
||||
return true
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -154,7 +140,6 @@ type Tunnel struct {
|
||||
NoStore bool
|
||||
LocalPath string
|
||||
StripPre string
|
||||
ProtoVersion string
|
||||
Target *Target
|
||||
MultiAccount *MultiAccount
|
||||
Health
|
||||
@@ -186,7 +171,6 @@ type Host struct {
|
||||
KeyFilePath string
|
||||
NoStore bool
|
||||
IsClose bool
|
||||
AutoHttps bool // 自动https
|
||||
Flow *Flow
|
||||
Client *Client
|
||||
Target *Target //目标
|
||||
@@ -224,9 +208,3 @@ func (s *Target) GetRandomTarget() (string, error) {
|
||||
s.nowIndex++
|
||||
return s.TargetArr[s.nowIndex], nil
|
||||
}
|
||||
|
||||
type Glob struct {
|
||||
BlackIpList []string
|
||||
ServerUrl string
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
@@ -1,171 +1,42 @@
|
||||
package goroutine
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"ehang.io/nps/lib/common"
|
||||
"ehang.io/nps/lib/file"
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/panjf2000/ants/v2"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type connGroup struct {
|
||||
src io.ReadWriteCloser
|
||||
dst io.ReadWriteCloser
|
||||
wg *sync.WaitGroup
|
||||
n *int64
|
||||
flow *file.Flow
|
||||
task *file.Tunnel
|
||||
remote string
|
||||
src io.ReadWriteCloser
|
||||
dst io.ReadWriteCloser
|
||||
wg *sync.WaitGroup
|
||||
n *int64
|
||||
}
|
||||
|
||||
//func newConnGroup(dst, src io.ReadWriteCloser, wg *sync.WaitGroup, n *int64) connGroup {
|
||||
// return connGroup{
|
||||
// src: src,
|
||||
// dst: dst,
|
||||
// wg: wg,
|
||||
// n: n,
|
||||
// }
|
||||
//}
|
||||
|
||||
func newConnGroup(dst, src io.ReadWriteCloser, wg *sync.WaitGroup, n *int64, flow *file.Flow, task *file.Tunnel, remote string) connGroup {
|
||||
func newConnGroup(dst, src io.ReadWriteCloser, wg *sync.WaitGroup, n *int64) connGroup {
|
||||
return connGroup{
|
||||
src: src,
|
||||
dst: dst,
|
||||
wg: wg,
|
||||
n: n,
|
||||
flow: flow,
|
||||
task: task,
|
||||
remote: remote,
|
||||
src: src,
|
||||
dst: dst,
|
||||
wg: wg,
|
||||
n: n,
|
||||
}
|
||||
}
|
||||
|
||||
func CopyBuffer(dst io.Writer, src io.Reader, flow *file.Flow, task *file.Tunnel, remote string) (err error) {
|
||||
buf := common.CopyBuff.Get()
|
||||
defer common.CopyBuff.Put(buf)
|
||||
for {
|
||||
if len(buf) <= 0 {
|
||||
break
|
||||
}
|
||||
nr, er := src.Read(buf)
|
||||
|
||||
if task != nil {
|
||||
if task.Client.IpWhite && task.Client.IpWhitePass != "" {
|
||||
|
||||
if common.IsAuthIp(remote, task.Client.VerifyKey, task.Client.IpWhiteList) {
|
||||
ip := common.GetIpByAddr(remote)
|
||||
var jsonBytes []byte
|
||||
|
||||
errorContent, _ := common.ReadAllFromFile(filepath.Join(common.GetRunPath(), "web", "static", "page", "auth.html"))
|
||||
authHtml := string(errorContent)
|
||||
authHtml = strings.ReplaceAll(authHtml, "${ip}", ip)
|
||||
|
||||
fullRequest := string(buf[0:nr])
|
||||
// 获取HTTP请求的第一行
|
||||
lines := strings.Split(fullRequest, "\r\n")
|
||||
if len(lines) == 0 {
|
||||
lines = strings.Split(fullRequest, "\n")
|
||||
}
|
||||
firstLine := lines[0]
|
||||
|
||||
// 优先处理客户端直接访问的 POST /authIp 请求,直接响应给客户端,不经隧道转发
|
||||
if strings.HasPrefix(firstLine, "POST /authIp") {
|
||||
pass := ""
|
||||
parts := strings.Split(firstLine, " ")
|
||||
if len(parts) > 1 {
|
||||
path := parts[1]
|
||||
if strings.Contains(path, "/authIp?pass=") {
|
||||
pass = strings.ReplaceAll(path, "/authIp?pass=", "")
|
||||
}
|
||||
}
|
||||
if pass == task.Client.IpWhitePass {
|
||||
task.Client.IpWhiteList = append(task.Client.IpWhiteList, ip)
|
||||
file.GetDb().UpdateClient(task.Client)
|
||||
logs.Info("客户端IP白名单认证授权成功:vkey [%s] ip [%s] password [%s]", task.Client.VerifyKey, ip, pass)
|
||||
jsonBytes, err = json.Marshal(map[string]interface{}{"success": true, "message": "授权成功"})
|
||||
} else {
|
||||
logs.Error("客户端IP白名单认证授权密码错误:vkey [%s] ip [%s] password [%s]", task.Client.VerifyKey, ip, pass)
|
||||
jsonBytes, err = json.Marshal(map[string]interface{}{"success": false, "message": "密码错误"})
|
||||
}
|
||||
response := fmt.Sprintf("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s", len(jsonBytes), jsonBytes)
|
||||
// 如果 src 是真实的客户端连接(net.Conn),直接写回客户端并关闭连接,避免走隧道转发
|
||||
if connSrc, ok := src.(net.Conn); ok {
|
||||
connSrc.Write([]byte(response))
|
||||
connSrc.Close()
|
||||
} else {
|
||||
dst.Write([]byte(response))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 非授权IP,返回授权页面(同样优先返回给客户端)
|
||||
response := fmt.Sprintf("HTTP/1.1 401 Unauthorized\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s", len(authHtml), authHtml)
|
||||
if connSrc, ok := src.(net.Conn); ok {
|
||||
connSrc.Write([]byte(response))
|
||||
connSrc.Close()
|
||||
} else {
|
||||
dst.Write([]byte(response))
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if nr > 0 {
|
||||
nw, ew := dst.Write(buf[0:nr])
|
||||
if nw > 0 {
|
||||
//written += int64(nw)
|
||||
if flow != nil {
|
||||
flow.Add(int64(nw), int64(nw))
|
||||
// <<20 = 1024 * 1024
|
||||
if flow.FlowLimit > 0 && (flow.FlowLimit<<20) < (flow.ExportFlow+flow.InletFlow) {
|
||||
logs.Error("隧道[%s]流量已经超出", task.Client.VerifyKey)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
if ew != nil {
|
||||
err = ew
|
||||
break
|
||||
}
|
||||
if nr != nw {
|
||||
err = io.ErrShortWrite
|
||||
break
|
||||
}
|
||||
}
|
||||
if er != nil {
|
||||
err = er
|
||||
break
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func copyConnGroup(group interface{}) {
|
||||
//logs.Info("copyConnGroup.........")
|
||||
cg, ok := group.(connGroup)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var err error
|
||||
err = CopyBuffer(cg.dst, cg.src, cg.flow, cg.task, cg.remote)
|
||||
*cg.n, err = common.CopyBuffer(cg.dst, cg.src)
|
||||
if err != nil {
|
||||
cg.src.Close()
|
||||
cg.dst.Close()
|
||||
//logs.Warn("close npc by copy from nps", err, c.connId)
|
||||
}
|
||||
|
||||
//if conns.flow != nil {
|
||||
// conns.flow.Add(in, out)
|
||||
//}
|
||||
cg.wg.Done()
|
||||
}
|
||||
|
||||
@@ -174,34 +45,30 @@ type Conns struct {
|
||||
conn2 net.Conn // outside connection
|
||||
flow *file.Flow
|
||||
wg *sync.WaitGroup
|
||||
task *file.Tunnel
|
||||
}
|
||||
|
||||
func NewConns(c1 io.ReadWriteCloser, c2 net.Conn, flow *file.Flow, wg *sync.WaitGroup, task *file.Tunnel) Conns {
|
||||
func NewConns(c1 io.ReadWriteCloser, c2 net.Conn, flow *file.Flow, wg *sync.WaitGroup) Conns {
|
||||
return Conns{
|
||||
conn1: c1,
|
||||
conn2: c2,
|
||||
flow: flow,
|
||||
wg: wg,
|
||||
task: task,
|
||||
}
|
||||
}
|
||||
|
||||
func copyConns(group interface{}) {
|
||||
//logs.Info("copyConns.........")
|
||||
conns := group.(Conns)
|
||||
wg := new(sync.WaitGroup)
|
||||
wg.Add(2)
|
||||
var in, out int64
|
||||
remoteAddr := conns.conn2.RemoteAddr().String()
|
||||
_ = connCopyPool.Invoke(newConnGroup(conns.conn1, conns.conn2, wg, &in, conns.flow, conns.task, remoteAddr))
|
||||
_ = connCopyPool.Invoke(newConnGroup(conns.conn1, conns.conn2, wg, &in))
|
||||
// outside to mux : incoming
|
||||
_ = connCopyPool.Invoke(newConnGroup(conns.conn2, conns.conn1, wg, &out, conns.flow, conns.task, remoteAddr))
|
||||
_ = connCopyPool.Invoke(newConnGroup(conns.conn2, conns.conn1, wg, &out))
|
||||
// mux to outside : outgoing
|
||||
wg.Wait()
|
||||
//if conns.flow != nil {
|
||||
// conns.flow.Add(in, out)
|
||||
//}
|
||||
if conns.flow != nil {
|
||||
conns.flow.Add(in, out)
|
||||
}
|
||||
conns.wg.Done()
|
||||
}
|
||||
|
||||
|
||||
@@ -141,13 +141,6 @@ func UpdateNps() {
|
||||
fmt.Println("Update completed, please restart")
|
||||
}
|
||||
|
||||
func UpdateNpsNew() {
|
||||
destPath := downloadLatest2("server", filepath.Join(common.GetAppPath(), "temp"))
|
||||
//复制文件到对应目录
|
||||
copyStaticFileReplaceNps(destPath, common.GetAppPath())
|
||||
fmt.Println("更新成功,请重启服务")
|
||||
}
|
||||
|
||||
func UpdateNpc() {
|
||||
destPath := downloadLatest("client")
|
||||
//复制文件到对应目录
|
||||
@@ -161,7 +154,7 @@ type release struct {
|
||||
|
||||
func downloadLatest(bin string) string {
|
||||
// get version
|
||||
data, err := http.Get("https://api.github.com/repos/yisier/nps/releases/latest")
|
||||
data, err := http.Get("https://api.github.com/repos/ehang-io/nps/releases/latest")
|
||||
if err != nil {
|
||||
log.Fatal(err.Error())
|
||||
}
|
||||
@@ -175,7 +168,7 @@ func downloadLatest(bin string) string {
|
||||
fmt.Println("the latest version is", version)
|
||||
filename := runtime.GOOS + "_" + runtime.GOARCH + "_" + bin + ".tar.gz"
|
||||
// download latest package
|
||||
downloadUrl := fmt.Sprintf("https://github.com/yisier/nps/releases/download/%s/%s", version, filename)
|
||||
downloadUrl := fmt.Sprintf("https://ehang.io/nps/releases/download/%s/%s", version, filename)
|
||||
fmt.Println("download package from ", downloadUrl)
|
||||
resp, err := http.Get(downloadUrl)
|
||||
if err != nil {
|
||||
@@ -197,43 +190,6 @@ func downloadLatest(bin string) string {
|
||||
return destPath
|
||||
}
|
||||
|
||||
func downloadLatest2(bin string, path string) string {
|
||||
// get version
|
||||
data, err := http.Get("https://api.github.com/repos/yisier/nps/releases/latest")
|
||||
if err != nil {
|
||||
log.Fatal(err.Error())
|
||||
}
|
||||
b, err := ioutil.ReadAll(data.Body)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
rl := new(release)
|
||||
json.Unmarshal(b, &rl)
|
||||
version := rl.TagName
|
||||
fmt.Println("the latest version is", version)
|
||||
filename := runtime.GOOS + "_" + runtime.GOARCH + "_" + bin + ".tar.gz"
|
||||
// download latest package
|
||||
downloadUrl := fmt.Sprintf("https://github.com/yisier/nps/releases/download/%s/%s", version, filename)
|
||||
fmt.Println("download package from ", downloadUrl)
|
||||
resp, err := http.Get(downloadUrl)
|
||||
if err != nil {
|
||||
log.Fatal(err.Error())
|
||||
}
|
||||
destPath, err := unpackit.Unpack(resp.Body, path)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if bin == "server" {
|
||||
destPath = strings.Replace(destPath, "/web", "", -1)
|
||||
destPath = strings.Replace(destPath, `\web`, "", -1)
|
||||
destPath = strings.Replace(destPath, "/views", "", -1)
|
||||
destPath = strings.Replace(destPath, `\views`, "", -1)
|
||||
} else {
|
||||
destPath = strings.Replace(destPath, `\conf`, "", -1)
|
||||
destPath = strings.Replace(destPath, "/conf", "", -1)
|
||||
}
|
||||
return destPath
|
||||
}
|
||||
func copyStaticFile(srcPath, bin string) string {
|
||||
path := common.GetInstallPath()
|
||||
if bin == "nps" {
|
||||
@@ -270,22 +226,6 @@ func copyStaticFile(srcPath, bin string) string {
|
||||
return binPath
|
||||
}
|
||||
|
||||
func copyStaticFileReplaceNps(srcPath, descPath string) string {
|
||||
//复制文件到对应目录
|
||||
os.Rename(filepath.Join(srcPath, "web"), filepath.Join(descPath, "web"))
|
||||
chMod(filepath.Join(descPath, "web"), 0766)
|
||||
|
||||
binPath, _ := filepath.Abs(os.Args[0])
|
||||
if !common.IsWindows() {
|
||||
os.Rename(filepath.Join(srcPath, "nps"), filepath.Join(descPath, "nps"))
|
||||
} else {
|
||||
os.Rename(filepath.Join(srcPath, "nps.exe"), filepath.Join(descPath, "nps.exe"))
|
||||
}
|
||||
chMod(binPath, 0755)
|
||||
os.RemoveAll(srcPath)
|
||||
return binPath
|
||||
}
|
||||
|
||||
func InstallNpc() {
|
||||
path := common.GetInstallPath()
|
||||
if !common.FileExists(path) {
|
||||
@@ -299,7 +239,6 @@ func InstallNpc() {
|
||||
|
||||
func InstallNps() string {
|
||||
path := common.GetInstallPath()
|
||||
log.Println("install path:" + path)
|
||||
if common.FileExists(path) {
|
||||
MkidrDirAll(path, "web/static", "web/views")
|
||||
} else {
|
||||
@@ -326,21 +265,6 @@ now!`)
|
||||
chMod(common.GetLogPath(), 0777)
|
||||
return binPath
|
||||
}
|
||||
|
||||
func InstallNpsToCurrentDir() string {
|
||||
path := common.GetAppPath()
|
||||
log.Println("install path:" + path)
|
||||
log.Println("install ok!")
|
||||
chMod(filepath.Join(path, "nps.log"), 0777)
|
||||
|
||||
if !common.IsWindows() {
|
||||
path = filepath.Join(path, "nps")
|
||||
} else {
|
||||
path = filepath.Join(path, "nps.exe")
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func MkidrDirAll(path string, v ...string) {
|
||||
for _, item := range v {
|
||||
if err := os.MkdirAll(filepath.Join(path, item), 0755); err != nil {
|
||||
@@ -385,7 +309,7 @@ func CopyDir(srcPath string, destPath string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// 生成目录并拷贝文件
|
||||
//生成目录并拷贝文件
|
||||
func copyFile(src, dest string) (w int64, err error) {
|
||||
srcFile, err := os.Open(src)
|
||||
if err != nil {
|
||||
@@ -420,7 +344,7 @@ func copyFile(src, dest string) (w int64, err error) {
|
||||
return io.Copy(dstFile, srcFile)
|
||||
}
|
||||
|
||||
// 检测文件夹路径时候存在
|
||||
//检测文件夹路径时候存在
|
||||
func pathExists(path string) (bool, error) {
|
||||
_, err := os.Stat(path)
|
||||
if err == nil {
|
||||
|
||||
@@ -1,692 +0,0 @@
|
||||
package nps_mux
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"math"
|
||||
"net"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
type conn struct {
|
||||
net.Conn
|
||||
connStatusOkCh chan struct{}
|
||||
connStatusFailCh chan struct{}
|
||||
connId int32
|
||||
isClose bool
|
||||
closingFlag bool // closing conn flag
|
||||
receiveWindow *receiveWindow
|
||||
sendWindow *sendWindow
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func NewConn(connId int32, mux *Mux) *conn {
|
||||
c := &conn{
|
||||
connStatusOkCh: make(chan struct{}),
|
||||
connStatusFailCh: make(chan struct{}),
|
||||
connId: connId,
|
||||
receiveWindow: new(receiveWindow),
|
||||
sendWindow: new(sendWindow),
|
||||
once: sync.Once{},
|
||||
}
|
||||
c.receiveWindow.New(mux)
|
||||
c.sendWindow.New(mux)
|
||||
return c
|
||||
}
|
||||
|
||||
func (s *conn) Read(buf []byte) (n int, err error) {
|
||||
if s.isClose || buf == nil {
|
||||
return 0, errors.New("the conn has closed")
|
||||
}
|
||||
if len(buf) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
// waiting for takeout from receive window finish or timeout
|
||||
n, err = s.receiveWindow.Read(buf, s.connId)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *conn) Write(buf []byte) (n int, err error) {
|
||||
if s.isClose {
|
||||
return 0, errors.New("the conn has closed")
|
||||
}
|
||||
if s.closingFlag {
|
||||
return 0, errors.New("io: write on closed conn")
|
||||
}
|
||||
if len(buf) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
n, err = s.sendWindow.WriteFull(buf, s.connId)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *conn) Close() (err error) {
|
||||
s.once.Do(s.closeProcess)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *conn) closeProcess() {
|
||||
s.isClose = true
|
||||
s.receiveWindow.mux.connMap.Delete(s.connId)
|
||||
if !s.receiveWindow.mux.IsClose {
|
||||
// if server or user close the conn while reading, will Get a io.EOF
|
||||
// and this Close method will be invoke, send this signal to close other side
|
||||
s.receiveWindow.mux.sendInfo(muxConnClose, s.connId, nil)
|
||||
}
|
||||
s.sendWindow.CloseWindow()
|
||||
s.receiveWindow.CloseWindow()
|
||||
return
|
||||
}
|
||||
|
||||
func (s *conn) LocalAddr() net.Addr {
|
||||
return s.receiveWindow.mux.conn.LocalAddr()
|
||||
}
|
||||
|
||||
func (s *conn) RemoteAddr() net.Addr {
|
||||
return s.receiveWindow.mux.conn.RemoteAddr()
|
||||
}
|
||||
|
||||
func (s *conn) SetDeadline(t time.Time) error {
|
||||
_ = s.SetReadDeadline(t)
|
||||
_ = s.SetWriteDeadline(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *conn) SetReadDeadline(t time.Time) error {
|
||||
s.receiveWindow.SetTimeOut(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *conn) SetWriteDeadline(t time.Time) error {
|
||||
s.sendWindow.SetTimeOut(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
type window struct {
|
||||
maxSizeDone uint64
|
||||
// 64bit alignment
|
||||
// maxSizeDone contains 4 parts
|
||||
// 1 31 1 31
|
||||
// wait maxSize useless done
|
||||
// wait zero means false, one means true
|
||||
off uint32
|
||||
closeOp bool
|
||||
closeOpCh chan struct{}
|
||||
mux *Mux
|
||||
}
|
||||
|
||||
const windowBits = 31
|
||||
const waitBits = dequeueBits + windowBits
|
||||
const mask1 = 1
|
||||
const mask31 = 1<<windowBits - 1
|
||||
|
||||
func (Self *window) unpack(ptrs uint64) (maxSize, done uint32, wait bool) {
|
||||
maxSize = uint32((ptrs >> dequeueBits) & mask31)
|
||||
done = uint32(ptrs & mask31)
|
||||
if ((ptrs >> waitBits) & mask1) == 1 {
|
||||
wait = true
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *window) pack(maxSize, done uint32, wait bool) uint64 {
|
||||
if wait {
|
||||
return (uint64(1)<<waitBits |
|
||||
uint64(maxSize&mask31)<<dequeueBits) |
|
||||
uint64(done&mask31)
|
||||
}
|
||||
return (uint64(0)<<waitBits |
|
||||
uint64(maxSize&mask31)<<dequeueBits) |
|
||||
uint64(done&mask31)
|
||||
}
|
||||
|
||||
func (Self *window) New() {
|
||||
Self.closeOpCh = make(chan struct{}, 2)
|
||||
}
|
||||
|
||||
func (Self *window) CloseWindow() {
|
||||
if !Self.closeOp {
|
||||
Self.closeOp = true
|
||||
Self.closeOpCh <- struct{}{}
|
||||
Self.closeOpCh <- struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
type receiveWindow struct {
|
||||
window
|
||||
bufQueue *receiveWindowQueue
|
||||
element *listElement
|
||||
count int8
|
||||
bw *writeBandwidth
|
||||
once sync.Once
|
||||
// receive window send the current max size and read size to send window
|
||||
// means done size actually store the size receive window has read
|
||||
}
|
||||
|
||||
func (Self *receiveWindow) New(mux *Mux) {
|
||||
// initial a window for receive
|
||||
Self.bufQueue = newReceiveWindowQueue()
|
||||
Self.element = listEle.Get()
|
||||
Self.maxSizeDone = Self.pack(maximumSegmentSize*30, 0, false)
|
||||
Self.mux = mux
|
||||
Self.window.New()
|
||||
Self.bw = newWriteBandwidth()
|
||||
}
|
||||
|
||||
func (Self *receiveWindow) remainingSize(maxSize uint32, delta uint16) (n uint32) {
|
||||
// receive window remaining
|
||||
l := int64(maxSize) - int64(Self.bufQueue.Len())
|
||||
l -= int64(delta)
|
||||
if l > 0 {
|
||||
n = uint32(l)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *receiveWindow) calcSize() {
|
||||
// calculating maximum receive window size
|
||||
if Self.count == 0 {
|
||||
muxBw := Self.mux.bw.Get()
|
||||
connBw := Self.bw.Get()
|
||||
latency := math.Float64frombits(atomic.LoadUint64(&Self.mux.latency))
|
||||
var n uint32
|
||||
if connBw > 0 && muxBw > 0 {
|
||||
if connBw > muxBw {
|
||||
connBw = muxBw
|
||||
Self.bw.GrowRatio()
|
||||
}
|
||||
n = uint32(latency * (muxBw + connBw))
|
||||
}
|
||||
if n < maximumSegmentSize*30 {
|
||||
n = maximumSegmentSize * 30
|
||||
}
|
||||
if n < uint32(float64(maximumSegmentSize*3000)*latency) {
|
||||
// latency gain
|
||||
// if there are some latency more than 10ms will trigger this gain
|
||||
// network pipeline need fill more data that we can measure the max bandwidth
|
||||
n = uint32(float64(maximumSegmentSize*3000) * latency)
|
||||
}
|
||||
for {
|
||||
ptrs := atomic.LoadUint64(&Self.maxSizeDone)
|
||||
size, read, wait := Self.unpack(ptrs)
|
||||
rem := Self.remainingSize(size, 0)
|
||||
ra := float64(rem) / float64(size)
|
||||
if ra > 0.8 {
|
||||
// low fill window gain
|
||||
// if receive window keep low fill, maybe pipeline fill the data, we need a gain
|
||||
// less than 20% fill, gain will trigger
|
||||
n = uint32(float64(n) * 1.5625 * ra * ra)
|
||||
}
|
||||
if n < size/2 {
|
||||
n = size / 2
|
||||
// half reduce
|
||||
}
|
||||
// set the minimal size
|
||||
if n > 2*size {
|
||||
if size == maximumSegmentSize*30 {
|
||||
// we give more ratio when the initial window size, to reduce the time window grow up
|
||||
if n > size*6 {
|
||||
n = size * 6
|
||||
}
|
||||
} else {
|
||||
n = 2 * size
|
||||
// twice grow
|
||||
}
|
||||
}
|
||||
if connBw > 0 && muxBw > 0 {
|
||||
limit := uint32(maximumWindowSize * (connBw / (muxBw + connBw)))
|
||||
if n > limit {
|
||||
log.Println("window too large, calculated:", n, "limit:", limit, connBw, muxBw)
|
||||
n = limit
|
||||
}
|
||||
}
|
||||
// set the maximum size
|
||||
if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(n, read, wait)) {
|
||||
// only change the maxSize
|
||||
break
|
||||
}
|
||||
}
|
||||
Self.count = -10
|
||||
}
|
||||
Self.count += 1
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *receiveWindow) Write(buf []byte, l uint16, part bool, id int32) (err error) {
|
||||
if Self.closeOp {
|
||||
return errors.New("conn.receiveWindow: write on closed window")
|
||||
}
|
||||
element, err := newListElement(buf, l, part)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
Self.calcSize() // calculate the max window size
|
||||
var wait bool
|
||||
var maxSize, read uint32
|
||||
start:
|
||||
ptrs := atomic.LoadUint64(&Self.maxSizeDone)
|
||||
maxSize, read, wait = Self.unpack(ptrs)
|
||||
remain := Self.remainingSize(maxSize, l)
|
||||
// calculate the remaining window size now, plus the element we will push
|
||||
if remain == 0 && !wait {
|
||||
wait = true
|
||||
if !atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, read, wait)) {
|
||||
// only change the wait status, not send the read size
|
||||
goto start
|
||||
// another goroutine change the status, make sure shall we need wait
|
||||
}
|
||||
} else if !wait {
|
||||
if !atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, 0, wait)) {
|
||||
// reset read size here, and send the read size directly
|
||||
goto start
|
||||
// another goroutine change the status, make sure shall we need wait
|
||||
}
|
||||
} // maybe there are still some data received even if window is full, just keep the wait status
|
||||
// and push into queue. when receive window read enough, send window will be acknowledged.
|
||||
Self.bufQueue.Push(element)
|
||||
// status check finish, now we can push the element into the queue
|
||||
if !wait {
|
||||
Self.mux.sendInfo(muxMsgSendOk, id, Self.pack(maxSize, read, false))
|
||||
// send the current status to send window
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (Self *receiveWindow) Read(p []byte, id int32) (n int, err error) {
|
||||
if Self.closeOp {
|
||||
return 0, io.EOF // receive close signal, returns eof
|
||||
}
|
||||
Self.bw.StartRead()
|
||||
n, err = Self.readFromQueue(p, id)
|
||||
Self.bw.SetCopySize(uint16(n))
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *receiveWindow) readFromQueue(p []byte, id int32) (n int, err error) {
|
||||
pOff := 0
|
||||
l := 0
|
||||
copyData:
|
||||
if Self.off == uint32(Self.element.L) {
|
||||
// on the first Read method invoked, Self.off and Self.element.l
|
||||
// both zero value
|
||||
listEle.Put(Self.element)
|
||||
if Self.closeOp {
|
||||
return 0, io.EOF
|
||||
}
|
||||
Self.element, err = Self.bufQueue.Pop()
|
||||
// if the queue is empty, Pop method will wait until one element push
|
||||
// into the queue successful, or timeout.
|
||||
// timer start on timeout parameter is set up
|
||||
Self.off = 0
|
||||
if err != nil {
|
||||
Self.CloseWindow() // also close the window, to avoid read twice
|
||||
return // queue receive stop or time out, break the loop and return
|
||||
}
|
||||
}
|
||||
l = copy(p[pOff:], Self.element.Buf[Self.off:Self.element.L])
|
||||
pOff += l
|
||||
Self.off += uint32(l)
|
||||
n += l
|
||||
l = 0
|
||||
if Self.off == uint32(Self.element.L) {
|
||||
windowBuff.Put(Self.element.Buf)
|
||||
Self.sendStatus(id, Self.element.L)
|
||||
// check the window full status
|
||||
}
|
||||
if pOff < len(p) && Self.element.Part {
|
||||
// element is a part of the segments, trying to fill up buf p
|
||||
goto copyData
|
||||
}
|
||||
return // buf p is full or all of segments in buf, return
|
||||
}
|
||||
|
||||
func (Self *receiveWindow) sendStatus(id int32, l uint16) {
|
||||
var maxSize, read uint32
|
||||
var wait bool
|
||||
for {
|
||||
ptrs := atomic.LoadUint64(&Self.maxSizeDone)
|
||||
maxSize, read, wait = Self.unpack(ptrs)
|
||||
if read <= (read+uint32(l))&mask31 {
|
||||
read += uint32(l)
|
||||
remain := Self.remainingSize(maxSize, 0)
|
||||
if wait && remain > 0 || read >= maxSize/2 || remain == maxSize {
|
||||
if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, 0, false)) {
|
||||
// now we get the current window status success
|
||||
// receive window free up some space we need acknowledge send window, also reset the read size
|
||||
// still having a condition that receive window is empty and not send the status to send window
|
||||
// so send the status here
|
||||
Self.mux.sendInfo(muxMsgSendOk, id, Self.pack(maxSize, read, false))
|
||||
break
|
||||
}
|
||||
} else {
|
||||
if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, read, wait)) {
|
||||
// receive window not into the wait status, or still not having any space now,
|
||||
// just change the read size
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
//overflow
|
||||
if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, uint32(l), wait)) {
|
||||
// reset to l
|
||||
Self.mux.sendInfo(muxMsgSendOk, id, Self.pack(maxSize, read, false))
|
||||
break
|
||||
}
|
||||
}
|
||||
runtime.Gosched()
|
||||
// another goroutine change remaining or wait status, make sure
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *receiveWindow) SetTimeOut(t time.Time) {
|
||||
// waiting for FIFO queue Pop method
|
||||
Self.bufQueue.SetTimeOut(t)
|
||||
}
|
||||
|
||||
func (Self *receiveWindow) Stop() {
|
||||
// queue has no more data to push, so unblock pop method
|
||||
Self.once.Do(Self.bufQueue.Stop)
|
||||
}
|
||||
|
||||
func (Self *receiveWindow) CloseWindow() {
|
||||
Self.window.CloseWindow()
|
||||
Self.Stop()
|
||||
Self.release()
|
||||
}
|
||||
|
||||
func (Self *receiveWindow) release() {
|
||||
//if Self.element != nil {
|
||||
// if Self.element.Buf != nil {
|
||||
// common.WindowBuff.Put(Self.element.Buf)
|
||||
// }
|
||||
// common.ListElementPool.Put(Self.element)
|
||||
//}
|
||||
for {
|
||||
ele := Self.bufQueue.TryPop()
|
||||
if ele == nil {
|
||||
return
|
||||
}
|
||||
if ele.Buf != nil {
|
||||
windowBuff.Put(ele.Buf)
|
||||
}
|
||||
listEle.Put(ele)
|
||||
} // release resource
|
||||
}
|
||||
|
||||
type sendWindow struct {
|
||||
window
|
||||
buf []byte
|
||||
setSizeCh chan struct{}
|
||||
timeout time.Time
|
||||
// send window receive the receive window max size and read size
|
||||
// done size store the size send window has send, send and read will be totally equal
|
||||
// so send minus read, send window can get the current window size remaining
|
||||
}
|
||||
|
||||
func (Self *sendWindow) New(mux *Mux) {
|
||||
Self.setSizeCh = make(chan struct{})
|
||||
Self.maxSizeDone = Self.pack(maximumSegmentSize*30, 0, false)
|
||||
Self.mux = mux
|
||||
Self.window.New()
|
||||
}
|
||||
|
||||
func (Self *sendWindow) SetSendBuf(buf []byte) {
|
||||
// send window buff from conn write method, set it to send window
|
||||
Self.buf = buf
|
||||
Self.off = 0
|
||||
}
|
||||
|
||||
func (Self *sendWindow) remainingSize(maxSize, send uint32) uint32 {
|
||||
l := int64(maxSize&mask31) - int64(send&mask31)
|
||||
if l > 0 {
|
||||
return uint32(l)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (Self *sendWindow) SetSize(currentMaxSizeDone uint64) (closed bool) {
|
||||
// set the window size from receive window
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
closed = true
|
||||
}
|
||||
}()
|
||||
if Self.closeOp {
|
||||
close(Self.setSizeCh)
|
||||
return true
|
||||
}
|
||||
var maxsize, send uint32
|
||||
var wait, newWait bool
|
||||
currentMaxSize, read, _ := Self.unpack(currentMaxSizeDone)
|
||||
for {
|
||||
ptrs := atomic.LoadUint64(&Self.maxSizeDone)
|
||||
maxsize, send, wait = Self.unpack(ptrs)
|
||||
if read > send {
|
||||
log.Println("window read > send: max size:", currentMaxSize, "read:", read, "send", send)
|
||||
return
|
||||
}
|
||||
if read == 0 && currentMaxSize == maxsize {
|
||||
return
|
||||
}
|
||||
send -= read
|
||||
remain := Self.remainingSize(currentMaxSize, send)
|
||||
if remain == 0 && wait {
|
||||
// just keep the wait status
|
||||
newWait = true
|
||||
}
|
||||
// remain > 0, change wait to false. or remain == 0, wait is false, just keep it
|
||||
if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(currentMaxSize, send, newWait)) {
|
||||
//log.Printf("currentMaxSize:%d read:%d send:%d", currentMaxSize, read, send)
|
||||
break
|
||||
}
|
||||
// anther goroutine change wait status or window size
|
||||
}
|
||||
if wait && !newWait {
|
||||
// send window into the wait status, need notice the channel
|
||||
Self.allow()
|
||||
}
|
||||
// send window not into the wait status, so just do slide
|
||||
return false
|
||||
}
|
||||
|
||||
func (Self *sendWindow) allow() {
|
||||
select {
|
||||
case Self.setSizeCh <- struct{}{}:
|
||||
return
|
||||
case <-Self.closeOpCh:
|
||||
close(Self.setSizeCh)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *sendWindow) sent(sentSize uint32) {
|
||||
var maxSie, send uint32
|
||||
var wait bool
|
||||
for {
|
||||
ptrs := atomic.LoadUint64(&Self.maxSizeDone)
|
||||
maxSie, send, wait = Self.unpack(ptrs)
|
||||
if (send+sentSize)&mask31 < send {
|
||||
// overflow
|
||||
runtime.Gosched()
|
||||
continue
|
||||
}
|
||||
if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSie, send+sentSize, wait)) {
|
||||
// set the send size
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *sendWindow) WriteTo() (p []byte, sendSize uint32, part bool, err error) {
|
||||
// returns buf segments, return only one segments, need a loop outside
|
||||
// until err = io.EOF
|
||||
if Self.closeOp {
|
||||
return nil, 0, false, errors.New("conn.writeWindow: window closed")
|
||||
}
|
||||
if Self.off >= uint32(len(Self.buf)) {
|
||||
return nil, 0, false, io.EOF
|
||||
// send window buff is drain, return eof and get another one
|
||||
}
|
||||
var maxSize, send uint32
|
||||
start:
|
||||
ptrs := atomic.LoadUint64(&Self.maxSizeDone)
|
||||
maxSize, send, _ = Self.unpack(ptrs)
|
||||
remain := Self.remainingSize(maxSize, send)
|
||||
if remain == 0 {
|
||||
if !atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, send, true)) {
|
||||
// just change the status wait status
|
||||
goto start // another goroutine change the window, try again
|
||||
}
|
||||
// into the wait status
|
||||
err = Self.waitReceiveWindow()
|
||||
if err != nil {
|
||||
return nil, 0, false, err
|
||||
}
|
||||
goto start
|
||||
}
|
||||
|
||||
if Self.off > uint32(len(Self.buf)) {
|
||||
return nil, 0, false, io.EOF
|
||||
}
|
||||
|
||||
//logs.Info("Self size:", len(Self.buf), "Self.off " ,Self.off)
|
||||
// there are still remaining window
|
||||
if len(Self.buf[Self.off:]) > maximumSegmentSize {
|
||||
sendSize = maximumSegmentSize
|
||||
} else {
|
||||
sendSize = uint32(len(Self.buf[Self.off:]))
|
||||
}
|
||||
if remain < sendSize {
|
||||
// usable window size is small than
|
||||
// window MAXIMUM_SEGMENT_SIZE or send buf left
|
||||
sendSize = remain
|
||||
}
|
||||
if sendSize < uint32(len(Self.buf[Self.off:])) {
|
||||
part = true
|
||||
}
|
||||
p = Self.buf[Self.off : sendSize+Self.off]
|
||||
Self.off += sendSize
|
||||
Self.sent(sendSize)
|
||||
//logs.Info("sendSize", sendSize, "Self.off " ,Self.off)
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *sendWindow) waitReceiveWindow() (err error) {
|
||||
t := Self.timeout.Sub(time.Now())
|
||||
if t < 0 { // not set the timeout, wait for it as long as connection close
|
||||
select {
|
||||
case _, ok := <-Self.setSizeCh:
|
||||
if !ok {
|
||||
return errors.New("conn.writeWindow: window closed")
|
||||
}
|
||||
return nil
|
||||
case <-Self.closeOpCh:
|
||||
return errors.New("conn.writeWindow: window closed")
|
||||
}
|
||||
}
|
||||
timer := time.NewTimer(t)
|
||||
defer timer.Stop()
|
||||
// waiting for receive usable window size, or timeout
|
||||
select {
|
||||
case _, ok := <-Self.setSizeCh:
|
||||
if !ok {
|
||||
return errors.New("conn.writeWindow: window closed")
|
||||
}
|
||||
return nil
|
||||
case <-timer.C:
|
||||
return errors.New("conn.writeWindow: write to time out")
|
||||
case <-Self.closeOpCh:
|
||||
return errors.New("conn.writeWindow: window closed")
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *sendWindow) WriteFull(buf []byte, id int32) (n int, err error) {
|
||||
Self.SetSendBuf(buf) // set the buf to send window
|
||||
var bufSeg []byte
|
||||
var part bool
|
||||
var l uint32
|
||||
for {
|
||||
bufSeg, l, part, err = Self.WriteTo()
|
||||
// get the buf segments from send window
|
||||
if bufSeg == nil && part == false && err == io.EOF {
|
||||
// send window is drain, break the loop
|
||||
err = nil
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
n += int(l)
|
||||
l = 0
|
||||
if part {
|
||||
Self.mux.sendInfo(muxNewMsgPart, id, bufSeg)
|
||||
} else {
|
||||
Self.mux.sendInfo(muxNewMsg, id, bufSeg)
|
||||
}
|
||||
// send to other side, not send nil data to other side
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *sendWindow) SetTimeOut(t time.Time) {
|
||||
// waiting for receive a receive window size
|
||||
Self.timeout = t
|
||||
}
|
||||
|
||||
type writeBandwidth struct {
|
||||
writeBW uint64 // store in bits, but it's float64
|
||||
readEnd time.Time
|
||||
duration float64
|
||||
bufLength uint32
|
||||
ratio uint32
|
||||
}
|
||||
|
||||
const writeCalcThreshold uint32 = 5 * 1024 * 1024
|
||||
|
||||
func newWriteBandwidth() *writeBandwidth {
|
||||
return &writeBandwidth{ratio: 1}
|
||||
}
|
||||
|
||||
func (Self *writeBandwidth) StartRead() {
|
||||
if Self.readEnd.IsZero() {
|
||||
Self.readEnd = time.Now()
|
||||
}
|
||||
Self.duration += time.Now().Sub(Self.readEnd).Seconds()
|
||||
if Self.bufLength >= writeCalcThreshold*atomic.LoadUint32(&Self.ratio) {
|
||||
Self.calcBandWidth()
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *writeBandwidth) SetCopySize(n uint16) {
|
||||
Self.bufLength += uint32(n)
|
||||
Self.endRead()
|
||||
}
|
||||
|
||||
func (Self *writeBandwidth) endRead() {
|
||||
Self.readEnd = time.Now()
|
||||
}
|
||||
|
||||
func (Self *writeBandwidth) calcBandWidth() {
|
||||
atomic.StoreUint64(&Self.writeBW, math.Float64bits(float64(Self.bufLength)/Self.duration))
|
||||
Self.bufLength = 0
|
||||
Self.duration = 0
|
||||
}
|
||||
|
||||
func (Self *writeBandwidth) Get() (bw float64) {
|
||||
// The zero value, 0 for numeric types
|
||||
bw = math.Float64frombits(atomic.LoadUint64(&Self.writeBW))
|
||||
if bw <= 0 {
|
||||
bw = 0
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *writeBandwidth) GrowRatio() {
|
||||
atomic.AddUint32(&Self.ratio, 1)
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package nps_mux
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
type connMap struct {
|
||||
cMap map[int32]*conn
|
||||
//closeCh chan struct{}
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func NewConnMap() *connMap {
|
||||
cMap := &connMap{
|
||||
cMap: make(map[int32]*conn),
|
||||
}
|
||||
return cMap
|
||||
}
|
||||
|
||||
func (s *connMap) Size() (n int) {
|
||||
s.RLock()
|
||||
n = len(s.cMap)
|
||||
s.RUnlock()
|
||||
return
|
||||
}
|
||||
|
||||
func (s *connMap) Get(id int32) (*conn, bool) {
|
||||
s.RLock()
|
||||
v, ok := s.cMap[id]
|
||||
s.RUnlock()
|
||||
if ok && v != nil {
|
||||
return v, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func (s *connMap) Set(id int32, v *conn) {
|
||||
s.Lock()
|
||||
s.cMap[id] = v
|
||||
s.Unlock()
|
||||
}
|
||||
|
||||
func (s *connMap) Close() {
|
||||
for _, v := range s.cMap {
|
||||
_ = v.Close() // close all the connections in the mux
|
||||
}
|
||||
}
|
||||
|
||||
func (s *connMap) Delete(id int32) {
|
||||
s.Lock()
|
||||
delete(s.cMap, id)
|
||||
s.Unlock()
|
||||
}
|
||||
@@ -1,514 +0,0 @@
|
||||
package nps_mux
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"math"
|
||||
"net"
|
||||
"os"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
muxPingFlag uint8 = iota
|
||||
muxNewConnOk
|
||||
muxNewConnFail
|
||||
muxNewMsg
|
||||
muxNewMsgPart
|
||||
muxMsgSendOk
|
||||
muxNewConn
|
||||
muxConnClose
|
||||
muxPingReturn
|
||||
muxPing int32 = -1
|
||||
maximumSegmentSize = poolSizeWindow
|
||||
maximumWindowSize = 1 << 27 // 1<<31-1 TCP slide window size is very large,
|
||||
// we use 128M, reduce memory usage
|
||||
)
|
||||
|
||||
type Mux struct {
|
||||
latency uint64 // we store latency in bits, but it's float64
|
||||
net.Listener
|
||||
conn net.Conn
|
||||
connMap *connMap
|
||||
newConnCh chan *conn
|
||||
id int32
|
||||
closeChan chan struct{}
|
||||
IsClose bool
|
||||
counter *latencyCounter
|
||||
bw *bandwidth
|
||||
pingCh chan []byte
|
||||
pingCheckTime uint32 // we check the ping per 5s
|
||||
pingCheckThreshold uint32
|
||||
connType string
|
||||
writeQueue priorityQueue
|
||||
newConnQueue connQueue
|
||||
}
|
||||
|
||||
func NewMux(c net.Conn, connType string, pingCheckThreshold int) *Mux {
|
||||
//c.(*net.TCPConn).SetReadBuffer(0)
|
||||
//c.(*net.TCPConn).SetWriteBuffer(0)
|
||||
fd, err := getConnFd(c)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
var checkThreshold uint32
|
||||
if pingCheckThreshold <= 0 {
|
||||
if connType == "kcp" {
|
||||
checkThreshold = 20
|
||||
} else {
|
||||
checkThreshold = 60
|
||||
}
|
||||
} else {
|
||||
checkThreshold = uint32(pingCheckThreshold)
|
||||
}
|
||||
m := &Mux{
|
||||
conn: c,
|
||||
connMap: NewConnMap(),
|
||||
id: 0,
|
||||
closeChan: make(chan struct{}, 1),
|
||||
newConnCh: make(chan *conn),
|
||||
bw: NewBandwidth(fd),
|
||||
IsClose: false,
|
||||
connType: connType,
|
||||
pingCh: make(chan []byte),
|
||||
pingCheckThreshold: checkThreshold,
|
||||
counter: newLatencyCounter(),
|
||||
}
|
||||
m.writeQueue.New()
|
||||
m.newConnQueue.New()
|
||||
//read session by flag
|
||||
m.readSession()
|
||||
//ping
|
||||
m.ping()
|
||||
m.writeSession()
|
||||
return m
|
||||
}
|
||||
|
||||
func (s *Mux) NewConn() (*conn, error) {
|
||||
if s.IsClose {
|
||||
return nil, errors.New("the mux has closed")
|
||||
}
|
||||
conn := NewConn(s.getId(), s)
|
||||
//it must be Set before send
|
||||
s.connMap.Set(conn.connId, conn)
|
||||
s.sendInfo(muxNewConn, conn.connId, nil)
|
||||
//Set a timer timeout 120 second
|
||||
timer := time.NewTimer(time.Minute * 2)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-conn.connStatusOkCh:
|
||||
return conn, nil
|
||||
case <-timer.C:
|
||||
}
|
||||
return nil, errors.New("create connection fail,the server refused the connection")
|
||||
}
|
||||
|
||||
func (s *Mux) Accept() (net.Conn, error) {
|
||||
if s.IsClose {
|
||||
return nil, errors.New("accpet error,the mux has closed")
|
||||
}
|
||||
conn := <-s.newConnCh
|
||||
if conn == nil {
|
||||
return nil, errors.New("accpet error,the conn has closed")
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (s *Mux) Addr() net.Addr {
|
||||
return s.conn.LocalAddr()
|
||||
}
|
||||
|
||||
func (s *Mux) sendInfo(flag uint8, id int32, data interface{}) {
|
||||
if s.IsClose {
|
||||
return
|
||||
}
|
||||
var err error
|
||||
pack := muxPack.Get()
|
||||
err = pack.Set(flag, id, data)
|
||||
if err != nil {
|
||||
muxPack.Put(pack)
|
||||
log.Println("mux: New Pack err", err)
|
||||
_ = s.Close()
|
||||
return
|
||||
}
|
||||
s.writeQueue.Push(pack)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Mux) writeSession() {
|
||||
go func() {
|
||||
for {
|
||||
if s.IsClose {
|
||||
break
|
||||
}
|
||||
pack := s.writeQueue.Pop()
|
||||
if s.IsClose {
|
||||
break
|
||||
}
|
||||
//if pack.flag == muxNewMsg || pack.flag == muxNewMsgPart {
|
||||
// if pack.length >= 100 {
|
||||
// log.Println("write session id", pack.id, "\n", string(pack.content[:100]))
|
||||
// } else {
|
||||
// log.Println("write session id", pack.id, "\n", string(pack.content[:pack.length]))
|
||||
// }
|
||||
//}
|
||||
err := pack.Pack(s.conn)
|
||||
muxPack.Put(pack)
|
||||
if err != nil {
|
||||
log.Println("mux: Pack err", err)
|
||||
_ = s.Close()
|
||||
break
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *Mux) ping() {
|
||||
go func() {
|
||||
now, _ := time.Now().UTC().MarshalText()
|
||||
s.sendInfo(muxPingFlag, muxPing, now)
|
||||
// send the ping flag and Get the latency first
|
||||
ticker := time.NewTicker(time.Second * 5)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
if s.IsClose {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-ticker.C:
|
||||
}
|
||||
if atomic.LoadUint32(&s.pingCheckTime) > s.pingCheckThreshold {
|
||||
log.Println("mux: ping time out, checktime", s.pingCheckTime, "threshold", s.pingCheckThreshold)
|
||||
_ = s.Close()
|
||||
// more than limit times not receive the ping return package,
|
||||
// mux conn is damaged, maybe a packet drop, close it
|
||||
break
|
||||
}
|
||||
now, _ = time.Now().UTC().MarshalText()
|
||||
s.sendInfo(muxPingFlag, muxPing, now)
|
||||
atomic.AddUint32(&s.pingCheckTime, 1)
|
||||
}
|
||||
return
|
||||
}()
|
||||
|
||||
go func() {
|
||||
var now time.Time
|
||||
var data []byte
|
||||
for {
|
||||
if s.IsClose {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case data = <-s.pingCh:
|
||||
atomic.StoreUint32(&s.pingCheckTime, 0)
|
||||
case <-s.closeChan:
|
||||
break
|
||||
}
|
||||
_ = now.UnmarshalText(data)
|
||||
latency := time.Now().UTC().Sub(now).Seconds()
|
||||
if latency > 0 {
|
||||
atomic.StoreUint64(&s.latency, math.Float64bits(s.counter.Latency(latency)))
|
||||
// convert float64 to bits, store it atomic
|
||||
//log.Println("ping", math.Float64frombits(atomic.LoadUint64(&s.latency)))
|
||||
}
|
||||
if cap(data) > 0 && !s.IsClose {
|
||||
windowBuff.Put(data)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *Mux) readSession() {
|
||||
go func() {
|
||||
var connection *conn
|
||||
for {
|
||||
if s.IsClose {
|
||||
break
|
||||
}
|
||||
connection = s.newConnQueue.Pop()
|
||||
if s.IsClose {
|
||||
break // make sure that is closed
|
||||
}
|
||||
s.connMap.Set(connection.connId, connection) //it has been Set before send ok
|
||||
s.newConnCh <- connection
|
||||
s.sendInfo(muxNewConnOk, connection.connId, nil)
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
var pack *muxPackager
|
||||
var l uint16
|
||||
var err error
|
||||
for {
|
||||
if s.IsClose {
|
||||
return
|
||||
}
|
||||
pack = muxPack.Get()
|
||||
s.bw.StartRead()
|
||||
if l, err = pack.UnPack(s.conn); err != nil {
|
||||
log.Println("mux: read session unpack from connection err", err)
|
||||
_ = s.Close()
|
||||
break
|
||||
}
|
||||
s.bw.SetCopySize(l)
|
||||
//if pack.flag == muxNewMsg || pack.flag == muxNewMsgPart {
|
||||
// if pack.length >= 100 {
|
||||
// log.Printf("read session id %d pointer %p\n%v", pack.id, pack.content, string(pack.content[:100]))
|
||||
// } else {
|
||||
// log.Printf("read session id %d pointer %p\n%v", pack.id, pack.content, string(pack.content[:pack.length]))
|
||||
// }
|
||||
//}
|
||||
switch pack.flag {
|
||||
case muxNewConn: //New connection
|
||||
connection := NewConn(pack.id, s)
|
||||
s.newConnQueue.Push(connection)
|
||||
continue
|
||||
case muxPingFlag: //ping
|
||||
s.sendInfo(muxPingReturn, muxPing, pack.content)
|
||||
windowBuff.Put(pack.content)
|
||||
continue
|
||||
case muxPingReturn:
|
||||
s.pingCh <- pack.content
|
||||
continue
|
||||
}
|
||||
if connection, ok := s.connMap.Get(pack.id); ok && !connection.isClose {
|
||||
switch pack.flag {
|
||||
case muxNewMsg, muxNewMsgPart: //New msg from remote connection
|
||||
err = s.newMsg(connection, pack)
|
||||
if err != nil {
|
||||
log.Println("mux: read session connection New msg err", err)
|
||||
_ = connection.Close()
|
||||
}
|
||||
continue
|
||||
case muxNewConnOk: //connection ok
|
||||
connection.connStatusOkCh <- struct{}{}
|
||||
continue
|
||||
case muxNewConnFail:
|
||||
connection.connStatusFailCh <- struct{}{}
|
||||
continue
|
||||
case muxMsgSendOk:
|
||||
if connection.isClose {
|
||||
continue
|
||||
}
|
||||
connection.sendWindow.SetSize(pack.window)
|
||||
continue
|
||||
case muxConnClose: //close the connection
|
||||
connection.closingFlag = true
|
||||
connection.receiveWindow.Stop() // close signal to receive window
|
||||
continue
|
||||
}
|
||||
} else if pack.flag == muxConnClose {
|
||||
continue
|
||||
}
|
||||
muxPack.Put(pack)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *Mux) newMsg(connection *conn, pack *muxPackager) (err error) {
|
||||
if connection.isClose {
|
||||
err = io.ErrClosedPipe
|
||||
return
|
||||
}
|
||||
//insert into queue
|
||||
if pack.flag == muxNewMsgPart {
|
||||
err = connection.receiveWindow.Write(pack.content, pack.length, true, pack.id)
|
||||
}
|
||||
if pack.flag == muxNewMsg {
|
||||
err = connection.receiveWindow.Write(pack.content, pack.length, false, pack.id)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Mux) Close() (err error) {
|
||||
if s.IsClose {
|
||||
return errors.New("the mux has closed")
|
||||
}
|
||||
s.IsClose = true
|
||||
log.Println("close mux")
|
||||
s.connMap.Close()
|
||||
//s.connMap = nil
|
||||
s.closeChan <- struct{}{}
|
||||
close(s.newConnCh)
|
||||
// while target host close socket without finish steps, conn.Close method maybe blocked
|
||||
// and tcp status change to CLOSE WAIT or TIME WAIT, so we close it in other goroutine
|
||||
_ = s.conn.SetDeadline(time.Now().Add(time.Second * 5))
|
||||
go s.conn.Close()
|
||||
s.release()
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Mux) release() {
|
||||
for {
|
||||
pack := s.writeQueue.TryPop()
|
||||
if pack == nil {
|
||||
break
|
||||
}
|
||||
if pack.basePackager.content != nil {
|
||||
windowBuff.Put(pack.basePackager.content)
|
||||
}
|
||||
muxPack.Put(pack)
|
||||
}
|
||||
for {
|
||||
connection := s.newConnQueue.TryPop()
|
||||
if connection == nil {
|
||||
break
|
||||
}
|
||||
connection = nil
|
||||
}
|
||||
s.writeQueue.Stop()
|
||||
s.newConnQueue.Stop()
|
||||
}
|
||||
|
||||
//Get New connId as unique flag
|
||||
func (s *Mux) getId() (id int32) {
|
||||
//Avoid going beyond the scope
|
||||
if (math.MaxInt32 - s.id) < 10000 {
|
||||
atomic.StoreInt32(&s.id, 0)
|
||||
}
|
||||
id = atomic.AddInt32(&s.id, 1)
|
||||
if _, ok := s.connMap.Get(id); ok {
|
||||
return s.getId()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type bandwidth struct {
|
||||
readBandwidth uint64 // store in bits, but it's float64
|
||||
readStart time.Time
|
||||
lastReadStart time.Time
|
||||
bufLength uint32
|
||||
fd *os.File
|
||||
calcThreshold uint32
|
||||
}
|
||||
|
||||
func NewBandwidth(fd *os.File) *bandwidth {
|
||||
return &bandwidth{fd: fd}
|
||||
}
|
||||
|
||||
func (Self *bandwidth) StartRead() {
|
||||
if Self.readStart.IsZero() {
|
||||
Self.readStart = time.Now()
|
||||
}
|
||||
if Self.bufLength >= Self.calcThreshold {
|
||||
Self.lastReadStart, Self.readStart = Self.readStart, time.Now()
|
||||
Self.calcBandWidth()
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *bandwidth) SetCopySize(n uint16) {
|
||||
Self.bufLength += uint32(n)
|
||||
}
|
||||
|
||||
func (Self *bandwidth) calcBandWidth() {
|
||||
t := Self.readStart.Sub(Self.lastReadStart)
|
||||
bufferSize, err := sysGetSock(Self.fd)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
Self.bufLength = 0
|
||||
return
|
||||
}
|
||||
if Self.bufLength >= uint32(bufferSize) {
|
||||
atomic.StoreUint64(&Self.readBandwidth, math.Float64bits(float64(Self.bufLength)/t.Seconds()))
|
||||
// calculate the whole socket buffer, the time meaning to fill the buffer
|
||||
} else {
|
||||
Self.calcThreshold = uint32(bufferSize)
|
||||
}
|
||||
// socket buffer size is bigger than bufLength, so we don't calculate it
|
||||
Self.bufLength = 0
|
||||
}
|
||||
|
||||
func (Self *bandwidth) Get() (bw float64) {
|
||||
// The zero value, 0 for numeric types
|
||||
bw = math.Float64frombits(atomic.LoadUint64(&Self.readBandwidth))
|
||||
if bw <= 0 {
|
||||
bw = 0
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const counterBits = 4
|
||||
const counterMask = 1<<counterBits - 1
|
||||
|
||||
func newLatencyCounter() *latencyCounter {
|
||||
return &latencyCounter{
|
||||
buf: make([]float64, 1<<counterBits, 1<<counterBits),
|
||||
headMin: 0,
|
||||
}
|
||||
}
|
||||
|
||||
type latencyCounter struct {
|
||||
buf []float64 //buf is a fixed length ring buffer,
|
||||
// if buffer is full, New value will replace the oldest one.
|
||||
headMin uint8 //head indicate the head in ring buffer,
|
||||
// in meaning, slot in list will be replaced;
|
||||
// min indicate this slot value is minimal in list.
|
||||
|
||||
// we delineate the effective range with three times the minimum latency
|
||||
// average of effective latency for all current data as a mux latency
|
||||
}
|
||||
|
||||
func (Self *latencyCounter) unpack(idxs uint8) (head, min uint8) {
|
||||
head = (idxs >> counterBits) & counterMask
|
||||
// we Set head is 4 bits
|
||||
min = idxs & counterMask
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *latencyCounter) pack(head, min uint8) uint8 {
|
||||
return head<<counterBits |
|
||||
min&counterMask
|
||||
}
|
||||
|
||||
func (Self *latencyCounter) add(value float64) {
|
||||
head, min := Self.unpack(Self.headMin)
|
||||
Self.buf[head] = value
|
||||
if head == min {
|
||||
min = Self.minimal()
|
||||
//if head equals min, means the min slot already be replaced,
|
||||
// so we need to find another minimal value in the list,
|
||||
// and change the min indicator
|
||||
}
|
||||
if Self.buf[min] > value {
|
||||
min = head
|
||||
}
|
||||
head++
|
||||
Self.headMin = Self.pack(head, min)
|
||||
}
|
||||
|
||||
func (Self *latencyCounter) minimal() (min uint8) {
|
||||
var val float64
|
||||
var i uint8
|
||||
for i = 0; i < counterMask; i++ {
|
||||
if Self.buf[i] > 0 {
|
||||
if val > Self.buf[i] {
|
||||
val = Self.buf[i]
|
||||
min = i
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *latencyCounter) Latency(value float64) (latency float64) {
|
||||
Self.add(value)
|
||||
latency = Self.countSuccess()
|
||||
return
|
||||
}
|
||||
|
||||
const lossRatio = 3
|
||||
|
||||
func (Self *latencyCounter) countSuccess() (successRate float64) {
|
||||
var i, success uint8
|
||||
_, min := Self.unpack(Self.headMin)
|
||||
for i = 0; i < counterMask; i++ {
|
||||
if Self.buf[i] <= lossRatio*Self.buf[min] && Self.buf[i] > 0 {
|
||||
success++
|
||||
successRate += Self.buf[i]
|
||||
}
|
||||
}
|
||||
// counting all the data in the ring buf, except zero
|
||||
successRate = successRate / float64(success)
|
||||
return
|
||||
}
|
||||
@@ -1,703 +0,0 @@
|
||||
package nps_mux
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
_ "net/http/pprof"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var conn1 net.Conn
|
||||
var conn2 net.Conn
|
||||
var clientIp = "172.18.0.5"
|
||||
var serverIp = "172.18.0.2"
|
||||
var appIp = "172.18.0.3"
|
||||
var userIp = "172.18.0.4"
|
||||
var bridgePort = "9999"
|
||||
var appPort = "9998"
|
||||
var serverPort = "9997"
|
||||
var appResultFileName = "app.txt"
|
||||
var userResultFileName = "user.txt"
|
||||
var serverResultFileName = "server.txt"
|
||||
var clientResultFileName = "client.txt"
|
||||
var dockerNetWorkName = "test"
|
||||
var network = "172.18.0.0/16"
|
||||
var fileSavePath = "/usr/src/myapp/"
|
||||
var dataSize = 1024 * 1024 * 100
|
||||
|
||||
func TestMux(t *testing.T) {
|
||||
pwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(3)
|
||||
_ = createNetwork(dockerNetWorkName, network)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_ = runDocker("server", dockerNetWorkName, serverIp, "TestServer", pwd)
|
||||
}()
|
||||
time.Sleep(time.Second * 5)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_ = runDocker("client", dockerNetWorkName, clientIp, "TestClient", pwd)
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_ = runDocker("app", dockerNetWorkName, appIp, "TestApp", pwd)
|
||||
}()
|
||||
time.Sleep(time.Second * 5)
|
||||
_ = runDocker("user", dockerNetWorkName, userIp, "TestUser", pwd)
|
||||
wg.Wait()
|
||||
_ = deleteNetwork(dockerNetWorkName)
|
||||
}
|
||||
|
||||
func writeResult(values []float64, outfile string) error {
|
||||
file, err := os.Create(fileSavePath + outfile)
|
||||
if err != nil {
|
||||
fmt.Println("writer", err)
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
writer := bufio.NewWriter(file)
|
||||
for _, v := range values {
|
||||
_, _ = writer.WriteString(fmt.Sprintf("%.2f", v))
|
||||
_, _ = writer.WriteString("\n")
|
||||
_ = writer.Flush()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func appendResult(values []float64, outfile string) error {
|
||||
file, err := os.OpenFile(fileSavePath+outfile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
fmt.Println("writer", err)
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
writer := bufio.NewWriter(file)
|
||||
for _, v := range values {
|
||||
_, _ = writer.WriteString(fmt.Sprintf("%.2f", v))
|
||||
_, _ = writer.WriteString("\n")
|
||||
_ = writer.Flush()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func TestServer(t *testing.T) {
|
||||
tc, err := NewTrafficControl(serverIp)
|
||||
if err != nil {
|
||||
t.Fatal(err, tc)
|
||||
}
|
||||
// do some tc settings
|
||||
tc.delay("add", "50ms", "10ms", "10%")
|
||||
_ = tc.Run()
|
||||
_ = tc.bandwidth("1Mbit")
|
||||
// start bridge
|
||||
bridgeListener, err := net.Listen("tcp", serverIp+":"+bridgePort)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// wait for client
|
||||
clientBridgeConn, err := bridgeListener.Accept()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer clientBridgeConn.Close()
|
||||
// new mux
|
||||
mux := NewMux(clientBridgeConn, "tcp", 60)
|
||||
// start server port
|
||||
serverListener, err := net.Listen("tcp", serverIp+":"+serverPort)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer serverListener.Close()
|
||||
for {
|
||||
// accept user connection
|
||||
userConn, err := serverListener.Accept()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
go func(userConn net.Conn) {
|
||||
// create a conn from mux
|
||||
clientConn, err := mux.NewConn()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
go io.Copy(userConn, clientConn)
|
||||
go func() {
|
||||
_ = writeResult([]float64{
|
||||
mux.bw.Get() / 1024 / 1024,
|
||||
math.Float64frombits(atomic.LoadUint64(&mux.latency)),
|
||||
}, serverResultFileName)
|
||||
ticker := time.NewTicker(time.Second * 1)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
fmt.Println(mux.bw.Get()/1024/1024, math.Float64frombits(atomic.LoadUint64(&mux.latency)))
|
||||
_ = appendResult([]float64{
|
||||
mux.bw.Get() / 1024 / 1024,
|
||||
math.Float64frombits(atomic.LoadUint64(&mux.latency)),
|
||||
}, serverResultFileName)
|
||||
}
|
||||
}
|
||||
}()
|
||||
_, _ = io.Copy(clientConn, userConn)
|
||||
os.Exit(0)
|
||||
}(userConn)
|
||||
}
|
||||
}
|
||||
func TestClient(t *testing.T) {
|
||||
tc, err := NewTrafficControl(clientIp)
|
||||
if err != nil {
|
||||
t.Fatal(err, tc)
|
||||
}
|
||||
// do some tc settings
|
||||
tc.delay("add", "30ms", "10ms", "5%")
|
||||
_ = tc.Run()
|
||||
_ = tc.bandwidth("1Mbit")
|
||||
serverConn, err := net.Dial("tcp", serverIp+":"+bridgePort)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// crete mux by serverConn
|
||||
mux := NewMux(serverConn, "tcp", 60)
|
||||
// start accept user connection
|
||||
for {
|
||||
userConn, err := mux.Accept()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
go func(userConn net.Conn) {
|
||||
// connect to app
|
||||
appConn, err := net.Dial("tcp", appIp+":"+appPort)
|
||||
if err != nil {
|
||||
t.Fatal()
|
||||
}
|
||||
defer appConn.Close()
|
||||
defer userConn.Close()
|
||||
go io.Copy(userConn, appConn)
|
||||
go func() {
|
||||
_ = writeResult([]float64{
|
||||
mux.bw.Get() / 1024 / 1024,
|
||||
math.Float64frombits(atomic.LoadUint64(&mux.latency)),
|
||||
}, clientResultFileName)
|
||||
ticker := time.NewTicker(time.Second * 1)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
_ = appendResult([]float64{
|
||||
mux.bw.Get() / 1024 / 1024,
|
||||
math.Float64frombits(atomic.LoadUint64(&mux.latency)),
|
||||
}, clientResultFileName)
|
||||
}
|
||||
}
|
||||
}()
|
||||
_, _ = io.Copy(appConn, userConn)
|
||||
os.Exit(0)
|
||||
}(userConn)
|
||||
}
|
||||
}
|
||||
func TestApp(t *testing.T) {
|
||||
tc, err := NewTrafficControl(appIp)
|
||||
if err != nil {
|
||||
t.Fatal(err, tc)
|
||||
}
|
||||
// do some tc settings
|
||||
tc.delay("add", "40ms", "5ms", "1%")
|
||||
_ = tc.Run()
|
||||
_ = tc.bandwidth("1Mbit")
|
||||
appListener, err := net.Listen("tcp", appIp+":"+appPort)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for {
|
||||
userConn, err := appListener.Accept()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
go func(userConn net.Conn) {
|
||||
b := bytes.Repeat([]byte{0}, 1024)
|
||||
startTime := time.Now()
|
||||
// send data to user
|
||||
for i := 0; i < dataSize/1024; i++ {
|
||||
n, err := userConn.Write(b)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != 1024 {
|
||||
t.Fatal("the write len is not right")
|
||||
}
|
||||
}
|
||||
// send bandwidth
|
||||
writeBw := float64(dataSize/1024/1024) / time.Now().Sub(startTime).Seconds()
|
||||
// get 100md from user
|
||||
startTime = time.Now()
|
||||
readLen := 0
|
||||
for i := 0; i < 2<<32; i++ {
|
||||
n, err := userConn.Read(b)
|
||||
fmt.Println(n)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Println(readLen)
|
||||
readLen += n
|
||||
if readLen == dataSize {
|
||||
break
|
||||
}
|
||||
}
|
||||
if readLen != dataSize {
|
||||
t.Fatal("the read len is not right")
|
||||
}
|
||||
_, _ = userConn.Write([]byte{0})
|
||||
// read bandwidth
|
||||
readBw := float64(dataSize/1024/1024) / time.Now().Sub(startTime).Seconds()
|
||||
// save result
|
||||
err := writeResult([]float64{writeBw, readBw}, appResultFileName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.Exit(0)
|
||||
}(userConn)
|
||||
}
|
||||
}
|
||||
func TestUser(t *testing.T) {
|
||||
tc, err := NewTrafficControl(userIp)
|
||||
if err != nil {
|
||||
t.Fatal(err, tc)
|
||||
}
|
||||
// do some tc settings
|
||||
tc.delay("add", "20ms", "40ms", "50%")
|
||||
_ = tc.Run()
|
||||
_ = tc.bandwidth("1Mbit")
|
||||
appConn, err := net.Dial("tcp", serverIp+":"+serverPort)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b := bytes.Repeat([]byte{0}, 1024)
|
||||
startTime := time.Now()
|
||||
// get 100md from app
|
||||
readLen := 0
|
||||
for i := 0; i < 2<<32; i++ {
|
||||
n, err := appConn.Read(b)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
readLen += n
|
||||
if readLen == dataSize {
|
||||
break
|
||||
}
|
||||
}
|
||||
if readLen != dataSize {
|
||||
t.Fatal("the read len is not right", readLen, dataSize)
|
||||
}
|
||||
// read bandwidth
|
||||
readBw := float64(dataSize/1024/1024) / time.Now().Sub(startTime).Seconds()
|
||||
// send 100mb data to app
|
||||
startTime = time.Now()
|
||||
b = bytes.Repeat([]byte{0}, 1024)
|
||||
for i := 0; i < dataSize/1024; i++ {
|
||||
n, err := appConn.Write(b)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != 1024 {
|
||||
t.Fatal("the write len is not right")
|
||||
}
|
||||
}
|
||||
b = make([]byte, 1)
|
||||
_, err = io.ReadFull(appConn, b)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// send bandwidth
|
||||
writeBw := float64(dataSize/1024/1024) / time.Now().Sub(startTime).Seconds()
|
||||
// save result
|
||||
err = writeResult([]float64{readBw, writeBw}, userResultFileName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
func TestNewMux2(t *testing.T) {
|
||||
tc, err := NewTrafficControl("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = tc.RunNetRangeTest(func() {
|
||||
server(tc.Eth.EthAddr)
|
||||
client(tc.Eth.EthAddr)
|
||||
time.Sleep(time.Second * 3)
|
||||
rate := NewRate(1024 * 1024 * 3)
|
||||
rate.Start()
|
||||
conn2 = NewRateConn(rate, conn2)
|
||||
go func() {
|
||||
m2 := NewMux(conn2, "tcp", 60)
|
||||
for {
|
||||
c, err := m2.Accept()
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
continue
|
||||
}
|
||||
go func() {
|
||||
_, _ = c.Write(bytes.Repeat([]byte{0}, 1024*1024*100))
|
||||
_ = c.Close()
|
||||
}()
|
||||
}
|
||||
}()
|
||||
|
||||
m1 := NewMux(conn1, "tcp", 60)
|
||||
tmpCpnn, err := m1.NewConn()
|
||||
if err != nil {
|
||||
log.Println("nps new conn err ", err)
|
||||
return
|
||||
}
|
||||
buf := make([]byte, 1024*1024)
|
||||
var count float64
|
||||
count = 0
|
||||
start := time.Now()
|
||||
for {
|
||||
n, err := tmpCpnn.Read(buf)
|
||||
count += float64(n)
|
||||
log.Println(m1.bw.Get())
|
||||
log.Println(uint32(math.Float64frombits(atomic.LoadUint64(&m1.latency))))
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
break
|
||||
}
|
||||
}
|
||||
log.Println("now rate", count/time.Now().Sub(start).Seconds()/1024/1024)
|
||||
})
|
||||
log.Println(err.Error())
|
||||
}
|
||||
func TestNewMux(t *testing.T) {
|
||||
go func() {
|
||||
_ = http.ListenAndServe("0.0.0.0:8889", nil)
|
||||
}()
|
||||
server("")
|
||||
client("")
|
||||
time.Sleep(time.Second * 3)
|
||||
go func() {
|
||||
m2 := NewMux(conn2, "tcp", 60)
|
||||
for {
|
||||
//log.Println("npc starting accept")
|
||||
c, err := m2.Accept()
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
continue
|
||||
}
|
||||
//log.Println("npc accept success ")
|
||||
c2, err := net.Dial("tcp", "127.0.0.1:80")
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
_ = c.Close()
|
||||
continue
|
||||
}
|
||||
//c2.(*net.TCPConn).SetReadBuffer(0)
|
||||
//c2.(*net.TCPConn).SetReadBuffer(0)
|
||||
go func(c2 net.Conn, c *conn) {
|
||||
go func() {
|
||||
buf := make([]byte, 32<<10)
|
||||
_, err = io.CopyBuffer(c2, c, buf)
|
||||
//if err != nil {
|
||||
// log.Println("close npc by copy from nps", err, c.connId)
|
||||
//}
|
||||
_ = c2.Close()
|
||||
_ = c.Close()
|
||||
}()
|
||||
buf := make([]byte, 32<<10)
|
||||
_, err = io.CopyBuffer(c, c2, buf)
|
||||
//if err != nil {
|
||||
// log.Println("close npc by copy from server", err, c.connId)
|
||||
//}
|
||||
_ = c2.Close()
|
||||
_ = c.Close()
|
||||
}(c2, c.(*conn))
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
m1 := NewMux(conn1, "tcp", 60)
|
||||
l, err := net.Listen("tcp", "127.0.0.1:7777")
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
for {
|
||||
//log.Println("nps starting accept")
|
||||
conns, err := l.Accept()
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
continue
|
||||
}
|
||||
//conns.(*net.TCPConn).SetReadBuffer(0)
|
||||
//conns.(*net.TCPConn).SetReadBuffer(0)
|
||||
//log.Println("nps accept success starting New conn")
|
||||
tmpCpnn, err := m1.NewConn()
|
||||
if err != nil {
|
||||
log.Println("nps New conn err ", err)
|
||||
continue
|
||||
}
|
||||
//logs.Warn("nps New conn success ", tmpCpnn.connId)
|
||||
go func(tmpCpnn *conn, conns net.Conn) {
|
||||
go func() {
|
||||
buf := make([]byte, 32<<10)
|
||||
_, _ = io.CopyBuffer(tmpCpnn, conns, buf)
|
||||
//if err != nil {
|
||||
// log.Println("close nps by copy from user", tmpCpnn.connId, err)
|
||||
//}
|
||||
_ = conns.Close()
|
||||
_ = tmpCpnn.Close()
|
||||
}()
|
||||
time.Sleep(time.Second)
|
||||
buf := make([]byte, 32<<10)
|
||||
_, err = io.CopyBuffer(conns, tmpCpnn, buf)
|
||||
//if err != nil {
|
||||
// log.Println("close nps by copy from npc ", tmpCpnn.connId, err)
|
||||
//}
|
||||
_ = conns.Close()
|
||||
_ = tmpCpnn.Close()
|
||||
}(tmpCpnn, conns)
|
||||
}
|
||||
}()
|
||||
|
||||
//go NewLogServer()
|
||||
time.Sleep(time.Second * 5)
|
||||
//for i := 0; i < 1; i++ {
|
||||
// go test_raw(i)
|
||||
//}
|
||||
//test_request()
|
||||
|
||||
for {
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
}
|
||||
|
||||
func server(ip string) {
|
||||
if ip == "" {
|
||||
ip = "127.0.0.1"
|
||||
}
|
||||
var err error
|
||||
l, err := net.Listen("tcp", ip+":9999")
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
go func() {
|
||||
conn1, err = l.Accept()
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
}()
|
||||
return
|
||||
}
|
||||
|
||||
func client(ip string) {
|
||||
if ip == "" {
|
||||
ip = "127.0.0.1"
|
||||
}
|
||||
var err error
|
||||
conn2, err = net.Dial("tcp", ip+":9999")
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
}
|
||||
|
||||
func test_request() {
|
||||
conn, _ := net.Dial("tcp", "127.0.0.1:7777")
|
||||
for i := 0; i < 1000; i++ {
|
||||
_, _ = conn.Write([]byte(`GET / HTTP/1.1
|
||||
Host: 127.0.0.1:7777
|
||||
Connection: keep-alive
|
||||
|
||||
|
||||
`))
|
||||
r, err := http.ReadResponse(bufio.NewReader(conn), nil)
|
||||
if err != nil {
|
||||
log.Println("close by read response err", err)
|
||||
break
|
||||
}
|
||||
log.Println("read response success", r)
|
||||
b, err := httputil.DumpResponse(r, true)
|
||||
if err != nil {
|
||||
log.Println("close by dump response err", err)
|
||||
break
|
||||
}
|
||||
fmt.Println(string(b[:20]), err)
|
||||
//time.Sleep(time.Second)
|
||||
}
|
||||
log.Println("finish")
|
||||
}
|
||||
|
||||
func test_raw(k int) {
|
||||
for i := 0; i < 1000; i++ {
|
||||
ti := time.Now()
|
||||
conn, err := net.Dial("tcp", "127.0.0.1:7777")
|
||||
if err != nil {
|
||||
log.Println("conn dial err", err)
|
||||
}
|
||||
tid := time.Now()
|
||||
_, _ = conn.Write([]byte(`GET /videojs5/video.js HTTP/1.1
|
||||
Host: 127.0.0.1:7777
|
||||
|
||||
|
||||
`))
|
||||
tiw := time.Now()
|
||||
buf := make([]byte, 3572)
|
||||
n, err := io.ReadFull(conn, buf)
|
||||
//n, err := conn.Read(buf)
|
||||
if err != nil {
|
||||
log.Println("close by read response err", err)
|
||||
break
|
||||
}
|
||||
log.Println(n, string(buf[:50]), "\n--------------\n", string(buf[n-50:n]))
|
||||
//time.Sleep(time.Second)
|
||||
err = conn.Close()
|
||||
if err != nil {
|
||||
log.Println("close conn err ", err)
|
||||
}
|
||||
now := time.Now()
|
||||
du := now.Sub(ti).Seconds()
|
||||
dud := now.Sub(tid).Seconds()
|
||||
duw := now.Sub(tiw).Seconds()
|
||||
if du > 1 {
|
||||
log.Println("duration long", du, dud, duw, k, i)
|
||||
}
|
||||
if n != 3572 {
|
||||
log.Println("n loss", n, string(buf))
|
||||
}
|
||||
}
|
||||
log.Println("finish")
|
||||
}
|
||||
|
||||
func TestNewConn(t *testing.T) {
|
||||
buf := make([]byte, 1024)
|
||||
log.Println(len(buf), cap(buf))
|
||||
//b := pool.GetBufPoolCopy()
|
||||
//b[0] = 1
|
||||
//b[1] = 2
|
||||
//b[2] = 3
|
||||
b := []byte{1, 2, 3}
|
||||
log.Println(copy(buf[:3], b), len(buf), cap(buf))
|
||||
log.Println(len(buf), buf[0])
|
||||
}
|
||||
|
||||
func TestDQueue(t *testing.T) {
|
||||
d := new(bufDequeue)
|
||||
d.vals = make([]unsafe.Pointer, 8)
|
||||
go func() {
|
||||
time.Sleep(time.Second)
|
||||
for i := 0; i < 10; i++ {
|
||||
log.Println(i)
|
||||
log.Println(d.popTail())
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
time.Sleep(time.Second)
|
||||
for i := 0; i < 10; i++ {
|
||||
data := "test"
|
||||
go log.Println(i, unsafe.Pointer(&data), d.pushHead(unsafe.Pointer(&data)))
|
||||
}
|
||||
}()
|
||||
time.Sleep(time.Second * 3)
|
||||
}
|
||||
|
||||
func TestChain(t *testing.T) {
|
||||
go func() {
|
||||
log.Println(http.ListenAndServe("0.0.0.0:8889", nil))
|
||||
}()
|
||||
time.Sleep(time.Second * 5)
|
||||
d := new(bufChain)
|
||||
d.new(256)
|
||||
go func() {
|
||||
time.Sleep(time.Second)
|
||||
for i := 0; i < 30000; i++ {
|
||||
unsa, ok := d.popTail()
|
||||
str := (*string)(unsa)
|
||||
if ok {
|
||||
fmt.Println(i, str, *str, ok)
|
||||
//logs.Warn(i, str, *str, ok)
|
||||
} else {
|
||||
fmt.Println("nil", i, ok)
|
||||
//logs.Warn("nil", i, ok)
|
||||
}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
time.Sleep(time.Second)
|
||||
for i := 0; i < 3000; i++ {
|
||||
go func(i int) {
|
||||
for n := 0; n < 10; n++ {
|
||||
data := "test " + strconv.Itoa(i) + strconv.Itoa(n)
|
||||
fmt.Println(data, unsafe.Pointer(&data))
|
||||
//logs.Warn(data, unsafe.Pointer(&data))
|
||||
d.pushHead(unsafe.Pointer(&data))
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
}()
|
||||
time.Sleep(time.Second * 100000)
|
||||
}
|
||||
|
||||
//func TestReceive(t *testing.T) {
|
||||
// go func() {
|
||||
// log.Println(http.ListenAndServe("0.0.0.0:8889", nil))
|
||||
// }()
|
||||
// logs.EnableFuncCallDepth(true)
|
||||
// logs.SetLogFuncCallDepth(3)
|
||||
// time.Sleep(time.Second * 5)
|
||||
// mux := New(Mux)
|
||||
// mux.bw.readBandwidth = float64(1*1024*1024)
|
||||
// mux.latency = float64(1/1000)
|
||||
// wind := New(receiveWindow)
|
||||
// wind.New(mux)
|
||||
// wind.
|
||||
// go func() {
|
||||
// time.Sleep(time.Second)
|
||||
// for i := 0; i < 36000; i++ {
|
||||
// data := d.Pop()
|
||||
// //fmt.Println(i, string(data.buf), err)
|
||||
// logs.Warn(i, string(data.content), data)
|
||||
// }
|
||||
// }()
|
||||
// go func() {
|
||||
// time.Sleep(time.Second*10)
|
||||
// for i := 0; i < 3000; i++ {
|
||||
// go func(i int) {
|
||||
// for n := 0; n < 10; n++{
|
||||
// data := New(common.muxPackager)
|
||||
// by := []byte("test " + strconv.Itoa(i) + strconv.Itoa(n))
|
||||
// _ = data.NewPac(common.MUX_NEW_MSG_PART, int32(i), by)
|
||||
// //fmt.Println(string((*data).buf), data)
|
||||
// logs.Warn(string((*data).content), data)
|
||||
// d.Push(data)
|
||||
// }
|
||||
// }(i)
|
||||
// go func(i int) {
|
||||
// data := New(common.muxPackager)
|
||||
// _ = data.NewPac(common.MUX_NEW_CONN, int32(i), nil)
|
||||
// //fmt.Println(string((*data).buf), data)
|
||||
// logs.Warn(data)
|
||||
// d.Push(data)
|
||||
// }(i)
|
||||
// go func(i int) {
|
||||
// data := New(common.muxPackager)
|
||||
// _ = data.NewPac(common.MUX_NEW_CONN_OK, int32(i), nil)
|
||||
// //fmt.Println(string((*data).buf), data)
|
||||
// logs.Warn(data)
|
||||
// d.Push(data)
|
||||
// }(i)
|
||||
// }
|
||||
// }()
|
||||
// time.Sleep(time.Second * 100000)
|
||||
//}
|
||||
@@ -1,165 +0,0 @@
|
||||
package nps_mux
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"github.com/astaxie/beego/logs"
|
||||
"io"
|
||||
)
|
||||
|
||||
type basePackager struct {
|
||||
buf []byte
|
||||
// buf contain the mux protocol struct binary data, we copy data to buf firstly.
|
||||
// replace binary.Read/Write method, it may use reflect shows slowly.
|
||||
// also reduce conn.Read/Write calls which use syscall.
|
||||
// due to our test, conn.Write method reduce by two-thirds CPU times,
|
||||
// conn.Write method has 20% reduction of the CPU times,
|
||||
// totally provides more than twice of the CPU performance improvement.
|
||||
length uint16
|
||||
content []byte
|
||||
}
|
||||
|
||||
func (Self *basePackager) Set(content []byte) (err error) {
|
||||
Self.reset()
|
||||
if content != nil {
|
||||
n := len(content)
|
||||
//fmt.Println(content)
|
||||
if n == 0 {
|
||||
// 长度为0的包,不应该向上抛,不然客户端会EOF,这里暂时没解决空包的问题 TODO
|
||||
//logs.Error("mux:packer: newpack content is zero length")
|
||||
//err = errors.New("mux:packer: newpack content is zero length")
|
||||
}
|
||||
if n > maximumSegmentSize {
|
||||
logs.Error("mux:packer: newpack content segment too large")
|
||||
//err = errors.New("mux:packer: newpack content segment too large")
|
||||
return
|
||||
}
|
||||
Self.content = Self.content[:n]
|
||||
copy(Self.content, content)
|
||||
} else {
|
||||
logs.Error("mux:packer: newpack content is nil")
|
||||
return
|
||||
//panic("mux:packer: newpack content is nil")
|
||||
//err = errors.New("mux:packer: newpack content is nil")
|
||||
}
|
||||
Self.setLength()
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *basePackager) Pack(writer io.Writer) (err error) {
|
||||
binary.LittleEndian.PutUint16(Self.buf[5:7], Self.length)
|
||||
_, err = writer.Write(Self.buf[:7])
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, err = writer.Write(Self.content[:Self.length])
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *basePackager) UnPack(reader io.Reader) (n uint16, err error) {
|
||||
Self.reset()
|
||||
l, err := io.ReadFull(reader, Self.buf[5:7])
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
n += uint16(l)
|
||||
Self.length = binary.LittleEndian.Uint16(Self.buf[5:7])
|
||||
if int(Self.length) > cap(Self.content) {
|
||||
err = errors.New("mux:packer: unpack err, content length too large")
|
||||
return
|
||||
}
|
||||
if Self.length > maximumSegmentSize {
|
||||
err = errors.New("mux:packer: unpack content segment too large")
|
||||
return
|
||||
}
|
||||
Self.content = Self.content[:int(Self.length)]
|
||||
l, err = io.ReadFull(reader, Self.content)
|
||||
n += uint16(l)
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *basePackager) setLength() {
|
||||
Self.length = uint16(len(Self.content))
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *basePackager) reset() {
|
||||
Self.length = 0
|
||||
Self.content = Self.content[:0] // reset length
|
||||
}
|
||||
|
||||
type muxPackager struct {
|
||||
flag uint8
|
||||
id int32
|
||||
window uint64
|
||||
basePackager
|
||||
}
|
||||
|
||||
func (Self *muxPackager) Set(flag uint8, id int32, content interface{}) (err error) {
|
||||
Self.buf = windowBuff.Get()
|
||||
Self.flag = flag
|
||||
Self.id = id
|
||||
switch flag {
|
||||
case muxPingFlag, muxPingReturn, muxNewMsg, muxNewMsgPart:
|
||||
Self.content = windowBuff.Get()
|
||||
if content != nil {
|
||||
err = Self.basePackager.Set(content.([]byte))
|
||||
}
|
||||
case muxMsgSendOk:
|
||||
// MUX_MSG_SEND_OK contains one data
|
||||
Self.window = content.(uint64)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *muxPackager) Pack(writer io.Writer) (err error) {
|
||||
Self.buf = Self.buf[0:13]
|
||||
Self.buf[0] = byte(Self.flag)
|
||||
binary.LittleEndian.PutUint32(Self.buf[1:5], uint32(Self.id))
|
||||
switch Self.flag {
|
||||
case muxNewMsg, muxNewMsgPart, muxPingFlag, muxPingReturn:
|
||||
err = Self.basePackager.Pack(writer)
|
||||
windowBuff.Put(Self.content)
|
||||
case muxMsgSendOk:
|
||||
binary.LittleEndian.PutUint64(Self.buf[5:13], Self.window)
|
||||
_, err = writer.Write(Self.buf[:13])
|
||||
default:
|
||||
_, err = writer.Write(Self.buf[:5])
|
||||
}
|
||||
windowBuff.Put(Self.buf)
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *muxPackager) UnPack(reader io.Reader) (n uint16, err error) {
|
||||
Self.buf = windowBuff.Get()
|
||||
Self.buf = Self.buf[0:13]
|
||||
l, err := io.ReadFull(reader, Self.buf[:5])
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
n += uint16(l)
|
||||
Self.flag = uint8(Self.buf[0])
|
||||
Self.id = int32(binary.LittleEndian.Uint32(Self.buf[1:5]))
|
||||
switch Self.flag {
|
||||
case muxNewMsg, muxNewMsgPart, muxPingFlag, muxPingReturn:
|
||||
var m uint16
|
||||
Self.content = windowBuff.Get() // need Get a window buf from pool
|
||||
m, err = Self.basePackager.UnPack(reader)
|
||||
n += m
|
||||
case muxMsgSendOk:
|
||||
l, err = io.ReadFull(reader, Self.buf[5:13])
|
||||
Self.window = binary.LittleEndian.Uint64(Self.buf[5:13])
|
||||
n += uint16(l) // uint64
|
||||
}
|
||||
windowBuff.Put(Self.buf)
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *muxPackager) reset() {
|
||||
Self.id = 0
|
||||
Self.flag = 0
|
||||
Self.length = 0
|
||||
Self.content = nil
|
||||
Self.window = 0
|
||||
Self.buf = nil
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
package nps_mux
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
const (
|
||||
poolSizeBuffer = 4096
|
||||
//poolSizeBuffer = 4096 * 10 // a mux packager total length
|
||||
poolSizeWindow = poolSizeBuffer - 2 - 4 - 4 - 1 // content length
|
||||
)
|
||||
|
||||
type windowBufferPool struct {
|
||||
pool sync.Pool
|
||||
}
|
||||
|
||||
func newWindowBufferPool() *windowBufferPool {
|
||||
return &windowBufferPool{
|
||||
pool: sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, poolSizeWindow, poolSizeWindow)
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
//func trace(buf []byte, ty string) {
|
||||
// pc := make([]uintptr, 10) // at least 1 entry needed
|
||||
// n := runtime.Callers(0, pc)
|
||||
// for i := 0; i < n; i++ {
|
||||
// f := runtime.FuncForPC(pc[i])
|
||||
// file, line := f.FileLine(pc[i])
|
||||
// log.Printf("%v %p %s:%d %s\n", ty, buf, file, line, f.Name())
|
||||
// }
|
||||
//}
|
||||
|
||||
func (Self *windowBufferPool) Get() (buf []byte) {
|
||||
buf = Self.pool.Get().([]byte)
|
||||
//trace(buf, "get")
|
||||
return buf[:poolSizeWindow]
|
||||
}
|
||||
|
||||
func (Self *windowBufferPool) Put(x []byte) {
|
||||
//trace(x, "put")
|
||||
Self.pool.Put(x[:poolSizeWindow]) // make buf to full
|
||||
}
|
||||
|
||||
type muxPackagerPool struct {
|
||||
pool sync.Pool
|
||||
}
|
||||
|
||||
func newMuxPackagerPool() *muxPackagerPool {
|
||||
return &muxPackagerPool{
|
||||
pool: sync.Pool{
|
||||
New: func() interface{} {
|
||||
pack := muxPackager{}
|
||||
return &pack
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *muxPackagerPool) Get() *muxPackager {
|
||||
return Self.pool.Get().(*muxPackager)
|
||||
}
|
||||
|
||||
func (Self *muxPackagerPool) Put(pack *muxPackager) {
|
||||
pack.reset()
|
||||
Self.pool.Put(pack)
|
||||
}
|
||||
|
||||
type listElementPool struct {
|
||||
pool sync.Pool
|
||||
}
|
||||
|
||||
func newListElementPool() *listElementPool {
|
||||
return &listElementPool{
|
||||
pool: sync.Pool{
|
||||
New: func() interface{} {
|
||||
element := listElement{}
|
||||
return &element
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *listElementPool) Get() *listElement {
|
||||
return Self.pool.Get().(*listElement)
|
||||
}
|
||||
|
||||
func (Self *listElementPool) Put(element *listElement) {
|
||||
element.Reset()
|
||||
Self.pool.Put(element)
|
||||
}
|
||||
|
||||
var (
|
||||
muxPack = newMuxPackagerPool()
|
||||
windowBuff = newWindowBufferPool()
|
||||
listEle = newListElementPool()
|
||||
)
|
||||
@@ -1,590 +0,0 @@
|
||||
package nps_mux
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
type priorityQueue struct {
|
||||
highestChain *bufChain
|
||||
middleChain *bufChain
|
||||
lowestChain *bufChain
|
||||
starving uint8
|
||||
stop bool
|
||||
cond *sync.Cond
|
||||
}
|
||||
|
||||
func (Self *priorityQueue) New() {
|
||||
Self.highestChain = new(bufChain)
|
||||
Self.highestChain.new(4)
|
||||
Self.middleChain = new(bufChain)
|
||||
Self.middleChain.new(32)
|
||||
Self.lowestChain = new(bufChain)
|
||||
Self.lowestChain.new(256)
|
||||
locker := new(sync.Mutex)
|
||||
Self.cond = sync.NewCond(locker)
|
||||
}
|
||||
|
||||
func (Self *priorityQueue) Push(packager *muxPackager) {
|
||||
Self.push(packager)
|
||||
Self.cond.Broadcast()
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *priorityQueue) push(packager *muxPackager) {
|
||||
switch packager.flag {
|
||||
case muxPingFlag, muxPingReturn:
|
||||
Self.highestChain.pushHead(unsafe.Pointer(packager))
|
||||
// the ping package need highest priority
|
||||
// prevent ping calculation error
|
||||
case muxNewConn, muxNewConnOk, muxNewConnFail:
|
||||
// the New conn package need some priority too
|
||||
Self.middleChain.pushHead(unsafe.Pointer(packager))
|
||||
default:
|
||||
Self.lowestChain.pushHead(unsafe.Pointer(packager))
|
||||
}
|
||||
}
|
||||
|
||||
const maxStarving uint8 = 8
|
||||
|
||||
func (Self *priorityQueue) Pop() (packager *muxPackager) {
|
||||
var iter bool
|
||||
for {
|
||||
packager = Self.TryPop()
|
||||
if packager != nil {
|
||||
return
|
||||
}
|
||||
if Self.stop {
|
||||
return
|
||||
}
|
||||
if iter {
|
||||
break
|
||||
// trying to pop twice
|
||||
}
|
||||
iter = true
|
||||
runtime.Gosched()
|
||||
}
|
||||
Self.cond.L.Lock()
|
||||
defer Self.cond.L.Unlock()
|
||||
for packager = Self.TryPop(); packager == nil; {
|
||||
if Self.stop {
|
||||
return
|
||||
}
|
||||
Self.cond.Wait()
|
||||
// wait for it with no more iter
|
||||
packager = Self.TryPop()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *priorityQueue) TryPop() (packager *muxPackager) {
|
||||
ptr, ok := Self.highestChain.popTail()
|
||||
if ok {
|
||||
packager = (*muxPackager)(ptr)
|
||||
return
|
||||
}
|
||||
if Self.starving < maxStarving {
|
||||
// not pop too much, lowestChain will wait too long
|
||||
ptr, ok = Self.middleChain.popTail()
|
||||
if ok {
|
||||
packager = (*muxPackager)(ptr)
|
||||
Self.starving++
|
||||
return
|
||||
}
|
||||
}
|
||||
ptr, ok = Self.lowestChain.popTail()
|
||||
if ok {
|
||||
packager = (*muxPackager)(ptr)
|
||||
if Self.starving > 0 {
|
||||
Self.starving = Self.starving / 2
|
||||
}
|
||||
return
|
||||
}
|
||||
if Self.starving > 0 {
|
||||
ptr, ok = Self.middleChain.popTail()
|
||||
if ok {
|
||||
packager = (*muxPackager)(ptr)
|
||||
Self.starving++
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *priorityQueue) Stop() {
|
||||
Self.stop = true
|
||||
Self.cond.Broadcast()
|
||||
}
|
||||
|
||||
type connQueue struct {
|
||||
chain *bufChain
|
||||
starving uint8
|
||||
stop bool
|
||||
cond *sync.Cond
|
||||
}
|
||||
|
||||
func (Self *connQueue) New() {
|
||||
Self.chain = new(bufChain)
|
||||
Self.chain.new(32)
|
||||
locker := new(sync.Mutex)
|
||||
Self.cond = sync.NewCond(locker)
|
||||
}
|
||||
|
||||
func (Self *connQueue) Push(connection *conn) {
|
||||
Self.chain.pushHead(unsafe.Pointer(connection))
|
||||
Self.cond.Broadcast()
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *connQueue) Pop() (connection *conn) {
|
||||
var iter bool
|
||||
for {
|
||||
connection = Self.TryPop()
|
||||
if connection != nil {
|
||||
return
|
||||
}
|
||||
if Self.stop {
|
||||
return
|
||||
}
|
||||
if iter {
|
||||
break
|
||||
// trying to pop twice
|
||||
}
|
||||
iter = true
|
||||
runtime.Gosched()
|
||||
}
|
||||
Self.cond.L.Lock()
|
||||
defer Self.cond.L.Unlock()
|
||||
for connection = Self.TryPop(); connection == nil; {
|
||||
if Self.stop {
|
||||
return
|
||||
}
|
||||
Self.cond.Wait()
|
||||
// wait for it with no more iter
|
||||
connection = Self.TryPop()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *connQueue) TryPop() (connection *conn) {
|
||||
ptr, ok := Self.chain.popTail()
|
||||
if ok {
|
||||
connection = (*conn)(ptr)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *connQueue) Stop() {
|
||||
Self.stop = true
|
||||
Self.cond.Broadcast()
|
||||
}
|
||||
|
||||
type listElement struct {
|
||||
Buf []byte
|
||||
L uint16
|
||||
Part bool
|
||||
}
|
||||
|
||||
func (Self *listElement) Reset() {
|
||||
Self.L = 0
|
||||
Self.Buf = nil
|
||||
Self.Part = false
|
||||
}
|
||||
|
||||
func newListElement(buf []byte, l uint16, part bool) (element *listElement, err error) {
|
||||
if uint16(len(buf)) != l {
|
||||
err = errors.New("listElement: buf length not match")
|
||||
return
|
||||
}
|
||||
element = listEle.Get()
|
||||
element.Buf = buf
|
||||
element.L = l
|
||||
element.Part = part
|
||||
return
|
||||
}
|
||||
|
||||
type receiveWindowQueue struct {
|
||||
lengthWait uint64
|
||||
chain *bufChain
|
||||
stopOp chan struct{}
|
||||
readOp chan struct{}
|
||||
// https://golang.org/pkg/sync/atomic/#pkg-note-BUG
|
||||
// On non-Linux ARM, the 64-bit functions use instructions unavailable before the ARMv6k core.
|
||||
// On ARM, x86-32, and 32-bit MIPS, it is the caller's responsibility
|
||||
// to arrange for 64-bit alignment of 64-bit words accessed atomically.
|
||||
// The first word in a variable or in an allocated struct, array, or slice can be relied upon to be 64-bit aligned.
|
||||
|
||||
// if there are implicit struct, careful the first word
|
||||
timeout time.Time
|
||||
}
|
||||
|
||||
func newReceiveWindowQueue() *receiveWindowQueue {
|
||||
queue := receiveWindowQueue{
|
||||
chain: new(bufChain),
|
||||
stopOp: make(chan struct{}, 2),
|
||||
readOp: make(chan struct{}),
|
||||
}
|
||||
queue.chain.new(64)
|
||||
return &queue
|
||||
}
|
||||
|
||||
func (Self *receiveWindowQueue) Push(element *listElement) {
|
||||
var length, wait uint32
|
||||
for {
|
||||
ptrs := atomic.LoadUint64(&Self.lengthWait)
|
||||
length, wait = Self.chain.head.unpack(ptrs)
|
||||
length += uint32(element.L)
|
||||
if atomic.CompareAndSwapUint64(&Self.lengthWait, ptrs, Self.chain.head.pack(length, 0)) {
|
||||
break
|
||||
}
|
||||
// another goroutine change the length or into wait, make sure
|
||||
}
|
||||
Self.chain.pushHead(unsafe.Pointer(element))
|
||||
if wait == 1 {
|
||||
Self.allowPop()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *receiveWindowQueue) Pop() (element *listElement, err error) {
|
||||
var length uint32
|
||||
startPop:
|
||||
ptrs := atomic.LoadUint64(&Self.lengthWait)
|
||||
length, _ = Self.chain.head.unpack(ptrs)
|
||||
if length == 0 {
|
||||
if !atomic.CompareAndSwapUint64(&Self.lengthWait, ptrs, Self.chain.head.pack(0, 1)) {
|
||||
goto startPop // another goroutine is pushing
|
||||
}
|
||||
err = Self.waitPush()
|
||||
// there is no more data in queue, wait for it
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
goto startPop // wait finish, trying to Get the New status
|
||||
}
|
||||
// length is not zero, so try to pop
|
||||
for {
|
||||
element = Self.TryPop()
|
||||
if element != nil {
|
||||
return
|
||||
}
|
||||
runtime.Gosched() // another goroutine is still pushing
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *receiveWindowQueue) TryPop() (element *listElement) {
|
||||
ptr, ok := Self.chain.popTail()
|
||||
if ok {
|
||||
element = (*listElement)(ptr)
|
||||
atomic.AddUint64(&Self.lengthWait, ^(uint64(element.L)<<dequeueBits - 1))
|
||||
return
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (Self *receiveWindowQueue) allowPop() (closed bool) {
|
||||
select {
|
||||
case Self.readOp <- struct{}{}:
|
||||
return false
|
||||
case <-Self.stopOp:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *receiveWindowQueue) waitPush() (err error) {
|
||||
t := Self.timeout.Sub(time.Now())
|
||||
if t <= 0 {
|
||||
// not Set the timeout, so wait for it without timeout, just like a tcp connection
|
||||
select {
|
||||
case <-Self.readOp:
|
||||
return nil
|
||||
case <-Self.stopOp:
|
||||
err = io.EOF
|
||||
return
|
||||
}
|
||||
}
|
||||
timer := time.NewTimer(t)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-Self.readOp:
|
||||
return nil
|
||||
case <-Self.stopOp:
|
||||
err = io.EOF
|
||||
return
|
||||
case <-timer.C:
|
||||
err = errors.New("mux.queue: read time out")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *receiveWindowQueue) Len() (n uint32) {
|
||||
ptrs := atomic.LoadUint64(&Self.lengthWait)
|
||||
n, _ = Self.chain.head.unpack(ptrs)
|
||||
// just for unpack method use
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *receiveWindowQueue) Stop() {
|
||||
Self.stopOp <- struct{}{}
|
||||
Self.stopOp <- struct{}{}
|
||||
}
|
||||
|
||||
func (Self *receiveWindowQueue) SetTimeOut(t time.Time) {
|
||||
Self.timeout = t
|
||||
}
|
||||
|
||||
// https://golang.org/src/sync/poolqueue.go
|
||||
|
||||
type bufDequeue struct {
|
||||
// headTail packs together a 32-bit head index and a 32-bit
|
||||
// tail index. Both are indexes into vals modulo len(vals)-1.
|
||||
//
|
||||
// tail = index of oldest data in queue
|
||||
// head = index of next slot to fill
|
||||
//
|
||||
// Slots in the range [tail, head) are owned by consumers.
|
||||
// A consumer continues to own a slot outside this range until
|
||||
// it nils the slot, at which point ownership passes to the
|
||||
// producer.
|
||||
//
|
||||
// The head index is stored in the most-significant bits so
|
||||
// that we can atomically add to it and the overflow is
|
||||
// harmless.
|
||||
headTail uint64
|
||||
|
||||
// vals is a ring buffer of interface{} values stored in this
|
||||
// dequeue. The size of this must be a power of 2.
|
||||
//
|
||||
// A slot is still in use until *both* the tail
|
||||
// index has moved beyond it and typ has been Set to nil. This
|
||||
// is Set to nil atomically by the consumer and read
|
||||
// atomically by the producer.
|
||||
vals []unsafe.Pointer
|
||||
starving uint32
|
||||
}
|
||||
|
||||
const dequeueBits = 32
|
||||
|
||||
// dequeueLimit is the maximum size of a bufDequeue.
|
||||
//
|
||||
// This must be at most (1<<dequeueBits)/2 because detecting fullness
|
||||
// depends on wrapping around the ring buffer without wrapping around
|
||||
// the index. We divide by 4 so this fits in an int on 32-bit.
|
||||
const dequeueLimit = (1 << dequeueBits) / 4
|
||||
|
||||
func (d *bufDequeue) unpack(ptrs uint64) (head, tail uint32) {
|
||||
const mask = 1<<dequeueBits - 1
|
||||
head = uint32((ptrs >> dequeueBits) & mask)
|
||||
tail = uint32(ptrs & mask)
|
||||
return
|
||||
}
|
||||
|
||||
func (d *bufDequeue) pack(head, tail uint32) uint64 {
|
||||
const mask = 1<<dequeueBits - 1
|
||||
return (uint64(head) << dequeueBits) |
|
||||
uint64(tail&mask)
|
||||
}
|
||||
|
||||
// pushHead adds val at the head of the queue. It returns false if the
|
||||
// queue is full.
|
||||
func (d *bufDequeue) pushHead(val unsafe.Pointer) bool {
|
||||
var slot *unsafe.Pointer
|
||||
var starve uint8
|
||||
if atomic.LoadUint32(&d.starving) > 0 {
|
||||
runtime.Gosched()
|
||||
}
|
||||
for {
|
||||
ptrs := atomic.LoadUint64(&d.headTail)
|
||||
head, tail := d.unpack(ptrs)
|
||||
if (tail+uint32(len(d.vals)))&(1<<dequeueBits-1) == head {
|
||||
// Queue is full.
|
||||
return false
|
||||
}
|
||||
ptrs2 := d.pack(head+1, tail)
|
||||
if atomic.CompareAndSwapUint64(&d.headTail, ptrs, ptrs2) {
|
||||
slot = &d.vals[head&uint32(len(d.vals)-1)]
|
||||
if starve >= 3 && atomic.LoadUint32(&d.starving) > 0 {
|
||||
atomic.StoreUint32(&d.starving, 0)
|
||||
}
|
||||
break
|
||||
}
|
||||
starve++
|
||||
if starve >= 3 {
|
||||
atomic.StoreUint32(&d.starving, 1)
|
||||
}
|
||||
}
|
||||
// The head slot is free, so we own it.
|
||||
*slot = val
|
||||
return true
|
||||
}
|
||||
|
||||
// popTail removes and returns the element at the tail of the queue.
|
||||
// It returns false if the queue is empty. It may be called by any
|
||||
// number of consumers.
|
||||
func (d *bufDequeue) popTail() (unsafe.Pointer, bool) {
|
||||
var val unsafe.Pointer
|
||||
var head, tail uint32
|
||||
for {
|
||||
ptrs := atomic.LoadUint64(&d.headTail)
|
||||
head, tail = d.unpack(ptrs)
|
||||
if tail == head {
|
||||
// Queue is empty.
|
||||
return nil, false
|
||||
}
|
||||
slot := &d.vals[tail&uint32(len(d.vals)-1)]
|
||||
val = atomic.LoadPointer(slot)
|
||||
if val != nil {
|
||||
// We now get a slot.
|
||||
if atomic.CompareAndSwapPointer(slot, val, nil) {
|
||||
break
|
||||
// Tell pushHead that we're done with this slot. Zeroing the
|
||||
// slot is also important so we don't leave behind references
|
||||
// that could keep this object live longer than necessary.
|
||||
//
|
||||
// We write to val first and then publish that we're done with
|
||||
}
|
||||
}
|
||||
// Maybe the value was taken by other goroutine or not push yet.
|
||||
}
|
||||
// At this point pushHead owns the slot.
|
||||
if tail < math.MaxUint32 {
|
||||
atomic.AddUint64(&d.headTail, 1)
|
||||
} else {
|
||||
atomic.AddUint64(&d.headTail, ^uint64(math.MaxUint32-1))
|
||||
}
|
||||
return val, true
|
||||
}
|
||||
|
||||
// bufChain is a dynamically-sized version of bufDequeue.
|
||||
//
|
||||
// This is implemented as a doubly-linked list queue of poolDequeues
|
||||
// where each dequeue is double the size of the previous one. Once a
|
||||
// dequeue fills up, this allocates a New one and only ever pushes to
|
||||
// the latest dequeue. Pops happen from the other end of the list and
|
||||
// once a dequeue is exhausted, it gets removed from the list.
|
||||
type bufChain struct {
|
||||
// head is the bufDequeue to push to. This is only accessed
|
||||
// by the producer, so doesn't need to be synchronized.
|
||||
head *bufChainElt
|
||||
|
||||
// tail is the bufDequeue to popTail from. This is accessed
|
||||
// by consumers, so reads and writes must be atomic.
|
||||
tail *bufChainElt
|
||||
newChain uint32
|
||||
}
|
||||
|
||||
type bufChainElt struct {
|
||||
bufDequeue
|
||||
|
||||
// next and prev link to the adjacent poolChainElts in this
|
||||
// bufChain.
|
||||
//
|
||||
// next is written atomically by the producer and read
|
||||
// atomically by the consumer. It only transitions from nil to
|
||||
// non-nil.
|
||||
//
|
||||
// prev is written atomically by the consumer and read
|
||||
// atomically by the producer. It only transitions from
|
||||
// non-nil to nil.
|
||||
next, prev *bufChainElt
|
||||
}
|
||||
|
||||
func storePoolChainElt(pp **bufChainElt, v *bufChainElt) {
|
||||
atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(pp)), unsafe.Pointer(v))
|
||||
}
|
||||
|
||||
func loadPoolChainElt(pp **bufChainElt) *bufChainElt {
|
||||
return (*bufChainElt)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(pp))))
|
||||
}
|
||||
|
||||
func (c *bufChain) new(initSize int) {
|
||||
// Initialize the chain.
|
||||
// initSize must be a power of 2
|
||||
d := new(bufChainElt)
|
||||
d.vals = make([]unsafe.Pointer, initSize)
|
||||
storePoolChainElt(&c.head, d)
|
||||
storePoolChainElt(&c.tail, d)
|
||||
}
|
||||
|
||||
func (c *bufChain) pushHead(val unsafe.Pointer) {
|
||||
startPush:
|
||||
for {
|
||||
if atomic.LoadUint32(&c.newChain) > 0 {
|
||||
runtime.Gosched()
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
d := loadPoolChainElt(&c.head)
|
||||
|
||||
if d.pushHead(val) {
|
||||
return
|
||||
}
|
||||
|
||||
// The current dequeue is full. Allocate a New one of twice
|
||||
// the size.
|
||||
if atomic.CompareAndSwapUint32(&c.newChain, 0, 1) {
|
||||
newSize := len(d.vals) * 2
|
||||
if newSize >= dequeueLimit {
|
||||
// Can't make it any bigger.
|
||||
newSize = dequeueLimit
|
||||
}
|
||||
|
||||
d2 := &bufChainElt{prev: d}
|
||||
d2.vals = make([]unsafe.Pointer, newSize)
|
||||
d2.pushHead(val)
|
||||
storePoolChainElt(&c.head, d2)
|
||||
storePoolChainElt(&d.next, d2)
|
||||
atomic.StoreUint32(&c.newChain, 0)
|
||||
return
|
||||
}
|
||||
goto startPush
|
||||
}
|
||||
|
||||
func (c *bufChain) popTail() (unsafe.Pointer, bool) {
|
||||
d := loadPoolChainElt(&c.tail)
|
||||
if d == nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
for {
|
||||
// It's important that we load the next pointer
|
||||
// *before* popping the tail. In general, d may be
|
||||
// transiently empty, but if next is non-nil before
|
||||
// the TryPop and the TryPop fails, then d is permanently
|
||||
// empty, which is the only condition under which it's
|
||||
// safe to drop d from the chain.
|
||||
d2 := loadPoolChainElt(&d.next)
|
||||
|
||||
if val, ok := d.popTail(); ok {
|
||||
return val, ok
|
||||
}
|
||||
|
||||
if d2 == nil {
|
||||
// This is the only dequeue. It's empty right
|
||||
// now, but could be pushed to in the future.
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// The tail of the chain has been drained, so move on
|
||||
// to the next dequeue. Try to drop it from the chain
|
||||
// so the next TryPop doesn't have to look at the empty
|
||||
// dequeue again.
|
||||
if atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&c.tail)), unsafe.Pointer(d), unsafe.Pointer(d2)) {
|
||||
// We won the race. Clear the prev pointer so
|
||||
// the garbage collector can collect the empty
|
||||
// dequeue and so popHead doesn't back up
|
||||
// further than necessary.
|
||||
storePoolChainElt(&d2.prev, nil)
|
||||
}
|
||||
d = d2
|
||||
}
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
package nps_mux
|
||||
|
||||
import (
|
||||
"net"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Rate struct {
|
||||
bucketSize int64
|
||||
bucketSurplusSize int64
|
||||
bucketAddSize int64
|
||||
stopChan chan bool
|
||||
NowRate int64
|
||||
}
|
||||
|
||||
func NewRate(addSize int64) *Rate {
|
||||
return &Rate{
|
||||
bucketSize: addSize * 2,
|
||||
bucketSurplusSize: 0,
|
||||
bucketAddSize: addSize,
|
||||
stopChan: make(chan bool),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Rate) Start() {
|
||||
go s.session()
|
||||
}
|
||||
|
||||
func (s *Rate) add(size int64) {
|
||||
if res := s.bucketSize - s.bucketSurplusSize; res < s.bucketAddSize {
|
||||
atomic.AddInt64(&s.bucketSurplusSize, res)
|
||||
return
|
||||
}
|
||||
atomic.AddInt64(&s.bucketSurplusSize, size)
|
||||
}
|
||||
|
||||
//回桶
|
||||
func (s *Rate) ReturnBucket(size int64) {
|
||||
s.add(size)
|
||||
}
|
||||
|
||||
//停止
|
||||
func (s *Rate) Stop() {
|
||||
s.stopChan <- true
|
||||
}
|
||||
|
||||
func (s *Rate) Get(size int64) {
|
||||
if s.bucketSurplusSize >= size {
|
||||
atomic.AddInt64(&s.bucketSurplusSize, -size)
|
||||
return
|
||||
}
|
||||
ticker := time.NewTicker(time.Millisecond * 100)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if s.bucketSurplusSize >= size {
|
||||
atomic.AddInt64(&s.bucketSurplusSize, -size)
|
||||
ticker.Stop()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Rate) session() {
|
||||
ticker := time.NewTicker(time.Second * 1)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if rs := s.bucketAddSize - s.bucketSurplusSize; rs > 0 {
|
||||
s.NowRate = rs
|
||||
} else {
|
||||
s.NowRate = s.bucketSize - s.bucketSurplusSize
|
||||
}
|
||||
s.add(s.bucketAddSize)
|
||||
case <-s.stopChan:
|
||||
ticker.Stop()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Conn struct {
|
||||
conn net.Conn
|
||||
rate *Rate
|
||||
}
|
||||
|
||||
func NewRateConn(rate *Rate, conn net.Conn) *Conn {
|
||||
return &Conn{
|
||||
conn: conn,
|
||||
rate: rate,
|
||||
}
|
||||
}
|
||||
|
||||
func (conn *Conn) Read(b []byte) (n int, err error) {
|
||||
defer func() {
|
||||
conn.rate.Get(int64(n))
|
||||
}()
|
||||
return conn.conn.Read(b)
|
||||
}
|
||||
|
||||
func (conn *Conn) Write(b []byte) (n int, err error) {
|
||||
defer func() {
|
||||
conn.rate.Get(int64(n))
|
||||
}()
|
||||
return conn.conn.Write(b)
|
||||
}
|
||||
|
||||
func (conn *Conn) LocalAddr() net.Addr {
|
||||
return conn.conn.LocalAddr()
|
||||
}
|
||||
|
||||
func (conn *Conn) RemoteAddr() net.Addr {
|
||||
return conn.conn.RemoteAddr()
|
||||
}
|
||||
|
||||
func (conn *Conn) SetDeadline(t time.Time) error {
|
||||
return conn.conn.SetDeadline(t)
|
||||
}
|
||||
|
||||
func (conn *Conn) SetWriteDeadline(t time.Time) error {
|
||||
return conn.conn.SetWriteDeadline(t)
|
||||
}
|
||||
|
||||
func (conn *Conn) SetReadDeadline(t time.Time) error {
|
||||
return conn.conn.SetReadDeadline(t)
|
||||
}
|
||||
|
||||
func (conn *Conn) Close() error {
|
||||
return conn.conn.Close()
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package nps_mux
|
||||
|
||||
import (
|
||||
"net"
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func sysGetSock(fd *os.File) (bufferSize int, err error) {
|
||||
if fd != nil {
|
||||
return syscall.GetsockoptInt(int(fd.Fd()), syscall.SOL_SOCKET, syscall.SO_RCVBUF)
|
||||
} else {
|
||||
return 5 * 1024 * 1024, nil
|
||||
}
|
||||
}
|
||||
|
||||
func getConnFd(c net.Conn) (fd *os.File, err error) {
|
||||
switch c.(type) {
|
||||
case *net.TCPConn:
|
||||
fd, err = c.(*net.TCPConn).File()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
case *net.UDPConn:
|
||||
fd, err = c.(*net.UDPConn).File()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
//go:build windows
|
||||
// +build windows
|
||||
|
||||
package nps_mux
|
||||
|
||||
import (
|
||||
"net"
|
||||
"os"
|
||||
)
|
||||
|
||||
func sysGetSock(fd *os.File) (bufferSize int, err error) {
|
||||
// https://github.com/golang/sys/blob/master/windows/syscall_windows.go#L1184
|
||||
// not support, WTF???
|
||||
// Todo
|
||||
// return syscall.GetsockoptInt((syscall.Handle)(unsafe.Pointer(fd.Fd())), syscall.SOL_SOCKET, syscall.SO_RCVBUF)
|
||||
bufferSize = 15 * 1024 * 1024
|
||||
return
|
||||
}
|
||||
|
||||
func getConnFd(c net.Conn) (fd *os.File, err error) {
|
||||
switch c.(type) {
|
||||
case *net.TCPConn:
|
||||
//fd, err = c.(*net.TCPConn).File()
|
||||
//if err != nil {
|
||||
// return
|
||||
//}
|
||||
return
|
||||
case *net.UDPConn:
|
||||
//fd, err = c.(*net.UDPConn).File()
|
||||
//if err != nil {
|
||||
// return
|
||||
//}
|
||||
return
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -1,224 +0,0 @@
|
||||
package nps_mux
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"net"
|
||||
"os/exec"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Eth struct {
|
||||
EthName string
|
||||
EthAddr string
|
||||
}
|
||||
|
||||
type TrafficControl struct {
|
||||
Eth *Eth
|
||||
params []string
|
||||
}
|
||||
|
||||
func Ips() (map[string]string, error) {
|
||||
|
||||
ips := make(map[string]string)
|
||||
|
||||
interfaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, i := range interfaces {
|
||||
byName, err := net.InterfaceByName(i.Name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !strings.Contains(byName.Name, "Loopback") && !strings.Contains(byName.Name, "isatap") {
|
||||
addresses, _ := byName.Addrs()
|
||||
for _, v := range addresses {
|
||||
ips[byName.Name] = v.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
return ips, nil
|
||||
}
|
||||
|
||||
// get ip and Eth information by Eth name
|
||||
func GetEthByIp(ipAddr string) (eth *Eth, err error) {
|
||||
var interfaces []net.Interface
|
||||
interfaces, err = net.Interfaces()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, i := range interfaces {
|
||||
var byName *net.Interface
|
||||
byName, err = net.InterfaceByName(i.Name)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// except lo
|
||||
if !strings.Contains(byName.Name, "Loopback") && !strings.Contains(byName.Name, "isatap") && !strings.Contains(byName.Name, "lo") {
|
||||
addresses, _ := byName.Addrs()
|
||||
for _, v := range addresses {
|
||||
ipMask := strings.Split(v.String(), "/")
|
||||
if len(ipMask) == 2 {
|
||||
if ipAddr == "" || ipMask[0] == ipAddr {
|
||||
eth = new(Eth)
|
||||
eth.EthAddr = ipMask[0]
|
||||
eth.EthName = byName.Name
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
err = errors.New("not found interface")
|
||||
return
|
||||
}
|
||||
|
||||
type tcFunc func()
|
||||
|
||||
func getArrayExhaustivity(arr []tcFunc) (result [][]tcFunc) {
|
||||
var l = int(math.Pow(float64(2), float64(len(arr))) - 1)
|
||||
var t []tcFunc
|
||||
for i := 1; i <= l; i++ {
|
||||
s := i
|
||||
t = []tcFunc{}
|
||||
for k := 0; s > 0; k++ {
|
||||
if s&1 == 1 {
|
||||
t = append(t, arr[k])
|
||||
}
|
||||
s >>= 1
|
||||
}
|
||||
result = append(result, t)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func NewTrafficControl(ipAddr string) (*TrafficControl, error) {
|
||||
Eth, err := GetEthByIp(ipAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t := new(TrafficControl)
|
||||
t.params = make([]string, 0)
|
||||
t.Eth = Eth
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// test the network randomly
|
||||
func (tc *TrafficControl) RunNetRangeTest(f func()) error {
|
||||
funcs := tc.getTestVariable()
|
||||
groups := getArrayExhaustivity(funcs)
|
||||
for _, v := range groups {
|
||||
tc.del()
|
||||
// execute bandwidth control, not good work
|
||||
//if err := tc.bandwidth("1mbit"); err != nil {
|
||||
// return err
|
||||
//}
|
||||
// execute random strategy
|
||||
for _, vv := range v {
|
||||
vv()
|
||||
}
|
||||
err := tc.Run()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// execute test func
|
||||
f()
|
||||
// clear strategy
|
||||
if err := tc.del(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// create test variables
|
||||
func (tc *TrafficControl) getTestVariable() []tcFunc {
|
||||
return []tcFunc{
|
||||
func() { tc.delay("add", "100ms", "10ms", "30%") },
|
||||
func() { tc.loss("add", "1%", "30%") },
|
||||
func() { tc.duplicate("add", "1%") },
|
||||
func() { tc.corrupt("add", "0.2%") },
|
||||
}
|
||||
}
|
||||
|
||||
// this command sets the transmission of the network card to delayVal. At the same time,
|
||||
// about waveRatio of the packets will be delayed by ± wave.
|
||||
func (tc *TrafficControl) delay(opt, delayVal, wave, waveRatio string) {
|
||||
tc.params = append(tc.params, []string{"delay", delayVal, wave, waveRatio}...)
|
||||
}
|
||||
|
||||
// this command sets the transmission of the network card to randomly drop lossRatio of packets with a success rate of lossSuccessRatio.
|
||||
func (tc *TrafficControl) loss(opt, lossRatio, lossSuccessRatio string) {
|
||||
tc.params = append(tc.params, []string{"loss", lossRatio, lossSuccessRatio}...)
|
||||
}
|
||||
|
||||
// this command sets the transmission of the network card to randomly generate repeatRatio duplicate packets
|
||||
func (tc *TrafficControl) duplicate(opt, duplicateRatio string) {
|
||||
tc.params = append(tc.params, []string{"duplicate", duplicateRatio}...)
|
||||
}
|
||||
|
||||
// this command sets the transmission of the network card to randomly generate corruptRatio corrupted packets.
|
||||
// the kernel version must be above 2.6.16
|
||||
func (tc *TrafficControl) corrupt(opt, corruptRatio string) {
|
||||
tc.params = append(tc.params, []string{"corrupt", corruptRatio}...)
|
||||
}
|
||||
|
||||
func (tc *TrafficControl) Run() error {
|
||||
tc.params = append([]string{"qdisc", "add", "dev", tc.Eth.EthName, "root", "netem"}, tc.params...)
|
||||
return runCmd(exec.Command("tc", tc.params...))
|
||||
}
|
||||
|
||||
// remove all tc setting
|
||||
func (tc *TrafficControl) del() error {
|
||||
tc.clear()
|
||||
return runCmd(exec.Command("tc", "qdisc", "del", "dev", tc.Eth.EthName, "root"))
|
||||
}
|
||||
|
||||
// clear the old settings
|
||||
func (tc *TrafficControl) clear() {
|
||||
tc.params = tc.params[:0]
|
||||
}
|
||||
|
||||
// remove all tc setting
|
||||
func (tc *TrafficControl) bandwidth(bw string) error {
|
||||
runCmd(exec.Command("tc", "qdisc", "add", "dev", tc.Eth.EthName, "root", "handle", "2:", "htb", "default", "30"))
|
||||
return runCmd(exec.Command("tc", "qdisc", "add", "dev", tc.Eth.EthName, "parent", "2:", "classid", "2:30", "htb", "rate", bw))
|
||||
}
|
||||
|
||||
func runCmd(cmd *exec.Cmd) error {
|
||||
fmt.Println("run cmd:", cmd.Args)
|
||||
var out bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stdout = &out
|
||||
cmd.Stderr = &stderr
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func createNetwork(name, networok string) error {
|
||||
// docker network create --subnet=172.18.0.0/16 test
|
||||
return runCmd(exec.Command("docker", "network", "create", "--subnet="+networok, name))
|
||||
}
|
||||
|
||||
func deleteNetwork(name string) error {
|
||||
return runCmd(exec.Command("docker", "network", "rm", name))
|
||||
}
|
||||
|
||||
func runDocker(dockerName, networkName, ip, testFunName, nowDir string) error {
|
||||
// docker run --env GOPROXY=https://goproxy.cn --rm --name client --net test --cap-add=NET_ADMIN --ip 172.18.0.5 -v "$PWD":/usr/src/myapp -w /usr/src/myapp golang go test -v -run TestClient ./
|
||||
return runCmd(exec.Command("docker", "run", "--env", "GOPROXY=https://goproxy.cn", "--rm", "--name", dockerName, "--net", networkName,
|
||||
"--cap-add=NET_ADMIN", "--ip", ip, "-v", nowDir+`:/usr/src/myapp`, "-w", `/usr/src/myapp`, "golang", "go", "test",
|
||||
"-v", "-run", testFunName, "./"))
|
||||
}
|
||||
|
||||
func stopDocker(dockerName string) error {
|
||||
return runCmd(exec.Command("docker", "stop", dockerName))
|
||||
}
|
||||
@@ -18,7 +18,7 @@ func NewRateConn(conn io.ReadWriteCloser, rate *Rate) io.ReadWriteCloser {
|
||||
|
||||
func (s *rateConn) Read(b []byte) (n int, err error) {
|
||||
n, err = s.conn.Read(b)
|
||||
if s.rate != nil && s.rate.addSize > 0 {
|
||||
if s.rate != nil {
|
||||
s.rate.Get(int64(n))
|
||||
}
|
||||
return
|
||||
@@ -26,7 +26,7 @@ func (s *rateConn) Read(b []byte) (n int, err error) {
|
||||
|
||||
func (s *rateConn) Write(b []byte) (n int, err error) {
|
||||
n, err = s.conn.Write(b)
|
||||
if s.rate != nil && s.rate.addSize > 0 {
|
||||
if s.rate != nil {
|
||||
s.rate.Get(int64(n))
|
||||
}
|
||||
return
|
||||
|
||||
@@ -1,59 +1,81 @@
|
||||
package rate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
xrate "golang.org/x/time/rate"
|
||||
)
|
||||
|
||||
type Rate struct {
|
||||
limiter *xrate.Limiter
|
||||
addSize int64
|
||||
stopChan chan struct{}
|
||||
NowRate int64
|
||||
bucketSize int64
|
||||
bucketSurplusSize int64
|
||||
bucketAddSize int64
|
||||
stopChan chan bool
|
||||
NowRate int64
|
||||
}
|
||||
|
||||
func NewRate(addSize int64) *Rate {
|
||||
return &Rate{
|
||||
limiter: xrate.NewLimiter(xrate.Limit(addSize), int(addSize)),
|
||||
addSize: addSize,
|
||||
stopChan: make(chan struct{}),
|
||||
NowRate: addSize,
|
||||
bucketSize: addSize * 2,
|
||||
bucketSurplusSize: 0,
|
||||
bucketAddSize: addSize,
|
||||
stopChan: make(chan bool),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Rate) Start() {
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
s.NowRate = s.addSize - (int64(s.limiter.Tokens()))
|
||||
case <-s.stopChan:
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
go s.session()
|
||||
}
|
||||
|
||||
func (s *Rate) Stop() {
|
||||
select {
|
||||
case <-s.stopChan:
|
||||
default:
|
||||
close(s.stopChan)
|
||||
func (s *Rate) add(size int64) {
|
||||
if res := s.bucketSize - s.bucketSurplusSize; res < s.bucketAddSize {
|
||||
atomic.AddInt64(&s.bucketSurplusSize, res)
|
||||
return
|
||||
}
|
||||
atomic.AddInt64(&s.bucketSurplusSize, size)
|
||||
}
|
||||
|
||||
//回桶
|
||||
func (s *Rate) ReturnBucket(size int64) {
|
||||
s.add(size)
|
||||
}
|
||||
|
||||
//停止
|
||||
func (s *Rate) Stop() {
|
||||
s.stopChan <- true
|
||||
}
|
||||
|
||||
func (s *Rate) Get(size int64) {
|
||||
if s.addSize <= 0 {
|
||||
if s.bucketSurplusSize >= size {
|
||||
atomic.AddInt64(&s.bucketSurplusSize, -size)
|
||||
return
|
||||
}
|
||||
if size <= 0 {
|
||||
return
|
||||
ticker := time.NewTicker(time.Millisecond * 100)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if s.bucketSurplusSize >= size {
|
||||
atomic.AddInt64(&s.bucketSurplusSize, -size)
|
||||
ticker.Stop()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Rate) session() {
|
||||
ticker := time.NewTicker(time.Second * 1)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if rs := s.bucketAddSize - s.bucketSurplusSize; rs > 0 {
|
||||
s.NowRate = rs
|
||||
} else {
|
||||
s.NowRate = s.bucketSize - s.bucketSurplusSize
|
||||
}
|
||||
s.add(s.bucketAddSize)
|
||||
case <-s.stopChan:
|
||||
ticker.Stop()
|
||||
return
|
||||
}
|
||||
}
|
||||
ctx := context.Background()
|
||||
_ = s.limiter.WaitN(ctx, int(size))
|
||||
s.NowRate = s.addSize - (int64(s.limiter.Tokens()))
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package version
|
||||
|
||||
const VERSION = "0.26.28"
|
||||
const VERSION = "100.26.10"
|
||||
|
||||
// Compulsory minimum version, Minimum downward compatibility to this version
|
||||
func GetVersion() string {
|
||||
return "0.26.0"
|
||||
return "100.26.0"
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
"ehang.io/nps/bridge"
|
||||
@@ -23,13 +22,12 @@ type NetBridge interface {
|
||||
SendLinkInfo(clientId int, link *conn.Link, t *file.Tunnel) (target net.Conn, err error)
|
||||
}
|
||||
|
||||
// BaseServer struct
|
||||
//BaseServer struct
|
||||
type BaseServer struct {
|
||||
id int
|
||||
bridge NetBridge
|
||||
task *file.Tunnel
|
||||
errorContent []byte
|
||||
errorCode int
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
@@ -42,7 +40,7 @@ func NewBaseServer(bridge *bridge.Bridge, task *file.Tunnel) *BaseServer {
|
||||
}
|
||||
}
|
||||
|
||||
// add the flow
|
||||
//add the flow
|
||||
func (s *BaseServer) FlowAdd(in, out int64) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
@@ -50,7 +48,7 @@ func (s *BaseServer) FlowAdd(in, out int64) {
|
||||
s.task.Flow.InletFlow += in
|
||||
}
|
||||
|
||||
// change the flow
|
||||
//change the flow
|
||||
func (s *BaseServer) FlowAddHost(host *file.Host, in, out int64) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
@@ -58,13 +56,13 @@ func (s *BaseServer) FlowAddHost(host *file.Host, in, out int64) {
|
||||
host.Flow.InletFlow += in
|
||||
}
|
||||
|
||||
// write fail bytes to the connection
|
||||
//write fail bytes to the connection
|
||||
func (s *BaseServer) writeConnFail(c net.Conn) {
|
||||
c.Write([]byte(common.ConnectionFailBytes))
|
||||
c.Write(s.errorContent)
|
||||
}
|
||||
|
||||
// auth check
|
||||
//auth check
|
||||
func (s *BaseServer) auth(r *http.Request, c *conn.Conn, u, p string) error {
|
||||
if u != "" && p != "" && !common.CheckAuth(r, u, p) {
|
||||
c.Write([]byte(common.UnauthorizedBytes))
|
||||
@@ -74,7 +72,7 @@ func (s *BaseServer) auth(r *http.Request, c *conn.Conn, u, p string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// check flow limit of the client ,and decrease the allow num of client
|
||||
//check flow limit of the client ,and decrease the allow num of client
|
||||
func (s *BaseServer) CheckFlowAndConnNum(client *file.Client) error {
|
||||
if client.Flow.FlowLimit > 0 && (client.Flow.FlowLimit<<20) < (client.Flow.ExportFlow+client.Flow.InletFlow) {
|
||||
return errors.New("Traffic exceeded")
|
||||
@@ -85,37 +83,9 @@ func (s *BaseServer) CheckFlowAndConnNum(client *file.Client) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func in(target string, str_array []string) bool {
|
||||
sort.Strings(str_array)
|
||||
index := sort.SearchStrings(str_array, target)
|
||||
if index < len(str_array) && str_array[index] == target {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// create a new connection and start bytes copying
|
||||
func (s *BaseServer) DealClient(c *conn.Conn, client *file.Client, addr string,
|
||||
rb []byte, tp string, f func(), flow *file.Flow, localProxy bool, task *file.Tunnel) error {
|
||||
|
||||
// 判断访问地址是否在全局黑名单内
|
||||
if IsGlobalBlackIp(c.RemoteAddr().String()) {
|
||||
c.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
// 判断访问地址是否在黑名单内
|
||||
if common.IsBlackIp(c.RemoteAddr().String(), client.VerifyKey, client.BlackIpList) {
|
||||
c.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
protoVersion := ""
|
||||
if task != nil {
|
||||
protoVersion = task.ProtoVersion
|
||||
}
|
||||
|
||||
link := conn.NewLink(tp, addr, client.Cnf.Crypt, client.Cnf.Compress, c.Conn.RemoteAddr().String(), localProxy, protoVersion)
|
||||
//create a new connection and start bytes copying
|
||||
func (s *BaseServer) DealClient(c *conn.Conn, client *file.Client, addr string, rb []byte, tp string, f func(), flow *file.Flow, localProxy bool) error {
|
||||
link := conn.NewLink(tp, addr, client.Cnf.Crypt, client.Cnf.Compress, c.Conn.RemoteAddr().String(), localProxy)
|
||||
if target, err := s.bridge.SendLinkInfo(client.Id, link, s.task); err != nil {
|
||||
logs.Warn("get connection from client id %d error %s", client.Id, err.Error())
|
||||
c.Close()
|
||||
@@ -124,22 +94,7 @@ func (s *BaseServer) DealClient(c *conn.Conn, client *file.Client, addr string,
|
||||
if f != nil {
|
||||
f()
|
||||
}
|
||||
conn.CopyWaitGroup(target, c.Conn, link.Crypt, link.Compress, client.Rate, flow, true, rb, task)
|
||||
conn.CopyWaitGroup(target, c.Conn, link.Crypt, link.Compress, client.Rate, flow, true, rb)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 判断访问地址是否在全局黑名单内
|
||||
func IsGlobalBlackIp(ipPort string) bool {
|
||||
// 判断访问地址是否在全局黑名单内
|
||||
global := file.GetDb().GetGlobal()
|
||||
if global != nil {
|
||||
ip := common.GetIpByAddr(ipPort)
|
||||
if in(ip, global.BlackIpList) {
|
||||
logs.Error("IP地址[" + ip + "]在全局黑名单列表内")
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -3,23 +3,23 @@ package proxy
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"ehang.io/nps/bridge"
|
||||
"ehang.io/nps/lib/cache"
|
||||
"ehang.io/nps/lib/common"
|
||||
"ehang.io/nps/lib/conn"
|
||||
"ehang.io/nps/lib/file"
|
||||
"ehang.io/nps/lib/goroutine"
|
||||
"ehang.io/nps/server/connection"
|
||||
"encoding/json"
|
||||
"github.com/astaxie/beego/logs"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"ehang.io/nps/bridge"
|
||||
"ehang.io/nps/lib/cache"
|
||||
"ehang.io/nps/lib/common"
|
||||
"ehang.io/nps/lib/conn"
|
||||
"ehang.io/nps/lib/file"
|
||||
"ehang.io/nps/server/connection"
|
||||
"github.com/astaxie/beego/logs"
|
||||
)
|
||||
|
||||
type httpServer struct {
|
||||
@@ -102,38 +102,16 @@ func (s *httpServer) Close() error {
|
||||
}
|
||||
|
||||
func (s *httpServer) handleTunneling(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var host *file.Host
|
||||
var err error
|
||||
host, err = file.GetDb().GetInfoByHost(r.Host, r)
|
||||
hijacker, ok := w.(http.Hijacker)
|
||||
if !ok {
|
||||
http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
c, _, err := hijacker.Hijack()
|
||||
if err != nil {
|
||||
logs.Debug("the url %s %s %s can't be parsed!", r.URL.Scheme, r.Host, r.RequestURI)
|
||||
return
|
||||
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
||||
}
|
||||
|
||||
// 自动 http 301 https
|
||||
if host.AutoHttps && r.TLS == nil {
|
||||
http.Redirect(w, r, "https://"+r.Host+r.RequestURI, http.StatusMovedPermanently)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Header.Get("Upgrade") != "" {
|
||||
rProxy := NewHttpReverseProxy(s)
|
||||
rProxy.ServeHTTP(w, r)
|
||||
} else {
|
||||
hijacker, ok := w.(http.Hijacker)
|
||||
if !ok {
|
||||
http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
c, _, err := hijacker.Hijack()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
||||
}
|
||||
|
||||
s.handleHttp(conn.NewConn(c), r)
|
||||
}
|
||||
|
||||
s.handleHttp(conn.NewConn(c), r)
|
||||
}
|
||||
|
||||
func (s *httpServer) handleHttp(c *conn.Conn, r *http.Request) {
|
||||
@@ -148,7 +126,6 @@ func (s *httpServer) handleHttp(c *conn.Conn, r *http.Request) {
|
||||
lenConn *conn.LenConn
|
||||
isReset bool
|
||||
wg sync.WaitGroup
|
||||
remoteAddr string
|
||||
)
|
||||
defer func() {
|
||||
if connClient != nil {
|
||||
@@ -162,27 +139,12 @@ reset:
|
||||
if isReset {
|
||||
host.Client.AddConn()
|
||||
}
|
||||
|
||||
remoteAddr = strings.TrimSpace(r.Header.Get("X-Forwarded-For"))
|
||||
if len(remoteAddr) == 0 {
|
||||
remoteAddr = c.RemoteAddr().String()
|
||||
}
|
||||
|
||||
// 判断访问地址是否在全局黑名单内
|
||||
if IsGlobalBlackIp(c.RemoteAddr().String()) {
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
|
||||
if host, err = file.GetDb().GetInfoByHost(r.Host, r); err != nil {
|
||||
logs.Notice("the url %s %s %s can't be parsed!, host %s, url %s, remote address %s", r.URL.Scheme, r.Host, r.RequestURI, r.Host, r.URL.Path, remoteAddr)
|
||||
c.Close()
|
||||
logs.Notice("the url %s %s %s can't be parsed!", r.URL.Scheme, r.Host, r.RequestURI)
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.CheckFlowAndConnNum(host.Client); err != nil {
|
||||
logs.Warn("client id %d, host id %d, error %s, when https connection", host.Client.Id, host.Id, err.Error())
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
if !isReset {
|
||||
@@ -196,53 +158,7 @@ reset:
|
||||
logs.Warn(err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if host.Client.IpWhite && host.Client.IpWhitePass != "" {
|
||||
if common.IsAuthIp(c.RemoteAddr().String(), host.Client.VerifyKey, host.Client.IpWhiteList) {
|
||||
|
||||
if r.URL.Path == "/authIp" {
|
||||
rawQuery := r.URL.RawQuery
|
||||
|
||||
var jsonBytes []byte
|
||||
ip := common.GetIpByAddr(c.RemoteAddr().String())
|
||||
|
||||
if strings.Contains(rawQuery, "pass=") {
|
||||
// 截取 = 后面的值
|
||||
pass := strings.Split(rawQuery, "pass=")[1]
|
||||
if pass == host.Client.IpWhitePass {
|
||||
host.Client.IpWhiteList = append(host.Client.IpWhiteList, ip)
|
||||
file.GetDb().UpdateClient(host.Client)
|
||||
logs.Info("客户端IP白名单认证授权成功:vkey [%s] ip [%s] password [%s]", host.Client.VerifyKey, ip, pass)
|
||||
jsonBytes, err = json.Marshal(map[string]interface{}{"success": true, "message": "授权成功"})
|
||||
} else {
|
||||
logs.Error("客户端IP白名单认证授权密码错误:vkey [%s] ip [%s] password [%s]", host.Client.VerifyKey, ip, pass)
|
||||
jsonBytes, err = json.Marshal(map[string]interface{}{"success": false, "message": "密码错误"})
|
||||
}
|
||||
} else {
|
||||
logs.Error("客户端IP白名单认证授权密码错误:vkey [%s] ip [%s]", host.Client.VerifyKey, ip)
|
||||
jsonBytes, err = json.Marshal(map[string]interface{}{"success": false, "message": "参数错误"})
|
||||
}
|
||||
s.errorContent, err = jsonBytes, err
|
||||
s.errorCode = 200
|
||||
return
|
||||
}
|
||||
|
||||
errorContent, _ := common.ReadAllFromFile(filepath.Join(common.GetRunPath(), "web", "static", "page", "auth.html"))
|
||||
authHtml := string(errorContent)
|
||||
authHtml = strings.ReplaceAll(authHtml, "${ip}", common.GetIpByAddr(c.RemoteAddr().String()))
|
||||
s.errorContent, err = []byte(authHtml), err
|
||||
s.errorCode = 401
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 判断访问地址是否在黑名单内
|
||||
if common.IsBlackIp(c.RemoteAddr().String(), host.Client.VerifyKey, host.Client.BlackIpList) {
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
|
||||
lk = conn.NewLink("http", targetAddr, host.Client.Cnf.Crypt, host.Client.Cnf.Compress, r.RemoteAddr, host.Target.LocalProxy, "")
|
||||
lk = conn.NewLink("http", targetAddr, host.Client.Cnf.Crypt, host.Client.Cnf.Compress, r.RemoteAddr, host.Target.LocalProxy)
|
||||
if target, err = s.bridge.SendLinkInfo(host.Client.Id, lk, nil); err != nil {
|
||||
logs.Notice("connect to target %s error %s", lk.Host, err)
|
||||
return
|
||||
@@ -260,23 +176,28 @@ reset:
|
||||
c.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
err1 := goroutine.CopyBuffer(c, connClient, host.Client.Flow, nil, "")
|
||||
if err1 != nil {
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := http.ReadResponse(bufio.NewReader(connClient), r)
|
||||
if err != nil || resp == nil || r == nil {
|
||||
// if there got broken pipe, http.ReadResponse will get a nil
|
||||
//break
|
||||
return
|
||||
} else {
|
||||
lenConn := conn.NewLenConn(c)
|
||||
if err := resp.Write(lenConn); err != nil {
|
||||
logs.Error(err)
|
||||
//break
|
||||
for {
|
||||
if resp, err := http.ReadResponse(bufio.NewReader(connClient), r); err != nil || resp == nil || r == nil {
|
||||
// if there got broken pipe, http.ReadResponse will get a nil
|
||||
return
|
||||
} else {
|
||||
//if the cache is start and the response is in the extension,store the response to the cache list
|
||||
if s.useCache && r.URL != nil && strings.Contains(r.URL.Path, ".") {
|
||||
b, err := httputil.DumpResponse(resp, true)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.Write(b)
|
||||
host.Flow.Add(0, int64(len(b)))
|
||||
s.cache.Add(filepath.Join(host.Host, r.URL.Path), b)
|
||||
} else {
|
||||
lenConn := conn.NewLenConn(c)
|
||||
if err := resp.Write(lenConn); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
host.Flow.Add(0, int64(lenConn.Len))
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
@@ -290,7 +211,7 @@ reset:
|
||||
break
|
||||
}
|
||||
logs.Trace("%s request, method %s, host %s, url %s, remote address %s, return cache", r.URL.Scheme, r.Method, r.Host, r.URL.Path, c.RemoteAddr().String())
|
||||
host.Client.Flow.Add(int64(n), int64(n))
|
||||
host.Flow.Add(0, int64(n))
|
||||
//if return cache and does not create a new conn with client and Connection is not set or close, close the connection.
|
||||
if strings.ToLower(r.Header.Get("Connection")) == "close" || strings.ToLower(r.Header.Get("Connection")) == "" {
|
||||
break
|
||||
@@ -300,25 +221,20 @@ reset:
|
||||
}
|
||||
|
||||
//change the host and header and set proxy setting
|
||||
common.ChangeHostAndHeader(r, host.HostChange, host.HeaderChange, c.Conn.RemoteAddr().String())
|
||||
|
||||
logs.Info("%s request, method %s, host %s, url %s, remote address %s, target %s", r.URL.Scheme, r.Method, r.Host, r.URL.Path, remoteAddr, lk.Host)
|
||||
|
||||
common.ChangeHostAndHeader(r, host.HostChange, host.HeaderChange, c.Conn.RemoteAddr().String(), s.addOrigin)
|
||||
logs.Trace("%s request, method %s, host %s, url %s, remote address %s, target %s", r.URL.Scheme, r.Method, r.Host, r.URL.Path, c.RemoteAddr().String(), lk.Host)
|
||||
//write
|
||||
lenConn = conn.NewLenConn(connClient)
|
||||
//lenConn = conn.LenConn
|
||||
if err := r.Write(lenConn); err != nil {
|
||||
logs.Error(err)
|
||||
break
|
||||
}
|
||||
host.Client.Flow.Add(int64(lenConn.Len), int64(lenConn.Len))
|
||||
host.Flow.Add(int64(lenConn.Len), 0)
|
||||
|
||||
readReq:
|
||||
//read req from connection
|
||||
r, err = http.ReadRequest(bufio.NewReader(c))
|
||||
if err != nil {
|
||||
//break
|
||||
return
|
||||
if r, err = http.ReadRequest(bufio.NewReader(c)); err != nil {
|
||||
break
|
||||
}
|
||||
r.URL.Scheme = scheme
|
||||
//What happened ,Why one character less???
|
||||
@@ -357,35 +273,3 @@ func (s *httpServer) NewServer(port int, scheme string) *http.Server {
|
||||
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *httpServer) NewServerWithTls(port int, scheme string, l net.Listener, certFile string, keyFile string) error {
|
||||
|
||||
if certFile == "" || keyFile == "" {
|
||||
logs.Error("证书文件为空")
|
||||
return nil
|
||||
}
|
||||
var certFileByte = []byte(certFile)
|
||||
var keyFileByte = []byte(keyFile)
|
||||
|
||||
config := &tls.Config{}
|
||||
config.Certificates = make([]tls.Certificate, 1)
|
||||
|
||||
var err error
|
||||
config.Certificates[0], err = tls.X509KeyPair(certFileByte, keyFileByte)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
s2 := &http.Server{
|
||||
Addr: ":" + strconv.Itoa(port),
|
||||
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.URL.Scheme = scheme
|
||||
s.handleTunneling(w, r)
|
||||
}),
|
||||
// Disable HTTP/2.
|
||||
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
|
||||
TLSConfig: config,
|
||||
}
|
||||
|
||||
return s2.ServeTLS(l, "", "")
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"ehang.io/nps/lib/cache"
|
||||
@@ -12,6 +11,7 @@ import (
|
||||
"ehang.io/nps/lib/conn"
|
||||
"ehang.io/nps/lib/crypt"
|
||||
"ehang.io/nps/lib/file"
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
@@ -20,7 +20,6 @@ type HttpsServer struct {
|
||||
httpServer
|
||||
listener net.Listener
|
||||
httpsListenerMap sync.Map
|
||||
hostIdCertMap sync.Map
|
||||
}
|
||||
|
||||
func NewHttpsServer(l net.Listener, bridge NetBridge, useCache bool, cacheLen int) *HttpsServer {
|
||||
@@ -33,199 +32,59 @@ func NewHttpsServer(l net.Listener, bridge NetBridge, useCache bool, cacheLen in
|
||||
return https
|
||||
}
|
||||
|
||||
// start https server
|
||||
//start https server
|
||||
func (https *HttpsServer) Start() error {
|
||||
|
||||
conn.Accept(https.listener, func(c net.Conn) {
|
||||
serverName, rb := GetServerNameFromClientHello(c)
|
||||
r := buildHttpsRequest(serverName)
|
||||
if host, err := file.GetDb().GetInfoByHost(serverName, r); err != nil {
|
||||
c.Close()
|
||||
logs.Debug("the url %s can't be parsed!,remote addr %s", serverName, c.RemoteAddr().String())
|
||||
return
|
||||
} else {
|
||||
if host.CertFilePath == "" || host.KeyFilePath == "" {
|
||||
logs.Debug("加载客户端本地证书")
|
||||
https.handleHttps2(c, serverName, rb, r)
|
||||
} else {
|
||||
logs.Debug("使用上传证书")
|
||||
|
||||
// 判断是路径还是证书,-----BEGIN 开头的为证书
|
||||
if strings.Contains(host.CertFilePath, "-----BEGIN") || strings.Contains(host.KeyFilePath, "-----BEGIN") {
|
||||
logs.Debug("通过上传文件加载证书")
|
||||
https.cert(host, c, rb, host.CertFilePath, host.KeyFilePath)
|
||||
} else {
|
||||
logs.Debug("通过路径加载证书")
|
||||
if !common.FileExists(host.CertFilePath) || !common.FileExists(host.KeyFilePath) {
|
||||
c.Close()
|
||||
logs.Error("证书或秘钥文件不存在", host.KeyFilePath, host.CertFilePath)
|
||||
return
|
||||
}
|
||||
|
||||
cert, err := common.ReadAllFromFile(host.CertFilePath)
|
||||
if err != nil {
|
||||
c.Close()
|
||||
logs.Error("加载证书失败", err)
|
||||
return
|
||||
}
|
||||
key, err := common.ReadAllFromFile(host.KeyFilePath)
|
||||
if err != nil {
|
||||
c.Close()
|
||||
logs.Error("加载证书秘钥失败", err)
|
||||
return
|
||||
}
|
||||
|
||||
https.cert(host, c, rb, string(cert), string(key))
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
//var err error
|
||||
//if https.errorContent, err = common.ReadAllFromFile(filepath.Join(common.GetRunPath(), "web", "static", "page", "error.html")); err != nil {
|
||||
// https.errorContent = []byte("nps 404")
|
||||
//}
|
||||
//if b, err := beego.AppConfig.Bool("https_just_proxy"); err == nil && b {
|
||||
// conn.Accept(https.listener, func(c net.Conn) {
|
||||
// https.handleHttps(c)
|
||||
// })
|
||||
//} else {
|
||||
// //start the default listener
|
||||
// certFile := beego.AppConfig.String("https_default_cert_file")
|
||||
// keyFile := beego.AppConfig.String("https_default_key_file")
|
||||
// if common.FileExists(certFile) && common.FileExists(keyFile) {
|
||||
// l := NewHttpsListener(https.listener)
|
||||
// https.NewHttps(l, certFile, keyFile)
|
||||
// https.httpsListenerMap.Store("default", l)
|
||||
// }
|
||||
// conn.Accept(https.listener, func(c net.Conn) {
|
||||
// serverName, rb := GetServerNameFromClientHello(c)
|
||||
// //if the clientHello does not contains sni ,use the default ssl certificate
|
||||
// if serverName == "" {
|
||||
// serverName = "default"
|
||||
// }
|
||||
// var l *HttpsListener
|
||||
// if v, ok := https.httpsListenerMap.Load(serverName); ok {
|
||||
// l = v.(*HttpsListener)
|
||||
// } else {
|
||||
// r := buildHttpsRequest(serverName)
|
||||
// if host, err := file.GetDb().GetInfoByHost(serverName, r); err != nil {
|
||||
// c.Close()
|
||||
// logs.Notice("the url %s can't be parsed!,remote addr %s", serverName, c.RemoteAddr().String())
|
||||
// return
|
||||
// } else {
|
||||
// if !common.FileExists(host.CertFilePath) || !common.FileExists(host.KeyFilePath) {
|
||||
// //if the host cert file or key file is not set ,use the default file
|
||||
// if v, ok := https.httpsListenerMap.Load("default"); ok {
|
||||
// l = v.(*HttpsListener)
|
||||
// } else {
|
||||
// c.Close()
|
||||
// logs.Error("the key %s cert %s file is not exist", host.KeyFilePath, host.CertFilePath)
|
||||
// return
|
||||
// }
|
||||
// } else {
|
||||
// l = NewHttpsListener(https.listener)
|
||||
// https.NewHttps(l, host.CertFilePath, host.KeyFilePath)
|
||||
// https.httpsListenerMap.Store(serverName, l)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// acceptConn := conn.NewConn(c)
|
||||
// acceptConn.Rb = rb
|
||||
// l.acceptConn <- acceptConn
|
||||
// })
|
||||
//}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (https *HttpsServer) cert(host *file.Host, c net.Conn, rb []byte, certFileUrl string, keyFileUrl string) {
|
||||
var l *HttpsListener
|
||||
i := 0
|
||||
https.hostIdCertMap.Range(func(key, value interface{}) bool {
|
||||
i++
|
||||
// 如果host Id 不存在,则删除map
|
||||
if id, ok := key.(int); ok {
|
||||
var err error
|
||||
_, err = file.GetDb().GetHostById(id)
|
||||
if err != nil {
|
||||
// 说明这个host已经不存了,需要释放Listener
|
||||
logs.Error(err)
|
||||
if oldL, ok := https.httpsListenerMap.Load(value); ok {
|
||||
err := oldL.(*HttpsListener).Close()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
}
|
||||
https.httpsListenerMap.Delete(value)
|
||||
https.hostIdCertMap.Delete(key)
|
||||
logs.Debug("Listener 已释放")
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
logs.Debug("当前 Listener 连接数量", i)
|
||||
|
||||
if cert, ok := https.hostIdCertMap.Load(host.Id); ok {
|
||||
if cert == certFileUrl {
|
||||
// 证书已经存在,直接加载
|
||||
if v, ok := https.httpsListenerMap.Load(certFileUrl); ok {
|
||||
l = v.(*HttpsListener)
|
||||
}
|
||||
} else {
|
||||
// 证书修改过,重新加载证书
|
||||
l = NewHttpsListener(https.listener)
|
||||
https.NewHttps(l, certFileUrl, keyFileUrl)
|
||||
if oldL, ok := https.httpsListenerMap.Load(cert); ok {
|
||||
err := oldL.(*HttpsListener).Close()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
}
|
||||
https.httpsListenerMap.Delete(cert)
|
||||
}
|
||||
https.httpsListenerMap.Store(certFileUrl, l)
|
||||
https.hostIdCertMap.Store(host.Id, certFileUrl)
|
||||
}
|
||||
if b, err := beego.AppConfig.Bool("https_just_proxy"); err == nil && b {
|
||||
conn.Accept(https.listener, func(c net.Conn) {
|
||||
https.handleHttps(c)
|
||||
})
|
||||
} else {
|
||||
// 第一次加载证书
|
||||
l = NewHttpsListener(https.listener)
|
||||
https.NewHttps(l, certFileUrl, keyFileUrl)
|
||||
https.httpsListenerMap.Store(certFileUrl, l)
|
||||
https.hostIdCertMap.Store(host.Id, certFileUrl)
|
||||
//start the default listener
|
||||
certFile := beego.AppConfig.String("https_default_cert_file")
|
||||
keyFile := beego.AppConfig.String("https_default_key_file")
|
||||
if common.FileExists(certFile) && common.FileExists(keyFile) {
|
||||
l := NewHttpsListener(https.listener)
|
||||
https.NewHttps(l, certFile, keyFile)
|
||||
https.httpsListenerMap.Store("default", l)
|
||||
}
|
||||
conn.Accept(https.listener, func(c net.Conn) {
|
||||
serverName, rb := GetServerNameFromClientHello(c)
|
||||
//if the clientHello does not contains sni ,use the default ssl certificate
|
||||
if serverName == "" {
|
||||
serverName = "default"
|
||||
}
|
||||
var l *HttpsListener
|
||||
if v, ok := https.httpsListenerMap.Load(serverName); ok {
|
||||
l = v.(*HttpsListener)
|
||||
} else {
|
||||
r := buildHttpsRequest(serverName)
|
||||
if host, err := file.GetDb().GetInfoByHost(serverName, r); err != nil {
|
||||
c.Close()
|
||||
logs.Notice("the url %s can't be parsed!,remote addr %s", serverName, c.RemoteAddr().String())
|
||||
return
|
||||
} else {
|
||||
if !common.FileExists(host.CertFilePath) || !common.FileExists(host.KeyFilePath) {
|
||||
//if the host cert file or key file is not set ,use the default file
|
||||
if v, ok := https.httpsListenerMap.Load("default"); ok {
|
||||
l = v.(*HttpsListener)
|
||||
} else {
|
||||
c.Close()
|
||||
logs.Error("the key %s cert %s file is not exist", host.KeyFilePath, host.CertFilePath)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
l = NewHttpsListener(https.listener)
|
||||
https.NewHttps(l, host.CertFilePath, host.KeyFilePath)
|
||||
https.httpsListenerMap.Store(serverName, l)
|
||||
}
|
||||
}
|
||||
}
|
||||
acceptConn := conn.NewConn(c)
|
||||
acceptConn.Rb = rb
|
||||
l.acceptConn <- acceptConn
|
||||
})
|
||||
}
|
||||
|
||||
acceptConn := conn.NewConn(c)
|
||||
acceptConn.Rb = rb
|
||||
l.acceptConn <- acceptConn
|
||||
}
|
||||
|
||||
// handle the https which is just proxy to other client
|
||||
func (https *HttpsServer) handleHttps2(c net.Conn, hostName string, rb []byte, r *http.Request) {
|
||||
var targetAddr string
|
||||
var host *file.Host
|
||||
var err error
|
||||
if host, err = file.GetDb().GetInfoByHost(hostName, r); err != nil {
|
||||
c.Close()
|
||||
logs.Debug("the url %s can't be parsed!", hostName)
|
||||
return
|
||||
}
|
||||
if err := https.CheckFlowAndConnNum(host.Client); err != nil {
|
||||
logs.Debug("client id %d, host id %d, error %s, when https connection", host.Client.Id, host.Id, err.Error())
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
defer host.Client.AddConn()
|
||||
if err = https.auth(r, conn.NewConn(c), host.Client.Cnf.U, host.Client.Cnf.P); err != nil {
|
||||
logs.Warn("auth error", err, r.RemoteAddr)
|
||||
return
|
||||
}
|
||||
if targetAddr, err = host.Target.GetRandomTarget(); err != nil {
|
||||
logs.Warn(err.Error())
|
||||
}
|
||||
logs.Info("new https connection,clientId %d,host %s,remote address %s", host.Client.Id, r.Host, c.RemoteAddr().String())
|
||||
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Client.Flow, host.Target.LocalProxy, nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
// close
|
||||
@@ -236,13 +95,11 @@ func (https *HttpsServer) Close() error {
|
||||
// new https server by cert and key file
|
||||
func (https *HttpsServer) NewHttps(l net.Listener, certFile string, keyFile string) {
|
||||
go func() {
|
||||
//logs.Error(https.NewServer(0, "https").ServeTLS(l, certFile, keyFile))
|
||||
logs.Error(https.NewServerWithTls(0, "https", l, certFile, keyFile))
|
||||
|
||||
logs.Error(https.NewServer(0, "https").ServeTLS(l, certFile, keyFile))
|
||||
}()
|
||||
}
|
||||
|
||||
// handle the https which is just proxy to other client
|
||||
//handle the https which is just proxy to other client
|
||||
func (https *HttpsServer) handleHttps(c net.Conn) {
|
||||
hostName, rb := GetServerNameFromClientHello(c)
|
||||
var targetAddr string
|
||||
@@ -268,7 +125,7 @@ func (https *HttpsServer) handleHttps(c net.Conn) {
|
||||
logs.Warn(err.Error())
|
||||
}
|
||||
logs.Trace("new https connection,clientId %d,host %s,remote address %s", host.Client.Id, r.Host, c.RemoteAddr().String())
|
||||
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Client.Flow, host.Target.LocalProxy, nil)
|
||||
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Flow, host.Target.LocalProxy)
|
||||
}
|
||||
|
||||
type HttpsListener struct {
|
||||
|
||||
@@ -51,7 +51,7 @@ type Sock5ModeServer struct {
|
||||
listener net.Listener
|
||||
}
|
||||
|
||||
// req
|
||||
//req
|
||||
func (s *Sock5ModeServer) handleRequest(c net.Conn) {
|
||||
/*
|
||||
The SOCKS request is formed as follows:
|
||||
@@ -84,7 +84,7 @@ func (s *Sock5ModeServer) handleRequest(c net.Conn) {
|
||||
}
|
||||
}
|
||||
|
||||
// reply
|
||||
//reply
|
||||
func (s *Sock5ModeServer) sendReply(c net.Conn, rep uint8) {
|
||||
reply := []byte{
|
||||
5,
|
||||
@@ -105,7 +105,7 @@ func (s *Sock5ModeServer) sendReply(c net.Conn, rep uint8) {
|
||||
c.Write(reply)
|
||||
}
|
||||
|
||||
// do conn
|
||||
//do conn
|
||||
func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) {
|
||||
addrType := make([]byte, 1)
|
||||
c.Read(addrType)
|
||||
@@ -142,11 +142,11 @@ func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) {
|
||||
}
|
||||
s.DealClient(conn.NewConn(c), s.task.Client, addr, nil, ltype, func() {
|
||||
s.sendReply(c, succeeded)
|
||||
}, s.task.Flow, s.task.Target.LocalProxy, nil)
|
||||
}, s.task.Flow, s.task.Target.LocalProxy)
|
||||
return
|
||||
}
|
||||
|
||||
// conn
|
||||
//conn
|
||||
func (s *Sock5ModeServer) handleConnect(c net.Conn) {
|
||||
s.doConnect(c, connectMethod)
|
||||
}
|
||||
@@ -216,7 +216,7 @@ func (s *Sock5ModeServer) handleUDP(c net.Conn) {
|
||||
s.sendUdpReply(c, reply, succeeded, common.GetServerIpByClientIp(c.RemoteAddr().(*net.TCPAddr).IP))
|
||||
defer reply.Close()
|
||||
// new a tunnel to client
|
||||
link := conn.NewLink("udp5", "", s.task.Client.Cnf.Crypt, s.task.Client.Cnf.Compress, c.RemoteAddr().String(), false, "")
|
||||
link := conn.NewLink("udp5", "", s.task.Client.Cnf.Crypt, s.task.Client.Cnf.Compress, c.RemoteAddr().String(), false)
|
||||
target, err := s.bridge.SendLinkInfo(s.task.Client.Id, link, s.task)
|
||||
if err != nil {
|
||||
logs.Warn("get connection from client id %d error %s", s.task.Client.Id, err.Error())
|
||||
@@ -280,7 +280,7 @@ func (s *Sock5ModeServer) handleUDP(c net.Conn) {
|
||||
}
|
||||
}
|
||||
|
||||
// new conn
|
||||
//new conn
|
||||
func (s *Sock5ModeServer) handleConn(c net.Conn) {
|
||||
buf := make([]byte, 2)
|
||||
if _, err := io.ReadFull(c, buf); err != nil {
|
||||
@@ -317,7 +317,7 @@ func (s *Sock5ModeServer) handleConn(c net.Conn) {
|
||||
s.handleRequest(c)
|
||||
}
|
||||
|
||||
// socks5 auth
|
||||
//socks5 auth
|
||||
func (s *Sock5ModeServer) Auth(c net.Conn) error {
|
||||
header := []byte{0, 0}
|
||||
if _, err := io.ReadAtLeast(c, header, 2); err != nil {
|
||||
@@ -344,9 +344,6 @@ func (s *Sock5ModeServer) Auth(c net.Conn) error {
|
||||
if s.task.MultiAccount != nil {
|
||||
// enable multi user auth
|
||||
U = string(user)
|
||||
if len(U) == 0 {
|
||||
return errors.New("验证不通过")
|
||||
}
|
||||
var ok bool
|
||||
P, ok = s.task.MultiAccount.AccountMap[U]
|
||||
if !ok {
|
||||
@@ -370,7 +367,7 @@ func (s *Sock5ModeServer) Auth(c net.Conn) error {
|
||||
}
|
||||
}
|
||||
|
||||
// start
|
||||
//start
|
||||
func (s *Sock5ModeServer) Start() error {
|
||||
return conn.NewTcpListenerAndProcess(s.task.ServerIp+":"+strconv.Itoa(s.task.Port), func(c net.Conn) {
|
||||
if err := s.CheckFlowAndConnNum(s.task.Client); err != nil {
|
||||
@@ -384,7 +381,7 @@ func (s *Sock5ModeServer) Start() error {
|
||||
}, &s.listener)
|
||||
}
|
||||
|
||||
// new
|
||||
//new
|
||||
func NewSock5ModeServer(bridge NetBridge, task *file.Tunnel) *Sock5ModeServer {
|
||||
s := new(Sock5ModeServer)
|
||||
s.bridge = bridge
|
||||
@@ -392,7 +389,7 @@ func NewSock5ModeServer(bridge NetBridge, task *file.Tunnel) *Sock5ModeServer {
|
||||
return s
|
||||
}
|
||||
|
||||
// close
|
||||
//close
|
||||
func (s *Sock5ModeServer) Close() error {
|
||||
return s.listener.Close()
|
||||
}
|
||||
|
||||
@@ -103,13 +103,11 @@ func ProcessTunnel(c *conn.Conn, s *TunnelModeServer) error {
|
||||
logs.Warn("tcp port %d ,client id %d,task id %d connect error %s", s.task.Port, s.task.Client.Id, s.task.Id, err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
return s.DealClient(c, s.task.Client, targetAddr, nil, common.CONN_TCP, nil, s.task.Client.Flow, s.task.Target.LocalProxy, s.task)
|
||||
return s.DealClient(c, s.task.Client, targetAddr, nil, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy)
|
||||
}
|
||||
|
||||
//http proxy
|
||||
func ProcessHttp(c *conn.Conn, s *TunnelModeServer) error {
|
||||
|
||||
_, addr, rb, err, r := c.GetHost()
|
||||
if err != nil {
|
||||
c.Close()
|
||||
@@ -123,6 +121,5 @@ func ProcessHttp(c *conn.Conn, s *TunnelModeServer) error {
|
||||
if err := s.auth(r, c, s.task.Client.Cnf.U, s.task.Client.Cnf.P); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.DealClient(c, s.task.Client, addr, rb, common.CONN_TCP, nil, s.task.Client.Flow, s.task.Target.LocalProxy, nil)
|
||||
|
||||
return s.DealClient(c, s.task.Client, addr, rb, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package proxy
|
||||
@@ -16,7 +15,7 @@ func HandleTrans(c *conn.Conn, s *TunnelModeServer) error {
|
||||
if addr, err := getAddress(c.Conn); err != nil {
|
||||
return err
|
||||
} else {
|
||||
return s.DealClient(c, s.task.Client, addr, nil, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy, nil)
|
||||
return s.DealClient(c, s.task.Client, addr, nil, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ func NewUdpModeServer(bridge *bridge.Bridge, task *file.Tunnel) *UdpModeServer {
|
||||
return s
|
||||
}
|
||||
|
||||
// 开始
|
||||
//开始
|
||||
func (s *UdpModeServer) Start() error {
|
||||
var err error
|
||||
if s.task.ServerIp == "" {
|
||||
@@ -46,17 +46,6 @@ func (s *UdpModeServer) Start() error {
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// 判断访问地址是否在全局黑名单内
|
||||
if IsGlobalBlackIp(addr.String()) {
|
||||
break
|
||||
}
|
||||
|
||||
// 判断访问地址是否在黑名单内
|
||||
if common.IsBlackIp(addr.String(), s.task.Client.VerifyKey, s.task.Client.BlackIpList) {
|
||||
break
|
||||
}
|
||||
|
||||
logs.Trace("New udp connection,client %d,remote address %s", s.task.Client.Id, addr)
|
||||
go s.process(addr, buf[:n])
|
||||
}
|
||||
@@ -67,12 +56,8 @@ func (s *UdpModeServer) process(addr *net.UDPAddr, data []byte) {
|
||||
if v, ok := s.addrMap.Load(addr.String()); ok {
|
||||
clientConn, ok := v.(io.ReadWriteCloser)
|
||||
if ok {
|
||||
_, err := clientConn.Write(data)
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
return
|
||||
}
|
||||
s.task.Client.Flow.Add(int64(len(data)), int64(len(data)))
|
||||
clientConn.Write(data)
|
||||
s.task.Flow.Add(int64(len(data)), 0)
|
||||
}
|
||||
} else {
|
||||
if err := s.CheckFlowAndConnNum(s.task.Client); err != nil {
|
||||
@@ -80,7 +65,7 @@ func (s *UdpModeServer) process(addr *net.UDPAddr, data []byte) {
|
||||
return
|
||||
}
|
||||
defer s.task.Client.AddConn()
|
||||
link := conn.NewLink(common.CONN_UDP, s.task.Target.TargetStr, s.task.Client.Cnf.Crypt, s.task.Client.Cnf.Compress, addr.String(), s.task.Target.LocalProxy, "")
|
||||
link := conn.NewLink(common.CONN_UDP, s.task.Target.TargetStr, s.task.Client.Cnf.Crypt, s.task.Client.Cnf.Compress, addr.String(), s.task.Target.LocalProxy)
|
||||
if clientConn, err := s.bridge.SendLinkInfo(s.task.Client.Id, link, s.task); err != nil {
|
||||
return
|
||||
} else {
|
||||
@@ -88,34 +73,22 @@ func (s *UdpModeServer) process(addr *net.UDPAddr, data []byte) {
|
||||
s.addrMap.Store(addr.String(), target)
|
||||
defer target.Close()
|
||||
|
||||
_, err := target.Write(data)
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
return
|
||||
}
|
||||
target.Write(data)
|
||||
|
||||
buf := common.BufPoolUdp.Get().([]byte)
|
||||
defer common.BufPoolUdp.Put(buf)
|
||||
|
||||
s.task.Client.Flow.Add(int64(len(data)), int64(len(data)))
|
||||
s.task.Flow.Add(int64(len(data)), 0)
|
||||
for {
|
||||
clientConn.SetReadDeadline(time.Now().Add(time.Duration(60) * time.Second))
|
||||
clientConn.SetReadDeadline(time.Now().Add(time.Minute * 10))
|
||||
if n, err := target.Read(buf); err != nil {
|
||||
s.addrMap.Delete(addr.String())
|
||||
logs.Warn(err)
|
||||
return
|
||||
} else {
|
||||
_, err := s.listener.WriteTo(buf[:n], addr)
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
return
|
||||
}
|
||||
s.task.Client.Flow.Add(int64(n), int64(n))
|
||||
s.listener.WriteTo(buf[:n], addr)
|
||||
s.task.Flow.Add(0, int64(n))
|
||||
}
|
||||
//if err := s.CheckFlowAndConnNum(s.task.Client); err != nil {
|
||||
// logs.Warn("client id %d, task id %d,error %s, when udp connection", s.task.Client.Id, s.task.Id, err.Error())
|
||||
// return
|
||||
//}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,270 +0,0 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"ehang.io/nps/lib/common"
|
||||
"ehang.io/nps/lib/conn"
|
||||
"ehang.io/nps/lib/file"
|
||||
"ehang.io/nps/lib/goroutine"
|
||||
"errors"
|
||||
"github.com/astaxie/beego/logs"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type HTTPError struct {
|
||||
error
|
||||
HTTPCode int
|
||||
}
|
||||
|
||||
type HttpReverseProxy struct {
|
||||
proxy *ReverseProxy
|
||||
responseHeaderTimeout time.Duration
|
||||
}
|
||||
type flowConn struct {
|
||||
io.ReadWriteCloser
|
||||
fakeAddr net.Addr
|
||||
host *file.Host
|
||||
flowIn int64
|
||||
flowOut int64
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (rp *HttpReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
var (
|
||||
host *file.Host
|
||||
targetAddr string
|
||||
err error
|
||||
)
|
||||
if host, err = file.GetDb().GetInfoByHost(req.Host, req); err != nil {
|
||||
rw.WriteHeader(http.StatusNotFound)
|
||||
rw.Write([]byte(req.Host + " not found"))
|
||||
return
|
||||
}
|
||||
if host.Client.Cnf.U != "" && host.Client.Cnf.P != "" && !common.CheckAuth(req, host.Client.Cnf.U, host.Client.Cnf.P) {
|
||||
rw.WriteHeader(http.StatusUnauthorized)
|
||||
rw.Write([]byte("Unauthorized"))
|
||||
return
|
||||
}
|
||||
if targetAddr, err = host.Target.GetRandomTarget(); err != nil {
|
||||
rw.WriteHeader(http.StatusBadGateway)
|
||||
rw.Write([]byte("502 Bad Gateway"))
|
||||
return
|
||||
}
|
||||
host.Client.CutConn()
|
||||
|
||||
req = req.WithContext(context.WithValue(req.Context(), "host", host))
|
||||
req = req.WithContext(context.WithValue(req.Context(), "target", targetAddr))
|
||||
req = req.WithContext(context.WithValue(req.Context(), "req", req))
|
||||
|
||||
rp.proxy.ServeHTTP(rw, req, host)
|
||||
|
||||
defer host.Client.AddConn()
|
||||
}
|
||||
|
||||
func (c *flowConn) Read(p []byte) (n int, err error) {
|
||||
n, err = c.ReadWriteCloser.Read(p)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (c *flowConn) Write(p []byte) (n int, err error) {
|
||||
n, err = c.ReadWriteCloser.Write(p)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (c *flowConn) Close() error {
|
||||
//c.once.Do(func() { c.host.Flow.Add(c.flowIn, c.flowOut) })
|
||||
return c.ReadWriteCloser.Close()
|
||||
}
|
||||
|
||||
func (c *flowConn) LocalAddr() net.Addr { return c.fakeAddr }
|
||||
|
||||
func (c *flowConn) RemoteAddr() net.Addr { return c.fakeAddr }
|
||||
|
||||
func (*flowConn) SetDeadline(t time.Time) error { return nil }
|
||||
|
||||
func (*flowConn) SetReadDeadline(t time.Time) error { return nil }
|
||||
|
||||
func (*flowConn) SetWriteDeadline(t time.Time) error { return nil }
|
||||
|
||||
func NewHttpReverseProxy(s *httpServer) *HttpReverseProxy {
|
||||
rp := &HttpReverseProxy{
|
||||
responseHeaderTimeout: 30 * time.Second,
|
||||
}
|
||||
local, _ := net.ResolveTCPAddr("tcp", "127.0.0.1")
|
||||
proxy := NewReverseProxy(&httputil.ReverseProxy{
|
||||
Director: func(r *http.Request) {
|
||||
host := r.Context().Value("host").(*file.Host)
|
||||
common.ChangeHostAndHeader(r, host.HostChange, host.HeaderChange, "")
|
||||
},
|
||||
Transport: &http.Transport{
|
||||
ResponseHeaderTimeout: rp.responseHeaderTimeout,
|
||||
DisableKeepAlives: true,
|
||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
var (
|
||||
host *file.Host
|
||||
target net.Conn
|
||||
err error
|
||||
connClient io.ReadWriteCloser
|
||||
targetAddr string
|
||||
lk *conn.Link
|
||||
)
|
||||
|
||||
r := ctx.Value("req").(*http.Request)
|
||||
host = ctx.Value("host").(*file.Host)
|
||||
targetAddr = ctx.Value("target").(string)
|
||||
|
||||
lk = conn.NewLink("http", targetAddr, host.Client.Cnf.Crypt, host.Client.Cnf.Compress, r.RemoteAddr, host.Target.LocalProxy, "")
|
||||
if target, err = s.bridge.SendLinkInfo(host.Client.Id, lk, nil); err != nil {
|
||||
logs.Notice("connect to target %s error %s", lk.Host, err)
|
||||
return nil, NewHTTPError(http.StatusBadGateway, "Cannot connect to the server")
|
||||
}
|
||||
connClient = conn.GetConn(target, lk.Crypt, lk.Compress, host.Client.Rate, true)
|
||||
return &flowConn{
|
||||
ReadWriteCloser: connClient,
|
||||
fakeAddr: local,
|
||||
host: host,
|
||||
}, nil
|
||||
},
|
||||
},
|
||||
ErrorHandler: func(rw http.ResponseWriter, req *http.Request, err error) {
|
||||
logs.Warn("do http proxy request error: %v", err)
|
||||
rw.WriteHeader(http.StatusNotFound)
|
||||
},
|
||||
})
|
||||
proxy.WebSocketDialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
var (
|
||||
host *file.Host
|
||||
target net.Conn
|
||||
err error
|
||||
connClient io.ReadWriteCloser
|
||||
targetAddr string
|
||||
lk *conn.Link
|
||||
)
|
||||
r := ctx.Value("req").(*http.Request)
|
||||
host = ctx.Value("host").(*file.Host)
|
||||
targetAddr = ctx.Value("target").(string)
|
||||
|
||||
lk = conn.NewLink("tcp", targetAddr, host.Client.Cnf.Crypt, host.Client.Cnf.Compress, r.RemoteAddr, host.Target.LocalProxy, "")
|
||||
if target, err = s.bridge.SendLinkInfo(host.Client.Id, lk, nil); err != nil {
|
||||
logs.Notice("connect to target %s error %s", lk.Host, err)
|
||||
return nil, NewHTTPError(http.StatusBadGateway, "Cannot connect to the target")
|
||||
}
|
||||
connClient = conn.GetConn(target, lk.Crypt, lk.Compress, host.Client.Rate, true)
|
||||
return &flowConn{
|
||||
ReadWriteCloser: connClient,
|
||||
fakeAddr: local,
|
||||
host: host,
|
||||
}, nil
|
||||
}
|
||||
rp.proxy = proxy
|
||||
return rp
|
||||
}
|
||||
|
||||
func NewHTTPError(code int, errmsg string) error {
|
||||
return &HTTPError{
|
||||
error: errors.New(errmsg),
|
||||
HTTPCode: code,
|
||||
}
|
||||
}
|
||||
|
||||
type ReverseProxy struct {
|
||||
*httputil.ReverseProxy
|
||||
WebSocketDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
|
||||
}
|
||||
|
||||
func IsWebsocketRequest(req *http.Request) bool {
|
||||
containsHeader := func(name, value string) bool {
|
||||
items := strings.Split(req.Header.Get(name), ",")
|
||||
for _, item := range items {
|
||||
if value == strings.ToLower(strings.TrimSpace(item)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
return containsHeader("Connection", "upgrade") && containsHeader("Upgrade", "websocket")
|
||||
}
|
||||
|
||||
func NewReverseProxy(orp *httputil.ReverseProxy) *ReverseProxy {
|
||||
rp := &ReverseProxy{
|
||||
ReverseProxy: orp,
|
||||
WebSocketDialContext: nil,
|
||||
}
|
||||
rp.ErrorHandler = rp.errHandler
|
||||
return rp
|
||||
}
|
||||
|
||||
func (p *ReverseProxy) errHandler(rw http.ResponseWriter, r *http.Request, e error) {
|
||||
if e == io.EOF {
|
||||
rw.WriteHeader(521)
|
||||
//rw.Write(getWaitingPageContent())
|
||||
} else {
|
||||
if httperr, ok := e.(*HTTPError); ok {
|
||||
rw.WriteHeader(httperr.HTTPCode)
|
||||
} else {
|
||||
rw.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
rw.Write([]byte("error: " + e.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request, host *file.Host) {
|
||||
if IsWebsocketRequest(req) {
|
||||
p.serveWebSocket(rw, req, host)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *ReverseProxy) serveWebSocket(rw http.ResponseWriter, req *http.Request, host *file.Host) {
|
||||
if p.WebSocketDialContext == nil {
|
||||
rw.WriteHeader(500)
|
||||
return
|
||||
}
|
||||
targetConn, err := p.WebSocketDialContext(req.Context(), "tcp", "")
|
||||
if err != nil {
|
||||
rw.WriteHeader(501)
|
||||
return
|
||||
}
|
||||
defer targetConn.Close()
|
||||
|
||||
p.Director(req)
|
||||
|
||||
hijacker, ok := rw.(http.Hijacker)
|
||||
if !ok {
|
||||
rw.WriteHeader(500)
|
||||
return
|
||||
}
|
||||
conn, _, errHijack := hijacker.Hijack()
|
||||
if errHijack != nil {
|
||||
rw.WriteHeader(500)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
req.Write(targetConn)
|
||||
|
||||
Join(conn, targetConn, host)
|
||||
}
|
||||
|
||||
func Join(c1 io.ReadWriteCloser, c2 io.ReadWriteCloser, host *file.Host) (inCount int64, outCount int64) {
|
||||
var wait sync.WaitGroup
|
||||
pipe := func(to io.ReadWriteCloser, from io.ReadWriteCloser, count *int64) {
|
||||
defer to.Close()
|
||||
defer from.Close()
|
||||
defer wait.Done()
|
||||
goroutine.CopyBuffer(to, from, host.Client.Flow, nil, "")
|
||||
//*count, _ = io.Copy(to, from)
|
||||
}
|
||||
|
||||
wait.Add(2)
|
||||
|
||||
go pipe(c1, c2, &inCount)
|
||||
go pipe(c2, c1, &outCount)
|
||||
wait.Wait()
|
||||
return
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"errors"
|
||||
"math"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -27,14 +26,13 @@ import (
|
||||
var (
|
||||
Bridge *bridge.Bridge
|
||||
RunList sync.Map //map[int]interface{}
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
func init() {
|
||||
RunList = sync.Map{}
|
||||
}
|
||||
|
||||
// init task from db
|
||||
//init task from db
|
||||
func InitFromCsv() {
|
||||
//Add a public password
|
||||
if vkey := beego.AppConfig.String("public_vkey"); vkey != "" {
|
||||
@@ -52,7 +50,7 @@ func InitFromCsv() {
|
||||
})
|
||||
}
|
||||
|
||||
// get bridge command
|
||||
//get bridge command
|
||||
func DealBridgeTask() {
|
||||
for {
|
||||
select {
|
||||
@@ -73,7 +71,7 @@ func DealBridgeTask() {
|
||||
logs.Trace("New secret connection, addr", s.Conn.Conn.RemoteAddr())
|
||||
if t := file.GetDb().GetTaskByMd5Password(s.Password); t != nil {
|
||||
if t.Status {
|
||||
go proxy.NewBaseServer(Bridge, t).DealClient(s.Conn, t.Client, t.Target.TargetStr, nil, common.CONN_TCP, nil, t.Flow, t.Target.LocalProxy, nil)
|
||||
go proxy.NewBaseServer(Bridge, t).DealClient(s.Conn, t.Client, t.Target.TargetStr, nil, common.CONN_TCP, nil, t.Flow, t.Target.LocalProxy)
|
||||
} else {
|
||||
s.Conn.Close()
|
||||
logs.Trace("This key %s cannot be processed,status is close", s.Password)
|
||||
@@ -86,7 +84,7 @@ func DealBridgeTask() {
|
||||
}
|
||||
}
|
||||
|
||||
// start a new server
|
||||
//start a new server
|
||||
func StartNewServer(bridgePort int, cnf *file.Tunnel, bridgeType string, bridgeDisconnect int) {
|
||||
Bridge = bridge.NewTunnel(bridgePort, bridgeType, common.GetBoolByStr(beego.AppConfig.String("ip_limit")), RunList, bridgeDisconnect)
|
||||
go func() {
|
||||
@@ -124,7 +122,7 @@ func dealClientFlow() {
|
||||
}
|
||||
}
|
||||
|
||||
// new a server by mode name
|
||||
//new a server by mode name
|
||||
func NewMode(Bridge *bridge.Bridge, c *file.Tunnel) proxy.Service {
|
||||
var service proxy.Service
|
||||
switch c.Mode {
|
||||
@@ -158,7 +156,7 @@ func NewMode(Bridge *bridge.Bridge, c *file.Tunnel) proxy.Service {
|
||||
return service
|
||||
}
|
||||
|
||||
// stop server
|
||||
//stop server
|
||||
func StopServer(id int) error {
|
||||
//if v, ok := RunList[id]; ok {
|
||||
if v, ok := RunList.Load(id); ok {
|
||||
@@ -184,7 +182,7 @@ func StopServer(id int) error {
|
||||
return errors.New("task is not running")
|
||||
}
|
||||
|
||||
// add task
|
||||
//add task
|
||||
func AddTask(t *file.Tunnel) error {
|
||||
if t.Mode == "secret" || t.Mode == "p2p" {
|
||||
logs.Info("secret task %s start ", t.Remark)
|
||||
@@ -217,7 +215,7 @@ func AddTask(t *file.Tunnel) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// start task
|
||||
//start task
|
||||
func StartTask(id int) error {
|
||||
if t, err := file.GetDb().GetTask(id); err != nil {
|
||||
return err
|
||||
@@ -229,7 +227,7 @@ func StartTask(id int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// delete task
|
||||
//delete task
|
||||
func DelTask(id int) error {
|
||||
//if _, ok := RunList[id]; ok {
|
||||
if _, ok := RunList.Load(id); ok {
|
||||
@@ -240,64 +238,18 @@ func DelTask(id int) error {
|
||||
return file.GetDb().DelTask(id)
|
||||
}
|
||||
|
||||
// get task list by page num
|
||||
func GetTunnel(start, length int, typeVal string, clientId int, search string, sortField string, order string) ([]*file.Tunnel, int) {
|
||||
all_list := make([]*file.Tunnel, 0) //store all Tunnel
|
||||
//get task list by page num
|
||||
func GetTunnel(start, length int, typeVal string, clientId int, search string) ([]*file.Tunnel, int) {
|
||||
list := make([]*file.Tunnel, 0)
|
||||
var cnt int
|
||||
keys := file.GetMapKeys(file.GetDb().JsonDb.Tasks, false, "", "")
|
||||
|
||||
//get all Tunnel and sort
|
||||
for _, key := range keys {
|
||||
if value, ok := file.GetDb().JsonDb.Tasks.Load(key); ok {
|
||||
v := value.(*file.Tunnel)
|
||||
if (typeVal != "" && v.Mode != typeVal || (clientId != 0 && v.Client.Id != clientId)) || (typeVal == "" && clientId != v.Client.Id) {
|
||||
continue
|
||||
}
|
||||
all_list = append(all_list, v)
|
||||
}
|
||||
}
|
||||
//sort by Id, Remark, TargetStr, Port, asc or desc
|
||||
if sortField == "Id" {
|
||||
if order == "asc" {
|
||||
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Id < all_list[j].Id })
|
||||
} else {
|
||||
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Id > all_list[j].Id })
|
||||
}
|
||||
} else if sortField == "ClientId" {
|
||||
if order == "asc" {
|
||||
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Client.Id < all_list[j].Client.Id })
|
||||
} else {
|
||||
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Client.Id > all_list[j].Client.Id })
|
||||
}
|
||||
} else if sortField == "Remark" {
|
||||
if order == "asc" {
|
||||
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Remark < all_list[j].Remark })
|
||||
} else {
|
||||
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Remark > all_list[j].Remark })
|
||||
}
|
||||
} else if sortField == "Client.VerifyKey" {
|
||||
if order == "asc" {
|
||||
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Client.VerifyKey < all_list[j].Client.VerifyKey })
|
||||
} else {
|
||||
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Client.VerifyKey > all_list[j].Client.VerifyKey })
|
||||
}
|
||||
} else if sortField == "Target" {
|
||||
if order == "asc" {
|
||||
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Target.TargetStr < all_list[j].Target.TargetStr })
|
||||
} else {
|
||||
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Target.TargetStr > all_list[j].Target.TargetStr })
|
||||
}
|
||||
}
|
||||
|
||||
//search
|
||||
for _, key := range all_list {
|
||||
if value, ok := file.GetDb().JsonDb.Tasks.Load(key.Id); ok {
|
||||
v := value.(*file.Tunnel)
|
||||
if (typeVal != "" && v.Mode != typeVal || (clientId != 0 && v.Client.Id != clientId)) || (typeVal == "" && clientId != v.Client.Id) {
|
||||
continue
|
||||
}
|
||||
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || v.Port == common.GetIntNoErrByStr(search) || strings.Contains(v.Password, search) || strings.Contains(v.Remark, search) || strings.Contains(v.Target.TargetStr, search)) {
|
||||
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || v.Port == common.GetIntNoErrByStr(search) || strings.Contains(v.Password, search) || strings.Contains(v.Remark, search)) {
|
||||
continue
|
||||
}
|
||||
cnt++
|
||||
@@ -308,6 +260,7 @@ func GetTunnel(start, length int, typeVal string, clientId int, search string, s
|
||||
}
|
||||
if start--; start < 0 {
|
||||
if length--; length >= 0 {
|
||||
//if _, ok := RunList[v.Id]; ok {
|
||||
if _, ok := RunList.Load(v.Id); ok {
|
||||
v.RunStatus = true
|
||||
} else {
|
||||
@@ -321,7 +274,7 @@ func GetTunnel(start, length int, typeVal string, clientId int, search string, s
|
||||
return list, cnt
|
||||
}
|
||||
|
||||
// get client list
|
||||
//get client list
|
||||
func GetClientList(start, length int, search, sort, order string, clientId int) (list []*file.Client, cnt int) {
|
||||
list, cnt = file.GetDb().GetClientList(start, length, search, sort, order, clientId)
|
||||
dealClientData()
|
||||
@@ -329,23 +282,38 @@ func GetClientList(start, length int, search, sort, order string, clientId int)
|
||||
}
|
||||
|
||||
func dealClientData() {
|
||||
|
||||
file.GetDb().JsonDb.Clients.Range(func(key, value interface{}) bool {
|
||||
v := value.(*file.Client)
|
||||
if vv, ok := Bridge.Client.Load(v.Id); ok {
|
||||
v.IsConnect = true
|
||||
v.LastOnlineTime = time.Now().Format("2006-01-02 15:04:05")
|
||||
v.Version = vv.(*bridge.Client).Version
|
||||
} else {
|
||||
v.IsConnect = false
|
||||
}
|
||||
|
||||
v.Flow.InletFlow = 0
|
||||
v.Flow.ExportFlow = 0
|
||||
file.GetDb().JsonDb.Hosts.Range(func(key, value interface{}) bool {
|
||||
h := value.(*file.Host)
|
||||
if h.Client.Id == v.Id {
|
||||
v.Flow.InletFlow += h.Flow.InletFlow
|
||||
v.Flow.ExportFlow += h.Flow.ExportFlow
|
||||
}
|
||||
return true
|
||||
})
|
||||
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
t := value.(*file.Tunnel)
|
||||
if t.Client.Id == v.Id {
|
||||
v.Flow.InletFlow += t.Flow.InletFlow
|
||||
v.Flow.ExportFlow += t.Flow.ExportFlow
|
||||
}
|
||||
return true
|
||||
})
|
||||
return true
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// delete all host and tasks by client id
|
||||
//delete all host and tasks by client id
|
||||
func DelTunnelAndHostByClientId(clientId int, justDelNoStore bool) {
|
||||
var ids []int
|
||||
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
@@ -377,7 +345,7 @@ func DelTunnelAndHostByClientId(clientId int, justDelNoStore bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// close the client
|
||||
//close the client
|
||||
func DelClientConnect(clientId int) {
|
||||
Bridge.DelClient(clientId)
|
||||
}
|
||||
@@ -479,19 +447,15 @@ func GetDashboardData() map[string]interface{} {
|
||||
return data
|
||||
}
|
||||
|
||||
// 实例化流量数据到文件
|
||||
func flowSession(m time.Duration) {
|
||||
once.Do(func() {
|
||||
ticker := time.NewTicker(m)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
file.GetDb().JsonDb.StoreHostToJsonFile()
|
||||
file.GetDb().JsonDb.StoreTasksToJsonFile()
|
||||
file.GetDb().JsonDb.StoreClientsToJsonFile()
|
||||
file.GetDb().JsonDb.StoreGlobalToJsonFile()
|
||||
}
|
||||
ticker := time.NewTicker(m)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
file.GetDb().JsonDb.StoreHostToJsonFile()
|
||||
file.GetDb().JsonDb.StoreTasksToJsonFile()
|
||||
file.GetDb().JsonDb.StoreClientsToJsonFile()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package tool
|
||||
|
||||
import (
|
||||
"math"
|
||||
"math/rand"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
@@ -51,20 +50,6 @@ func TestServerPort(p int, m string) (b bool) {
|
||||
return
|
||||
}
|
||||
|
||||
func GenerateServerPort(m string) int {
|
||||
for {
|
||||
//生成随机数 1024 - 65535
|
||||
serverPort := rand.Intn(65535)
|
||||
if serverPort < 1024 {
|
||||
serverPort = 1024
|
||||
}
|
||||
|
||||
if TestServerPort(serverPort, m) {
|
||||
return serverPort
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getSeverStatus() {
|
||||
for {
|
||||
if len(ServerStatus) < 10 {
|
||||
|
||||
@@ -2,12 +2,8 @@ package controllers
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"github.com/astaxie/beego/logs"
|
||||
"html"
|
||||
"time"
|
||||
|
||||
"ehang.io/nps/lib/file"
|
||||
|
||||
"ehang.io/nps/lib/crypt"
|
||||
"github.com/astaxie/beego"
|
||||
)
|
||||
@@ -44,63 +40,3 @@ func (s *AuthController) GetTime() {
|
||||
s.Data["json"] = m
|
||||
s.ServeJSON()
|
||||
}
|
||||
|
||||
func (s *AuthController) IpWhiteAuth() {
|
||||
s.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
s.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
||||
s.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
vkey := s.getEscapeString("vkey")
|
||||
ip := s.getEscapeString("ip")
|
||||
password := s.getEscapeString("pass")
|
||||
|
||||
if vkey == "" || password == "" {
|
||||
s.Data["json"] = map[string]interface{}{"success": false, "message": "参数错误"}
|
||||
s.ServeJSON()
|
||||
return
|
||||
}
|
||||
|
||||
// 如果未提供 ip,则使用请求中的客户端 IP(支持代理头)
|
||||
if ip == "" {
|
||||
ip = s.Ctx.Input.IP()
|
||||
ip = html.EscapeString(ip)
|
||||
}
|
||||
|
||||
c, err := file.GetDb().GetClientByVkey(vkey)
|
||||
if err != nil {
|
||||
s.Data["json"] = map[string]interface{}{"success": false, "message": "客户端密钥错误"}
|
||||
s.ServeJSON()
|
||||
logs.Error("客户端IP白名单认证失败,客户端密钥错误:vkey [%s] ip [%s] password [%s]", vkey, ip, password)
|
||||
return
|
||||
}
|
||||
|
||||
if c.IpWhitePass != password {
|
||||
s.Data["json"] = map[string]interface{}{"success": false, "message": "授权密码错误"}
|
||||
s.ServeJSON()
|
||||
logs.Error("客户端IP白名单认证失败,授权密码错误:vkey [%s] ip [%s] password [%s]", vkey, ip, password)
|
||||
return
|
||||
}
|
||||
|
||||
ipExists := false
|
||||
for _, existingIp := range c.IpWhiteList {
|
||||
if existingIp == ip {
|
||||
ipExists = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !ipExists {
|
||||
c.IpWhiteList = append(c.IpWhiteList, ip)
|
||||
file.GetDb().UpdateClient(c)
|
||||
}
|
||||
|
||||
s.Data["json"] = map[string]interface{}{"success": true, "message": "授权成功"}
|
||||
s.ServeJSON()
|
||||
|
||||
logs.Info("客户端IP白名单认证授权成功:vkey [%s] ip [%s] password [%s]", vkey, ip, password)
|
||||
|
||||
}
|
||||
|
||||
func (s *AuthController) getEscapeString(key string) string {
|
||||
return html.EscapeString(s.GetString(key))
|
||||
}
|
||||
|
||||
@@ -7,8 +7,6 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"ehang.io/nps/bridge"
|
||||
|
||||
"ehang.io/nps/lib/common"
|
||||
"ehang.io/nps/lib/crypt"
|
||||
"ehang.io/nps/lib/file"
|
||||
@@ -34,10 +32,10 @@ func (s *BaseController) Prepare() {
|
||||
md5Key := s.getEscapeString("auth_key")
|
||||
timestamp := s.GetIntNoErr("timestamp")
|
||||
configKey := beego.AppConfig.String("auth_key")
|
||||
if configKey == "" {
|
||||
configKey = crypt.GetRandomString(64)
|
||||
}
|
||||
timeNowUnix := time.Now().Unix()
|
||||
if configKey == "" {
|
||||
configKey = crypt.GetRandomString(128)
|
||||
}
|
||||
if !(md5Key != "" && (math.Abs(float64(timeNowUnix-int64(timestamp))) <= 20) && (crypt.Md5(configKey+strconv.Itoa(timestamp)) == md5Key)) {
|
||||
if s.GetSession("auth") != true {
|
||||
s.Redirect(beego.AppConfig.String("web_base_url")+"/login/index", 302)
|
||||
@@ -81,31 +79,11 @@ func (s *BaseController) display(tpl ...string) {
|
||||
}
|
||||
ip := s.Ctx.Request.Host
|
||||
s.Data["ip"] = common.GetIpByAddr(ip)
|
||||
|
||||
global := file.GetDb().GetGlobal()
|
||||
if global != nil && global.ServerUrl != "" && global.ServerUrl != ip {
|
||||
// 替换掉 http:// 或者 https://
|
||||
ip = global.ServerUrl
|
||||
ip = strings.ReplaceAll(ip, "http://", "")
|
||||
ip = strings.ReplaceAll(ip, "https://", "")
|
||||
s.Data["ip"] = ip
|
||||
}
|
||||
|
||||
s.Data["bridgeType"] = beego.AppConfig.String("bridge_type")
|
||||
if common.IsWindows() {
|
||||
s.Data["win"] = ".exe"
|
||||
}
|
||||
|
||||
s.Data["p"] = strconv.Itoa(server.Bridge.TunnelPort)
|
||||
|
||||
if bridge.ServerTlsEnable {
|
||||
tlsPort := strconv.Itoa(beego.AppConfig.DefaultInt("tls_bridge_port", 8025))
|
||||
s.Data["tls_p"] = tlsPort
|
||||
s.Data["p1"] = strconv.Itoa(server.Bridge.TunnelPort) + " / " + tlsPort
|
||||
} else {
|
||||
s.Data["p1"] = strconv.Itoa(server.Bridge.TunnelPort)
|
||||
}
|
||||
|
||||
s.Data["p"] = server.Bridge.TunnelPort
|
||||
s.Data["proxyPort"] = beego.AppConfig.String("hostPort")
|
||||
s.Layout = "public/layout.html"
|
||||
s.TplName = tplname
|
||||
@@ -150,13 +128,6 @@ func (s *BaseController) AjaxOk(str string) {
|
||||
s.StopRun()
|
||||
}
|
||||
|
||||
// ajax正确返回
|
||||
func (s *BaseController) AjaxOkWithId(str string, id int) {
|
||||
s.Data["json"] = ajaxWithId(str, 1, id)
|
||||
s.ServeJSON()
|
||||
s.StopRun()
|
||||
}
|
||||
|
||||
// ajax错误返回
|
||||
func (s *BaseController) AjaxErr(str string) {
|
||||
s.Data["json"] = ajax(str, 0)
|
||||
@@ -172,15 +143,6 @@ func ajax(str string, status int) map[string]interface{} {
|
||||
return json
|
||||
}
|
||||
|
||||
// 组装ajax
|
||||
func ajaxWithId(str string, status int, id int) map[string]interface{} {
|
||||
json := make(map[string]interface{})
|
||||
json["status"] = status
|
||||
json["msg"] = str
|
||||
json["id"] = id
|
||||
return json
|
||||
}
|
||||
|
||||
// ajax table返回
|
||||
func (s *BaseController) AjaxTable(list interface{}, cnt int, recordsTotal int, kwargs map[string]interface{}) {
|
||||
json := make(map[string]interface{})
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"ehang.io/nps/lib/common"
|
||||
"ehang.io/nps/lib/file"
|
||||
"ehang.io/nps/lib/rate"
|
||||
@@ -39,17 +36,16 @@ func (s *ClientController) List() {
|
||||
s.AjaxTable(list, cnt, cnt, cmd)
|
||||
}
|
||||
|
||||
// 添加客户端
|
||||
//添加客户端
|
||||
func (s *ClientController) Add() {
|
||||
if s.Ctx.Request.Method == "GET" {
|
||||
s.Data["menu"] = "client"
|
||||
s.SetInfo("add client")
|
||||
s.display()
|
||||
} else {
|
||||
id := int(file.GetDb().JsonDb.GetClientId())
|
||||
t := &file.Client{
|
||||
VerifyKey: s.getEscapeString("vkey"),
|
||||
Id: id,
|
||||
Id: int(file.GetDb().JsonDb.GetClientId()),
|
||||
Status: true,
|
||||
Remark: s.getEscapeString("remark"),
|
||||
Cnf: &file.Config{
|
||||
@@ -69,16 +65,11 @@ func (s *ClientController) Add() {
|
||||
InletFlow: 0,
|
||||
FlowLimit: int64(s.GetIntNoErr("flow_limit")),
|
||||
},
|
||||
BlackIpList: RemoveRepeatedElement(strings.Split(s.getEscapeString("blackiplist"), "\r\n")),
|
||||
IpWhite: s.GetBoolNoErr("ipwhite"),
|
||||
IpWhitePass: s.getEscapeString("ipwhitepass"),
|
||||
IpWhiteList: RemoveRepeatedElement(strings.Split(s.getEscapeString("ipwhitelist"), "\r\n")),
|
||||
CreateTime: time.Now().Format("2006-01-02 15:04:05"),
|
||||
}
|
||||
if err := file.GetDb().NewClient(t); err != nil {
|
||||
s.AjaxErr(err.Error())
|
||||
}
|
||||
s.AjaxOkWithId("add success", id)
|
||||
s.AjaxOk("add success")
|
||||
}
|
||||
}
|
||||
func (s *ClientController) GetClient() {
|
||||
@@ -96,7 +87,7 @@ func (s *ClientController) GetClient() {
|
||||
}
|
||||
}
|
||||
|
||||
// 修改客户端
|
||||
//修改客户端
|
||||
func (s *ClientController) Edit() {
|
||||
id := s.GetIntNoErr("id")
|
||||
if s.Ctx.Request.Method == "GET" {
|
||||
@@ -105,8 +96,6 @@ func (s *ClientController) Edit() {
|
||||
s.error()
|
||||
} else {
|
||||
s.Data["c"] = c
|
||||
s.Data["BlackIpList"] = strings.Join(c.BlackIpList, "\r\n")
|
||||
s.Data["IpWhiteList"] = strings.Join(c.IpWhiteList, "\r\n")
|
||||
}
|
||||
s.SetInfo("edit client")
|
||||
s.display()
|
||||
@@ -144,9 +133,6 @@ func (s *ClientController) Edit() {
|
||||
}
|
||||
c.WebPassword = s.getEscapeString("web_password")
|
||||
c.ConfigConnAllow = s.GetBoolNoErr("config_conn_allow")
|
||||
c.IpWhite = s.GetBoolNoErr("ipwhite")
|
||||
c.IpWhitePass = s.getEscapeString("ipwhitepass")
|
||||
c.IpWhiteList = RemoveRepeatedElement(strings.Split(s.getEscapeString("ipwhitelist"), "\r\n"))
|
||||
if c.Rate != nil {
|
||||
c.Rate.Stop()
|
||||
}
|
||||
@@ -154,39 +140,16 @@ func (s *ClientController) Edit() {
|
||||
c.Rate = rate.NewRate(int64(c.RateLimit * 1024))
|
||||
c.Rate.Start()
|
||||
} else {
|
||||
c.Rate = rate.NewRate((2 << 23) * 1024)
|
||||
c.Rate = rate.NewRate(int64(2 << 23))
|
||||
c.Rate.Start()
|
||||
}
|
||||
|
||||
c.BlackIpList = RemoveRepeatedElement(strings.Split(s.getEscapeString("blackiplist"), "\r\n"))
|
||||
file.GetDb().JsonDb.StoreClientsToJsonFile()
|
||||
}
|
||||
s.AjaxOk("save success")
|
||||
}
|
||||
}
|
||||
|
||||
func RemoveRepeatedElement(arr []string) (newArr []string) {
|
||||
newArr = make([]string, 0)
|
||||
for i := 0; i < len(arr); i++ {
|
||||
// 过滤空IP
|
||||
if strings.TrimSpace(arr[i]) == "" {
|
||||
continue
|
||||
}
|
||||
repeat := false
|
||||
for j := i + 1; j < len(arr); j++ {
|
||||
if arr[i] == arr[j] {
|
||||
repeat = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !repeat {
|
||||
newArr = append(newArr, arr[i])
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 更改状态
|
||||
//更改状态
|
||||
func (s *ClientController) ChangeStatus() {
|
||||
id := s.GetIntNoErr("id")
|
||||
if client, err := file.GetDb().GetClient(id); err == nil {
|
||||
@@ -199,7 +162,7 @@ func (s *ClientController) ChangeStatus() {
|
||||
s.AjaxErr("modified fail")
|
||||
}
|
||||
|
||||
// 删除客户端
|
||||
//删除客户端
|
||||
func (s *ClientController) Del() {
|
||||
id := s.GetIntNoErr("id")
|
||||
if err := file.GetDb().DelClient(id); err != nil {
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"ehang.io/nps/lib/file"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type GlobalController struct {
|
||||
BaseController
|
||||
}
|
||||
|
||||
func (s *GlobalController) Index() {
|
||||
//if s.Ctx.Request.Method == "GET" {
|
||||
//
|
||||
// return
|
||||
//}
|
||||
s.Data["menu"] = "global"
|
||||
s.SetInfo("global")
|
||||
s.display("global/index")
|
||||
|
||||
global := file.GetDb().GetGlobal()
|
||||
if global == nil {
|
||||
return
|
||||
}
|
||||
s.Data["globalBlackIpList"] = strings.Join(global.BlackIpList, "\r\n")
|
||||
s.Data["serverUrl"] = global.ServerUrl
|
||||
}
|
||||
|
||||
// 添加全局参数
|
||||
func (s *GlobalController) Save() {
|
||||
if s.Ctx.Request.Method == "GET" {
|
||||
s.Data["menu"] = "global"
|
||||
s.SetInfo("save global")
|
||||
s.display()
|
||||
} else {
|
||||
|
||||
t := &file.Glob{
|
||||
BlackIpList: RemoveRepeatedElement(strings.Split(s.getEscapeString("globalBlackIpList"), "\r\n")),
|
||||
ServerUrl: s.getEscapeString("serverUrl")}
|
||||
|
||||
if err := file.GetDb().SaveGlobal(t); err != nil {
|
||||
s.AjaxErr(err.Error())
|
||||
}
|
||||
s.AjaxOk("save success")
|
||||
}
|
||||
}
|
||||
@@ -81,7 +81,7 @@ func (s *IndexController) GetTunnel() {
|
||||
start, length := s.GetAjaxParams()
|
||||
taskType := s.getEscapeString("type")
|
||||
clientId := s.GetIntNoErr("client_id")
|
||||
list, cnt := server.GetTunnel(start, length, taskType, clientId, s.getEscapeString("search"), s.getEscapeString("sort"), s.getEscapeString("order"))
|
||||
list, cnt := server.GetTunnel(start, length, taskType, clientId, s.getEscapeString("search"))
|
||||
s.AjaxTable(list, cnt, cnt, nil)
|
||||
}
|
||||
|
||||
@@ -92,26 +92,19 @@ func (s *IndexController) Add() {
|
||||
s.SetInfo("add tunnel")
|
||||
s.display()
|
||||
} else {
|
||||
id := int(file.GetDb().JsonDb.GetTaskId())
|
||||
t := &file.Tunnel{
|
||||
Port: s.GetIntNoErr("port"),
|
||||
ServerIp: s.getEscapeString("server_ip"),
|
||||
Mode: s.getEscapeString("type"),
|
||||
Target: &file.Target{TargetStr: s.getEscapeString("target"), LocalProxy: s.GetBoolNoErr("local_proxy")},
|
||||
Id: id,
|
||||
Status: true,
|
||||
Remark: s.getEscapeString("remark"),
|
||||
Password: s.getEscapeString("password"),
|
||||
LocalPath: s.getEscapeString("local_path"),
|
||||
StripPre: s.getEscapeString("strip_pre"),
|
||||
ProtoVersion: s.getEscapeString("proto_version"),
|
||||
Flow: &file.Flow{},
|
||||
Port: s.GetIntNoErr("port"),
|
||||
ServerIp: s.getEscapeString("server_ip"),
|
||||
Mode: s.getEscapeString("type"),
|
||||
Target: &file.Target{TargetStr: s.getEscapeString("target"), LocalProxy: s.GetBoolNoErr("local_proxy")},
|
||||
Id: int(file.GetDb().JsonDb.GetTaskId()),
|
||||
Status: true,
|
||||
Remark: s.getEscapeString("remark"),
|
||||
Password: s.getEscapeString("password"),
|
||||
LocalPath: s.getEscapeString("local_path"),
|
||||
StripPre: s.getEscapeString("strip_pre"),
|
||||
Flow: &file.Flow{},
|
||||
}
|
||||
|
||||
if t.Port <= 0 {
|
||||
t.Port = tool.GenerateServerPort(t.Mode)
|
||||
}
|
||||
|
||||
if !tool.TestServerPort(t.Port, t.Mode) {
|
||||
s.AjaxErr("The port cannot be opened because it may has been occupied or is no longer allowed.")
|
||||
}
|
||||
@@ -128,57 +121,10 @@ func (s *IndexController) Add() {
|
||||
if err := server.AddTask(t); err != nil {
|
||||
s.AjaxErr(err.Error())
|
||||
} else {
|
||||
s.AjaxOkWithId("add success", id)
|
||||
s.AjaxOk("add success")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *IndexController) Copy() {
|
||||
oldId := s.GetIntNoErr("id")
|
||||
if oldTask, err := file.GetDb().GetTask(oldId); err != nil {
|
||||
s.error()
|
||||
} else {
|
||||
if client, err := file.GetDb().GetClient(oldTask.Client.Id); err != nil {
|
||||
s.AjaxErr("modified error,the client is not exist")
|
||||
return
|
||||
} else {
|
||||
oldTask.Client = client
|
||||
}
|
||||
|
||||
id := int(file.GetDb().JsonDb.GetTaskId())
|
||||
newTask := &file.Tunnel{
|
||||
Client: oldTask.Client,
|
||||
Port: tool.GenerateServerPort(oldTask.Mode),
|
||||
ServerIp: oldTask.ServerIp,
|
||||
Mode: oldTask.Mode,
|
||||
Target: oldTask.Target,
|
||||
Id: id,
|
||||
Status: true,
|
||||
Remark: oldTask.Remark,
|
||||
Password: oldTask.Password,
|
||||
LocalPath: oldTask.LocalPath,
|
||||
StripPre: oldTask.StripPre,
|
||||
ProtoVersion: oldTask.ProtoVersion,
|
||||
Flow: &file.Flow{},
|
||||
}
|
||||
if !tool.TestServerPort(newTask.Port, newTask.Mode) {
|
||||
s.AjaxErr("The port cannot be opened because it may has been occupied or is no longer allowed.")
|
||||
}
|
||||
|
||||
if newTask.Client.MaxTunnelNum != 0 && newTask.Client.GetTunnelNum() >= newTask.Client.MaxTunnelNum {
|
||||
s.AjaxErr("The number of tunnels exceeds the limit")
|
||||
}
|
||||
if err := file.GetDb().NewTask(newTask); err != nil {
|
||||
s.AjaxErr(err.Error())
|
||||
}
|
||||
if err := server.AddTask(newTask); err != nil {
|
||||
s.AjaxErr(err.Error())
|
||||
} else {
|
||||
s.AjaxOkWithId("add success", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *IndexController) GetOneTunnel() {
|
||||
id := s.GetIntNoErr("id")
|
||||
data := make(map[string]interface{})
|
||||
@@ -212,16 +158,11 @@ func (s *IndexController) Edit() {
|
||||
t.Client = client
|
||||
}
|
||||
if s.GetIntNoErr("port") != t.Port {
|
||||
t.Port = s.GetIntNoErr("port")
|
||||
|
||||
if t.Port <= 0 {
|
||||
t.Port = tool.GenerateServerPort(t.Mode)
|
||||
}
|
||||
|
||||
if !tool.TestServerPort(s.GetIntNoErr("port"), t.Mode) {
|
||||
s.AjaxErr("The port cannot be opened because it may has been occupied or is no longer allowed.")
|
||||
return
|
||||
}
|
||||
t.Port = s.GetIntNoErr("port")
|
||||
}
|
||||
t.ServerIp = s.getEscapeString("server_ip")
|
||||
t.Mode = s.getEscapeString("type")
|
||||
@@ -229,7 +170,6 @@ func (s *IndexController) Edit() {
|
||||
t.Password = s.getEscapeString("password")
|
||||
t.Id = id
|
||||
t.LocalPath = s.getEscapeString("local_path")
|
||||
t.ProtoVersion = s.getEscapeString("proto_version")
|
||||
t.StripPre = s.getEscapeString("strip_pre")
|
||||
t.Remark = s.getEscapeString("remark")
|
||||
t.Target.LocalProxy = s.GetBoolNoErr("local_proxy")
|
||||
@@ -308,9 +248,8 @@ func (s *IndexController) AddHost() {
|
||||
s.SetInfo("add host")
|
||||
s.display("index/hadd")
|
||||
} else {
|
||||
id := int(file.GetDb().JsonDb.GetHostId())
|
||||
h := &file.Host{
|
||||
Id: id,
|
||||
Id: int(file.GetDb().JsonDb.GetHostId()),
|
||||
Host: s.getEscapeString("host"),
|
||||
Target: &file.Target{TargetStr: s.getEscapeString("target"), LocalProxy: s.GetBoolNoErr("local_proxy")},
|
||||
HeaderChange: s.getEscapeString("header"),
|
||||
@@ -321,25 +260,15 @@ func (s *IndexController) AddHost() {
|
||||
Scheme: s.getEscapeString("scheme"),
|
||||
KeyFilePath: s.getEscapeString("key_file_path"),
|
||||
CertFilePath: s.getEscapeString("cert_file_path"),
|
||||
AutoHttps: s.GetBoolNoErr("AutoHttps"),
|
||||
}
|
||||
|
||||
if h.Scheme == "http" {
|
||||
h.AutoHttps = false
|
||||
}
|
||||
|
||||
var err error
|
||||
if h.Client, err = file.GetDb().GetClient(s.GetIntNoErr("client_id")); err != nil {
|
||||
s.AjaxErr("add error the client can not be found")
|
||||
}
|
||||
if h.Client.MaxTunnelNum != 0 && h.Client.GetTunnelNum() >= h.Client.MaxTunnelNum {
|
||||
s.AjaxErr("The number of tunnels exceeds the limit")
|
||||
}
|
||||
|
||||
if err := file.GetDb().NewHost(h); err != nil {
|
||||
s.AjaxErr("add fail" + err.Error())
|
||||
}
|
||||
s.AjaxOkWithId("add success", id)
|
||||
s.AjaxOk("add success")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -383,12 +312,6 @@ func (s *IndexController) EditHost() {
|
||||
h.KeyFilePath = s.getEscapeString("key_file_path")
|
||||
h.CertFilePath = s.getEscapeString("cert_file_path")
|
||||
h.Target.LocalProxy = s.GetBoolNoErr("local_proxy")
|
||||
h.AutoHttps = s.GetBoolNoErr("AutoHttps")
|
||||
|
||||
if h.Scheme == "http" {
|
||||
h.AutoHttps = false
|
||||
}
|
||||
|
||||
file.GetDb().JsonDb.StoreHostToJsonFile()
|
||||
}
|
||||
s.AjaxOk("modified success")
|
||||
|
||||
@@ -14,8 +14,6 @@ func Init() {
|
||||
beego.NSAutoRouter(&controllers.LoginController{}),
|
||||
beego.NSAutoRouter(&controllers.ClientController{}),
|
||||
beego.NSAutoRouter(&controllers.AuthController{}),
|
||||
beego.NSRouter("/auth/ipwhiteauth", &controllers.AuthController{}, "*:IpWhiteAuth"),
|
||||
beego.NSAutoRouter(&controllers.GlobalController{}),
|
||||
)
|
||||
beego.AddNamespace(ns)
|
||||
} else {
|
||||
@@ -24,8 +22,5 @@ func Init() {
|
||||
beego.AutoRouter(&controllers.LoginController{})
|
||||
beego.AutoRouter(&controllers.ClientController{})
|
||||
beego.AutoRouter(&controllers.AuthController{})
|
||||
beego.Router("/auth/ipwhiteauth", &controllers.AuthController{}, "*:IpWhiteAuth")
|
||||
beego.AutoRouter(&controllers.GlobalController{})
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*@import url("https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700");*/
|
||||
/*@import url("https://fonts.googleapis.com/css?family=Roboto:400,300,500,700");*/
|
||||
@import url("https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700");
|
||||
@import url("https://fonts.googleapis.com/css?family=Roboto:400,300,500,700");
|
||||
/*
|
||||
*
|
||||
* INSPINIA - Responsive Admin Theme
|
||||
|
||||
@@ -59,7 +59,7 @@
|
||||
$.fn.cloudLang = function () {
|
||||
$.ajax({
|
||||
type: 'GET',
|
||||
url: window.nps.web_base_url + '/static/page/languages.xml?v=202512051',
|
||||
url: window.nps.web_base_url + '/static/page/languages.xml',
|
||||
dataType: 'xml',
|
||||
success: function (xml) {
|
||||
languages['content'] = xml2json($(xml).children())['content'];
|
||||
@@ -144,7 +144,6 @@ function submitform(action, url, postdata) {
|
||||
case 'start':
|
||||
case 'stop':
|
||||
case 'delete':
|
||||
case 'copy':
|
||||
var langobj = languages['content']['confirm'][action];
|
||||
action = (langobj[languages['current']] || langobj[languages['default']] || 'Are you sure you want to ' + action + ' it?');
|
||||
if (! confirm(action)) return;
|
||||
@@ -158,27 +157,10 @@ function submitform(action, url, postdata) {
|
||||
success: function (res) {
|
||||
alert(langreply(res.msg));
|
||||
if (res.status) {
|
||||
if (postsubmit) {
|
||||
document.location.reload();
|
||||
}else{
|
||||
window.location.href= document.referrer
|
||||
}
|
||||
if (postsubmit) {document.location.reload();}else{history.back(-1);}
|
||||
}
|
||||
}
|
||||
});
|
||||
return;
|
||||
case 'global':
|
||||
$.ajax({
|
||||
type: "POST",
|
||||
url: url,
|
||||
data: postdata,
|
||||
success: function (res) {
|
||||
alert(langreply(res.msg));
|
||||
if (res.status) {
|
||||
document.location.reload();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,227 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="initial-scale=1, user-scalable=0, minimal-ui">
|
||||
<title>NPS访问验证</title>
|
||||
<style>
|
||||
html {
|
||||
padding: 30px 10px;
|
||||
font-size: 20px;
|
||||
line-height: 1.4;
|
||||
color: #737373;
|
||||
background: #ddd;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
-ms-text-size-adjust: 100%;
|
||||
}
|
||||
|
||||
html,
|
||||
input {
|
||||
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
|
||||
}
|
||||
|
||||
body {
|
||||
max-width: 500px;
|
||||
_width: 500px;
|
||||
padding: 30px 20px 50px;
|
||||
/* background-color: white; */
|
||||
margin: 40px auto;
|
||||
-webkit-border-radius: 6px;
|
||||
-moz-border-radius: 6px;
|
||||
border-radius: 6px;
|
||||
-webkit-box-shadow: 0 0px 2px rgba(0, 0, 0, 0.05);
|
||||
-moz-box-shadow: 0 0px 2px rgba(0, 0, 0, 0.1);
|
||||
box-shadow: 0 0px 2px rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0 10px;
|
||||
font-size: 50px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
h1 span {
|
||||
color: #bbb;
|
||||
}
|
||||
|
||||
h3 {
|
||||
margin: 1.5em 0 0.5em;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 1em 0;
|
||||
}
|
||||
|
||||
ul {
|
||||
padding: 0 0 0 40px;
|
||||
margin: 1em 0;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 380px;
|
||||
_width: 380px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
|
||||
html .login-wrap {
|
||||
position: relative;
|
||||
/* margin: 180px auto; */
|
||||
background: #ecf0f1;
|
||||
/* width: 350px; */
|
||||
border-radius: 5px;
|
||||
box-shadow: 3px 3px 10px #333;
|
||||
padding: 15px;
|
||||
}
|
||||
|
||||
html .login-wrap h2 {
|
||||
text-align: center;
|
||||
/* font-weight: 200; */
|
||||
font-size: 1.6em;
|
||||
margin-top: 20px;
|
||||
color: #34495e;
|
||||
height: 50px;
|
||||
}
|
||||
|
||||
html .login-wrap .form {
|
||||
padding-top: 20px;
|
||||
}
|
||||
|
||||
|
||||
html .login-wrap .form input[type="text"],
|
||||
html .login-wrap .form input[type="password"],
|
||||
html .login-wrap .form button {
|
||||
width: 80%;
|
||||
margin-left: 10%;
|
||||
margin-bottom: 25px;
|
||||
height: 40px;
|
||||
border-radius: 5px;
|
||||
outline: 0;
|
||||
-moz-outline-style: none;
|
||||
}
|
||||
|
||||
|
||||
html .login-wrap .form input[type="text"],
|
||||
html .login-wrap .form input[type="password"] {
|
||||
border: 1px solid #bbb;
|
||||
padding: 0 0 0 10px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
html .login-wrap .form input[type="text"]:focus,
|
||||
html .login-wrap .form input[type="password"]:focus {
|
||||
border: 1px solid #3498db;
|
||||
}
|
||||
|
||||
|
||||
html .login-wrap .form a {
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
color: #3498db;
|
||||
}
|
||||
|
||||
|
||||
html .login-wrap .form a {
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
color: #3498db;
|
||||
}
|
||||
|
||||
html .login-wrap .form a p {
|
||||
padding-bottom: 10px;
|
||||
}
|
||||
|
||||
html .login-wrap .form button {
|
||||
background: #e74c3c;
|
||||
border: none;
|
||||
color: white;
|
||||
font-size: 18px;
|
||||
font-weight: 200;
|
||||
cursor: pointer;
|
||||
transition: box-shadow .4s ease;
|
||||
}
|
||||
|
||||
html .login-wrap .form button:hover {
|
||||
box-shadow: 1px 1px 5px #555;
|
||||
}
|
||||
|
||||
html .login-wrap .form button:active {
|
||||
box-shadow: 1px 1px 7px #222;
|
||||
}
|
||||
|
||||
|
||||
html .login-wrap:after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
background: -webkit-linear-gradient(left, #27ae60 0%, #27ae60 20%, #8e44ad 20%, #8e44ad 40%, #3498db 40%, #3498db 60%, #e74c3c 60%, #e74c3c 80%, #f1c40f 80%, #f1c40f 100%);
|
||||
background: -moz-linear-gradient(left, #27ae60 0%, #27ae60 20%, #8e44ad 20%, #8e44ad 40%, #3498db 40%, #3498db 60%, #e74c3c 60%, #e74c3c 80%, #f1c40f 80%, #f1c40f 100%);
|
||||
height: 5px;
|
||||
border-radius: 5px 5px 0 0;
|
||||
}
|
||||
|
||||
.tips {
|
||||
text-align: center;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.ip-addr {
|
||||
font-weight: bolder;
|
||||
}
|
||||
|
||||
.error {
|
||||
text-align: center;
|
||||
color: red;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div hidden id="port">${port}</div>
|
||||
|
||||
<div class="container">
|
||||
<div class="login-wrap">
|
||||
<h2>访问验证</h2>
|
||||
<div class="tips">当前 IP (<span class="ip-addr" id="ip_addr">${ip}</span>) 未经授权, 已禁止访问</div>
|
||||
<div class="form">
|
||||
<input type="text" id="pwd" placeholder="请输入访问密码" name="pw">
|
||||
<button onclick="submitAuth()"> 提交验证</button>
|
||||
<div hidden id="error" class="error"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
<script>
|
||||
function submitAuth() {
|
||||
var pwd = document.getElementById("pwd").value
|
||||
|
||||
if (pwd === '' || pwd == null) {
|
||||
document.getElementById("error").hidden = false;
|
||||
document.getElementById("error").innerHTML = "请输入授权秘钥"
|
||||
}
|
||||
const xhr = new XMLHttpRequest()
|
||||
xhr.addEventListener("readystatechange", function () {
|
||||
// debugger
|
||||
if (xhr.response != null && xhr.response !== '') {
|
||||
var resp = JSON.parse(xhr.response);
|
||||
console.log(resp)
|
||||
if (resp.success !== true) {
|
||||
document.getElementById("error").hidden = false;
|
||||
document.getElementById("error").innerHTML = resp.message
|
||||
} else {
|
||||
location.reload();
|
||||
}
|
||||
|
||||
}
|
||||
console.log(xhr.response)
|
||||
})
|
||||
xhr.open("post", "/authIp?pass=" + pwd)
|
||||
xhr.send()
|
||||
}
|
||||
</script>
|
||||
|
||||
</html>
|
||||
@@ -149,10 +149,6 @@
|
||||
<zh-CN>Basic 认证用户名</zh-CN>
|
||||
<en-US>Basic authentication username</en-US>
|
||||
</lang>
|
||||
<lang id="word-ishttp">
|
||||
<zh-CN>是否为HTTP</zh-CN>
|
||||
<en-US>Is HTTP</en-US>
|
||||
</lang>
|
||||
<lang id="word-bridgingmode">
|
||||
<zh-CN>桥接模式</zh-CN>
|
||||
<en-US>Bridging mode</en-US>
|
||||
@@ -189,31 +185,10 @@
|
||||
<zh-CN>访问端命令</zh-CN>
|
||||
<en-US>Access command</en-US>
|
||||
</lang>
|
||||
<lang id="word-protoversion">
|
||||
<zh-CN>Proxy Protocol Version</zh-CN>
|
||||
<en-US>Proxy Protocol Version</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="word-quicklycommand">
|
||||
<zh-CN>快捷启动命令</zh-CN>
|
||||
<en-US>Quickly command</en-US>
|
||||
</lang>
|
||||
<lang id="word-tlsquicklycommand">
|
||||
<zh-CN>TLS快捷启动命令</zh-CN>
|
||||
<en-US>TLS Quickly command</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="word-commandclient">
|
||||
<zh-CN>客户端命令</zh-CN>
|
||||
<en-US>Command</en-US>
|
||||
</lang>
|
||||
<lang id="word-commandclient-tls">
|
||||
<zh-CN>TLS 启动命令</zh-CN>
|
||||
<en-US>TLS Command</en-US>
|
||||
</lang>
|
||||
|
||||
|
||||
|
||||
<lang id="word-compress">
|
||||
<zh-CN>压缩</zh-CN>
|
||||
<en-US>Compress</en-US>
|
||||
@@ -258,10 +233,6 @@
|
||||
<zh-CN>仪表盘</zh-CN>
|
||||
<en-US>Dashboard</en-US>
|
||||
</lang>
|
||||
<lang id="word-globalparam">
|
||||
<zh-CN>全局参数</zh-CN>
|
||||
<en-US>Global Params</en-US>
|
||||
</lang>
|
||||
<lang id="word-exportflow">
|
||||
<zh-CN>出口流量</zh-CN>
|
||||
<en-US>Export Flow</en-US>
|
||||
@@ -293,13 +264,13 @@
|
||||
<en-US>HTTP port</en-US>
|
||||
</lang>
|
||||
<lang id="word-httpscert">
|
||||
<zh-CN>HTTPS 证书(或证书路径)</zh-CN>
|
||||
<zh-CN>HTTPS 证书</zh-CN>
|
||||
<en-US>HTTPS cert</en-US>
|
||||
</lang>
|
||||
<lang id="word-https">HTTPS
|
||||
</lang>
|
||||
<lang id="word-httpskey">
|
||||
<zh-CN>HTTPS 密钥(或秘钥路径)</zh-CN>
|
||||
<zh-CN>HTTPS 密钥</zh-CN>
|
||||
<en-US>HTTPS key</en-US>
|
||||
</lang>
|
||||
<lang id="word-httpsport">
|
||||
@@ -404,12 +375,6 @@
|
||||
<zh-CN>端口</zh-CN>
|
||||
<en-US>Port</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="word-accessaddress">
|
||||
<zh-CN>访问地址</zh-CN>
|
||||
<en-US>Access address</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="word-proxytolocal">
|
||||
<zh-CN>代理到服务器本地</zh-CN>
|
||||
<en-US>Proxy to server local</en-US>
|
||||
@@ -463,7 +428,7 @@
|
||||
<en-US>Server IP</en-US>
|
||||
</lang>
|
||||
<lang id="word-serverport">
|
||||
<zh-CN>服务端端口(留空自动生成)</zh-CN>
|
||||
<zh-CN>服务端端口</zh-CN>
|
||||
<en-US>Server Port</en-US>
|
||||
</lang>
|
||||
<lang id="word-serverversion">
|
||||
@@ -589,22 +554,10 @@
|
||||
<lang id="word-">
|
||||
</lang>
|
||||
|
||||
|
||||
<lang id="word-globalparam">
|
||||
<zh-CN>全局参数</zh-CN>
|
||||
<en-US>global Param</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="info-autogenerated">
|
||||
<zh-CN>唯一值,不填将自动生成</zh-CN>
|
||||
<en-US>Unique, non-filling will be generated automatically</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="info-ipwhitepass">
|
||||
<zh-CN>IP授权密码,不在IP白名单的访问将被跳转到IP授权页面,输入正确的授权密码,即可完成添加IP。</zh-CN>
|
||||
<en-US>IP White Password, access that is not in the IP white list will be redirected to the IP authorization page, enter the correct authorization password, and you can complete the addition of IP.</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="info-casefile">
|
||||
<zh-CN>通提供一个公网可访问的本地文件服务,此模式仅客户端使用配置文件模式方可启动。</zh-CN>
|
||||
<en-US>Provide a local file service accessible to the public network, which can only be started by the client using the profile mode.</en-US>
|
||||
@@ -738,75 +691,6 @@
|
||||
<en-US>Empty means to be unrestricted</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="info-input-whitepass">
|
||||
<zh-CN>留空表示不跳转IP授权页面</zh-CN>
|
||||
<en-US>Empty means not to jump to the IP authorization page</en-US>
|
||||
</lang>
|
||||
|
||||
|
||||
|
||||
<lang id="word-blackiplist">
|
||||
<zh-CN>IP黑名单(防暴力破解)</zh-CN>
|
||||
<en-US>IP Black List</en-US>
|
||||
</lang>
|
||||
|
||||
|
||||
<lang id="word-globalblackiplist">
|
||||
<zh-CN>全局IP黑名单(防暴力破解)</zh-CN>
|
||||
<en-US>Global IP Black List</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="word-serverurl">
|
||||
<zh-CN>服务地址</zh-CN>
|
||||
<en-US>Server</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="info-servertips">
|
||||
<zh-CN>客户端命令地址显示、隧道访问显示</zh-CN>
|
||||
<en-US>Server URL, Tunnel Access</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="info-suchasblackiplist">
|
||||
<zh-CN>例如 10.1.50.203 10.1.50.202</zh-CN>
|
||||
<en-US>such as 10.1.50.203 10.1.50.202</en-US>
|
||||
</lang>
|
||||
|
||||
|
||||
<lang id="info-descblackiplist">
|
||||
<zh-CN>一行一个,IPV4,不支持范围匹配</zh-CN>
|
||||
<en-US>IPV4</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="word-blackip">
|
||||
<zh-CN>IP黑名单</zh-CN>
|
||||
<en-US>IP Black List</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="word-createtime">
|
||||
<zh-CN>创建时间</zh-CN>
|
||||
<en-US>Create Time</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="word-lastonlinetime">
|
||||
<zh-CN>上次在线时间</zh-CN>
|
||||
<en-US>Last Online Time</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="word-ipwhite">
|
||||
<zh-CN>启用IP白名单</zh-CN>
|
||||
<en-US> Enable IP White </en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="word-ipwhitepass">
|
||||
<zh-CN>IP白名单授权密码</zh-CN>
|
||||
<en-US>IP White Password </en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="word-ipwhitelist">
|
||||
<zh-CN>IP白名单</zh-CN>
|
||||
<en-US>IP White List </en-US>
|
||||
</lang>
|
||||
|
||||
<confirm>
|
||||
<lang id="delete">
|
||||
<zh-CN>你确定你要删除它吗?</zh-CN>
|
||||
@@ -820,10 +704,6 @@
|
||||
<zh-CN>你确定你要停止它吗?</zh-CN>
|
||||
<en-US>Are you sure you want to stop it?</en-US>
|
||||
</lang>
|
||||
<lang id="copy">
|
||||
<zh-CN>你确定要复制它吗?</zh-CN>
|
||||
<en-US>Are you sure you want to copy it?</en-US>
|
||||
</lang>
|
||||
</confirm>
|
||||
|
||||
<reply>
|
||||
@@ -1098,7 +978,5 @@
|
||||
</array>
|
||||
</series>
|
||||
</lang>
|
||||
|
||||
|
||||
</charts>
|
||||
</content>
|
||||
|
||||
@@ -88,60 +88,24 @@
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<!-- <div class="form-group" id="compress">-->
|
||||
<!-- <label class="control-label font-bold" langtag="word-compress"></label>-->
|
||||
<!-- <div class="col-sm-10">-->
|
||||
<!-- <select class="form-control" name="compress">-->
|
||||
<!-- <option value="0" langtag="word-no"></option>-->
|
||||
<!-- <option value="1" langtag="word-yes"></option>-->
|
||||
<!-- </select>-->
|
||||
<!-- </div>-->
|
||||
<!-- </div>-->
|
||||
<!-- <div class="form-group" id="compress">-->
|
||||
<!-- <label class="control-label font-bold" langtag="word-crypt"></label>-->
|
||||
<!-- <div class="col-sm-10">-->
|
||||
<!-- <select class="form-control" name="crypt">-->
|
||||
<!-- <option value="0" langtag="word-no"></option>-->
|
||||
<!-- <option value="1" langtag="word-yes"></option>-->
|
||||
<!-- </select>-->
|
||||
<!-- </div>-->
|
||||
<!-- </div>-->
|
||||
|
||||
<div class="form-group" id="ip_white">
|
||||
<label class="control-label font-bold" langtag="word-ipwhite"></label>
|
||||
<div class="form-group" id="compress">
|
||||
<label class="control-label font-bold" langtag="word-compress"></label>
|
||||
<div class="col-sm-10">
|
||||
<select class="form-control" name="ipwhite">
|
||||
<select class="form-control" name="compress">
|
||||
<option value="0" langtag="word-no"></option>
|
||||
<option value="1" langtag="word-yes"></option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="form-group" id="Ip_white_pass" style="display: none;">
|
||||
<label class="control-label font-bold" langtag="word-ipwhitepass"></label>
|
||||
<div class="form-group" id="compress">
|
||||
<label class="control-label font-bold" langtag="word-crypt"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" type="text" name="ipwhitepass" placeholder="" langtag="info-input-whitepass">
|
||||
<span class="help-block m-b-none" langtag="info-ipwhitepass"></span>
|
||||
<select class="form-control" name="crypt">
|
||||
<option value="0" langtag="word-no"></option>
|
||||
<option value="1" langtag="word-yes"></option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="ip_white_list" style="display: none;">
|
||||
<label class="control-label font-bold" langtag="word-ipwhitelist"></label>
|
||||
<div class="col-sm-10">
|
||||
<textarea class="form-control" rows="4" type="text" name="ipwhitelist" placeholder="" langtag="info-suchasblackiplist">{{.BlackIpList}}</textarea>
|
||||
<span class="help-block m-b-none" langtag="info-descblackiplist"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="black_ip_list">
|
||||
<label class="control-label font-bold" langtag="word-blackiplist"></label>
|
||||
<div class="col-sm-10">
|
||||
<textarea class="form-control" rows="4" type="text" name="blackiplist" placeholder="" langtag="info-suchasblackiplist">{{.BlackIpList}}</textarea>
|
||||
<span class="help-block m-b-none" langtag="info-descblackiplist"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="hr-line-dashed"></div>
|
||||
<div class="form-group">
|
||||
<div class="col-sm-4 col-sm-offset-2">
|
||||
@@ -155,20 +119,3 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
$(document).ready(function() {
|
||||
// IP白名单选择change事件
|
||||
$('select[name="ipwhite"]').change(function() {
|
||||
if ($(this).val() == '1') {
|
||||
$('#Ip_white_pass').show();
|
||||
$('#ip_white_list').show();
|
||||
$('#black_ip_list').hide();
|
||||
} else {
|
||||
$('#Ip_white_pass').hide();
|
||||
$('#ip_white_list').hide();
|
||||
$('#black_ip_list').show();
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -8,108 +8,96 @@
|
||||
<div class="form-group" id="remark">
|
||||
<label class="control-label font-bold" langtag="word-remark"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" value="{{.c.Remark}}" type="text" name="remark" placeholder=""
|
||||
langtag="word-remark">
|
||||
<input class="form-control" value="{{.c.Remark}}" type="text" name="remark" placeholder="" langtag="word-remark">
|
||||
</div>
|
||||
</div>
|
||||
{{if eq true .isAdmin}}
|
||||
{{if eq true .allow_flow_limit}}
|
||||
{{if eq true .isAdmin}}
|
||||
{{if eq true .allow_flow_limit}}
|
||||
<div class="form-group" id="flow_limit">
|
||||
<label class="control-label font-bold" langtag="word-flowlimit"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" value="{{.c.Flow.FlowLimit}}" type="text" name="flow_limit"
|
||||
placeholder="" langtag="info-unrestricted">
|
||||
<input class="form-control" value="{{.c.Flow.FlowLimit}}" type="text" name="flow_limit" placeholder="" langtag="info-unrestricted">
|
||||
<span class="help-block m-b-none" langtag="word-unit"></span>: M
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if eq true .allow_rate_limit}}
|
||||
{{end}}
|
||||
{{if eq true .allow_rate_limit}}
|
||||
|
||||
<div class="form-group" id="rate_limit">
|
||||
<label class="control-label font-bold" langtag="word-ratelimit"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" value="{{.c.RateLimit}}" type="text" name="rate_limit"
|
||||
placeholder="" langtag="info-unrestricted">
|
||||
<input class="form-control" value="{{.c.RateLimit}}" type="text" name="rate_limit" placeholder="" langtag="info-unrestricted">
|
||||
<span class="help-block m-b-none" langtag="word-unit"></span>: KB/S
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if eq true .allow_connection_num_limit}}
|
||||
{{end}}
|
||||
{{if eq true .allow_connection_num_limit}}
|
||||
|
||||
<div class="form-group" id="max_conn">
|
||||
<label class="control-label font-bold" langtag="word-maxconnections"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" value="{{.c.MaxConn}}" type="text" name="max_conn"
|
||||
placeholder="" langtag="info-unrestricted">
|
||||
<input class="form-control" value="{{.c.MaxConn}}" type="text" name="max_conn" placeholder="" langtag="info-unrestricted">
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if eq true .allow_tunnel_num_limit}}
|
||||
{{end}}
|
||||
{{if eq true .allow_tunnel_num_limit}}
|
||||
<div class="form-group" id="max_tunnel">
|
||||
<label class="control-label font-bold" langtag="word-maxtunnels"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" value="{{.c.MaxTunnelNum}}" type="text" name="max_tunnel"
|
||||
placeholder="" langtag="info-unrestricted">
|
||||
<input class="form-control" value="{{.c.MaxTunnelNum}}" type="text" name="max_tunnel" placeholder="" langtag="info-unrestricted">
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{end}}
|
||||
{{end}}
|
||||
{{end}}
|
||||
<div class="form-group" id="u">
|
||||
<label class="control-label font-bold" langtag="word-basicusername"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" value="{{.c.Cnf.U}}" type="text" name="u" placeholder=""
|
||||
langtag="info-unrestricted">
|
||||
<input class="form-control" value="{{.c.Cnf.U}}" type="text" name="u" placeholder="" langtag="info-unrestricted">
|
||||
<span class="help-block m-b-none" langtag="info-onlyproxy"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group" id="p">
|
||||
<label class="control-label font-bold" langtag="word-basicpassword"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" value="{{.c.Cnf.P}}" type="text" name="p" placeholder=""
|
||||
langtag="info-unrestricted">
|
||||
<input class="form-control" value="{{.c.Cnf.P}}" type="text" name="p" placeholder="" langtag="info-unrestricted">
|
||||
<span class="help-block m-b-none" langtag="info-onlyproxy"></span>
|
||||
</div>
|
||||
</div>
|
||||
{{if eq true .isAdmin}}
|
||||
{{if eq true .isAdmin}}
|
||||
<div class="form-group" id="vkey">
|
||||
<label class="control-label font-bold" langtag="word-verifyKey"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" value="{{.c.VerifyKey}}" type="text" name="vkey" placeholder=""
|
||||
langtag="info-unrestricted">
|
||||
<input class="form-control" value="{{.c.VerifyKey}}" type="text" name="vkey" placeholder="" langtag="info-unrestricted">
|
||||
<span class="help-block m-b-none" langtag="info-autogenerated"></span>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if eq true .allow_user_login}}
|
||||
{{if or (eq true .allow_user_change_username) (eq true .isAdmin)}}
|
||||
{{end}}
|
||||
{{if eq true .allow_user_login}}
|
||||
{{if or (eq true .allow_user_change_username) (eq true .isAdmin)}}
|
||||
<div class="form-group" id="web_username">
|
||||
<label class="control-label font-bold" langtag="word-webusername"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" value="{{.c.WebUserName}}" type="text" name="web_username"
|
||||
placeholder="" langtag="info-unrestricted">
|
||||
<input class="form-control" value="{{.c.WebUserName}}" type="text" name="web_username" placeholder="" langtag="info-unrestricted">
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{end}}
|
||||
<div class="form-group" id="web_password">
|
||||
<label class="control-label font-bold" langtag="word-webpassword"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" value="{{.c.WebPassword}}" type="text" name="web_password"
|
||||
placeholder="" langtag="info-unrestricted">
|
||||
<input class="form-control" value="{{.c.WebPassword}}" type="text" name="web_password" placeholder="" langtag="info-unrestricted">
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{end}}
|
||||
<div class="form-group" id="config_conn_allow">
|
||||
<label class="control-label font-bold" langtag="word-connectbyconfig"></label>
|
||||
<div class="col-sm-10">
|
||||
<select class="form-control" name="config_conn_allow">
|
||||
<option {{if eq true .c.ConfigConnAllow}}selected{{end}} value="1" langtag="word-yes">
|
||||
</option>
|
||||
<option {{if eq false .c.ConfigConnAllow}}selected{{end}} value="0" langtag="word-no">
|
||||
</option>
|
||||
<option {{if eq true .c.ConfigConnAllow}}selected{{end}} value="1" langtag="word-yes"></option>
|
||||
<option {{if eq false .c.ConfigConnAllow}}selected{{end}} value="0" langtag="word-no"></option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<!-- <div class="form-group" id="compress">
|
||||
<div class="form-group" id="compress">
|
||||
<label class="control-label font-bold" langtag="word-compress"></label>
|
||||
<div class="col-sm-10">
|
||||
<select class="form-control" name="compress">
|
||||
@@ -126,52 +114,12 @@
|
||||
<option {{if eq true .c.Cnf.Crypt}}selected{{end}} value="1" langtag="word-yes"></option>
|
||||
</select>
|
||||
</div>
|
||||
</div> -->
|
||||
|
||||
<div class="form-group" id="ip_white">
|
||||
<label class="control-label font-bold" langtag="word-ipwhite"></label>
|
||||
<div class="col-sm-10">
|
||||
<select class="form-control" name="ipwhite" onchange="changeIpWhite()">
|
||||
<option {{if eq false .c.IpWhite}}selected{{end}} value="0" langtag="word-no"></option>
|
||||
<option {{if eq true .c.IpWhite}}selected{{end}} value="1" langtag="word-yes"></option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="form-group" id="ip_white_pass" style="display: none;">
|
||||
<label class="control-label font-bold" langtag="word-ipwhitepass"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" type="text" name="ipwhitepass" placeholder=""
|
||||
langtag="info-input-whitepass" value="{{.c.IpWhitePass}}">
|
||||
<span class="help-block m-b-none" langtag="info-ipwhitepass"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="ip_white_list" style="display: none;">
|
||||
<label class="control-label font-bold" langtag="word-ipwhitelist"></label>
|
||||
<div class="col-sm-10">
|
||||
<textarea class="form-control" rows="4" type="text" name="ipwhitelist" placeholder=""
|
||||
langtag="info-suchasblackiplist">{{.IpWhiteList}}</textarea>
|
||||
<span class="help-block m-b-none" langtag="info-descblackiplist"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="black_ip_list">
|
||||
<label class="control-label font-bold" langtag="word-blackiplist"></label>
|
||||
<div class="col-sm-10">
|
||||
<textarea class="form-control" rows="4" type="text" name="blackiplist" placeholder=""
|
||||
langtag="info-suchasblackiplist">{{.BlackIpList}}</textarea>
|
||||
<span class="help-block m-b-none" langtag="info-descblackiplist"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="hr-line-dashed"></div>
|
||||
<div class="form-group">
|
||||
<div class="col-sm-4 col-sm-offset-2">
|
||||
<button class="btn btn-success" type="button"
|
||||
onclick="submitform('add', '{{.web_base_url}}/client/edit', $('form').serializeArray())">
|
||||
<i class="fa fa-fw fa-lg fa-save"></i><span langtag="word-save"></span>
|
||||
<button class="btn btn-success" type="button" onclick="submitform('add', '{{.web_base_url}}/client/edit', $('form').serializeArray())"> <i
|
||||
class="fa fa-fw fa-lg fa-save"></i><span langtag="word-save"></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -180,24 +128,3 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<script>
|
||||
function changeIpWhite() {
|
||||
var ipWhite = $('select[name="ipwhite"]').val();
|
||||
if (ipWhite == '1') {
|
||||
$('#ip_white_pass').show();
|
||||
$('#ip_white_list').show();
|
||||
$('#black_ip_list').hide();
|
||||
} else {
|
||||
$('#ip_white_pass').hide();
|
||||
$('#ip_white_list').hide();
|
||||
$('#black_ip_list').show();
|
||||
}
|
||||
}
|
||||
|
||||
$(document).ready(function () {
|
||||
// 页面加载时初始化显示状态
|
||||
changeIpWhite();
|
||||
});
|
||||
</script>
|
||||
@@ -61,23 +61,16 @@
|
||||
return '<b langtag="word-maxconnections"></b>: ' + row.MaxConn + ' '
|
||||
+ '<b langtag="word-curconnections"></b>: ' + row.NowConn + ' '
|
||||
+ '<b langtag="word-flowlimit"></b>: ' + row.Flow.FlowLimit + 'm '
|
||||
+ '<b langtag="word-ratelimit"></b>: ' + row.RateLimit + 'KB/s '
|
||||
+ '<b langtag="word-ratelimit"></b>: ' + row.RateLimit + 'kb/s '
|
||||
+ '<b langtag="word-maxtunnels"></b>: ' + row.MaxTunnelNum + ' <br/><br/>'
|
||||
+ '<b langtag="word-webusername"></b>: ' + row.WebUserName + ' '
|
||||
+ '<b langtag="word-webpassword"></b>: ' + row.WebPassword + ' '
|
||||
+ '<b langtag="word-basicusername"></b>: ' + row.Cnf.U + ' '
|
||||
+ '<b langtag="word-basicpassword"></b>: ' + row.Cnf.P + ' <br/><br/>'
|
||||
+ '<b langtag="word-crypt"></b>: <span langtag="word-' + row.Cnf.Crypt + '"></span> '
|
||||
+ '<b langtag="word-compress"></b>: <span langtag="word-' + row.Cnf.Compress + '"></span> '
|
||||
+ '<b langtag="word-connectbyconfig"></b>: <span langtag="word-' + row.ConfigConnAllow + '"></span> <br/><br/>'
|
||||
+ '<b langtag="word-ipwhite"></b>: ' + row.IpWhite + ' '
|
||||
+ '<b langtag="word-ipwhitepass"></b>: ' + row.IpWhitePass + ' <br/>'
|
||||
+ '<b langtag="word-ipwhitelist"></b>: ' + row.IpWhiteList + ' <br/>'
|
||||
+ '<b langtag="word-blackip"></b>: ' + row.BlackIpList + ' <br/><br/>'
|
||||
+ '<b langtag="word-createtime"></b>: ' + row.CreateTime + ' <br/>'
|
||||
+ '<b langtag="word-lastonlinetime"></b>: ' + row.LastOnlineTime + ' <br/><br/>'
|
||||
+ '<b langtag="word-quicklycommand"></b>: <span>' + encodeToBase64('{{.ip}}:{{.p}} ' + row.VerifyKey) + '</span> <button class="copy btn btn-info btn-xs" onclick="copyCommand(this)" data-clipboard-text="">复制</button><br/>'
|
||||
+ '<b langtag="word-tlsquicklycommand"></b>: <span>' + encodeToBase64('{{.ip}}:{{.tls_p}} ' + row.VerifyKey + ' true') + '</span> <button class="copy btn btn-info btn-xs" onclick="copyCommand(this)" data-clipboard-text="">复制</button><br/>'
|
||||
+ '<b langtag="word-commandclient"></b>: ' + "<code>./npc{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.VerifyKey + " -type=" +{{.bridgeType}} +"</code><button class=\"copy btn btn-info btn-xs\" onclick=\"copyCommand(this)\" data-clipboard-text=\"\">复制</button><br/>"
|
||||
+ '<b langtag="word-commandclient-tls"></b>: ' + "<code>./npc{{.win}} -server={{.ip}}:{{.tls_p}} -vkey=" + row.VerifyKey + " -tls_enable=true</code><button class=\"copy btn btn-info btn-xs\" onclick=\"copyCommand(this)\" data-clipboard-text=\"\">复制</button>"
|
||||
+ '<b langtag="word-commandclient"></b>: ' + "<code>./npc{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.VerifyKey + " -type=" +{{.bridgeType}} +"</code>"
|
||||
},
|
||||
//表格的列
|
||||
columns: [
|
||||
@@ -216,26 +209,4 @@
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
function encodeToBase64(str){
|
||||
return btoa("nps "+ str);
|
||||
}
|
||||
|
||||
function copyCommand(data) {
|
||||
data.setAttribute("data-clipboard-text", data.previousElementSibling.innerHTML)
|
||||
}
|
||||
|
||||
var clipboard = new ClipboardJS('.copy');
|
||||
clipboard.on('success', function (e) {
|
||||
// alert("复制成功"+e.text)
|
||||
toastr.success('复制成功');
|
||||
e.clearSelection();
|
||||
});
|
||||
|
||||
clipboard.on('error', function (e) {
|
||||
// alert("复制失败")
|
||||
toastr.error('复制失败', '提示');
|
||||
});
|
||||
|
||||
|
||||
</script>
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
<div class="wrapper wrapper-content">
|
||||
<!--全局参数-->
|
||||
<div class="row">
|
||||
<div class="col-lg-12">
|
||||
<div class="ibox float-e-margins">
|
||||
<div class="ibox-title">
|
||||
<h5 langtag="word-globalparam"></h5>
|
||||
</div>
|
||||
<div class="ibox-content">
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="form-group" id="black_ip_list">
|
||||
<label class="control-label font-bold" langtag="word-globalblackiplist"></label>
|
||||
<div class="col-sm-4">
|
||||
<textarea class="form-control" rows="10" type="text" name="globalBlackIpList" placeholder=""
|
||||
langtag="info-suchasblackiplist">{{.globalBlackIpList}}</textarea>
|
||||
<span class="help-block m-b-none" langtag="info-descblackiplist"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="server_url">
|
||||
<label class="control-label font-bold" langtag="word-serverurl"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" value="{{.serverUrl}}" type="text" name="serverUrl"
|
||||
placeholder="" langtag="info-servertips">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<div class="col-sm-4 col-sm-offset-2">
|
||||
<button class="btn btn-success" type="button"
|
||||
onclick="submitform('global', '{{.web_base_url}}/global/save', $('form').serializeArray())">
|
||||
<i class="fa fa-fw fa-lg fa-check-circle"></i> <span langtag="word-save"></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
<script>
|
||||
window.addEventListener('resize', () => {
|
||||
for (var key in charts) {
|
||||
charts[key].resize();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
@@ -24,9 +24,7 @@
|
||||
<option value="socks5" langtag="scheme-socks5"></option>
|
||||
<option value="secret" langtag="scheme-secret"></option>
|
||||
<option value="p2p" langtag="scheme-p2p"></option>
|
||||
{{/*
|
||||
<option value="file" langtag="scheme-file"></option>
|
||||
*/}}
|
||||
{{/*<option value="file" langtag="scheme-file"></option>*/}}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
@@ -34,11 +32,8 @@
|
||||
<div class="form-group" id="client_id">
|
||||
<label class="control-label font-bold" langtag="word-clientid"></label>
|
||||
<div class="col-sm-10">
|
||||
<select class="form-control" name="client_id" placeholder="" id="nps_client_id"
|
||||
langtag="word-belongclient"></select>
|
||||
|
||||
<!-- <input value="{{.client_id}}" class="form-control" type="text" name="client_id"-->
|
||||
<!-- placeholder="" langtag="word-clientid">-->
|
||||
<input value="{{.client_id}}" class="form-control" type="text" name="client_id"
|
||||
placeholder="" langtag="word-clientid">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -50,13 +45,13 @@
|
||||
</div>
|
||||
</div>
|
||||
{{if eq true .allow_multi_ip}}
|
||||
<div class="form-group" id="server_ip">
|
||||
<label class="control-label font-bold" langtag="word-serverip"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" type="text" value="0.0.0.0" name="server_ip" placeholder=""
|
||||
langtag="info-suchasip">
|
||||
<div class="form-group" id="server_ip">
|
||||
<label class="control-label font-bold" langtag="word-serverip"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" type="text" value="0.0.0.0" name="server_ip" placeholder=""
|
||||
langtag="info-suchasip">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
<div class="form-group" id="port">
|
||||
<label class="control-label font-bold" langtag="word-serverport"></label>
|
||||
@@ -67,15 +62,15 @@
|
||||
</div>
|
||||
|
||||
{{if eq true .allow_local_proxy}}
|
||||
<div class="form-group" id="local_proxy">
|
||||
<label class="control-label font-bold" langtag="word-proxytolocal"></label>
|
||||
<div class="col-sm-10">
|
||||
<select class="form-control" name="local_proxy">
|
||||
<option value="0" langtag="word-no"></option>
|
||||
<option value="1" langtag="word-yes"></option>
|
||||
</select>
|
||||
<div class="form-group" id="local_proxy">
|
||||
<label class="control-label font-bold" langtag="word-proxytolocal"></label>
|
||||
<div class="col-sm-10">
|
||||
<select class="form-control" name="local_proxy">
|
||||
<option value="0" langtag="word-no"></option>
|
||||
<option value="1" langtag="word-yes"></option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
<div class="form-group" id="target">
|
||||
@@ -111,20 +106,6 @@
|
||||
<span class="help-block m-b-none" langtag="info-identificationkey"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="proto_version">
|
||||
<label class="control-label font-bold">Proxy Protocol Version:</label>
|
||||
<div class="col-sm-10">
|
||||
<select class="form-control" name="proto_version">
|
||||
<option value=""></option>
|
||||
<option value="V1">V1</option>
|
||||
<option value="V2">V2</option>
|
||||
</select>
|
||||
<span class="help-block m-b-none">开启此功能,请确保本地的服务能够支持 Proxy Protocol 协议。</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="hr-line-dashed"></div>
|
||||
<div class="form-group">
|
||||
<div class="col-sm-4 col-sm-offset-2">
|
||||
@@ -143,7 +124,7 @@
|
||||
<script>
|
||||
var arr = []
|
||||
arr["all"] = ["port", "target", "password", "local_path", "strip_pre", "local_proxy", "client_id", "server_ip"]
|
||||
arr["tcp"] = ["port", "target", "local_proxy", "client_id", "server_ip", "proto_version"]
|
||||
arr["tcp"] = ["port", "target", "local_proxy", "client_id", "server_ip"]
|
||||
arr["udp"] = ["port", "target", "local_proxy", "client_id", "server_ip"]
|
||||
arr["socks5"] = ["port", "client_id", "server_ip"]
|
||||
arr["httpProxy"] = ["port", "client_id", "server_ip"]
|
||||
@@ -170,27 +151,5 @@
|
||||
$("#use_client").on("change", function () {
|
||||
resetForm()
|
||||
})
|
||||
|
||||
getClientList()
|
||||
})
|
||||
|
||||
function getClientList() {
|
||||
$("select[name='client_id']").empty();
|
||||
$.ajax({
|
||||
type: "POST",
|
||||
url: "{{.web_base_url}}/client/list", // 服务器数据的加载地址
|
||||
data: {order: "asc", offset: 0, limit: 999},
|
||||
dataType: "json",
|
||||
success: function (data) {
|
||||
if (data && data.rows.length > 0) {
|
||||
for (var i = 0; i < data.rows.length; i++) {
|
||||
var option = "<option value=\"" + data.rows[i].Id + "\"";
|
||||
option += ">" + data.rows[i].Id + '-' + data.rows[i].Remark + "</option>"; //动态添加数据
|
||||
$("select[name='client_id']").append(option);
|
||||
$("select[name='client_id']").find("option[value='{{.client_id}}']").attr("selected", true);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label font-bold" langtag="word-scheme"></label>
|
||||
<div class="col-sm-10">
|
||||
<span class="help-block m-b-none font-bold" langtag="word-usecase"></span>:
|
||||
<span class="help-block m-b-none font-bold" langtag="word-usecase"></span>:
|
||||
<span id="usecase">
|
||||
<span id="casetcp" langtag="info-casetcp"></span>
|
||||
<span id="caseudp" langtag="info-caseudp"></span>
|
||||
@@ -25,9 +25,7 @@
|
||||
<option value="socks5" langtag="scheme-socks5"></option>
|
||||
<option value="secret" langtag="scheme-secret"></option>
|
||||
<option value="p2p" langtag="scheme-p2p"></option>
|
||||
{{/*
|
||||
<option value="file" langtag="scheme-file"></option>
|
||||
*/}}
|
||||
{{/*<option value="file" langtag="scheme-file"></option>*/}}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
@@ -35,52 +33,45 @@
|
||||
<div class="form-group" id="client_id">
|
||||
<label class="col-sm-2 control-label font-bold" langtag="word-clientid"></label>
|
||||
<div class="col-sm-10">
|
||||
<input value="{{.t.Client.Id}}" value="{{.client_id}}" class="form-control" type="text"
|
||||
name="client_id" placeholder="" langtag="word-clientid">
|
||||
<input value="{{.t.Client.Id}}" value="{{.client_id}}" class="form-control" type="text" name="client_id" placeholder="" langtag="word-clientid">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label font-bold" langtag="word-remark"></label>
|
||||
<div class="col-sm-10">
|
||||
<input value="{{.t.Remark}}" class="form-control" type="text" name="remark" placeholder=""
|
||||
langtag="info-unrestricted">
|
||||
<input value="{{.t.Remark}}" class="form-control" type="text" name="remark" placeholder="" langtag="info-unrestricted">
|
||||
</div>
|
||||
</div>
|
||||
{{if eq true .allow_multi_ip}}
|
||||
{{if eq true .allow_multi_ip}}
|
||||
<div class="form-group" id="server_ip">
|
||||
<label class="col-sm-2 control-label font-bold" langtag="word-serverip"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" type="text" value="{{.t.ServerIp}}" name="server_ip"
|
||||
placeholder="" langtag="info-suchasip">
|
||||
<input class="form-control" type="text" value="{{.t.ServerIp}}" name="server_ip" placeholder="" langtag="info-suchasip">
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{end}}
|
||||
<div class="form-group" id="port">
|
||||
<label class="col-sm-2 control-label font-bold" langtag="word-serverport"></label>
|
||||
<div class="col-sm-10">
|
||||
<input value="{{.t.Port}}" class="form-control" type="text" name="port" placeholder=""
|
||||
langtag="info-suchasport">
|
||||
<input value="{{.t.Port}}" class="form-control" type="text" name="port" placeholder="" langtag="info-suchasport">
|
||||
</div>
|
||||
</div>
|
||||
{{if eq true .allow_local_proxy}}
|
||||
{{if eq true .allow_local_proxy}}
|
||||
<div class="form-group" id="local_proxy">
|
||||
<label class="control-label col-sm-2 font-bold" langtag="word-proxytolocal"></label>
|
||||
<div class="col-sm-10">
|
||||
<select class="form-control" name="local_proxy">
|
||||
<option {{if eq false .t.Target.LocalProxy}}selected{{end}} value="0"
|
||||
langtag="word-no"></option>
|
||||
<option {{if eq true .t.Target.LocalProxy}}selected{{end}} value="1"
|
||||
langtag="word-yes"></option>
|
||||
<option {{if eq false .t.Target.LocalProxy}}selected{{end}} value="0" langtag="word-no"></option>
|
||||
<option {{if eq true .t.Target.LocalProxy}}selected{{end}} value="1" langtag="word-yes"></option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{end}}
|
||||
<div class="form-group" id="target">
|
||||
<label class="col-sm-2 control-label font-bold" langtag="word-target"></label>
|
||||
<div class="col-sm-10">
|
||||
<textarea class="form-control" name="target" rows="4" placeholder=""
|
||||
langtag="info-suchasiplist">{{.t.Target.TargetStr}}</textarea>
|
||||
<textarea class="form-control" name="target" rows="4" placeholder="" langtag="info-suchasiplist">{{.t.Target.TargetStr}}</textarea>
|
||||
<span class="help-block m-b-none" langtag="info-targettunnel"></span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -88,48 +79,30 @@
|
||||
<div class="form-group" id="local_path">
|
||||
<label class="col-sm-2 control-label font-bold" langtag="word-localpath"></label>
|
||||
<div class="col-sm-10">
|
||||
<input value="{{.t.LocalPath}}" class="form-control" type="text" name="local_path"
|
||||
placeholder="" langtag="info-suchaslocalpath">
|
||||
<input value="{{.t.LocalPath}}" class="form-control" type="text" name="local_path" placeholder="" langtag="info-suchaslocalpath">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="strip_pre">
|
||||
<label class="col-sm-2 control-label font-bold" langtag="word-stripprefix"></label>
|
||||
<div class="col-sm-10">
|
||||
<input value="{{.t.StripPre}}" class="form-control" type="text" name="strip_pre"
|
||||
placeholder="" langtag="info-suchasstripprefix">
|
||||
<input value="{{.t.StripPre}}" class="form-control" type="text" name="strip_pre" placeholder="" langtag="info-suchasstripprefix">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="password">
|
||||
<label class="col-sm-2 control-label font-bold" langtag="word-identificationkey"></label>
|
||||
<div class="col-sm-10">
|
||||
<input value="{{.t.Password}}" class="form-control" type="text" name="password"
|
||||
placeholder="" langtag="word-identificationkey">
|
||||
<input value="{{.t.Password}}" class="form-control" type="text" name="password" placeholder="" langtag="word-identificationkey">
|
||||
<span class="help-block m-b-none" langtag="info-identificationkey"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="proto_version">
|
||||
<label class="control-label font-bold">Proxy Protocol Version:</label>
|
||||
<div class="col-sm-10">
|
||||
<select class="form-control" name="proto_version" id="ProtoVersion">
|
||||
<option value=""></option>
|
||||
<option value="V1">V1</option>
|
||||
<option value="V2">V2</option>
|
||||
</select>
|
||||
<span class="help-block m-b-none">开启此功能,请确保本地的服务能够支持 Proxy Protocol 协议。</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="hr-line-dashed"></div>
|
||||
<div class="form-group">
|
||||
<div class="col-sm-4 col-sm-offset-2">
|
||||
<button class="btn btn-success" type="button"
|
||||
onclick="submitform('edit', '{{.web_base_url}}/index/edit', $('form').serializeArray())">
|
||||
<button class="btn btn-success" type="button" onclick="submitform('edit', '{{.web_base_url}}/index/edit', $('form').serializeArray())">
|
||||
<i class="fa fa-fw fa-lg fa-check-circle"></i> <span langtag="word-save"></span>
|
||||
|
||||
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -142,7 +115,7 @@
|
||||
<script>
|
||||
var arr = []
|
||||
arr["all"] = ["port", "target", "password", "local_path", "strip_pre", "local_proxy"]
|
||||
arr["tcp"] = ["client_id", "port", "target", "local_proxy", "proto_version"]
|
||||
arr["tcp"] = ["client_id", "port", "target", "local_proxy"]
|
||||
arr["udp"] = ["client_id", "port", "target", "local_proxy"]
|
||||
arr["socks5"] = ["client_id", "port"]
|
||||
arr["httpProxy"] = ["client_id", "port"]
|
||||
@@ -154,7 +127,7 @@
|
||||
$(".form-group[id]").css("display", "none");
|
||||
$("#usecase span").css("display", "none");
|
||||
o = $("#type").val();
|
||||
$('#case' + o).css("display", "inline")
|
||||
$('#case'+ o).css("display", "inline")
|
||||
for (var i = 0; i < arr[o].length; i++) {
|
||||
$("#" + arr[o][i]).css("display", "block")
|
||||
}
|
||||
@@ -162,7 +135,6 @@
|
||||
|
||||
$(function () {
|
||||
$("#type").val('{{.t.Mode}}');
|
||||
$("#ProtoVersion").val('{{.t.ProtoVersion}}');
|
||||
resetForm()
|
||||
$("#type").on("change", function () {
|
||||
resetForm()
|
||||
|
||||
@@ -7,9 +7,7 @@
|
||||
<div class="form-group">
|
||||
<label class="control-label font-bold" langtag="word-clientid"></label>
|
||||
<div class="col-sm-10">
|
||||
<select class="form-control" name="client_id" placeholder=""
|
||||
langtag="word-belongclient"></select>
|
||||
<!-- <input value="{{.client_id}}" class="form-control" type="text" name="client_id" placeholder="" langtag="word-clientid">-->
|
||||
<input value="{{.client_id}}" class="form-control" type="text" name="client_id" placeholder="" langtag="word-clientid">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
@@ -21,8 +19,7 @@
|
||||
<div class="form-group">
|
||||
<label class="control-label font-bold" langtag="word-host"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" type="text" name="host" placeholder=""
|
||||
langtag="info-suchashost">
|
||||
<input class="form-control" type="text" name="host" placeholder="" langtag="info-suchashost">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group" id="scheme">
|
||||
@@ -35,41 +32,27 @@
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="AutoHttps">
|
||||
<label class="control-label font-bold">自动HTTPS(301)</label>
|
||||
<div class="col-sm-10">
|
||||
<select class="form-control" name="AutoHttps">
|
||||
<option value="0" langtag="word-no"></option>
|
||||
<option value="1" langtag="word-yes"></option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{{if eq false .https_just_proxy}}
|
||||
<div class="form-group" id="cert_file">
|
||||
<label class="control-label font-bold" langtag="word-httpscert"></label>
|
||||
<div class="col-sm-10">
|
||||
<textarea rows="6" class="form-control" type="text" name="cert_file_path" id="pemText"
|
||||
placeholder="请将证书文件拖拽或将内容复制粘贴到此处,证书文件格式为:xxxx_example.com.pem。
|
||||
或者配置证书文件路径。"></textarea>
|
||||
<input class="form-control" type="text" name="cert_file_path" placeholder="" langtag="info-unrestricted">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group" id="key_file">
|
||||
<label class="control-label font-bold" langtag="word-httpskey"></label>
|
||||
<div class="col-sm-10">
|
||||
<textarea rows="6" class="form-control" type="text" name="key_file_path" id="pemKey"
|
||||
placeholder="请将私钥文件拖拽或复制粘贴到此处,证书秘钥格式为:xxxx_example.com.key。
|
||||
或者配置秘钥文件路径。"></textarea>
|
||||
<input class="form-control" type="text" name="key_file_path" placeholder="" langtag="info-unrestricted">
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
<div class="form-group">
|
||||
<label class="control-label font-bold" langtag="word-urlroute"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" type="text" name="location" placeholder=""
|
||||
langtag="info-unrestricted">
|
||||
<input class="form-control" type="text" name="location" placeholder="" langtag="info-unrestricted">
|
||||
</div>
|
||||
</div>
|
||||
{{if eq true .allow_local_proxy}}
|
||||
{{if eq true .allow_local_proxy}}
|
||||
<div class="form-group" id="local_proxy">
|
||||
<label class="control-label font-bold" langtag="word-proxytolocal"></label>
|
||||
<div class="col-sm-10">
|
||||
@@ -79,12 +62,11 @@
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{end}}
|
||||
<div class="form-group">
|
||||
<label class="control-label font-bold" langtag="word-target"></label>
|
||||
<div class="col-sm-10">
|
||||
<textarea class="form-control" rows="4" type="text" name="target" placeholder=""
|
||||
langtag="info-suchasiplist"></textarea>
|
||||
<textarea class="form-control" rows="4" type="text" name="target" placeholder="" langtag="info-suchasiplist"></textarea>
|
||||
<span class="help-block m-b-none" langtag="info-targethost"></span>
|
||||
|
||||
</div>
|
||||
@@ -92,8 +74,7 @@
|
||||
<div class="form-group" id="header">
|
||||
<label class="control-label font-bold" langtag="word-requestheader"></label>
|
||||
<div class="col-sm-10">
|
||||
<textarea class="form-control" rows="4" type="text" name="header"
|
||||
placeholder="Cache-Control: no-cache"></textarea>
|
||||
<textarea class="form-control" rows="4" type="text" name="header" placeholder="Cache-Control: no-cache"></textarea>
|
||||
<span class="help-block m-b-none" langtag="info-header"></span>
|
||||
</div>
|
||||
|
||||
@@ -101,15 +82,13 @@
|
||||
<div class="form-group" id="hostchange">
|
||||
<label class="control-label font-bold" langtag="word-requesthost"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" value="" type="text" name="hostchange" placeholder=""
|
||||
langtag="word-requesthost">
|
||||
<input class="form-control" value="" type="text" name="hostchange" placeholder="" langtag="word-requesthost">
|
||||
</div>
|
||||
</div>
|
||||
<div class="hr-line-dashed"></div>
|
||||
<div class="form-group">
|
||||
<div class="col-sm-4 col-sm-offset-2">
|
||||
<button class="btn btn-success" type="button"
|
||||
onclick="submitform('add', '{{.web_base_url}}/index/addhost', $('form').serializeArray())">
|
||||
<button class="btn btn-success" type="button" onclick="submitform('add', '{{.web_base_url}}/index/addhost', $('form').serializeArray())">
|
||||
<i class="fa fa-fw fa-lg fa-check-circle"></i> <span langtag="word-add"></span>
|
||||
</button>
|
||||
</div>
|
||||
@@ -121,75 +100,14 @@
|
||||
</div>
|
||||
<script>
|
||||
$(function () {
|
||||
const pemText = document.getElementById("pemText");
|
||||
const pemKey = document.getElementById("pemKey");
|
||||
|
||||
// 阻止浏览器默认打开文件的行为
|
||||
document.addEventListener("dragover", function (event) {
|
||||
event.preventDefault();
|
||||
});
|
||||
|
||||
pemText.addEventListener("drop", function (event) {
|
||||
event.preventDefault();
|
||||
const file = event.dataTransfer.files[0];
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = function (e) {
|
||||
pemText.value = e.target.result;
|
||||
console.log("上传pem")
|
||||
$('#edit_form').data('bootstrapValidator').updateStatus('pemText', 'NOT_VALIDATED');
|
||||
$('#edit_form').data('bootstrapValidator').validateField('pemText');
|
||||
}
|
||||
|
||||
reader.readAsText(file);
|
||||
});
|
||||
|
||||
pemKey.addEventListener("drop", function (event) {
|
||||
event.preventDefault();
|
||||
const file = event.dataTransfer.files[0];
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = function (e) {
|
||||
pemKey.value = e.target.result;
|
||||
$('#edit_form').data('bootstrapValidator').updateStatus('pemKey', 'NOT_VALIDATED');
|
||||
$('#edit_form').data('bootstrapValidator').validateField('pemKey');
|
||||
}
|
||||
|
||||
reader.readAsText(file);
|
||||
});
|
||||
|
||||
|
||||
$("#scheme_select").on("change", function () {
|
||||
if ($("#scheme_select").val() == "all" || $("#scheme_select").val() == "https") {
|
||||
$("#cert_file").css("display", "block")
|
||||
$("#key_file").css("display", "block")
|
||||
$("#AutoHttps").css("display", "block")
|
||||
} else {
|
||||
$("#cert_file").css("display", "none")
|
||||
$("#key_file").css("display", "none")
|
||||
$("#AutoHttps").css("display", "none")
|
||||
}
|
||||
})
|
||||
|
||||
getClientList();
|
||||
})
|
||||
|
||||
function getClientList() {
|
||||
$("select[name='client_id']").empty();
|
||||
$.ajax({
|
||||
type: "POST",
|
||||
url: "{{.web_base_url}}/client/list", // 服务器数据的加载地址
|
||||
data: {order: "asc", offset: 0, limit: 999},
|
||||
dataType: "json",
|
||||
success: function (data) {
|
||||
if (data && data.rows.length > 0) {
|
||||
for (var i = 0; i < data.rows.length; i++) {
|
||||
var option = "<option value=\"" + data.rows[i].Id + "\"";
|
||||
option += ">" + data.rows[i].Id + '-' + data.rows[i].Remark + "</option>"; //动态添加数据
|
||||
$("select[name='client_id']").append(option);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
</script>
|
||||
@@ -34,37 +34,24 @@
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="AutoHttps">
|
||||
<label class="control-label font-bold">自动HTTPS(301)</label>
|
||||
<div class="col-sm-10">
|
||||
<select class="form-control" name="AutoHttps">
|
||||
<option {{if eq false .h.AutoHttps}}selected{{end}} value="0" langtag="word-no"></option>
|
||||
<option {{if eq true .h.AutoHttps}}selected{{end}} value="1" langtag="word-yes"></option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{{if eq false .https_just_proxy}}
|
||||
<div class="form-group" id="cert_file">
|
||||
<label class="control-label font-bold" langtag="word-httpscert"></label>
|
||||
<div class="col-sm-10">
|
||||
<textarea rows="6" class="form-control" type="text" name="cert_file_path" id="pemText"
|
||||
placeholder="请将证书文件拖拽或将内容复制粘贴到此处,证书文件格式为:xxxx_example.com.pem。
|
||||
或者配置证书文件路径。">{{.h.CertFilePath}}</textarea>
|
||||
<input value="{{.h.CertFilePath}}" class="form-control" type="text" name="cert_file_path" placeholder="" langtag="info-unrestricted">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group" id="key_file">
|
||||
<label class="control-label font-bold" langtag="word-httpskey"></label>
|
||||
<div class="col-sm-10">
|
||||
<textarea rows="6" class="form-control" type="text" name="key_file_path" id="pemKey"
|
||||
placeholder="请将私钥文件拖拽或复制粘贴到此处,证书秘钥格式为:xxxx_example.com.key。
|
||||
或者配置秘钥文件路径。">{{.h.KeyFilePath}}</textarea>
|
||||
<input value="{{.h.KeyFilePath}}" class="form-control" type="text" name="key_file_path" placeholder="" langtag="info-unrestricted">
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
<div class="form-group">
|
||||
<label class="control-label font-bold" langtag="word-urlroute"></label>
|
||||
<div class="col-sm-10">
|
||||
<input value="{{.h.Location}}" class="form-control" type="text" name="location" placeholder="" langtag="info-unrestricted">
|
||||
<input value="{{.h.Location}}" class="form-control" type="text" name="location" placeholder="" langtag="info-unrestricted">
|
||||
</div>
|
||||
</div>
|
||||
{{if eq true .allow_local_proxy}}
|
||||
@@ -116,66 +103,13 @@
|
||||
|
||||
<script>
|
||||
$(function () {
|
||||
if ($("#scheme_select").val() == "all" || $("#scheme_select").val() == "https") {
|
||||
$("#cert_file").css("display", "block")
|
||||
$("#key_file").css("display", "block")
|
||||
$("#AutoHttps").css("display", "block")
|
||||
} else {
|
||||
$("#cert_file").css("display", "none")
|
||||
$("#key_file").css("display", "none")
|
||||
$("#AutoHttps").css("display", "none")
|
||||
}
|
||||
|
||||
|
||||
const pemText = document.getElementById("pemText");
|
||||
const pemKey = document.getElementById("pemKey");
|
||||
|
||||
// 阻止浏览器默认打开文件的行为
|
||||
document.addEventListener("dragover", function(event) {
|
||||
event.preventDefault();
|
||||
});
|
||||
|
||||
pemText.addEventListener("drop", function(event) {
|
||||
event.preventDefault();
|
||||
const file = event.dataTransfer.files[0];
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = function(e) {
|
||||
pemText.value = e.target.result;
|
||||
console.log("上传pem")
|
||||
$('#edit_form').data('bootstrapValidator').updateStatus('pemText', 'NOT_VALIDATED');
|
||||
$('#edit_form').data('bootstrapValidator').validateField('pemText');
|
||||
}
|
||||
|
||||
reader.readAsText(file);
|
||||
});
|
||||
|
||||
pemKey.addEventListener("drop", function(event) {
|
||||
event.preventDefault();
|
||||
const file = event.dataTransfer.files[0];
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = function(e) {
|
||||
pemKey.value = e.target.result;
|
||||
$('#edit_form').data('bootstrapValidator').updateStatus('pemKey', 'NOT_VALIDATED');
|
||||
$('#edit_form').data('bootstrapValidator').validateField('pemKey');
|
||||
}
|
||||
|
||||
reader.readAsText(file);
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
$("#scheme_select").on("change", function () {
|
||||
if ($("#scheme_select").val() == "all" || $("#scheme_select").val() == "https") {
|
||||
$("#cert_file").css("display", "block")
|
||||
$("#key_file").css("display", "block")
|
||||
$("#AutoHttps").css("display", "block")
|
||||
} else {
|
||||
$("#cert_file").css("display", "none")
|
||||
$("#key_file").css("display", "none")
|
||||
$("#AutoHttps").css("display", "none")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -88,7 +88,7 @@
|
||||
halign: 'center',
|
||||
visible: true,//false表示不显示
|
||||
formatter: function (value, row, index) {
|
||||
return row.Client.Id + '-' + row.Client.Remark
|
||||
return row.Client.Id
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -97,20 +97,11 @@
|
||||
halign: 'center',
|
||||
visible: true//false表示不显示
|
||||
},
|
||||
{
|
||||
field: 'Client.VerifyKey',//域值
|
||||
title: '<span langtag="word-verifykey"></span>',//标题
|
||||
halign: 'center',
|
||||
visible: true//false表示不显示
|
||||
},
|
||||
{
|
||||
field: 'Host',//域值
|
||||
title: '<span langtag="word-host"></span>',//标题
|
||||
halign: 'center',
|
||||
visible: true,//false表示不显示
|
||||
formatter: function (value, row, index) {
|
||||
return "<a href='http://" + row.Host + "' target='_blank'>" + row.Host + "</a>"
|
||||
}
|
||||
visible: true//false表示不显示
|
||||
},
|
||||
{
|
||||
field: 'Scheme',//域值
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<h5 langtag="word-connectionport"></h5>
|
||||
</div>
|
||||
<div class="ibox-content">
|
||||
<h1 class="no-margins">{{.p1}}</h1>
|
||||
<h1 class="no-margins">{{.p}}</h1>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -45,7 +45,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="row">
|
||||
<div class="col-lg-6">
|
||||
<div class="ibox float-e-margins">
|
||||
|
||||
@@ -49,9 +49,7 @@
|
||||
"limit": params.limit,
|
||||
"type":{{.type}},
|
||||
"client_id":{{.client_id}},
|
||||
"search": params.search,
|
||||
"sort": params.sort,
|
||||
"order": params.order
|
||||
"search": params.search
|
||||
}
|
||||
},
|
||||
search: true,
|
||||
@@ -76,7 +74,6 @@
|
||||
+ '<b langtag="word-compress"></b>: ' + row.Client.Cnf.Compress + ' '
|
||||
+ '<b langtag="word-basicusername"></b>: ' + row.Client.Cnf.U + ' '
|
||||
+ '<b langtag="word-basicpassword"></b>: ' + row.Client.Cnf.P + ' '
|
||||
+ '<b langtag="word-protoversion"></b>: ' + row.ProtoVersion + ' '
|
||||
if (row.Mode == "p2p") {
|
||||
return tmp + "<br/><br>"
|
||||
+ '<b langtag="word-commandaccessp2p"></b>: ' + "<code>./npc{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.Client.VerifyKey
|
||||
@@ -99,17 +96,15 @@
|
||||
field: 'Id',//域值
|
||||
title: '<span langtag="word-id"></span>',//标题
|
||||
halign: 'center',
|
||||
visible: true,//false表示不显示
|
||||
sortable: true,//启用排序
|
||||
visible: true//false表示不显示
|
||||
},
|
||||
{
|
||||
field: 'ClientId',//域值
|
||||
field: 'Id',//域值
|
||||
title: '<span langtag="word-clientid"></span>',//标题
|
||||
halign: 'center',
|
||||
visible: true,//false表示不显示
|
||||
sortable: true, //启用排序
|
||||
formatter: function (value, row, index) {
|
||||
return row.Client.Id + '-' + row.Client.Remark
|
||||
return row.Client.Id
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -118,13 +113,6 @@
|
||||
halign: 'center',
|
||||
visible: true//false表示不显示
|
||||
},
|
||||
{
|
||||
field: 'Client.VerifyKey',//域值
|
||||
title: '<span langtag="word-verifykey"></span>',//标题
|
||||
halign: 'center',
|
||||
sortable: true, //启用排序
|
||||
visible: true//false表示不显示
|
||||
},
|
||||
{
|
||||
field: 'Mode',//域值
|
||||
title: '<span langtag="word-scheme"></span>',//标题
|
||||
@@ -138,26 +126,13 @@
|
||||
field: 'Port',//域值
|
||||
title: '<span langtag="word-port"></span>',//标题
|
||||
halign: 'center',
|
||||
sortable: true, //启用排序
|
||||
visible: true//false表示不显示
|
||||
},
|
||||
{
|
||||
field: 'address',//域值
|
||||
title: '<span langtag="word-accessaddress"></span>',//标题
|
||||
halign: 'center',
|
||||
sortable: false, //启用排序
|
||||
visible: true,//false表示不显示
|
||||
formatter: function (value, row, index) {
|
||||
var address = {{.ip}} + ":" + row.Port
|
||||
return "<a href='http://" + address + "' target='_blank'>" + address + "</a>"
|
||||
}
|
||||
},
|
||||
{
|
||||
field: 'Target',//域值
|
||||
title: '<span langtag="word-target"></span>',//标题
|
||||
halign: 'center',
|
||||
visible: true,//false表示不显示
|
||||
sortable: true, //启用排序
|
||||
formatter: function (value, row, index) {
|
||||
return row.Target.TargetStr
|
||||
}
|
||||
@@ -215,7 +190,6 @@
|
||||
title: '<span langtag="word-option"></span>',//内容
|
||||
align: 'center',
|
||||
halign: 'center',
|
||||
width: '200px',
|
||||
visible: true,//false表示不显示
|
||||
formatter: function (value, row, index) {
|
||||
btn_group = '<div class="btn-group">'
|
||||
@@ -228,12 +202,8 @@
|
||||
}
|
||||
btn_group += "<a onclick=\"submitform('delete', '{{.web_base_url}}/index/del', {'id':" + row.Id
|
||||
btn_group += '})" class="btn btn-outline btn-danger"><i class="fa fa-trash"></i></a>'
|
||||
|
||||
btn_group += '<a href="{{.web_base_url}}/index/edit?id=' + row.Id
|
||||
btn_group += '" class="btn btn-outline btn-success"><i class="fa fa-edit"></i></a>'
|
||||
|
||||
btn_group += "<a onclick=\"submitform('copy', '{{.web_base_url}}/index/copy', {'id':" + row.Id
|
||||
btn_group += '})" class="btn btn-outline btn-primary"><i class="fa fa-copy"></i></a></div>'
|
||||
btn_group += '" class="btn btn-outline btn-success"><i class="fa fa-edit"></i></a></div>'
|
||||
return btn_group
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
<script src="{{.web_base_url}}/static/js/jquery-3.4.1.min.js"></script>
|
||||
<script src="{{.web_base_url}}/static/js/bootstrap.min.js"></script>
|
||||
<!-- Latest compiled and minified Locales -->
|
||||
<script src="{{.web_base_url}}/static/js/language.js?v=202512054" type="text/javascript"></script>
|
||||
<script src="{{.web_base_url}}/static/js/language.js" type="text/javascript"></script>
|
||||
|
||||
</head>
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
<script src="{{.web_base_url}}/static/js/jquery-3.4.1.min.js"></script>
|
||||
<script src="{{.web_base_url}}/static/js/bootstrap.min.js"></script>
|
||||
<!-- Latest compiled and minified Locales -->
|
||||
<script src="{{.web_base_url}}/static/js/language.js?v=202512054" type="text/javascript"></script>
|
||||
<script src="{{.web_base_url}}/static/js/language.js" type="text/javascript"></script>
|
||||
|
||||
</head>
|
||||
|
||||
|
||||