Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ef519331e2 | ||
|
|
19fee9b51b | ||
|
|
16a7f6a4c4 | ||
|
|
1aca99b2d7 | ||
|
|
2733d99cf7 | ||
|
|
6750103337 | ||
|
|
eaff3b8c39 | ||
|
|
c9a9807dd5 | ||
|
|
2b04bf8b5a | ||
|
|
62c84206a4 | ||
|
|
2650174eed | ||
|
|
d199b26ce2 | ||
|
|
0c25ec5978 | ||
|
|
055ff30e39 | ||
|
|
0f39cdbe7b | ||
|
|
4710432572 | ||
|
|
e0c8c73b91 | ||
|
|
b39f0c30ef | ||
|
|
c1753a6d19 | ||
|
|
8f384eaac4 | ||
|
|
a51d6bc50a | ||
|
|
43144804c7 | ||
|
|
dfe4748e97 | ||
|
|
30af159034 | ||
|
|
8819907be5 | ||
|
|
1a29ab0046 | ||
|
|
0ffec7df7f | ||
|
|
876b2d2588 | ||
|
|
af4be7f130 |
@@ -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 }}
|
||||
@@ -2,9 +2,6 @@ name: Release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
release:
|
||||
types: [published]
|
||||
branches: [ master ]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -17,17 +14,15 @@ env:
|
||||
|
||||
jobs:
|
||||
|
||||
# ==================== 跨平台服务端/客户端打包 ====================
|
||||
build_assets:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
- name: Set up Go 1.x
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.22
|
||||
id: go
|
||||
- name: Check out code into the Go module directory
|
||||
go-version: "1.22"
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v2
|
||||
- name: Get dependencies
|
||||
run: |
|
||||
@@ -84,10 +79,11 @@ jobs:
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# ==================== Android APK ====================
|
||||
build_android:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out code into the Go module directory
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v4
|
||||
- name: Build
|
||||
run: |
|
||||
@@ -104,6 +100,52 @@ jobs:
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# ==================== Docker 镜像 ====================
|
||||
build_docker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out code
|
||||
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 }}
|
||||
|
||||
# ==================== Windows GUI ====================
|
||||
build_windows_gui:
|
||||
runs-on: windows-latest
|
||||
strategy:
|
||||
@@ -121,40 +163,33 @@ jobs:
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
cache: yarn
|
||||
cache-dependency-path: ${{ env.FRONTEND_DIR }}/yarn.lock
|
||||
|
||||
- name: Enable Yarn (corepack)
|
||||
run: corepack enable
|
||||
|
||||
- name: Install frontend dependencies
|
||||
run: yarn install --frozen-lockfile
|
||||
working-directory: ${{ env.FRONTEND_DIR }}
|
||||
|
||||
- name: Build frontend
|
||||
run: yarn build
|
||||
working-directory: ${{ env.FRONTEND_DIR }}
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: ${{ env.GUI_DIR }}/go.mod
|
||||
check-latest: true
|
||||
|
||||
- name: Install Wails CLI
|
||||
run: go install github.com/wailsapp/wails/v2/cmd/wails@${{ env.WAILS_VERSION }}
|
||||
working-directory: ${{ env.GUI_DIR }}
|
||||
|
||||
- name: Build and package (Windows)
|
||||
shell: pwsh
|
||||
working-directory: ${{ env.GUI_DIR }}
|
||||
run: |
|
||||
$wails = Join-Path (go env GOPATH) "bin\\wails.exe"
|
||||
$wails = Join-Path (go env GOPATH) "bin\wails.exe"
|
||||
$tagArgs = @()
|
||||
if ($env:WAILS_TAGS) { $tagArgs += @("-tags", $env:WAILS_TAGS) }
|
||||
& $wails build -m -s -trimpath -skipbindings @tagArgs -platform ${{ matrix.platform }} -o "$env:APP_NAME.exe"
|
||||
@@ -170,13 +205,13 @@ jobs:
|
||||
exit 1
|
||||
}
|
||||
Compress-Archive -Path $exe.Name -DestinationPath $zipName -Force
|
||||
|
||||
- name: Upload Windows artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-builds-${{ matrix.arch }}
|
||||
path: ${{ env.GUI_DIR }}/build/bin/${{ env.APP_NAME }}-${{ matrix.os_name }}-${{ matrix.arch }}.zip
|
||||
|
||||
# ==================== macOS GUI ====================
|
||||
build_macos_gui:
|
||||
runs-on: macos-latest
|
||||
strategy:
|
||||
@@ -191,35 +226,28 @@ jobs:
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
cache: yarn
|
||||
cache-dependency-path: ${{ env.FRONTEND_DIR }}/yarn.lock
|
||||
|
||||
- name: Enable Yarn (corepack)
|
||||
run: corepack enable
|
||||
|
||||
- name: Install frontend dependencies
|
||||
run: yarn install --frozen-lockfile
|
||||
working-directory: ${{ env.FRONTEND_DIR }}
|
||||
|
||||
- name: Build frontend
|
||||
run: yarn build
|
||||
working-directory: ${{ env.FRONTEND_DIR }}
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: ${{ env.GUI_DIR }}/go.mod
|
||||
check-latest: true
|
||||
|
||||
- name: Install Wails CLI
|
||||
run: go install github.com/wailsapp/wails/v2/cmd/wails@${{ env.WAILS_VERSION }}
|
||||
working-directory: ${{ env.GUI_DIR }}
|
||||
|
||||
- name: Build and package (macOS)
|
||||
shell: bash
|
||||
working-directory: ${{ env.GUI_DIR }}
|
||||
@@ -238,13 +266,13 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
zip -q -r "$APP_NAME-${{ matrix.os_name }}-${{ matrix.arch }}.zip" "$app"
|
||||
|
||||
- name: Upload macOS artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: macos-builds-${{ matrix.arch }}
|
||||
path: ${{ env.GUI_DIR }}/build/bin/${{ env.APP_NAME }}-${{ matrix.os_name }}-${{ matrix.arch }}.zip
|
||||
|
||||
# ==================== Linux GUI ====================
|
||||
build_linux_gui:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
@@ -258,40 +286,32 @@ jobs:
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install Linux dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
cache: yarn
|
||||
cache-dependency-path: ${{ env.FRONTEND_DIR }}/yarn.lock
|
||||
|
||||
- name: Enable Yarn (corepack)
|
||||
run: corepack enable
|
||||
|
||||
- name: Install frontend dependencies
|
||||
run: yarn install --frozen-lockfile
|
||||
working-directory: ${{ env.FRONTEND_DIR }}
|
||||
|
||||
- name: Build frontend
|
||||
run: yarn build
|
||||
working-directory: ${{ env.FRONTEND_DIR }}
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: ${{ env.GUI_DIR }}/go.mod
|
||||
check-latest: true
|
||||
|
||||
- name: Install Wails CLI
|
||||
run: go install github.com/wailsapp/wails/v2/cmd/wails@${{ env.WAILS_VERSION }}
|
||||
working-directory: ${{ env.GUI_DIR }}
|
||||
|
||||
- name: Build and package (Linux)
|
||||
shell: bash
|
||||
working-directory: ${{ env.GUI_DIR }}
|
||||
@@ -310,13 +330,13 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
zip -q "$APP_NAME-${{ matrix.os_name }}-${{ matrix.arch }}.zip" "$bin"
|
||||
|
||||
- name: Upload Linux artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: linux-builds-${{ matrix.arch }}
|
||||
path: ${{ env.GUI_DIR }}/build/bin/${{ env.APP_NAME }}-${{ matrix.os_name }}-${{ matrix.arch }}.zip
|
||||
|
||||
# ==================== GUI Release 上传 ====================
|
||||
upload_gui_release:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [build_windows_gui, build_macos_gui, build_linux_gui]
|
||||
@@ -326,7 +346,6 @@ jobs:
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: release-assets
|
||||
|
||||
- name: Upload release assets
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
@@ -7,6 +7,5 @@ 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"]
|
||||
|
||||
@@ -1,30 +1,88 @@
|
||||
# NPS
|
||||
|
||||
[新特性文档](https://dqg9t9eulqq.feishu.cn/wiki/FmVVwDcEGiTZxekYJl5ccuFanlg?from=from_copylink)
|
||||
|
||||
[新特性文档](https://dqg9t9eulqq.feishu.cn/wiki/FmVVwDcEGiTZxekYJl5ccuFanlg?from=from_copylink)
|
||||
[原版文档](https://ehang.io/nps/documents)
|
||||
# 说明
|
||||
由于nps已经停更多年,存留了不少bug和未完善的功能。
|
||||
|
||||
此版本基于 nps 0.26.10的基础上二次开发而来。
|
||||
### 交流
|
||||
聊天灌水QQ群:619833483,热心群主可提供免费远程协助👍👍👍
|
||||
|
||||
***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/register?utm_from=MQ==),免费4M带宽,2条隧道;6.8元12M带宽,10条隧道;13.8元24M带宽,20条隧道。
|
||||
|
||||
雨云,500M带宽服务器;云服务器15元起,[专属连接,首月5折](https://www.rainyun.com/MjY0MzY1_)。
|
||||
|
||||
# 提示
|
||||
强烈推荐使用无配置文件模式启动客户端(删除掉npc.exe 目录下的`conf`文件夹即可),所有数据应该在服务端保存和配置,而客户端只做连接转发。客户端配置文件对小白极不友好,配置繁琐,容易出错。
|
||||
0.26.21 版本后的客户端,无需再通过命令行方式启动、安装、卸载客户端,直接双击运行,按照提示输入指令即可完成,非常方便。
|
||||
|
||||
# 广告
|
||||
[NPS云穿透](https://natnps.com/register?utm_from=MQ==),免费3M带宽,2条隧道;6.8元12M带宽,10条隧道;13.8元24M带宽,20条隧道。
|
||||
雨云,500M带宽服务器;云服务器15元起,[专属连接,首月5折](https://www.rainyun.com/MjY0MzY1_)。
|
||||
|
||||
# 快速上手
|
||||
***服务端启动/安装:***`./npc(.exe) -server`
|
||||
|
||||

|
||||
|
||||
***客户端启动/安装:*** `./npc(.exe)`
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
# 更新日志
|
||||
- 2026-06-04 v0.26.34
|
||||
- 新增:
|
||||
- `nps -server` 管理脚本欢迎语显示当前版本号,更新版本时比对版本,已是最新则直接退出,避免无谓覆盖 [#328](https://github.com/yisier/nps/issues/328)
|
||||
- `npc` 管理脚本欢迎语显示当前版本号,新增 `[5] 更新客户端` 选项,更新并替换 npc 二进制
|
||||
- 客户端新增到期时间字段,创建/修改客户端时可选填写,到期后自动暂停客户端 [#322](https://github.com/yisier/nps/issues/322)
|
||||
- 修复:
|
||||
- Dashboard IO 速率采集阻塞请求 500ms,改为后台采集缓存,消除 Sleep 等待
|
||||
- ServerStatus 切片并发读写不安全,添加 RWMutex 保护
|
||||
- flowSession goroutine 泄漏,改为仅在 StartNewServer 启动一次
|
||||
- GetTunnel 双重遍历 sync.Map 性能问题,合并为单次 Range
|
||||
- Bridge Client 字段并发读写不安全,添加 Mutex 保护
|
||||
- TLS ClientHello recordLen 无上限,添加 16KB 限制防止内存耗尽
|
||||
- SOCKS5 地址解析未检查 Read 返回值,改用 io.ReadFull
|
||||
- 文件存储 panic 改为错误日志,defer 清理临时文件防止泄漏
|
||||
- GenerateServerPort 可能无限循环,限制 1000 次重试
|
||||
- P2P UDP 无超时永久阻塞,添加 30s ReadDeadline
|
||||
- P2P goroutine 退出控制改用 context,修复潜在泄漏
|
||||
- 客户端 UDP ReadFrom 错误后未退出,修复无效数据继续处理
|
||||
- [#324](https://github.com/yisier/nps/issues/324) 隧道/域名解析/UDP 流量始终为 0
|
||||
- muxPackager buffer pool 泄漏:UnPack() 错误路径未归还 windowBuff 导致内存持续增长
|
||||
- bridge 客户端重连时旧 WORK_CHAN/WORK_FILE mux 未关闭,底层连接和 goroutine 永不释放
|
||||
- pmux 连接超时泄漏:process() channel 发送超时后连接未关闭,且 ACCEPT_TIME_OUT 单位错误(10ns 应为 10s)
|
||||
- pmux 关闭流程 panic:加 done channel + WaitGroup 保证 Close() 等所有 process() 退出后再 close conn channel;process() 入口设 ReadDeadline 防止阻塞读导致 wg.Wait() 死锁;PortListener 加 done channel 唤醒 Accept()
|
||||
- 优化:ioutil.WriteFile → os.WriteFile、rand.Seed → rand.New 本地随机源
|
||||
|
||||
- 2026-05-23 v0.26.33
|
||||
- 新增:
|
||||
- 配置文件自动生成:启动时若 conf 目录或 nps.conf 不存在,自动创建并写入默认配置,方便 Docker 部署
|
||||
- 首次启动默认 web_username/admin、web_password、auth_key、auth_crypt_key 均改为随机生成,并打印到终端,提升安全性
|
||||
- Web 静态文件打包进可执行文件 + 静态文件 URL 加入版本号参数,升级后自动刷新缓存,部署无需单独拷贝 web 目录
|
||||
- 精简发布包:去除打包时冗余的 conf/nps.conf、web 目录
|
||||
- 清理失效配置项:移除 appname、runmode、https_default_cert_file、https_default_key_file、https_just_proxy
|
||||
- 修复:
|
||||
- [#184](https://github.com/yisier/nps/issues/184) 限速导致隧道中断:UpdateClient 在 RateLimit=0 时创建零速率令牌桶导致永久阻塞
|
||||
- [#159](https://github.com/yisier/nps/issues/159) 关闭隧道端口仍可用:StopServer 错误时提前返回未更新状态 + 重复 OpenTask case 导致隧道被自动重启
|
||||
- [#170](https://github.com/yisier/nps/issues/170) TCP 负载均衡只有一个后端可达:GetRandomTarget 未处理 \r 换行符和尾部空行
|
||||
- [#319](https://github.com/yisier/nps/issues/319) 客户端列表不显示实时网速:NowRate 计算逻辑错误,改为统计每秒实际消耗字节数
|
||||
- [#306](https://github.com/yisier/nps/issues/306) [#316](https://github.com/yisier/nps/issues/316) TCP Basic 认证与域名解析冲突:移除 TCP 隧道 Basic 认证探测,域名解析继续使用客户端 Basic 认证
|
||||
|
||||
- 2026-03-27 v0.26.32
|
||||
- 修复:
|
||||
- 客户端注册参数未正确处理[快捷启动命令]和[TLS快捷启动命令] [#303](https://github.com/yisier/nps/issues/303)
|
||||
- 修复https反向代理bug,感谢[okawao](https://github.com/okawao) 的 PR
|
||||
|
||||
|
||||
- 2026-03-23 v0.26.31
|
||||
- 新增:
|
||||
- 域名解析记录开关功能 [#314](https://github.com/yisier/nps/issues/314)
|
||||
- TCP隧道增加Basic认证 [306](https://github.com/yisier/nps/issues/306)
|
||||
- 修复:
|
||||
- 新增隧道出现secret mode keys must be unique [301](https://github.com/yisier/nps/issues/301)
|
||||
|
||||
|
||||
- 2026-03-12 v0.26.30
|
||||
修复:
|
||||
|
||||
+59
-18
@@ -12,6 +12,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"ehang.io/nps/lib/common"
|
||||
@@ -28,11 +29,12 @@ import (
|
||||
var ServerTlsEnable bool = false
|
||||
|
||||
type Client struct {
|
||||
mu sync.Mutex // 保护 signal/tunnel/Version 等字段的并发读写
|
||||
tunnel *nps_mux.Mux
|
||||
signal *conn.Conn
|
||||
file *nps_mux.Mux
|
||||
Version string
|
||||
retryTime int // it will be add 1 when ping not ok until to 3 will close the client
|
||||
retryTime atomic.Int32 // it will be add 1 when ping not ok until to 3 will close the client
|
||||
}
|
||||
|
||||
func NewClient(t, f *nps_mux.Mux, s *conn.Conn, vs string) *Client {
|
||||
@@ -237,8 +239,13 @@ func (s *Bridge) cliProcess(c *conn.Conn) {
|
||||
|
||||
func (s *Bridge) DelClient(id int) {
|
||||
if v, ok := s.Client.Load(id); ok {
|
||||
if v.(*Client).signal != nil {
|
||||
v.(*Client).signal.Close()
|
||||
cl := v.(*Client)
|
||||
cl.mu.Lock()
|
||||
signalToClose := cl.signal
|
||||
cl.signal = nil
|
||||
cl.mu.Unlock()
|
||||
if signalToClose != nil {
|
||||
signalToClose.Close()
|
||||
}
|
||||
s.Client.Delete(id)
|
||||
if file.GetDb().IsPubClient(id) {
|
||||
@@ -267,18 +274,30 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int, vs string) {
|
||||
}
|
||||
//the vKey connect by another ,close the client of before
|
||||
if v, ok := s.Client.LoadOrStore(id, NewClient(nil, nil, c, vs)); ok {
|
||||
if v.(*Client).signal != nil {
|
||||
v.(*Client).signal.WriteClose()
|
||||
cl := v.(*Client)
|
||||
cl.mu.Lock()
|
||||
oldSignal := cl.signal
|
||||
cl.signal = c
|
||||
cl.Version = vs
|
||||
cl.mu.Unlock()
|
||||
cl.retryTime.Store(0)
|
||||
if oldSignal != nil {
|
||||
oldSignal.WriteClose()
|
||||
}
|
||||
v.(*Client).signal = c
|
||||
v.(*Client).Version = vs
|
||||
}
|
||||
go s.GetHealthFromClient(id, c)
|
||||
logs.Info("clientId %d connection succeeded, address:%s ", id, c.Conn.RemoteAddr())
|
||||
case common.WORK_CHAN:
|
||||
muxConn := nps_mux.NewMux(c.Conn, s.tunnelType, s.disconnectTime)
|
||||
if v, ok := s.Client.LoadOrStore(id, NewClient(muxConn, nil, nil, vs)); ok {
|
||||
v.(*Client).tunnel = muxConn
|
||||
cl := v.(*Client)
|
||||
cl.mu.Lock()
|
||||
oldTunnel := cl.tunnel
|
||||
cl.tunnel = muxConn
|
||||
cl.mu.Unlock()
|
||||
if oldTunnel != nil {
|
||||
oldTunnel.Close()
|
||||
}
|
||||
}
|
||||
case common.WORK_CONFIG:
|
||||
client, err := file.GetDb().GetClient(id)
|
||||
@@ -299,7 +318,14 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int, vs string) {
|
||||
case common.WORK_FILE:
|
||||
muxConn := nps_mux.NewMux(c.Conn, s.tunnelType, s.disconnectTime)
|
||||
if v, ok := s.Client.LoadOrStore(id, NewClient(nil, muxConn, nil, vs)); ok {
|
||||
v.(*Client).file = muxConn
|
||||
cl := v.(*Client)
|
||||
cl.mu.Lock()
|
||||
oldFile := cl.file
|
||||
cl.file = muxConn
|
||||
cl.mu.Unlock()
|
||||
if oldFile != nil {
|
||||
oldFile.Close()
|
||||
}
|
||||
}
|
||||
case common.WORK_P2P:
|
||||
//read md5 secret
|
||||
@@ -311,15 +337,22 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int, vs string) {
|
||||
if v, ok := s.Client.Load(t.Client.Id); !ok {
|
||||
return
|
||||
} else {
|
||||
cl := v.(*Client)
|
||||
cl.mu.Lock()
|
||||
sig := cl.signal
|
||||
cl.mu.Unlock()
|
||||
if sig == nil {
|
||||
return
|
||||
}
|
||||
//向密钥对应的客户端发送与服务端udp建立连接信息,地址,密钥
|
||||
v.(*Client).signal.Write([]byte(common.NEW_UDP_CONN))
|
||||
sig.Write([]byte(common.NEW_UDP_CONN))
|
||||
svrAddr := beego.AppConfig.String("p2p_ip") + ":" + beego.AppConfig.String("p2p_port")
|
||||
if err != nil {
|
||||
logs.Warn("get local udp addr error")
|
||||
return
|
||||
}
|
||||
v.(*Client).signal.WriteLenContent([]byte(svrAddr))
|
||||
v.(*Client).signal.WriteLenContent(b)
|
||||
sig.WriteLenContent([]byte(svrAddr))
|
||||
sig.WriteLenContent(b)
|
||||
//向该请求者发送建立连接请求,服务器地址
|
||||
c.WriteLenContent([]byte(svrAddr))
|
||||
}
|
||||
@@ -356,11 +389,14 @@ func (s *Bridge) SendLinkInfo(clientId int, link *conn.Link, t *file.Tunnel) (ta
|
||||
}
|
||||
}
|
||||
var tunnel *nps_mux.Mux
|
||||
cl := v.(*Client)
|
||||
cl.mu.Lock()
|
||||
if t != nil && t.Mode == "file" {
|
||||
tunnel = v.(*Client).file
|
||||
tunnel = cl.file
|
||||
} else {
|
||||
tunnel = v.(*Client).tunnel
|
||||
tunnel = cl.tunnel
|
||||
}
|
||||
cl.mu.Unlock()
|
||||
if tunnel == nil {
|
||||
err = errors.New("the client connect error")
|
||||
return
|
||||
@@ -393,14 +429,19 @@ func (s *Bridge) ping() {
|
||||
arr := make([]int, 0)
|
||||
s.Client.Range(func(key, value interface{}) bool {
|
||||
v := value.(*Client)
|
||||
if v.tunnel == nil || v.signal == nil {
|
||||
v.retryTime += 1
|
||||
if v.retryTime >= 3 {
|
||||
v.mu.Lock()
|
||||
tunnel := v.tunnel
|
||||
signal := v.signal
|
||||
if tunnel == nil || signal == nil {
|
||||
v.mu.Unlock()
|
||||
if v.retryTime.Add(1) >= 3 {
|
||||
arr = append(arr, key.(int))
|
||||
}
|
||||
return true
|
||||
}
|
||||
if v.tunnel.IsClose {
|
||||
isClose := tunnel.IsClose()
|
||||
v.mu.Unlock()
|
||||
if isClose {
|
||||
arr = append(arr, key.(int))
|
||||
}
|
||||
return true
|
||||
|
||||
+17
-17
@@ -85,83 +85,83 @@ tar -czvf darwin_arm64_client.tar.gz npc
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 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
|
||||
tar -czvf linux_amd64_server.tar.gz nps
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=386 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
|
||||
tar -czvf linux_386_server.tar.gz nps
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 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
|
||||
tar -czvf linux_arm_v5_server.tar.gz nps
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 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
|
||||
tar -czvf linux_arm_v6_server.tar.gz nps
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 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
|
||||
tar -czvf linux_arm_v7_server.tar.gz nps
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 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
|
||||
tar -czvf linux_arm64_server.tar.gz nps
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm 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
|
||||
tar -czvf freebsd_arm_server.tar.gz nps
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 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
|
||||
tar -czvf freebsd_386_server.tar.gz nps
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 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
|
||||
tar -czvf freebsd_amd64_server.tar.gz nps
|
||||
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mips 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
|
||||
tar -czvf linux_mips_server.tar.gz nps
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 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
|
||||
tar -czvf linux_mips64_server.tar.gz nps
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le 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
|
||||
tar -czvf linux_mips64le_server.tar.gz nps
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle 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
|
||||
tar -czvf linux_mipsle_server.tar.gz nps
|
||||
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 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
|
||||
tar -czvf darwin_amd64_server.tar.gz 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
|
||||
tar -czvf darwin_arm64_server.tar.gz 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
|
||||
tar -czvf windows_amd64_server.tar.gz nps.exe
|
||||
|
||||
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=386 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
|
||||
tar -czvf windows_386_server.tar.gz nps.exe
|
||||
@@ -1,5 +1,5 @@
|
||||
#/bash/sh
|
||||
export VERSION=0.26.30
|
||||
export VERSION=0.26.33
|
||||
export GOPROXY=direct
|
||||
|
||||
sudo apt-get update
|
||||
|
||||
+7
-5
@@ -307,7 +307,7 @@ func (s *TRPClient) handleChan(src net.Conn) {
|
||||
}
|
||||
}
|
||||
|
||||
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, nil, nil)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -324,20 +324,22 @@ func (s *TRPClient) handleUdp(serverConn net.Conn) {
|
||||
defer serverConn.Close()
|
||||
b := common.BufPoolUdp.Get().([]byte)
|
||||
defer common.BufPoolUdp.Put(b)
|
||||
var buf bytes.Buffer
|
||||
for {
|
||||
n, raddr, err := local.ReadFrom(b)
|
||||
if err != nil {
|
||||
s.logError("read data from remote server error %s", err.Error())
|
||||
return
|
||||
}
|
||||
buf := bytes.Buffer{}
|
||||
buf.Reset()
|
||||
dgram := common.NewUDPDatagram(common.NewUDPHeader(0, 0, common.ToSocksAddr(raddr)), b[:n])
|
||||
dgram.Write(&buf)
|
||||
b, err := conn.GetLenBytes(buf.Bytes())
|
||||
data, err := conn.GetLenBytes(buf.Bytes())
|
||||
if err != nil {
|
||||
s.logWarn("get len bytes error %s", err.Error())
|
||||
continue
|
||||
}
|
||||
if _, err := serverConn.Write(b); err != nil {
|
||||
if _, err := serverConn.Write(data); err != nil {
|
||||
s.logError("write data to remote error %s", err.Error())
|
||||
return
|
||||
}
|
||||
@@ -377,7 +379,7 @@ loop:
|
||||
for {
|
||||
select {
|
||||
case <-s.ticker.C:
|
||||
if s.tunnel != nil && s.tunnel.IsClose {
|
||||
if s.tunnel != nil && s.tunnel.IsClose() {
|
||||
s.Close()
|
||||
break loop
|
||||
}
|
||||
|
||||
+33
-30
@@ -2,12 +2,12 @@ package client
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"math"
|
||||
"math/rand"
|
||||
@@ -147,7 +147,7 @@ re:
|
||||
}
|
||||
vkey = string(b)
|
||||
}
|
||||
ioutil.WriteFile(filepath.Join(common.GetTmpPath(), "npc_vkey.txt"), []byte(vkey), 0600)
|
||||
os.WriteFile(filepath.Join(common.GetTmpPath(), "npc_vkey.txt"), []byte(vkey), 0600)
|
||||
|
||||
//send hosts to server
|
||||
for _, v := range cnf.Hosts {
|
||||
@@ -343,6 +343,7 @@ func handleP2PUdp(localAddr, rAddr, md5Password, role string) (remoteAddress str
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer localConn.Close()
|
||||
err = getRemoteAddressFromServer(rAddr, localConn, md5Password, role, 0)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
@@ -359,27 +360,32 @@ func handleP2PUdp(localAddr, rAddr, md5Password, role string) (remoteAddress str
|
||||
return
|
||||
}
|
||||
var remoteAddr1, remoteAddr2, remoteAddr3 string
|
||||
// 修复:添加超时,避免无限等待远端响应
|
||||
localConn.SetReadDeadline(time.Now().Add(30 * time.Second))
|
||||
buf := make([]byte, 1024)
|
||||
for {
|
||||
buf := make([]byte, 1024)
|
||||
if n, addr, er := localConn.ReadFromUDP(buf); er != nil {
|
||||
err = er
|
||||
var n int
|
||||
var addr *net.UDPAddr
|
||||
n, addr, err = localConn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
localConn.SetReadDeadline(time.Time{})
|
||||
return
|
||||
} else {
|
||||
rAddr2, _ := getNextAddr(rAddr, 1)
|
||||
rAddr3, _ := getNextAddr(rAddr, 2)
|
||||
switch addr.String() {
|
||||
case rAddr:
|
||||
remoteAddr1 = string(buf[:n])
|
||||
case rAddr2:
|
||||
remoteAddr2 = string(buf[:n])
|
||||
case rAddr3:
|
||||
remoteAddr3 = string(buf[:n])
|
||||
}
|
||||
}
|
||||
rAddr2, _ := getNextAddr(rAddr, 1)
|
||||
rAddr3, _ := getNextAddr(rAddr, 2)
|
||||
switch addr.String() {
|
||||
case rAddr:
|
||||
remoteAddr1 = string(buf[:n])
|
||||
case rAddr2:
|
||||
remoteAddr2 = string(buf[:n])
|
||||
case rAddr3:
|
||||
remoteAddr3 = string(buf[:n])
|
||||
}
|
||||
if remoteAddr1 != "" && remoteAddr2 != "" && remoteAddr3 != "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
localConn.SetReadDeadline(time.Time{})
|
||||
if remoteAddress, err = sendP2PTestMsg(localConn, remoteAddr1, remoteAddr2, remoteAddr3); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -389,9 +395,8 @@ func handleP2PUdp(localAddr, rAddr, md5Password, role string) (remoteAddress str
|
||||
|
||||
func sendP2PTestMsg(localConn *net.UDPConn, remoteAddr1, remoteAddr2, remoteAddr3 string) (string, error) {
|
||||
logs.Trace(remoteAddr3, remoteAddr2, remoteAddr1)
|
||||
defer localConn.Close()
|
||||
isClose := false
|
||||
defer func() { isClose = true }()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
interval, err := getAddrInterval(remoteAddr1, remoteAddr2, remoteAddr3)
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -410,10 +415,9 @@ func sendP2PTestMsg(localConn *net.UDPConn, remoteAddr1, remoteAddr2, remoteAddr
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if isClose {
|
||||
return
|
||||
}
|
||||
if _, err := localConn.WriteTo([]byte(common.WORK_P2P_CONNECT), remoteUdpAddr); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -436,10 +440,9 @@ func sendP2PTestMsg(localConn *net.UDPConn, remoteAddr1, remoteAddr2, remoteAddr
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if isClose {
|
||||
return
|
||||
}
|
||||
if _, err := localConn.WriteTo([]byte(common.WORK_P2P_CONNECT), remoteUdpAddr); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -552,13 +555,13 @@ func getRandomPortArr(min, max int) []int {
|
||||
for i := min; i <= max; i++ {
|
||||
addrAddr[max-i] = i
|
||||
}
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
var r, temp int
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
var ri, temp int
|
||||
for i := max - min; i > 0; i-- {
|
||||
r = rand.Int() % i
|
||||
ri = r.Int() % i
|
||||
temp = addrAddr[i]
|
||||
addrAddr[i] = addrAddr[r]
|
||||
addrAddr[r] = temp
|
||||
addrAddr[i] = addrAddr[ri]
|
||||
addrAddr[ri] = temp
|
||||
}
|
||||
return addrAddr
|
||||
}
|
||||
|
||||
+2
-2
@@ -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, nil, nil)
|
||||
}
|
||||
|
||||
func handleP2PVisitor(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
|
||||
@@ -178,7 +178,7 @@ func handleP2PVisitor(localTcpConn net.Conn, config *config.CommonConfig, l *con
|
||||
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, nil, nil)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
},
|
||||
"info": {
|
||||
"productName": "NPS Client",
|
||||
"productVersion": "0.26.30",
|
||||
"productVersion": "0.26.33",
|
||||
"companyName": "NPS",
|
||||
"copyright": "Copyright © 2026 NPS"
|
||||
},
|
||||
|
||||
+16
-4
@@ -292,8 +292,10 @@ func printSlogan() {
|
||||
fmt.Printf("\u001B[32m输入[3]\u001B[0m - 启动系统服务\n")
|
||||
fmt.Printf("\u001B[32m输入[4]\u001B[0m - 停止系统服务\n")
|
||||
fmt.Printf("---------------------\n")
|
||||
fmt.Printf("\u001B[32m输入[5]\u001B[0m - 更新客户端\n")
|
||||
fmt.Printf("\u001B[32m输入[0]\u001B[0m - 退出\n")
|
||||
fmt.Printf("---------------------\n")
|
||||
fmt.Printf("\u001B[32m当前版本:%s\u001B[0m\n", version.VERSION)
|
||||
fmt.Printf("直接输入[快捷启动命令]则是启动隧道,多个[快捷启动命令]用英文逗号拼接\n")
|
||||
fmt.Printf("\n")
|
||||
}
|
||||
@@ -314,8 +316,8 @@ func inputCmd() {
|
||||
|
||||
flag := strings.Replace(flag, " ", "", -1)
|
||||
|
||||
// 如果输入不等于 1,2,3,4,则启动隧道
|
||||
if flag != "1" && flag != "2" && flag != "3" && flag != "4" {
|
||||
// 如果输入不等于 1,2,3,4,5,则启动隧道
|
||||
if flag != "1" && flag != "2" && flag != "3" && flag != "4" && flag != "5" {
|
||||
|
||||
vkeys := strings.Split(flag, `,`)
|
||||
var cmdArray []string
|
||||
@@ -336,7 +338,12 @@ func inputCmd() {
|
||||
}
|
||||
|
||||
} else {
|
||||
systemService(flag)
|
||||
if flag == "5" {
|
||||
install.UpdateNpcNew()
|
||||
inputCmd()
|
||||
} else {
|
||||
systemService(flag)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -410,8 +417,13 @@ func systemService(flag string) {
|
||||
|
||||
for _, item := range cmdArray {
|
||||
array := strings.Fields(item)
|
||||
// tls
|
||||
|
||||
tls := "false"
|
||||
if len(array) > 2 {
|
||||
tls = array[2]
|
||||
}
|
||||
// tls
|
||||
if tls == "-tls_enable=true" || tls == "true" {
|
||||
systemPro(flag, array[0], array[1], true)
|
||||
} else {
|
||||
systemPro(flag, array[0], array[1], false)
|
||||
|
||||
+86
-2
@@ -26,6 +26,7 @@ import (
|
||||
|
||||
"ehang.io/nps/lib/common"
|
||||
"ehang.io/nps/lib/crypt"
|
||||
"ehang.io/nps/web"
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/astaxie/beego/logs"
|
||||
|
||||
@@ -72,6 +73,9 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
// auto-generate default config files if not exist
|
||||
initConfig(filepath.Join(common.GetRunPath(), "conf"))
|
||||
|
||||
if err := beego.LoadAppConfig("ini", filepath.Join(common.GetRunPath(), "conf", "nps.conf")); err != nil {
|
||||
log.Fatalln("load config file error", err.Error())
|
||||
}
|
||||
@@ -211,7 +215,7 @@ func printSlogan() {
|
||||
|
||||
fmt.Printf("%s", green(""))
|
||||
|
||||
fmt.Printf("\033[32;0m欢迎使用 NPS 管理脚本 \n")
|
||||
fmt.Printf("\033[32;0m欢迎使用 NPS 管理脚本,当前版本:v%s\n", version.VERSION)
|
||||
fmt.Printf("\033[0m") // 重置颜色
|
||||
|
||||
fmt.Printf("\n")
|
||||
@@ -328,7 +332,7 @@ func inputCmd() {
|
||||
break
|
||||
case "3":
|
||||
install.UpdateNpsNew()
|
||||
return
|
||||
break
|
||||
case "4":
|
||||
// 查看状态
|
||||
var statusMsg = ""
|
||||
@@ -444,3 +448,83 @@ func run() {
|
||||
}
|
||||
go server.StartNewServer(bridgePort, task, beego.AppConfig.String("bridge_type"), timeout)
|
||||
}
|
||||
|
||||
func initConfig(confDir string) {
|
||||
if !common.FileExists(confDir) {
|
||||
os.MkdirAll(confDir, 0755)
|
||||
}
|
||||
confPath := filepath.Join(confDir, "nps.conf")
|
||||
if !common.FileExists(confPath) {
|
||||
webPassword := crypt.GetRandomString(8)
|
||||
authKey := crypt.GetRandomString(8)
|
||||
authCryptKey := crypt.GetRandomString(16)
|
||||
content := strings.Replace(defaultNpsConf, "web_password=123", "web_password="+webPassword, 1)
|
||||
content = strings.Replace(content, "auth_key=123", "auth_key="+authKey, 1)
|
||||
content = strings.Replace(content, "auth_crypt_key =213", "auth_crypt_key ="+authCryptKey, 1)
|
||||
f, err := os.Create(confPath)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
f.WriteString(content)
|
||||
logs.Info("Auto-generated default config file:", confPath)
|
||||
logs.Info("Web login username: admin, password:", webPassword)
|
||||
logs.Info("auth_key:", authKey)
|
||||
logs.Info("auth_crypt_key:", authCryptKey)
|
||||
}
|
||||
web.ExtractWebFiles(common.GetRunPath())
|
||||
}
|
||||
|
||||
const defaultNpsConf = `http_proxy_ip=0.0.0.0
|
||||
http_proxy_port=80
|
||||
https_proxy_port=443
|
||||
show_http_proxy_port=true
|
||||
|
||||
bridge_type=tcp
|
||||
bridge_port=8024
|
||||
bridge_ip=0.0.0.0
|
||||
|
||||
public_vkey=123
|
||||
|
||||
flow_store_interval=1
|
||||
|
||||
log_level=6
|
||||
log_path=nps.log
|
||||
|
||||
web_host=a.o.com
|
||||
web_username=admin
|
||||
web_password=123
|
||||
web_port = 8081
|
||||
web_ip=0.0.0.0
|
||||
web_base_url=
|
||||
web_open_ssl=false
|
||||
web_cert_file=conf/server.pem
|
||||
web_key_file=conf/server.key
|
||||
|
||||
auth_key=123
|
||||
auth_crypt_key =213
|
||||
|
||||
allow_user_login=true
|
||||
allow_user_register=false
|
||||
allow_user_change_username=true
|
||||
|
||||
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
|
||||
|
||||
http_add_origin_header=true
|
||||
|
||||
http_cache=false
|
||||
http_cache_length=100
|
||||
|
||||
disconnect_timeout=60
|
||||
|
||||
open_captcha=false
|
||||
|
||||
tls_enable=true
|
||||
tls_bridge_port=8025
|
||||
`
|
||||
|
||||
+3
-10
@@ -1,16 +1,9 @@
|
||||
appname = nps
|
||||
#Boot mode(dev|pro)
|
||||
runmode = dev
|
||||
|
||||
#HTTP(S) proxy port, no startup if empty
|
||||
http_proxy_ip=0.0.0.0
|
||||
http_proxy_port=80
|
||||
https_proxy_port=443
|
||||
https_just_proxy=true
|
||||
#default https certificate setting
|
||||
https_default_cert_file=conf/server.pem
|
||||
https_default_key_file=conf/server.key
|
||||
|
||||
# 是否展示非【80】端口
|
||||
show_http_proxy_port=true
|
||||
##bridge
|
||||
bridge_type=tcp
|
||||
bridge_port=8024
|
||||
@@ -99,4 +92,4 @@ open_captcha=false
|
||||
|
||||
# 是否开启tls
|
||||
tls_enable=true
|
||||
tls_bridge_port=8025
|
||||
tls_bridge_port=8025
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEpAIBAAKCAQEA2MVLOHvgU8FCp6LgQrPfaWcGygrsRk7TL9hbT8MxbCRUSLV7
|
||||
Lbt3q5Knz8eTN4NWmwE6L5glOcH2x3Hnn+hPjbvgq35XBBIccAm0cYYKqoKkikeK
|
||||
FZM0Gp/WhSrhJ4laTyQqyleIFKpwD9kHDiC/sxjGDhSFmHKhhAnsQIRm2tppFXX0
|
||||
aAMqJEm88jzk1BN2QtKjEAn1u8v1+QW1KP3WuzdXH4L7hhMll66/KIm6Hfs2FRHQ
|
||||
pRUWqZeJY4q79NW5p5f+siGwOsGpxb/p11pM+0xnCH3UIFbm3zCTzP4sLvkfFGAe
|
||||
yAHsAwmaP8dJxh40ej3NN8uNiNvt8nw2Vb/1LwIDAQABAoIBAD40x/RKoEKIyE8B
|
||||
D6g0pB1EQo+CePFoN3SYewO1uR4WgtVmtxWVoa7r5BpdZGLe3uCWhpMX7z7W6bGs
|
||||
f1LFQOckjkHIfMIfTGfecRjO5Yqu+Pbxtq+gUah+S/plJr3IzdC+SUVNvzBnBMeX
|
||||
eU3Vmg2UQ2nQ+9GWu8D/c/vDwxx0X8oQ2G8QaxX0tUurlSMNA3M7xySwEvhx54fO
|
||||
UrDF3Q4yF48eA4butxVLFWf3cnlY+nR8uYd2vKfmp689/8C6kkfoM9igB78e93sm
|
||||
uDM2eRLm4kU5WLl301T42n6AF7w8J0MhLLVOIeLs4l5gZPa3uKvYFmuHQao7e/5R
|
||||
U/jHKrECgYEA8alPXuxFSVOvdhIsSN//Frj9CdExVdYmaLkt/2LO4FMnOaWh1xh7
|
||||
5iCY1bJT8D9dhfbqRg3qW2oguZD8gu04R8fTRegQ89qmAIwsEYqVf9salR41lZU4
|
||||
Rc+5yc7O11WIe9Lzu+ONFBFkAh3UFMR4zVZ/JhKIG/P5Srm7SUdKW2cCgYEA5aHo
|
||||
x2LR+yKhjkrBzHG3Qrfy1PtlYHjOpYYAKHQcBFuiG08W3CK/vkYl+mhv0uyhT7mn
|
||||
q6NDqrpZPRnDlOoEqgRS1X/QWKN6Pgd4HNLIawvp0vK9jYXDPcAXFzVthXCIwFcn
|
||||
3a3m4cHiuLdRNOHkydiHQyTOF6eEneN07TDvwvkCgYEApzOd1u9igPmFzQuF2GYi
|
||||
+HXFnaU/nUQuDwcQ7EJRIKRn31raPxiRoQesty5LJU6yRp4wOYgnPliPi9Tk4TGA
|
||||
XynC4/tMv2vorzhMxVY9Wdke602bhYNZC/RNd3O/aP2lEQdD3Bv04I2nxE8fDb9i
|
||||
VbAjCRSJV83WDf2zt1+78sECgYEAzezjRiKdcZu9y0/I+WEk2cUCE/MaF2he0FsZ
|
||||
uy1cjp/qAJltQ5452xUnK6cKWNlxU4CHF0mC/hC8xCldliZCZoEYE3PaUBLSJdwm
|
||||
35o6tpxpZI3gZJCG5NJlIp/8BkVDrVC7ZHV17hAkFEf4n/bPaB8wNYtE8jt8luaK
|
||||
TcarzGkCgYBn2alN0RLN2PHDurraFZB6GuCvh/arEjSCY3SDFQPF10CVjTDV7sx3
|
||||
eqJkwJ81syTmfJwZIceWbOFGgsuSx37UrQAVlHZSvzeqEg9dA5HqSoOACyidJI7j
|
||||
RG2+HB+KpsIZjGgLrEM4i7VOpYUDRdaouIXngFq/t9HNT+MDck5/Lw==
|
||||
-----END RSA PRIVATE KEY-----
|
||||
@@ -1,22 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDtTCCAp2gAwIBAgIJAPXRSiP0Fs7sMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV
|
||||
BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX
|
||||
aWRnaXRzIFB0eSBMdGQwHhcNMTcxMTA3MDg1MzQ2WhcNMjcxMTA1MDg1MzQ2WjBF
|
||||
MQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50
|
||||
ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
|
||||
CgKCAQEA2MVLOHvgU8FCp6LgQrPfaWcGygrsRk7TL9hbT8MxbCRUSLV7Lbt3q5Kn
|
||||
z8eTN4NWmwE6L5glOcH2x3Hnn+hPjbvgq35XBBIccAm0cYYKqoKkikeKFZM0Gp/W
|
||||
hSrhJ4laTyQqyleIFKpwD9kHDiC/sxjGDhSFmHKhhAnsQIRm2tppFXX0aAMqJEm8
|
||||
8jzk1BN2QtKjEAn1u8v1+QW1KP3WuzdXH4L7hhMll66/KIm6Hfs2FRHQpRUWqZeJ
|
||||
Y4q79NW5p5f+siGwOsGpxb/p11pM+0xnCH3UIFbm3zCTzP4sLvkfFGAeyAHsAwma
|
||||
P8dJxh40ej3NN8uNiNvt8nw2Vb/1LwIDAQABo4GnMIGkMB0GA1UdDgQWBBQdPc0R
|
||||
a8alY6Ab7voidkTGaH4PxzB1BgNVHSMEbjBsgBQdPc0Ra8alY6Ab7voidkTGaH4P
|
||||
x6FJpEcwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNV
|
||||
BAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZIIJAPXRSiP0Fs7sMAwGA1UdEwQF
|
||||
MAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAH1IZNkjuvt2nZPzXsuiVNyCE1vm346z
|
||||
naE0Uzt3aseAN9m/iiB8mLz+ryvWc2aFMX5lTdsHdm2rqmqBCBXeRwTLf4OeHIju
|
||||
ZQW6makWt6PxANEo6gbdPbQXbS420ssUhnR2irIH1SdI31iikVFPdiS0baRRE/gS
|
||||
+440M1jOOOnKm0Qin92ejsshmji/0qaD2+6D5TNw4HmIZaFTBw+kfjxCL6trfeBn
|
||||
4fT0RJ121V3G3+AtG5sWQ93B3pCg+jtD+fGKkNSLhphq84bD1Zv7l73QGOoylkEn
|
||||
Sc0ajTLOXFBb83yRdlgV3Da95jH9rDZ4jSod48m+KemoZTDQw0vSwAU=
|
||||
-----END CERTIFICATE-----
|
||||
@@ -45,6 +45,7 @@ POST /client/add/
|
||||
| flow\_limit | 流量限制 单位M 空则为不限制 |
|
||||
| max\_conn | 客户端最大连接数量 空则为不限制 |
|
||||
| max\_tunnel | 客户端最大隧道数量 空则为不限制 |
|
||||
| expire\_time | 到期时间,留空表示永不过期,到期后自动暂停。支持格式:`2006-01-02 15:04:05`、`2006-01-02 15:04`、`2006-01-02T15:04:05`、`2006-01-02T15:04`、`2006-01-02` |
|
||||
|
||||
***
|
||||
修改客户端
|
||||
@@ -67,6 +68,7 @@ POST /client/edit/
|
||||
| flow\_limit | 流量限制 单位M 空则为不限制 |
|
||||
| max\_conn | 客户端最大连接数量 空则为不限制 |
|
||||
| max\_tunnel | 客户端最大隧道数量 空则为不限制 |
|
||||
| expire\_time | 到期时间,留空表示永不过期,到期后自动暂停。格式同新增接口 |
|
||||
| id | 要修改的客户端id |
|
||||
|
||||
***
|
||||
|
||||
+7
-5
@@ -39,10 +39,10 @@ func (s *Conn) readRequest(buf []byte) (n int, err error) {
|
||||
var rd int
|
||||
for {
|
||||
rd, err = s.Read(buf[n:])
|
||||
n += rd
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
n += rd
|
||||
if n < 4 {
|
||||
continue
|
||||
}
|
||||
@@ -61,10 +61,12 @@ func (s *Conn) readRequest(buf []byte) (n int, err error) {
|
||||
func (s *Conn) GetHost() (method, address string, rb []byte, err error, r *http.Request) {
|
||||
var b [32 * 1024]byte
|
||||
var n int
|
||||
if n, err = s.readRequest(b[:]); err != nil {
|
||||
if n, err = s.readRequest(b[:]); n > 0 {
|
||||
rb = b[:n]
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
rb = b[:n]
|
||||
r, err = http.ReadRequest(bufio.NewReader(bytes.NewReader(rb)))
|
||||
if err != nil {
|
||||
return
|
||||
@@ -374,7 +376,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) {
|
||||
flow *file.Flow, isServer bool, rb []byte, task *file.Tunnel, host *file.Host) {
|
||||
//var in, out int64
|
||||
//var wg sync.WaitGroup
|
||||
connHandle := GetConn(conn1, crypt, snappy, rate, isServer)
|
||||
@@ -397,7 +399,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, task, host))
|
||||
wg.Wait()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package conn
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type bytesThenErrConn struct {
|
||||
net.Conn
|
||||
payload []byte
|
||||
err error
|
||||
read bool
|
||||
}
|
||||
|
||||
func (c *bytesThenErrConn) Read(b []byte) (int, error) {
|
||||
if c.read {
|
||||
return 0, c.err
|
||||
}
|
||||
c.read = true
|
||||
return copy(b, c.payload), c.err
|
||||
}
|
||||
|
||||
func TestGetHostReturnsBufferedBytesOnReadError(t *testing.T) {
|
||||
clientConn, serverConn := net.Pipe()
|
||||
defer clientConn.Close()
|
||||
defer serverConn.Close()
|
||||
|
||||
payload := []byte("SSH-2.0-OpenSSH_9.0\r\n")
|
||||
if err := serverConn.SetReadDeadline(time.Now().Add(50 * time.Millisecond)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
type result struct {
|
||||
rb []byte
|
||||
err error
|
||||
}
|
||||
done := make(chan result, 1)
|
||||
go func() {
|
||||
_, _, rb, err, _ := NewConn(serverConn).GetHost()
|
||||
done <- result{rb: rb, err: err}
|
||||
}()
|
||||
|
||||
if _, err := clientConn.Write(payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
select {
|
||||
case got := <-done:
|
||||
if got.err == nil {
|
||||
t.Fatal("expected GetHost to fail for non-HTTP payload")
|
||||
}
|
||||
if !bytes.Equal(got.rb, payload) {
|
||||
t.Fatalf("expected buffered payload %q, got %q", payload, got.rb)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("GetHost did not return after read deadline")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetHostReturnsBufferedBytesWhenReadReturnsBytesAndError(t *testing.T) {
|
||||
payload := []byte("SSH-2.0-OpenSSH_9.0\r\n")
|
||||
c := &bytesThenErrConn{
|
||||
payload: payload,
|
||||
err: io.ErrUnexpectedEOF,
|
||||
}
|
||||
|
||||
_, _, rb, err, _ := NewConn(c).GetHost()
|
||||
if err == nil {
|
||||
t.Fatal("expected GetHost to fail for non-HTTP payload")
|
||||
}
|
||||
if !bytes.Equal(rb, payload) {
|
||||
t.Fatalf("expected buffered payload %q, got %q", payload, rb)
|
||||
}
|
||||
}
|
||||
+9
-2
@@ -96,7 +96,7 @@ func (s *DbUtils) GetIdByVerifyKey(vKey string, addr string) (id int, err error)
|
||||
func (s *DbUtils) NewTask(t *Tunnel) (err error) {
|
||||
s.JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
v := value.(*Tunnel)
|
||||
if (v.Mode == "secret" || v.Mode == "p2p") && v.Password == t.Password {
|
||||
if (v.Mode == "secret" || v.Mode == "p2p") && v.Password == t.Password && t.Password != "" {
|
||||
err = errors.New(fmt.Sprintf("secret mode keys %s must be unique", t.Password))
|
||||
return false
|
||||
}
|
||||
@@ -273,7 +273,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) * 1024))
|
||||
t.Rate.Start()
|
||||
}
|
||||
return nil
|
||||
@@ -377,6 +377,13 @@ func (s *DbUtils) GetInfoByHost(host string, r *http.Request) (h *Host, err erro
|
||||
if v.Location == "" {
|
||||
v.Location = "/"
|
||||
}
|
||||
// "*" means SNI-based HTTPS lookup where actual URI is unknown, skip location filter
|
||||
if r.RequestURI == "*" {
|
||||
if h == nil || (len(v.Location) > len(h.Location)) {
|
||||
h = v
|
||||
}
|
||||
continue
|
||||
}
|
||||
if strings.Index(r.RequestURI, v.Location) == 0 {
|
||||
if h == nil || (len(v.Location) > len(h.Location)) {
|
||||
h = v
|
||||
|
||||
+31
-11
@@ -158,6 +158,9 @@ func (s *JsonDb) GetHostId() int32 {
|
||||
}
|
||||
|
||||
func loadSyncMapFromFile(filePath string, f func(value string)) {
|
||||
if !common.FileExists(filePath) {
|
||||
return
|
||||
}
|
||||
b, err := common.ReadAllFromFile(filePath)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
@@ -184,8 +187,14 @@ func storeSyncMapToFile(m sync.Map, filePath string) {
|
||||
file, err := os.Create(filePath + ".tmp")
|
||||
// first create a temporary file to store
|
||||
if err != nil {
|
||||
panic(err)
|
||||
logs.Error("store to file: create tmp file error: %v", err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
file.Close()
|
||||
os.Remove(filePath + ".tmp")
|
||||
}()
|
||||
var writeErr bool
|
||||
m.Range(func(key, value interface{}) bool {
|
||||
var b []byte
|
||||
var err error
|
||||
@@ -208,9 +217,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
|
||||
}
|
||||
@@ -219,40 +225,54 @@ func storeSyncMapToFile(m sync.Map, filePath string) {
|
||||
}
|
||||
_, err = file.Write(b)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
logs.Error("store to file: write error: %v", err)
|
||||
writeErr = true
|
||||
return false
|
||||
}
|
||||
_, err = file.Write([]byte("\n" + common.CONN_DATA_SEQ))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
logs.Error("store to file: write separator error: %v", err)
|
||||
writeErr = true
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
if writeErr {
|
||||
return
|
||||
}
|
||||
_ = 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")
|
||||
}
|
||||
// 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)
|
||||
logs.Error("store global to file: create tmp file error: %v", err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
file.Close()
|
||||
os.Remove(filePath + ".tmp")
|
||||
}()
|
||||
|
||||
var b []byte
|
||||
b, err = json.Marshal(m)
|
||||
if err != nil {
|
||||
logs.Error("store global to file: marshal error: %v", err)
|
||||
return
|
||||
}
|
||||
_, err = file.Write(b)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
logs.Error("store global to file: write error: %v", err)
|
||||
return
|
||||
}
|
||||
_ = 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")
|
||||
|
||||
+14
-7
@@ -57,6 +57,7 @@ type Client struct {
|
||||
IpWhite bool // 是否启用ip白名单
|
||||
IpWhitePass string // ip授权密码
|
||||
IpWhiteList []string // ip白名单
|
||||
ExpireTime string // 到期时间,留空表示永不过期,格式 2006-01-02 15:04:05
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
@@ -207,22 +208,28 @@ type MultiAccount struct {
|
||||
}
|
||||
|
||||
func (s *Target) GetRandomTarget() (string, error) {
|
||||
s.Lock()
|
||||
if s.TargetArr == nil {
|
||||
s.TargetArr = strings.Split(s.TargetStr, "\n")
|
||||
}
|
||||
if len(s.TargetArr) == 1 {
|
||||
return s.TargetArr[0], nil
|
||||
arr := strings.Split(s.TargetStr, "\n")
|
||||
s.TargetArr = make([]string, 0, len(arr))
|
||||
for _, v := range arr {
|
||||
v = strings.TrimRight(v, "\r")
|
||||
if v != "" {
|
||||
s.TargetArr = append(s.TargetArr, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(s.TargetArr) == 0 {
|
||||
s.Unlock()
|
||||
return "", errors.New("all inward-bending targets are offline")
|
||||
}
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
if s.nowIndex >= len(s.TargetArr)-1 {
|
||||
s.nowIndex = -1
|
||||
}
|
||||
s.nowIndex++
|
||||
return s.TargetArr[s.nowIndex], nil
|
||||
addr := s.TargetArr[s.nowIndex]
|
||||
s.Unlock()
|
||||
return addr, nil
|
||||
}
|
||||
|
||||
type Glob struct {
|
||||
|
||||
+16
-7
@@ -22,6 +22,7 @@ type connGroup struct {
|
||||
n *int64
|
||||
flow *file.Flow
|
||||
task *file.Tunnel
|
||||
host *file.Host
|
||||
remote string
|
||||
}
|
||||
|
||||
@@ -34,7 +35,7 @@ type connGroup struct {
|
||||
// }
|
||||
//}
|
||||
|
||||
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, flow *file.Flow, task *file.Tunnel, host *file.Host, remote string) connGroup {
|
||||
return connGroup{
|
||||
src: src,
|
||||
dst: dst,
|
||||
@@ -42,11 +43,12 @@ func newConnGroup(dst, src io.ReadWriteCloser, wg *sync.WaitGroup, n *int64, flo
|
||||
n: n,
|
||||
flow: flow,
|
||||
task: task,
|
||||
host: host,
|
||||
remote: remote,
|
||||
}
|
||||
}
|
||||
|
||||
func CopyBuffer(dst io.Writer, src io.Reader, flow *file.Flow, task *file.Tunnel, remote string) (err error) {
|
||||
func CopyBuffer(dst io.Writer, src io.Reader, flow *file.Flow, task *file.Tunnel, host *file.Host, remote string) (err error) {
|
||||
buf := common.CopyBuff.Get()
|
||||
defer common.CopyBuff.Put(buf)
|
||||
for {
|
||||
@@ -129,7 +131,12 @@ func CopyBuffer(dst io.Writer, src io.Reader, flow *file.Flow, task *file.Tunnel
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if task != nil && task.Flow != nil && task.Flow != flow {
|
||||
task.Flow.Add(int64(nw), int64(nw))
|
||||
}
|
||||
if host != nil && host.Flow != nil && host.Flow != flow {
|
||||
host.Flow.Add(int64(nw), int64(nw))
|
||||
}
|
||||
}
|
||||
if ew != nil {
|
||||
err = ew
|
||||
@@ -156,7 +163,7 @@ func copyConnGroup(group interface{}) {
|
||||
}
|
||||
|
||||
var err error
|
||||
err = CopyBuffer(cg.dst, cg.src, cg.flow, cg.task, cg.remote)
|
||||
err = CopyBuffer(cg.dst, cg.src, cg.flow, cg.task, cg.host, cg.remote)
|
||||
if err != nil {
|
||||
cg.src.Close()
|
||||
cg.dst.Close()
|
||||
@@ -175,15 +182,17 @@ type Conns struct {
|
||||
flow *file.Flow
|
||||
wg *sync.WaitGroup
|
||||
task *file.Tunnel
|
||||
host *file.Host
|
||||
}
|
||||
|
||||
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, task *file.Tunnel, host *file.Host) Conns {
|
||||
return Conns{
|
||||
conn1: c1,
|
||||
conn2: c2,
|
||||
flow: flow,
|
||||
wg: wg,
|
||||
task: task,
|
||||
host: host,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,9 +203,9 @@ func copyConns(group interface{}) {
|
||||
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, conns.flow, conns.task, conns.host, remoteAddr))
|
||||
// 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, conns.flow, conns.task, conns.host, remoteAddr))
|
||||
// mux to outside : outgoing
|
||||
wg.Wait()
|
||||
//if conns.flow != nil {
|
||||
|
||||
@@ -2,6 +2,7 @@ package install
|
||||
|
||||
import (
|
||||
"ehang.io/nps/lib/common"
|
||||
"ehang.io/nps/lib/version"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -13,6 +14,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -142,12 +144,52 @@ func UpdateNps() {
|
||||
}
|
||||
|
||||
func UpdateNpsNew() {
|
||||
latest, err := fetchLatestVersion()
|
||||
if err != nil {
|
||||
log.Println("获取最新版本失败:", err)
|
||||
return
|
||||
} else {
|
||||
fmt.Println("最新版本为:", latest)
|
||||
if compareVersion(version.VERSION, latest) >= 0 {
|
||||
fmt.Println("当前已是最新版本,无需更新")
|
||||
return
|
||||
}
|
||||
}
|
||||
destPath := downloadLatest2("server", filepath.Join(common.GetAppPath(), "temp"))
|
||||
//复制文件到对应目录
|
||||
copyStaticFileReplaceNps(destPath, common.GetAppPath())
|
||||
fmt.Println("更新成功,请重启服务")
|
||||
}
|
||||
|
||||
func fetchLatestVersion() (string, error) {
|
||||
resp, err := http.Get("https://api.github.com/repos/yisier/nps/releases/latest")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
rl := new(release)
|
||||
if err := json.Unmarshal(b, rl); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return rl.TagName, nil
|
||||
}
|
||||
|
||||
func compareVersion(a, b string) int {
|
||||
ai, _ := strconv.Atoi(strings.ReplaceAll(strings.TrimPrefix(a, "v"), ".", ""))
|
||||
bi, _ := strconv.Atoi(strings.ReplaceAll(strings.TrimPrefix(b, "v"), ".", ""))
|
||||
if ai < bi {
|
||||
return -1
|
||||
}
|
||||
if ai > bi {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func UpdateNpc() {
|
||||
destPath := downloadLatest("client")
|
||||
//复制文件到对应目录
|
||||
@@ -155,6 +197,23 @@ func UpdateNpc() {
|
||||
fmt.Println("Update completed, please restart")
|
||||
}
|
||||
|
||||
func UpdateNpcNew() {
|
||||
latest, err := fetchLatestVersion()
|
||||
if err != nil {
|
||||
log.Println("获取最新版本失败:", err)
|
||||
return
|
||||
} else {
|
||||
fmt.Println("最新版本为:", latest)
|
||||
if compareVersion(version.VERSION, latest) >= 0 {
|
||||
fmt.Println("当前已是最新版本,无需更新")
|
||||
return
|
||||
}
|
||||
}
|
||||
destPath := downloadLatest2("client", filepath.Join(common.GetAppPath(), "temp"))
|
||||
copyStaticFileReplaceNpc(destPath, common.GetAppPath())
|
||||
fmt.Println("更新成功,请重启客户端")
|
||||
}
|
||||
|
||||
type release struct {
|
||||
TagName string `json:"tag_name"`
|
||||
}
|
||||
@@ -286,6 +345,18 @@ func copyStaticFileReplaceNps(srcPath, descPath string) string {
|
||||
return binPath
|
||||
}
|
||||
|
||||
func copyStaticFileReplaceNpc(srcPath, descPath string) string {
|
||||
binPath, _ := filepath.Abs(os.Args[0])
|
||||
if !common.IsWindows() {
|
||||
os.Rename(filepath.Join(srcPath, "npc"), filepath.Join(descPath, "npc"))
|
||||
} else {
|
||||
os.Rename(filepath.Join(srcPath, "npc.exe"), filepath.Join(descPath, "npc.exe"))
|
||||
}
|
||||
chMod(binPath, 0755)
|
||||
os.RemoveAll(srcPath)
|
||||
return binPath
|
||||
}
|
||||
|
||||
func InstallNpc() {
|
||||
path := common.GetInstallPath()
|
||||
if !common.FileExists(path) {
|
||||
|
||||
+1
-1
@@ -72,7 +72,7 @@ func (s *conn) Close() (err error) {
|
||||
func (s *conn) closeProcess() {
|
||||
s.isClose = true
|
||||
s.receiveWindow.mux.connMap.Delete(s.connId)
|
||||
if !s.receiveWindow.mux.IsClose {
|
||||
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)
|
||||
|
||||
+18
-16
@@ -35,7 +35,7 @@ type Mux struct {
|
||||
newConnCh chan *conn
|
||||
id int32
|
||||
closeChan chan struct{}
|
||||
IsClose bool
|
||||
isClose atomic.Bool
|
||||
counter *latencyCounter
|
||||
bw *bandwidth
|
||||
pingCh chan []byte
|
||||
@@ -70,7 +70,6 @@ func NewMux(c net.Conn, connType string, pingCheckThreshold int) *Mux {
|
||||
closeChan: make(chan struct{}, 1),
|
||||
newConnCh: make(chan *conn),
|
||||
bw: NewBandwidth(fd),
|
||||
IsClose: false,
|
||||
connType: connType,
|
||||
pingCh: make(chan []byte),
|
||||
pingCheckThreshold: checkThreshold,
|
||||
@@ -86,8 +85,11 @@ func NewMux(c net.Conn, connType string, pingCheckThreshold int) *Mux {
|
||||
return m
|
||||
}
|
||||
|
||||
// IsClose returns whether the mux connection has been closed.
|
||||
func (s *Mux) IsClose() bool { return s.isClose.Load() }
|
||||
|
||||
func (s *Mux) NewConn() (*conn, error) {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
return nil, errors.New("the mux has closed")
|
||||
}
|
||||
conn := NewConn(s.getId(), s)
|
||||
@@ -106,7 +108,7 @@ func (s *Mux) NewConn() (*conn, error) {
|
||||
}
|
||||
|
||||
func (s *Mux) Accept() (net.Conn, error) {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
return nil, errors.New("accpet error,the mux has closed")
|
||||
}
|
||||
conn := <-s.newConnCh
|
||||
@@ -121,7 +123,7 @@ func (s *Mux) Addr() net.Addr {
|
||||
}
|
||||
|
||||
func (s *Mux) sendInfo(flag uint8, id int32, data interface{}) {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
return
|
||||
}
|
||||
var err error
|
||||
@@ -140,11 +142,11 @@ func (s *Mux) sendInfo(flag uint8, id int32, data interface{}) {
|
||||
func (s *Mux) writeSession() {
|
||||
go func() {
|
||||
for {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
break
|
||||
}
|
||||
pack := s.writeQueue.Pop()
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
break
|
||||
}
|
||||
//if pack.flag == muxNewMsg || pack.flag == muxNewMsgPart {
|
||||
@@ -173,7 +175,7 @@ func (s *Mux) ping() {
|
||||
ticker := time.NewTicker(time.Second * 5)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
break
|
||||
}
|
||||
select {
|
||||
@@ -197,7 +199,7 @@ func (s *Mux) ping() {
|
||||
var now time.Time
|
||||
var data []byte
|
||||
for {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
break
|
||||
}
|
||||
select {
|
||||
@@ -213,7 +215,7 @@ func (s *Mux) ping() {
|
||||
// convert float64 to bits, store it atomic
|
||||
//log.Println("ping", math.Float64frombits(atomic.LoadUint64(&s.latency)))
|
||||
}
|
||||
if cap(data) > 0 && !s.IsClose {
|
||||
if cap(data) > 0 && !s.isClose.Load() {
|
||||
windowBuff.Put(data)
|
||||
}
|
||||
}
|
||||
@@ -224,11 +226,11 @@ func (s *Mux) readSession() {
|
||||
go func() {
|
||||
var connection *conn
|
||||
for {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
break
|
||||
}
|
||||
connection = s.newConnQueue.Pop()
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
break // make sure that is closed
|
||||
}
|
||||
s.connMap.Set(connection.connId, connection) //it has been Set before send ok
|
||||
@@ -241,7 +243,7 @@ func (s *Mux) readSession() {
|
||||
var l uint16
|
||||
var err error
|
||||
for {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
return
|
||||
}
|
||||
pack = muxPack.Get()
|
||||
@@ -322,10 +324,10 @@ func (s *Mux) newMsg(connection *conn, pack *muxPackager) (err error) {
|
||||
}
|
||||
|
||||
func (s *Mux) Close() (err error) {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
return errors.New("the mux has closed")
|
||||
}
|
||||
s.IsClose = true
|
||||
s.isClose.Store(true)
|
||||
log.Println("close mux")
|
||||
s.connMap.Close()
|
||||
//s.connMap = nil
|
||||
@@ -361,7 +363,7 @@ func (s *Mux) release() {
|
||||
s.newConnQueue.Stop()
|
||||
}
|
||||
|
||||
//Get New connId as unique flag
|
||||
// Get New connId as unique flag
|
||||
func (s *Mux) getId() (id int32) {
|
||||
//Avoid going beyond the scope
|
||||
if (math.MaxInt32 - s.id) < 10000 {
|
||||
|
||||
@@ -135,6 +135,7 @@ func (Self *muxPackager) UnPack(reader io.Reader) (n uint16, err error) {
|
||||
Self.buf = Self.buf[0:13]
|
||||
l, err := io.ReadFull(reader, Self.buf[:5])
|
||||
if err != nil {
|
||||
windowBuff.Put(Self.buf) // 归还 buf,避免 pool 泄漏
|
||||
return
|
||||
}
|
||||
n += uint16(l)
|
||||
@@ -145,6 +146,11 @@ func (Self *muxPackager) UnPack(reader io.Reader) (n uint16, err error) {
|
||||
var m uint16
|
||||
Self.content = windowBuff.Get() // need Get a window buf from pool
|
||||
m, err = Self.basePackager.UnPack(reader)
|
||||
if err != nil {
|
||||
windowBuff.Put(Self.content) // 归还 content buf,避免 pool 泄漏
|
||||
windowBuff.Put(Self.buf)
|
||||
return
|
||||
}
|
||||
n += m
|
||||
case muxMsgSendOk:
|
||||
l, err = io.ReadFull(reader, Self.buf[5:13])
|
||||
|
||||
+11
-5
@@ -10,12 +10,14 @@ type PortListener struct {
|
||||
connCh chan *PortConn
|
||||
addr net.Addr
|
||||
isClose bool
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func NewPortListener(connCh chan *PortConn, addr net.Addr) *PortListener {
|
||||
return &PortListener{
|
||||
connCh: connCh,
|
||||
addr: addr,
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,19 +25,23 @@ func (pListener *PortListener) Accept() (net.Conn, error) {
|
||||
if pListener.isClose {
|
||||
return nil, errors.New("the listener has closed")
|
||||
}
|
||||
conn := <-pListener.connCh
|
||||
if conn != nil {
|
||||
return conn, nil
|
||||
select {
|
||||
case <-pListener.done:
|
||||
return nil, errors.New("the listener has closed")
|
||||
case conn := <-pListener.connCh:
|
||||
if conn != nil {
|
||||
return conn, nil
|
||||
}
|
||||
return nil, errors.New("the listener has closed")
|
||||
}
|
||||
return nil, errors.New("the listener has closed")
|
||||
}
|
||||
|
||||
func (pListener *PortListener) Close() error {
|
||||
//close
|
||||
if pListener.isClose {
|
||||
return errors.New("the listener has closed")
|
||||
}
|
||||
pListener.isClose = true
|
||||
close(pListener.done)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
+29
-5
@@ -10,6 +10,7 @@ import (
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"ehang.io/nps/lib/common"
|
||||
@@ -34,6 +35,8 @@ type PortMux struct {
|
||||
net.Listener
|
||||
port int
|
||||
isClose bool
|
||||
done chan struct{} // 关闭时触发 process() 退出,避免 send on closed channel
|
||||
wg sync.WaitGroup // 跟踪 in-flight process(),保证 Close() 关闭 conn channel 前全部退出
|
||||
managerHost string
|
||||
clientConn chan *PortConn
|
||||
httpConn chan *PortConn
|
||||
@@ -45,6 +48,7 @@ func NewPortMux(port int, managerHost string) *PortMux {
|
||||
pMux := &PortMux{
|
||||
managerHost: managerHost,
|
||||
port: port,
|
||||
done: make(chan struct{}),
|
||||
clientConn: make(chan *PortConn),
|
||||
httpConn: make(chan *PortConn),
|
||||
httpsConn: make(chan *PortConn),
|
||||
@@ -65,25 +69,35 @@ func (pMux *PortMux) Start() error {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
pMux.wg.Add(1)
|
||||
go func() {
|
||||
defer pMux.wg.Done()
|
||||
for {
|
||||
conn, err := pMux.Listener.Accept()
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
//close
|
||||
pMux.Close()
|
||||
return
|
||||
}
|
||||
go pMux.process(conn)
|
||||
pMux.wg.Add(1)
|
||||
go func(c net.Conn) {
|
||||
defer pMux.wg.Done()
|
||||
pMux.process(c)
|
||||
}(conn)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pMux *PortMux) process(conn net.Conn) {
|
||||
// 设置读超时,防止客户端不发数据导致 goroutine 永久阻塞,造成 wg.Wait() 死锁
|
||||
readTimeout := ACCEPT_TIME_OUT * time.Second
|
||||
conn.SetReadDeadline(time.Now().Add(readTimeout))
|
||||
|
||||
// Recognition according to different signs
|
||||
// read 3 byte
|
||||
buf := make([]byte, 3)
|
||||
if n, err := io.ReadFull(conn, buf); err != nil || n != 3 {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
var ch chan *PortConn
|
||||
@@ -92,6 +106,7 @@ func (pMux *PortMux) process(conn net.Conn) {
|
||||
var readMore = false
|
||||
switch common.BytesToNum(buf) {
|
||||
case HTTP_CONNECT, HTTP_DELETE, HTTP_GET, HTTP_HEAD, HTTP_OPTIONS, HTTP_POST, HTTP_PUT, HTTP_TRACE: //http and manager
|
||||
conn.SetReadDeadline(time.Now().Add(readTimeout)) // 刷新超时,给 HTTP 头读取完整时间窗口
|
||||
buffer.Reset()
|
||||
r := bufio.NewReader(conn)
|
||||
buffer.Write(buf)
|
||||
@@ -127,12 +142,18 @@ func (pMux *PortMux) process(conn net.Conn) {
|
||||
readMore = true
|
||||
ch = pMux.httpsConn
|
||||
}
|
||||
// 清除读超时,后续由 PortConn 的消费者自行管理超时
|
||||
conn.SetReadDeadline(time.Time{})
|
||||
if len(rs) == 0 {
|
||||
rs = buf
|
||||
}
|
||||
timer := time.NewTimer(ACCEPT_TIME_OUT)
|
||||
timer := time.NewTimer(readTimeout)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-pMux.done:
|
||||
conn.Close()
|
||||
case <-timer.C:
|
||||
conn.Close()
|
||||
case ch <- newPortConn(conn, rs, readMore):
|
||||
}
|
||||
}
|
||||
@@ -142,11 +163,14 @@ func (pMux *PortMux) Close() error {
|
||||
return errors.New("the port pmux has closed")
|
||||
}
|
||||
pMux.isClose = true
|
||||
_ = pMux.Listener.Close() // 停止接收新连接,触发 accept 协程退出
|
||||
close(pMux.done) // 唤醒 in-flight process()
|
||||
pMux.wg.Wait() // 等待所有 process() 退出后再 close conn channel
|
||||
close(pMux.clientConn)
|
||||
close(pMux.httpsConn)
|
||||
close(pMux.httpConn)
|
||||
close(pMux.managerConn)
|
||||
return pMux.Listener.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pMux *PortMux) GetClientListener() net.Listener {
|
||||
|
||||
+4
-3
@@ -2,6 +2,7 @@ package rate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
xrate "golang.org/x/time/rate"
|
||||
@@ -11,6 +12,7 @@ type Rate struct {
|
||||
limiter *xrate.Limiter
|
||||
addSize int64
|
||||
stopChan chan struct{}
|
||||
consumed int64
|
||||
NowRate int64
|
||||
}
|
||||
|
||||
@@ -19,7 +21,6 @@ func NewRate(addSize int64) *Rate {
|
||||
limiter: xrate.NewLimiter(xrate.Limit(addSize), int(addSize)),
|
||||
addSize: addSize,
|
||||
stopChan: make(chan struct{}),
|
||||
NowRate: addSize,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +31,7 @@ func (s *Rate) Start() {
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
s.NowRate = s.addSize - (int64(s.limiter.Tokens()))
|
||||
s.NowRate = atomic.SwapInt64(&s.consumed, 0)
|
||||
case <-s.stopChan:
|
||||
return
|
||||
}
|
||||
@@ -55,5 +56,5 @@ func (s *Rate) Get(size int64) {
|
||||
}
|
||||
ctx := context.Background()
|
||||
_ = s.limiter.WaitN(ctx, int(size))
|
||||
s.NowRate = s.addSize - (int64(s.limiter.Tokens()))
|
||||
atomic.AddInt64(&s.consumed, size)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package version
|
||||
|
||||
const VERSION = "0.26.30"
|
||||
const VERSION = "0.26.34"
|
||||
|
||||
// Compulsory minimum version, Minimum downward compatibility to this version
|
||||
func GetVersion() string {
|
||||
|
||||
@@ -96,7 +96,7 @@ func in(target string, str_array []string) bool {
|
||||
|
||||
// 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 {
|
||||
rb []byte, tp string, f func(), flow *file.Flow, localProxy bool, task *file.Tunnel, host *file.Host) error {
|
||||
|
||||
// 判断访问地址是否在全局黑名单内
|
||||
if IsGlobalBlackIp(c.RemoteAddr().String()) {
|
||||
@@ -124,7 +124,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, task, host)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -262,7 +262,7 @@ reset:
|
||||
}
|
||||
}()
|
||||
|
||||
err1 := goroutine.CopyBuffer(c, connClient, host.Client.Flow, nil, "")
|
||||
err1 := goroutine.CopyBuffer(c, connClient, host.Client.Flow, nil, host, "")
|
||||
if err1 != nil {
|
||||
return
|
||||
}
|
||||
@@ -292,6 +292,7 @@ reset:
|
||||
}
|
||||
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(int64(n), 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
|
||||
@@ -313,6 +314,7 @@ reset:
|
||||
break
|
||||
}
|
||||
host.Client.Flow.Add(int64(lenConn.Len), int64(lenConn.Len))
|
||||
host.Flow.Add(int64(lenConn.Len), int64(lenConn.Len))
|
||||
|
||||
readReq:
|
||||
//read req from connection
|
||||
|
||||
+63
-15
@@ -1,6 +1,7 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -38,10 +39,14 @@ func (https *HttpsServer) Start() error {
|
||||
|
||||
conn.Accept(https.listener, func(c net.Conn) {
|
||||
serverName, rb := GetServerNameFromClientHello(c)
|
||||
if serverName == "" {
|
||||
serverName = getFallbackServerName()
|
||||
logs.Debug("https fallback server name result, remote addr %s, server name %q", c.RemoteAddr().String(), serverName)
|
||||
}
|
||||
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())
|
||||
logs.Debug("https host lookup failed, server name %q, remote addr %s, error %v", serverName, c.RemoteAddr().String(), err)
|
||||
return
|
||||
} else {
|
||||
if host.CertFilePath == "" || host.KeyFilePath == "" {
|
||||
@@ -140,6 +145,35 @@ func (https *HttpsServer) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func getFallbackServerName() string {
|
||||
global := file.GetDb().GetGlobal()
|
||||
if global == nil {
|
||||
return ""
|
||||
}
|
||||
serverName := strings.TrimSpace(global.ServerUrl)
|
||||
if serverName == "" {
|
||||
return ""
|
||||
}
|
||||
if strings.Contains(serverName, "://") {
|
||||
if u, err := url.Parse(serverName); err == nil && u.Host != "" {
|
||||
serverName = u.Host
|
||||
}
|
||||
}
|
||||
if i := strings.Index(serverName, "/"); i >= 0 {
|
||||
serverName = serverName[:i]
|
||||
}
|
||||
serverName = common.GetIpByAddr(serverName)
|
||||
serverName = strings.TrimSpace(serverName)
|
||||
if serverName == "" {
|
||||
return ""
|
||||
}
|
||||
ip := net.ParseIP(serverName)
|
||||
if ip != nil && ip.IsUnspecified() {
|
||||
return ""
|
||||
}
|
||||
return serverName
|
||||
}
|
||||
|
||||
func (https *HttpsServer) cert(host *file.Host, c net.Conn, rb []byte, certFileUrl string, keyFileUrl string) {
|
||||
var l *HttpsListener
|
||||
i := 0
|
||||
@@ -225,7 +259,7 @@ func (https *HttpsServer) handleHttps2(c net.Conn, hostName string, rb []byte, r
|
||||
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)
|
||||
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Client.Flow, host.Target.LocalProxy, nil, host)
|
||||
}
|
||||
|
||||
// close
|
||||
@@ -268,7 +302,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.Client.Flow, host.Target.LocalProxy, nil, host)
|
||||
}
|
||||
|
||||
type HttpsListener struct {
|
||||
@@ -300,27 +334,41 @@ func (httpsListener *HttpsListener) Addr() net.Addr {
|
||||
return httpsListener.parentListener.Addr()
|
||||
}
|
||||
|
||||
// get server name from connection by read client hello bytes
|
||||
// get server name from connection by read full client hello bytes
|
||||
func GetServerNameFromClientHello(c net.Conn) (string, []byte) {
|
||||
buf := make([]byte, 4096)
|
||||
data := make([]byte, 4096)
|
||||
n, err := c.Read(buf)
|
||||
header := make([]byte, 5)
|
||||
headerN, err := io.ReadFull(c, header)
|
||||
if err != nil {
|
||||
return "", nil
|
||||
return "", header[:headerN]
|
||||
}
|
||||
if n < 42 {
|
||||
return "", nil
|
||||
if header[0] != 0x16 {
|
||||
return "", header
|
||||
}
|
||||
copy(data, buf[:n])
|
||||
recordLen := int(header[3])<<8 | int(header[4])
|
||||
if recordLen <= 0 || recordLen > 16384 {
|
||||
return "", header
|
||||
}
|
||||
|
||||
body := make([]byte, recordLen)
|
||||
bodyN, err := io.ReadFull(c, body)
|
||||
if err != nil {
|
||||
return "", append(header, body[:bodyN]...)
|
||||
}
|
||||
|
||||
rawBytes := append(header, body...)
|
||||
clientHello := new(crypt.ClientHelloMsg)
|
||||
clientHello.Unmarshal(data[5:n])
|
||||
return clientHello.GetServerName(), buf[:n]
|
||||
if !clientHello.Unmarshal(body) {
|
||||
return "", rawBytes
|
||||
}
|
||||
return clientHello.GetServerName(), rawBytes
|
||||
}
|
||||
|
||||
// build https request
|
||||
// build https request for SNI-based host lookup.
|
||||
// RequestURI is set to "*" to skip Location filtering in GetInfoByHost,
|
||||
// because at TLS handshake stage the actual HTTP request path is unknown.
|
||||
func buildHttpsRequest(hostName string) *http.Request {
|
||||
r := new(http.Request)
|
||||
r.RequestURI = "/"
|
||||
r.RequestURI = "*"
|
||||
r.URL = new(url.URL)
|
||||
r.URL.Scheme = "https"
|
||||
r.Host = hostName
|
||||
|
||||
+68
-14
@@ -108,22 +108,47 @@ func (s *Sock5ModeServer) sendReply(c net.Conn, rep uint8) {
|
||||
// do conn
|
||||
func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) {
|
||||
addrType := make([]byte, 1)
|
||||
c.Read(addrType)
|
||||
if _, err := io.ReadFull(c, addrType); err != nil {
|
||||
logs.Warn("read addr type error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
var host string
|
||||
switch addrType[0] {
|
||||
case ipV4:
|
||||
ipv4 := make(net.IP, net.IPv4len)
|
||||
c.Read(ipv4)
|
||||
if _, err := io.ReadFull(c, ipv4); err != nil {
|
||||
logs.Warn("read ipv4 error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
host = ipv4.String()
|
||||
case ipV6:
|
||||
ipv6 := make(net.IP, net.IPv6len)
|
||||
c.Read(ipv6)
|
||||
if _, err := io.ReadFull(c, ipv6); err != nil {
|
||||
logs.Warn("read ipv6 error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
host = ipv6.String()
|
||||
case domainName:
|
||||
var domainLen uint8
|
||||
binary.Read(c, binary.BigEndian, &domainLen)
|
||||
if err := binary.Read(c, binary.BigEndian, &domainLen); err != nil {
|
||||
logs.Warn("read domain len error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
domain := make([]byte, domainLen)
|
||||
c.Read(domain)
|
||||
if _, err := io.ReadFull(c, domain); err != nil {
|
||||
logs.Warn("read domain error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
host = string(domain)
|
||||
default:
|
||||
s.sendReply(c, addrTypeNotSupported)
|
||||
@@ -131,7 +156,12 @@ func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) {
|
||||
}
|
||||
|
||||
var port uint16
|
||||
binary.Read(c, binary.BigEndian, &port)
|
||||
if err := binary.Read(c, binary.BigEndian, &port); err != nil {
|
||||
logs.Warn("read port error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
// connect to host
|
||||
addr := net.JoinHostPort(host, strconv.Itoa(int(port)))
|
||||
var ltype string
|
||||
@@ -142,7 +172,7 @@ 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, nil, nil)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -176,22 +206,42 @@ func (s *Sock5ModeServer) sendUdpReply(writeConn net.Conn, c net.Conn, rep uint8
|
||||
func (s *Sock5ModeServer) handleUDP(c net.Conn) {
|
||||
defer c.Close()
|
||||
addrType := make([]byte, 1)
|
||||
c.Read(addrType)
|
||||
if _, err := io.ReadFull(c, addrType); err != nil {
|
||||
logs.Warn("read addr type error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
return
|
||||
}
|
||||
var host string
|
||||
switch addrType[0] {
|
||||
case ipV4:
|
||||
ipv4 := make(net.IP, net.IPv4len)
|
||||
c.Read(ipv4)
|
||||
if _, err := io.ReadFull(c, ipv4); err != nil {
|
||||
logs.Warn("read ipv4 error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
return
|
||||
}
|
||||
host = ipv4.String()
|
||||
case ipV6:
|
||||
ipv6 := make(net.IP, net.IPv6len)
|
||||
c.Read(ipv6)
|
||||
if _, err := io.ReadFull(c, ipv6); err != nil {
|
||||
logs.Warn("read ipv6 error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
return
|
||||
}
|
||||
host = ipv6.String()
|
||||
case domainName:
|
||||
var domainLen uint8
|
||||
binary.Read(c, binary.BigEndian, &domainLen)
|
||||
if err := binary.Read(c, binary.BigEndian, &domainLen); err != nil {
|
||||
logs.Warn("read domain len error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
return
|
||||
}
|
||||
domain := make([]byte, domainLen)
|
||||
c.Read(domain)
|
||||
if _, err := io.ReadFull(c, domain); err != nil {
|
||||
logs.Warn("read domain error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
return
|
||||
}
|
||||
host = string(domain)
|
||||
default:
|
||||
s.sendReply(c, addrTypeNotSupported)
|
||||
@@ -199,8 +249,12 @@ func (s *Sock5ModeServer) handleUDP(c net.Conn) {
|
||||
}
|
||||
//读取端口
|
||||
var port uint16
|
||||
binary.Read(c, binary.BigEndian, &port)
|
||||
logs.Warn(host, string(port))
|
||||
if err := binary.Read(c, binary.BigEndian, &port); err != nil {
|
||||
logs.Warn("read port error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
return
|
||||
}
|
||||
logs.Warn(host, strconv.Itoa(int(port)))
|
||||
replyAddr, err := net.ResolveUDPAddr("udp", s.task.ServerIp+":0")
|
||||
if err != nil {
|
||||
logs.Error("build local reply addr error", err)
|
||||
|
||||
+2
-3
@@ -106,8 +106,7 @@ 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.Client.Flow, s.task.Target.LocalProxy, s.task, nil)
|
||||
}
|
||||
|
||||
// http proxy
|
||||
@@ -126,6 +125,6 @@ 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.Client.Flow, s.task.Target.LocalProxy, nil, nil)
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"ehang.io/nps/lib/common"
|
||||
"ehang.io/nps/lib/conn"
|
||||
"ehang.io/nps/lib/file"
|
||||
)
|
||||
|
||||
type tunnelTestBridge struct {
|
||||
target net.Conn
|
||||
}
|
||||
|
||||
func (b *tunnelTestBridge) SendLinkInfo(clientId int, link *conn.Link, t *file.Tunnel) (net.Conn, error) {
|
||||
return b.target, nil
|
||||
}
|
||||
|
||||
func TestProcessTunnelForwardsBufferedBytesWhenAuthProbeFails(t *testing.T) {
|
||||
confPath := t.TempDir()
|
||||
confDir := filepath.Join(confPath, "conf")
|
||||
if err := os.MkdirAll(confDir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range []string{"clients.json", "tasks.json", "hosts.json"} {
|
||||
if err := os.WriteFile(filepath.Join(confDir, name), nil, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
oldConfPath := common.ConfPath
|
||||
common.ConfPath = confPath
|
||||
t.Cleanup(func() {
|
||||
common.ConfPath = oldConfPath
|
||||
})
|
||||
|
||||
clientConn, serverConn := net.Pipe()
|
||||
defer clientConn.Close()
|
||||
defer serverConn.Close()
|
||||
|
||||
targetClient, targetServer := net.Pipe()
|
||||
defer targetClient.Close()
|
||||
defer targetServer.Close()
|
||||
|
||||
client := file.NewClient("test", true, true)
|
||||
client.Id = 1
|
||||
client.Cnf.U = "user"
|
||||
client.Cnf.P = "pass"
|
||||
task := &file.Tunnel{
|
||||
Id: 1,
|
||||
Client: client,
|
||||
Target: &file.Target{
|
||||
TargetStr: "127.0.0.1:22",
|
||||
},
|
||||
}
|
||||
server := NewTunnelModeServer(ProcessTunnel, &tunnelTestBridge{target: targetServer}, task)
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- ProcessTunnel(conn.NewConn(serverConn), server)
|
||||
}()
|
||||
|
||||
payload := []byte("SSH-2.0-OpenSSH_9.0\r\n")
|
||||
if _, err := clientConn.Write(payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := targetClient.SetReadDeadline(time.Now().Add(time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := make([]byte, len(payload))
|
||||
if _, err := io.ReadFull(targetClient, got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatalf("expected forwarded payload %q, got %q", payload, got)
|
||||
}
|
||||
|
||||
clientConn.Close()
|
||||
targetClient.Close()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("ProcessTunnel did not exit after connections closed")
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,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, nil, nil)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+198
-56
@@ -5,6 +5,7 @@ import (
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"ehang.io/nps/bridge"
|
||||
@@ -14,20 +15,51 @@ import (
|
||||
"github.com/astaxie/beego/logs"
|
||||
)
|
||||
|
||||
const (
|
||||
udpSessionIdleTimeout = 120 * time.Second
|
||||
udpSweepInterval = 30 * time.Second
|
||||
udpReadDeadline = 60 * time.Second
|
||||
udpBuildTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
// udpSession 代表一个客户端 src addr ↔ npc 之间的 UDP 转发会话。
|
||||
//
|
||||
// 同一个 src addr 在并发场景下可能被多个 goroutine 同时尝试建立会话。为避免
|
||||
// 重复建立,采用"原子占位"模式:第一个 goroutine 通过 sync.Map.LoadOrStore
|
||||
// 占位(此时 ready 通道未关闭),后续 goroutine 检测到占位后阻塞在 ready
|
||||
// 通道上等待会话就绪,然后复用同一个 target 转发数据。这样:
|
||||
// - 同一 src addr 始终只有 1 条到 npc 的 mux stream
|
||||
// - 只有"赢家"消耗一个 NowConn 配额,输家不再重复占用
|
||||
// - 避免了 race window 期间的 NowConn 配额泄漏
|
||||
type udpSession struct {
|
||||
target io.ReadWriteCloser // 用于 Read/Write 的封装层(可能含加密/压缩)
|
||||
rawConn net.Conn // 底层 mux conn,用于 SetReadDeadline
|
||||
lastActive int64 // 最近活跃时间(unix nano,原子读写)
|
||||
ready chan struct{} // 会话就绪后关闭;建立失败时也关闭
|
||||
err error // 建立失败时设置;ready 关闭后才允许读
|
||||
}
|
||||
|
||||
func (u *udpSession) touch() {
|
||||
atomic.StoreInt64(&u.lastActive, time.Now().UnixNano())
|
||||
}
|
||||
|
||||
type UdpModeServer struct {
|
||||
BaseServer
|
||||
addrMap sync.Map
|
||||
listener *net.UDPConn
|
||||
addrMap sync.Map
|
||||
listener *net.UDPConn
|
||||
closeOnce sync.Once
|
||||
closeCh chan struct{}
|
||||
}
|
||||
|
||||
func NewUdpModeServer(bridge *bridge.Bridge, task *file.Tunnel) *UdpModeServer {
|
||||
s := new(UdpModeServer)
|
||||
s.bridge = bridge
|
||||
s.task = task
|
||||
s.closeCh = make(chan struct{})
|
||||
return s
|
||||
}
|
||||
|
||||
// 开始
|
||||
// Start 启动 UDP 监听,主循环只负责快速收包并分发,不做任何耗时操作。
|
||||
func (s *UdpModeServer) Start() error {
|
||||
var err error
|
||||
if s.task.ServerIp == "" {
|
||||
@@ -37,90 +69,200 @@ func (s *UdpModeServer) Start() error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
go s.sweeper()
|
||||
for {
|
||||
buf := common.BufPoolUdp.Get().([]byte)
|
||||
n, addr, err := s.listener.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
common.BufPoolUdp.Put(buf)
|
||||
if strings.Contains(err.Error(), "use of closed network connection") {
|
||||
break
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// 判断访问地址是否在全局黑名单内
|
||||
if IsGlobalBlackIp(addr.String()) {
|
||||
break
|
||||
common.BufPoolUdp.Put(buf)
|
||||
continue
|
||||
}
|
||||
|
||||
// 判断访问地址是否在黑名单内
|
||||
if common.IsBlackIp(addr.String(), s.task.Client.VerifyKey, s.task.Client.BlackIpList) {
|
||||
break
|
||||
common.BufPoolUdp.Put(buf)
|
||||
continue
|
||||
}
|
||||
|
||||
logs.Trace("New udp connection,client %d,remote address %s", s.task.Client.Id, addr)
|
||||
go s.process(addr, buf[:n])
|
||||
go s.process(addr, buf, n)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
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)
|
||||
// process 处理单个 UDP 包。函数持有 buf 的所有权,所有路径必须归还。
|
||||
func (s *UdpModeServer) process(addr *net.UDPAddr, buf []byte, n int) {
|
||||
key := addr.String()
|
||||
data := buf[:n]
|
||||
|
||||
// 快路径:会话已存在
|
||||
if v, ok := s.addrMap.Load(key); ok {
|
||||
s.dispatch(key, v.(*udpSession), data, n)
|
||||
common.BufPoolUdp.Put(buf)
|
||||
return
|
||||
}
|
||||
|
||||
// 慢路径:尝试成为该 key 的"会话建立者"
|
||||
placeholder := &udpSession{ready: make(chan struct{})}
|
||||
placeholder.touch()
|
||||
if existing, loaded := s.addrMap.LoadOrStore(key, placeholder); loaded {
|
||||
// 输了占位竞争,等赢家把会话建好后复用
|
||||
s.dispatch(key, existing.(*udpSession), data, n)
|
||||
common.BufPoolUdp.Put(buf)
|
||||
return
|
||||
}
|
||||
|
||||
// 赢得占位 —— 我去建立会话
|
||||
s.runSession(addr, key, placeholder, buf, n)
|
||||
}
|
||||
|
||||
// dispatch 把数据写入 sess.target。若 sess 仍在建立中则阻塞等待,超时则丢包。
|
||||
func (s *UdpModeServer) dispatch(key string, sess *udpSession, data []byte, n int) {
|
||||
if sess.ready != nil {
|
||||
select {
|
||||
case <-sess.ready:
|
||||
if sess.err != nil {
|
||||
logs.Trace("udp session build failed for %s: %v", key, sess.err)
|
||||
return
|
||||
}
|
||||
s.task.Client.Flow.Add(int64(len(data)), int64(len(data)))
|
||||
}
|
||||
} else {
|
||||
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())
|
||||
case <-time.After(udpBuildTimeout):
|
||||
logs.Warn("udp session build timeout for %s, drop packet", key)
|
||||
return
|
||||
case <-s.closeCh:
|
||||
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, "")
|
||||
if clientConn, err := s.bridge.SendLinkInfo(s.task.Client.Id, link, s.task); err != nil {
|
||||
}
|
||||
if _, err := sess.target.Write(data); err != nil {
|
||||
logs.Warn(err)
|
||||
s.removeSession(key, sess)
|
||||
return
|
||||
}
|
||||
sess.touch()
|
||||
s.task.Client.Flow.Add(int64(n), int64(n))
|
||||
s.task.Flow.Add(int64(n), int64(n))
|
||||
}
|
||||
|
||||
// runSession 由占位赢家执行:建立到 npc 的 stream、发送首包、运行下行读循环。
|
||||
// buf 由本函数负责归还。
|
||||
func (s *UdpModeServer) runSession(addr *net.UDPAddr, key string, sess *udpSession, buf []byte, n int) {
|
||||
data := buf[:n]
|
||||
|
||||
// 失败时统一清理:关 ready 通道唤醒所有输家、删占位、归还 buf。
|
||||
failBuild := func(err error) {
|
||||
sess.err = err
|
||||
close(sess.ready)
|
||||
s.addrMap.Delete(key)
|
||||
common.BufPoolUdp.Put(buf)
|
||||
}
|
||||
|
||||
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())
|
||||
failBuild(err)
|
||||
return
|
||||
}
|
||||
// 只有赢家消耗 NowConn 配额,函数返回时释放。
|
||||
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, "")
|
||||
clientConn, err := s.bridge.SendLinkInfo(s.task.Client.Id, link, s.task)
|
||||
if err != nil {
|
||||
failBuild(err)
|
||||
return
|
||||
}
|
||||
|
||||
target := conn.GetConn(clientConn, s.task.Client.Cnf.Crypt, s.task.Client.Cnf.Compress, nil, true)
|
||||
sess.target = target
|
||||
sess.rawConn = clientConn
|
||||
sess.touch()
|
||||
close(sess.ready) // 唤醒所有等待该会话的输家
|
||||
|
||||
defer s.removeSession(key, sess)
|
||||
|
||||
logs.Trace("New udp connection,client %d,remote address %s", s.task.Client.Id, addr)
|
||||
|
||||
if _, err := target.Write(data); err != nil {
|
||||
logs.Warn(err)
|
||||
common.BufPoolUdp.Put(buf)
|
||||
return
|
||||
}
|
||||
common.BufPoolUdp.Put(buf)
|
||||
s.task.Client.Flow.Add(int64(n), int64(n))
|
||||
s.task.Flow.Add(int64(n), int64(n))
|
||||
|
||||
// 下行读循环
|
||||
rbuf := common.BufPoolUdp.Get().([]byte)
|
||||
defer common.BufPoolUdp.Put(rbuf)
|
||||
|
||||
for {
|
||||
// 设到 rawConn 上:mux stream 的 SetReadDeadline 是底层 net.Conn 实现,
|
||||
// 比设在加密/压缩包装层 target 上更可靠。
|
||||
clientConn.SetReadDeadline(time.Now().Add(udpReadDeadline))
|
||||
rn, err := target.Read(rbuf)
|
||||
if err != nil {
|
||||
// sweeper 主动 Close、idle deadline 触发、或对端断开都会落到这里
|
||||
return
|
||||
} else {
|
||||
target := conn.GetConn(clientConn, s.task.Client.Cnf.Crypt, s.task.Client.Cnf.Compress, nil, true)
|
||||
s.addrMap.Store(addr.String(), target)
|
||||
defer target.Close()
|
||||
}
|
||||
sess.touch()
|
||||
if _, err := s.listener.WriteTo(rbuf[:rn], addr); err != nil {
|
||||
logs.Warn(err)
|
||||
return
|
||||
}
|
||||
s.task.Client.Flow.Add(int64(rn), int64(rn))
|
||||
s.task.Flow.Add(int64(rn), int64(rn))
|
||||
}
|
||||
}
|
||||
|
||||
_, err := target.Write(data)
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
return
|
||||
}
|
||||
// removeSession 安全地从 addrMap 移除并关闭会话。
|
||||
// 用 == 比对避免误删被替换的新 session(虽然当前协议不会发生,但保持防御性)。
|
||||
func (s *UdpModeServer) removeSession(key string, sess *udpSession) {
|
||||
if v, ok := s.addrMap.Load(key); ok && v.(*udpSession) == sess {
|
||||
s.addrMap.Delete(key)
|
||||
}
|
||||
if sess.target != nil {
|
||||
sess.target.Close()
|
||||
}
|
||||
}
|
||||
|
||||
buf := common.BufPoolUdp.Get().([]byte)
|
||||
defer common.BufPoolUdp.Put(buf)
|
||||
|
||||
s.task.Client.Flow.Add(int64(len(data)), int64(len(data)))
|
||||
for {
|
||||
clientConn.SetReadDeadline(time.Now().Add(time.Duration(60) * time.Second))
|
||||
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))
|
||||
// sweeper 周期性扫描 addrMap,把空闲超过 udpSessionIdleTimeout 的会话清掉。
|
||||
// 关闭 target 会让阻塞中的 target.Read 立即返回错误,让对应的 runSession
|
||||
// 走 defer 链路自然退出(释放 NowConn 配额、删 addrMap 条目)。
|
||||
func (s *UdpModeServer) sweeper() {
|
||||
ticker := time.NewTicker(udpSweepInterval)
|
||||
defer ticker.Stop()
|
||||
idleNs := int64(udpSessionIdleTimeout)
|
||||
for {
|
||||
select {
|
||||
case <-s.closeCh:
|
||||
return
|
||||
case <-ticker.C:
|
||||
now := time.Now().UnixNano()
|
||||
s.addrMap.Range(func(k, v interface{}) bool {
|
||||
sess := v.(*udpSession)
|
||||
// 跳过仍在建立中的占位(target 尚未填充)
|
||||
if sess.target == nil {
|
||||
return true
|
||||
}
|
||||
//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
|
||||
//}
|
||||
}
|
||||
if now-atomic.LoadInt64(&sess.lastActive) > idleNs {
|
||||
s.removeSession(k.(string), sess)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *UdpModeServer) Close() error {
|
||||
s.closeOnce.Do(func() {
|
||||
close(s.closeCh)
|
||||
})
|
||||
s.addrMap.Range(func(k, v interface{}) bool {
|
||||
s.removeSession(k.(string), v.(*udpSession))
|
||||
return true
|
||||
})
|
||||
return s.listener.Close()
|
||||
}
|
||||
|
||||
@@ -257,7 +257,7 @@ func Join(c1 io.ReadWriteCloser, c2 io.ReadWriteCloser, host *file.Host) (inCoun
|
||||
defer to.Close()
|
||||
defer from.Close()
|
||||
defer wait.Done()
|
||||
goroutine.CopyBuffer(to, from, host.Client.Flow, nil, "")
|
||||
goroutine.CopyBuffer(to, from, host.Client.Flow, nil, host, "")
|
||||
//*count, _ = io.Copy(to, from)
|
||||
}
|
||||
|
||||
|
||||
+92
-58
@@ -57,7 +57,7 @@ func DealBridgeTask() {
|
||||
for {
|
||||
select {
|
||||
case t := <-Bridge.OpenTask:
|
||||
AddTask(t)
|
||||
StartTask(t.Id)
|
||||
case t := <-Bridge.CloseTask:
|
||||
StopServer(t.Id)
|
||||
case id := <-Bridge.CloseClient:
|
||||
@@ -67,13 +67,11 @@ func DealBridgeTask() {
|
||||
file.GetDb().DelClient(id)
|
||||
}
|
||||
}
|
||||
case tunnel := <-Bridge.OpenTask:
|
||||
StartTask(tunnel.Id)
|
||||
case s := <-Bridge.SecretChan:
|
||||
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, nil, nil)
|
||||
} else {
|
||||
s.Conn.Close()
|
||||
logs.Trace("This key %s cannot be processed,status is close", s.Password)
|
||||
@@ -89,6 +87,12 @@ func DealBridgeTask() {
|
||||
// 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)
|
||||
// 启动流量持久化(只启动一次,避免每次 AddTask 创建泄漏的 goroutine)
|
||||
if minute, err := beego.AppConfig.Int("flow_store_interval"); err == nil && minute > 0 {
|
||||
go flowSession(time.Minute * time.Duration(minute))
|
||||
}
|
||||
// 启动后台 IO 速率采集,Dashboard 直接读缓存,无需 Sleep
|
||||
tool.StartIORateCollector()
|
||||
go func() {
|
||||
if err := Bridge.StartTunnel(); err != nil {
|
||||
logs.Error("start server bridge error", err)
|
||||
@@ -102,6 +106,7 @@ func StartNewServer(bridgePort int, cnf *file.Tunnel, bridgeType string, bridgeD
|
||||
}
|
||||
go DealBridgeTask()
|
||||
go dealClientFlow()
|
||||
go dealClientExpire()
|
||||
if svr := NewMode(Bridge, cnf); svr != nil {
|
||||
if err := svr.Start(); err != nil {
|
||||
logs.Error(err)
|
||||
@@ -124,6 +129,50 @@ func dealClientFlow() {
|
||||
}
|
||||
}
|
||||
|
||||
// dealClientExpire 周期性扫描客户端到期时间,过期则自动暂停
|
||||
func dealClientExpire() {
|
||||
// 启动时立即检查一次,避免重启后到期客户端最多 1 分钟内才被暂停
|
||||
checkClientExpire()
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
checkClientExpire()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkClientExpire 遍历所有客户端,若 ExpireTime 已过则将 Status 置为 false 并断开连接
|
||||
func checkClientExpire() {
|
||||
now := time.Now()
|
||||
changed := false
|
||||
file.GetDb().JsonDb.Clients.Range(func(key, value interface{}) bool {
|
||||
v, ok := value.(*file.Client)
|
||||
if !ok || v == nil {
|
||||
return true
|
||||
}
|
||||
if v.ExpireTime == "" || !v.Status {
|
||||
return true
|
||||
}
|
||||
t, err := time.ParseInLocation("2006-01-02 15:04:05", v.ExpireTime, time.Local)
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
if now.Before(t) {
|
||||
return true
|
||||
}
|
||||
v.Status = false
|
||||
changed = true
|
||||
logs.Info("client id %d (remark: %s) expired at %s, auto paused", v.Id, v.Remark, v.ExpireTime)
|
||||
DelClientConnect(v.Id)
|
||||
return true
|
||||
})
|
||||
if changed {
|
||||
file.GetDb().JsonDb.StoreClientsToJsonFile()
|
||||
}
|
||||
}
|
||||
|
||||
// new a server by mode name
|
||||
func NewMode(Bridge *bridge.Bridge, c *file.Tunnel) proxy.Service {
|
||||
var service proxy.Service
|
||||
@@ -160,25 +209,20 @@ func NewMode(Bridge *bridge.Bridge, c *file.Tunnel) proxy.Service {
|
||||
|
||||
// stop server
|
||||
func StopServer(id int) error {
|
||||
//if v, ok := RunList[id]; ok {
|
||||
if v, ok := RunList.Load(id); ok {
|
||||
if svr, ok := v.(proxy.Service); ok {
|
||||
if err := svr.Close(); err != nil {
|
||||
return err
|
||||
logs.Error("stop server id %d error", id, err)
|
||||
}
|
||||
logs.Info("stop server id %d", id)
|
||||
} else {
|
||||
logs.Warn("stop server id %d error", id)
|
||||
}
|
||||
if t, err := file.GetDb().GetTask(id); err != nil {
|
||||
return err
|
||||
} else {
|
||||
RunList.Delete(id)
|
||||
if t, err := file.GetDb().GetTask(id); err == nil {
|
||||
t.Status = false
|
||||
logs.Info("close port %d,remark %s,client id %d,task id %d", t.Port, t.Remark, t.Client.Id, t.Id)
|
||||
file.GetDb().UpdateTask(t)
|
||||
}
|
||||
//delete(RunList, id)
|
||||
RunList.Delete(id)
|
||||
return nil
|
||||
}
|
||||
return errors.New("task is not running")
|
||||
@@ -196,9 +240,6 @@ func AddTask(t *file.Tunnel) error {
|
||||
logs.Error("taskId %d start error port %d open failed", t.Id, t.Port)
|
||||
return errors.New("the port open error")
|
||||
}
|
||||
if minute, err := beego.AppConfig.Int("flow_store_interval"); err == nil && minute > 0 {
|
||||
go flowSession(time.Minute * time.Duration(minute))
|
||||
}
|
||||
if svr := NewMode(Bridge, t); svr != nil {
|
||||
logs.Info("tunnel task %s start mode:%s port %d", t.Remark, t.Mode, t.Port)
|
||||
//RunList[t.Id] = svr
|
||||
@@ -245,18 +286,16 @@ func GetTunnel(start, length int, typeVal string, clientId int, search string, s
|
||||
all_list := make([]*file.Tunnel, 0) //store all Tunnel
|
||||
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)
|
||||
// 单次遍历收集所有符合条件的 Tunnel(修复原代码双重遍历 sync.Map 的性能问题)
|
||||
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
v := value.(*file.Tunnel)
|
||||
if (typeVal != "" && v.Mode != typeVal || (clientId != 0 && v.Client.Id != clientId)) || (typeVal == "" && clientId != v.Client.Id) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
all_list = append(all_list, v)
|
||||
return true
|
||||
})
|
||||
//sort by Id, Remark, TargetStr, Port, asc or desc
|
||||
if sortField == "Id" {
|
||||
if order == "asc" {
|
||||
@@ -290,31 +329,25 @@ func GetTunnel(start, length int, typeVal string, clientId int, search string, s
|
||||
}
|
||||
}
|
||||
|
||||
//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)) {
|
||||
continue
|
||||
}
|
||||
cnt++
|
||||
if _, ok := Bridge.Client.Load(v.Client.Id); ok {
|
||||
v.Client.IsConnect = true
|
||||
} else {
|
||||
v.Client.IsConnect = false
|
||||
}
|
||||
if start--; start < 0 {
|
||||
if length--; length >= 0 {
|
||||
if _, ok := RunList.Load(v.Id); ok {
|
||||
v.RunStatus = true
|
||||
} else {
|
||||
v.RunStatus = false
|
||||
}
|
||||
list = append(list, v)
|
||||
//search and paginate(直接在已排序的列表上操作,避免二次 Load)
|
||||
for _, v := range all_list {
|
||||
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)) {
|
||||
continue
|
||||
}
|
||||
cnt++
|
||||
if _, ok := Bridge.Client.Load(v.Client.Id); ok {
|
||||
v.Client.IsConnect = true
|
||||
} else {
|
||||
v.Client.IsConnect = false
|
||||
}
|
||||
if start--; start < 0 {
|
||||
if length--; length >= 0 {
|
||||
if _, ok := RunList.Load(v.Id); ok {
|
||||
v.RunStatus = true
|
||||
} else {
|
||||
v.RunStatus = false
|
||||
}
|
||||
list = append(list, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -457,25 +490,26 @@ func GetDashboardData() map[string]interface{} {
|
||||
data["swap_mem"] = math.Round(swap.UsedPercent)
|
||||
vir, _ := mem.VirtualMemory()
|
||||
data["virtual_mem"] = math.Round(vir.UsedPercent)
|
||||
conn, _ := net.ProtoCounters(nil)
|
||||
io1, _ := net.IOCounters(false)
|
||||
time.Sleep(time.Millisecond * 500)
|
||||
io2, _ := net.IOCounters(false)
|
||||
if len(io2) > 0 && len(io1) > 0 {
|
||||
data["io_send"] = (io2[0].BytesSent - io1[0].BytesSent) * 2
|
||||
data["io_recv"] = (io2[0].BytesRecv - io1[0].BytesRecv) * 2
|
||||
// IO 速率从后台缓存读取,无需 Sleep 500ms
|
||||
if cached, ok := tool.IORateCache.Load().(map[string]uint64); ok {
|
||||
data["io_send"] = cached["io_send"]
|
||||
data["io_recv"] = cached["io_recv"]
|
||||
}
|
||||
conn, _ := net.ProtoCounters(nil)
|
||||
for _, v := range conn {
|
||||
data[v.Protocol] = v.Stats["CurrEstab"]
|
||||
}
|
||||
//chart
|
||||
var fg int
|
||||
if len(tool.ServerStatus) >= 10 {
|
||||
fg = len(tool.ServerStatus) / 10
|
||||
tool.ServerStatusMu.RLock()
|
||||
statusLen := len(tool.ServerStatus)
|
||||
if statusLen >= 10 {
|
||||
fg = statusLen / 10
|
||||
for i := 0; i <= 9; i++ {
|
||||
data["sys"+strconv.Itoa(i+1)] = tool.ServerStatus[i*fg]
|
||||
}
|
||||
}
|
||||
tool.ServerStatusMu.RUnlock()
|
||||
return data
|
||||
}
|
||||
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"log"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
"ehang.io/nps/lib/common"
|
||||
"ehang.io/nps/lib/file"
|
||||
"github.com/astaxie/beego"
|
||||
)
|
||||
|
||||
func TestServerConfig() {
|
||||
var postTcpArr []int
|
||||
var postUdpArr []int
|
||||
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
v := value.(*file.Tunnel)
|
||||
if v.Mode == "udp" {
|
||||
isInArr(&postUdpArr, v.Port, v.Remark, "udp")
|
||||
} else if v.Port != 0 {
|
||||
|
||||
isInArr(&postTcpArr, v.Port, v.Remark, "tcp")
|
||||
}
|
||||
return true
|
||||
})
|
||||
p, err := beego.AppConfig.Int("web_port")
|
||||
if err != nil {
|
||||
log.Fatalln("Getting web management port error :", err)
|
||||
} else {
|
||||
isInArr(&postTcpArr, p, "Web Management port", "tcp")
|
||||
}
|
||||
|
||||
if p := beego.AppConfig.String("bridge_port"); p != "" {
|
||||
if port, err := strconv.Atoi(p); err != nil {
|
||||
log.Fatalln("get Server and client communication portserror:", err)
|
||||
} else if beego.AppConfig.String("bridge_type") == "kcp" {
|
||||
isInArr(&postUdpArr, port, "Server and client communication ports", "udp")
|
||||
} else {
|
||||
isInArr(&postTcpArr, port, "Server and client communication ports", "tcp")
|
||||
}
|
||||
}
|
||||
|
||||
if p := beego.AppConfig.String("httpProxyPort"); p != "" {
|
||||
if port, err := strconv.Atoi(p); err != nil {
|
||||
log.Fatalln("get http port error:", err)
|
||||
} else {
|
||||
isInArr(&postTcpArr, port, "https port", "tcp")
|
||||
}
|
||||
}
|
||||
if p := beego.AppConfig.String("https_proxy_port"); p != "" {
|
||||
if b, err := beego.AppConfig.Bool("https_just_proxy"); !(err == nil && b) {
|
||||
if port, err := strconv.Atoi(p); err != nil {
|
||||
log.Fatalln("get https port error", err)
|
||||
} else {
|
||||
if beego.AppConfig.String("pemPath") != "" && !common.FileExists(filepath.Join(common.GetRunPath(), beego.AppConfig.String("pemPath"))) {
|
||||
log.Fatalf("ssl certFile %s is not exist", beego.AppConfig.String("pemPath"))
|
||||
}
|
||||
if beego.AppConfig.String("keyPath") != "" && !common.FileExists(filepath.Join(common.GetRunPath(), beego.AppConfig.String("keyPath"))) {
|
||||
log.Fatalf("ssl keyFile %s is not exist", beego.AppConfig.String("pemPath"))
|
||||
}
|
||||
isInArr(&postTcpArr, port, "http port", "tcp")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func isInArr(arr *[]int, val int, remark string, tp string) {
|
||||
for _, v := range *arr {
|
||||
if v == val {
|
||||
log.Fatalf("the port %d is reused,remark: %s", val, remark)
|
||||
}
|
||||
}
|
||||
if tp == "tcp" {
|
||||
if !common.TestTcpPort(val) {
|
||||
log.Fatalf("open the %d port error ,remark: %s", val, remark)
|
||||
}
|
||||
} else {
|
||||
if !common.TestUdpPort(val) {
|
||||
log.Fatalf("open the %d port error ,remark: %s", val, remark)
|
||||
}
|
||||
}
|
||||
*arr = append(*arr, val)
|
||||
return
|
||||
}
|
||||
+59
-9
@@ -4,6 +4,8 @@ import (
|
||||
"math"
|
||||
"math/rand"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"ehang.io/nps/lib/common"
|
||||
@@ -15,8 +17,10 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ports []int
|
||||
ServerStatus []map[string]interface{}
|
||||
ports []int
|
||||
ServerStatus []map[string]interface{}
|
||||
ServerStatusMu sync.RWMutex
|
||||
IORateCache atomic.Value
|
||||
)
|
||||
|
||||
func StartSystemInfo() {
|
||||
@@ -52,7 +56,7 @@ func TestServerPort(p int, m string) (b bool) {
|
||||
}
|
||||
|
||||
func GenerateServerPort(m string) int {
|
||||
for {
|
||||
for i := 0; i < 1000; i++ {
|
||||
//生成随机数 1024 - 65535
|
||||
serverPort := rand.Intn(65535)
|
||||
if serverPort < 1024 {
|
||||
@@ -63,6 +67,7 @@ func GenerateServerPort(m string) int {
|
||||
return serverPort
|
||||
}
|
||||
}
|
||||
return 0 // 超过最大重试次数,返回0表示无法分配端口
|
||||
}
|
||||
|
||||
func getSeverStatus() {
|
||||
@@ -88,12 +93,9 @@ func getSeverStatus() {
|
||||
vir, _ := mem.VirtualMemory()
|
||||
m["virtual_mem"] = math.Round(vir.UsedPercent)
|
||||
conn, _ := net.ProtoCounters(nil)
|
||||
io1, _ := net.IOCounters(false)
|
||||
time.Sleep(time.Millisecond * 500)
|
||||
io2, _ := net.IOCounters(false)
|
||||
if len(io2) > 0 && len(io1) > 0 {
|
||||
m["io_send"] = (io2[0].BytesSent - io1[0].BytesSent) * 2
|
||||
m["io_recv"] = (io2[0].BytesRecv - io1[0].BytesRecv) * 2
|
||||
if cached, ok := IORateCache.Load().(map[string]uint64); ok {
|
||||
m["io_send"] = cached["io_send"]
|
||||
m["io_recv"] = cached["io_recv"]
|
||||
}
|
||||
t := time.Now()
|
||||
m["time"] = strconv.Itoa(t.Hour()) + ":" + strconv.Itoa(t.Minute()) + ":" + strconv.Itoa(t.Second())
|
||||
@@ -102,8 +104,56 @@ func getSeverStatus() {
|
||||
m[v.Protocol] = v.Stats["CurrEstab"]
|
||||
}
|
||||
if len(ServerStatus) >= 1440 {
|
||||
ServerStatusMu.Lock()
|
||||
ServerStatus = ServerStatus[1:]
|
||||
ServerStatusMu.Unlock()
|
||||
}
|
||||
ServerStatusMu.Lock()
|
||||
ServerStatus = append(ServerStatus, m)
|
||||
ServerStatusMu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// StartIORateCollector 启动后台 IO 速率采集,每 2s 刷新一次 IORateCache
|
||||
func StartIORateCollector() {
|
||||
go collectIORate()
|
||||
}
|
||||
|
||||
func collectIORate() {
|
||||
var lastSent, lastRecv uint64
|
||||
// 修复:无论首次 IOCounters 是否成功,都把 lastTime 设为 now,
|
||||
// 否则首次有效采样的 elapsed 会是几十年,导致 sendRate/recvRate 直接为 0
|
||||
lastTime := time.Now()
|
||||
if io, err := net.IOCounters(false); err == nil && len(io) > 0 {
|
||||
lastSent = io[0].BytesSent
|
||||
lastRecv = io[0].BytesRecv
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(2 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
now := time.Now()
|
||||
io, err := net.IOCounters(false)
|
||||
if err != nil || len(io) == 0 {
|
||||
continue
|
||||
}
|
||||
elapsed := now.Sub(lastTime).Seconds()
|
||||
if elapsed <= 0 {
|
||||
continue
|
||||
}
|
||||
var sendRate, recvRate uint64
|
||||
if io[0].BytesSent >= lastSent {
|
||||
sendRate = uint64(float64(io[0].BytesSent-lastSent) / elapsed)
|
||||
}
|
||||
if io[0].BytesRecv >= lastRecv {
|
||||
recvRate = uint64(float64(io[0].BytesRecv-lastRecv) / elapsed)
|
||||
}
|
||||
lastSent = io[0].BytesSent
|
||||
lastRecv = io[0].BytesRecv
|
||||
lastTime = now
|
||||
IORateCache.Store(map[string]uint64{
|
||||
"io_send": sendRate,
|
||||
"io_recv": recvRate,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"ehang.io/nps/lib/common"
|
||||
"ehang.io/nps/lib/crypt"
|
||||
"ehang.io/nps/lib/file"
|
||||
"ehang.io/nps/lib/version"
|
||||
"ehang.io/nps/server"
|
||||
"github.com/astaxie/beego"
|
||||
)
|
||||
@@ -55,7 +56,6 @@ func (s *BaseController) Prepare() {
|
||||
} else {
|
||||
s.Data["isAdmin"] = true
|
||||
}
|
||||
s.Data["https_just_proxy"], _ = beego.AppConfig.Bool("https_just_proxy")
|
||||
s.Data["allow_user_login"], _ = beego.AppConfig.Bool("allow_user_login")
|
||||
s.Data["allow_flow_limit"], _ = beego.AppConfig.Bool("allow_flow_limit")
|
||||
s.Data["allow_rate_limit"], _ = beego.AppConfig.Bool("allow_rate_limit")
|
||||
@@ -65,9 +65,10 @@ func (s *BaseController) Prepare() {
|
||||
s.Data["allow_tunnel_num_limit"], _ = beego.AppConfig.Bool("allow_tunnel_num_limit")
|
||||
s.Data["allow_local_proxy"], _ = beego.AppConfig.Bool("allow_local_proxy")
|
||||
s.Data["allow_user_change_username"], _ = beego.AppConfig.Bool("allow_user_change_username")
|
||||
showHttpProxyPort := beego.AppConfig.DefaultBool("show_http_proxy_port", true)
|
||||
httpPort := beego.AppConfig.String("http_proxy_port")
|
||||
if httpPort != "80" {
|
||||
s.Data["http_proxy_port"] = ":" + beego.AppConfig.String("http_proxy_port")
|
||||
if httpPort != "80" && showHttpProxyPort {
|
||||
s.Data["http_proxy_port"] = ":" + httpPort
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,10 +98,13 @@ func (s *BaseController) display(tpl ...string) {
|
||||
|
||||
s.Data["bridgeType"] = beego.AppConfig.String("bridge_type")
|
||||
if common.IsWindows() {
|
||||
s.Data["win"] = ".exe"
|
||||
s.Data["win"] = "npc.exe"
|
||||
} else {
|
||||
s.Data["win"] = "./npc"
|
||||
}
|
||||
|
||||
s.Data["p"] = strconv.Itoa(server.Bridge.TunnelPort)
|
||||
s.Data["version"] = version.VERSION
|
||||
|
||||
if bridge.ServerTlsEnable {
|
||||
tlsPort := strconv.Itoa(beego.AppConfig.DefaultInt("tls_bridge_port", 8025))
|
||||
|
||||
@@ -73,6 +73,7 @@ func (s *ClientController) Add() {
|
||||
IpWhite: s.GetBoolNoErr("ipwhite"),
|
||||
IpWhitePass: s.getEscapeString("ipwhitepass"),
|
||||
IpWhiteList: RemoveRepeatedElement(strings.Split(s.getEscapeString("ipwhitelist"), "\r\n")),
|
||||
ExpireTime: normalizeExpireTime(s.getEscapeString("expire_time")),
|
||||
CreateTime: time.Now().Format("2006-01-02 15:04:05"),
|
||||
}
|
||||
if err := file.GetDb().NewClient(t); err != nil {
|
||||
@@ -159,6 +160,7 @@ func (s *ClientController) Edit() {
|
||||
}
|
||||
|
||||
c.BlackIpList = RemoveRepeatedElement(strings.Split(s.getEscapeString("blackiplist"), "\r\n"))
|
||||
c.ExpireTime = normalizeExpireTime(s.getEscapeString("expire_time"))
|
||||
file.GetDb().JsonDb.StoreClientsToJsonFile()
|
||||
}
|
||||
s.AjaxOk("save success")
|
||||
@@ -186,6 +188,39 @@ func RemoveRepeatedElement(arr []string) (newArr []string) {
|
||||
return
|
||||
}
|
||||
|
||||
// expireTimeFormats 支持的到期时间输入格式
|
||||
var expireTimeFormats = []string{
|
||||
"2006-01-02 15:04:05",
|
||||
"2006-01-02 15:04",
|
||||
"2006-01-02T15:04:05",
|
||||
"2006-01-02T15:04",
|
||||
"2006-01-02",
|
||||
}
|
||||
|
||||
// ParseExpireTime 将多种格式的到期时间字符串解析为 time.Time
|
||||
// 留空或无法解析返回 ok=false
|
||||
func ParseExpireTime(s string) (time.Time, bool) {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return time.Time{}, false
|
||||
}
|
||||
for _, f := range expireTimeFormats {
|
||||
if t, err := time.ParseInLocation(f, s, time.Local); err == nil {
|
||||
return t, true
|
||||
}
|
||||
}
|
||||
return time.Time{}, false
|
||||
}
|
||||
|
||||
// normalizeExpireTime 将用户提交的到期时间统一为 "2006-01-02 15:04:05"
|
||||
// 无法解析则返回空串表示不限制
|
||||
func normalizeExpireTime(s string) string {
|
||||
if t, ok := ParseExpireTime(s); ok {
|
||||
return t.Format("2006-01-02 15:04:05")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// 更改状态
|
||||
func (s *ClientController) ChangeStatus() {
|
||||
id := s.GetIntNoErr("id")
|
||||
|
||||
@@ -301,6 +301,26 @@ func (s *IndexController) DelHost() {
|
||||
s.AjaxOk("delete success")
|
||||
}
|
||||
|
||||
func (s *IndexController) HostStop() {
|
||||
id := s.GetIntNoErr("id")
|
||||
if h, err := file.GetDb().GetHostById(id); err != nil {
|
||||
s.AjaxErr("stop error")
|
||||
} else {
|
||||
h.IsClose = true
|
||||
}
|
||||
s.AjaxOk("stop success")
|
||||
}
|
||||
|
||||
func (s *IndexController) HostStart() {
|
||||
id := s.GetIntNoErr("id")
|
||||
if h, err := file.GetDb().GetHostById(id); err != nil {
|
||||
s.AjaxErr("start error")
|
||||
} else {
|
||||
h.IsClose = false
|
||||
}
|
||||
s.AjaxOk("start success")
|
||||
}
|
||||
|
||||
func (s *IndexController) AddHost() {
|
||||
if s.Ctx.Request.Method == "GET" {
|
||||
s.Data["client_id"] = s.getEscapeString("client_id")
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"ehang.io/nps/lib/common"
|
||||
"github.com/astaxie/beego/logs"
|
||||
)
|
||||
|
||||
//go:embed static
|
||||
var StaticFS embed.FS
|
||||
|
||||
//go:embed views
|
||||
var ViewsFS embed.FS
|
||||
|
||||
func ExtractWebFiles(runPath string) {
|
||||
webDir := filepath.Join(runPath, "web")
|
||||
staticDir := filepath.Join(webDir, "static")
|
||||
viewsDir := filepath.Join(webDir, "views")
|
||||
|
||||
if !common.FileExists(staticDir) {
|
||||
extractFS(StaticFS, "static", webDir)
|
||||
logs.Info("Extracted embedded web/static to", staticDir)
|
||||
}
|
||||
if !common.FileExists(viewsDir) {
|
||||
extractFS(ViewsFS, "views", webDir)
|
||||
logs.Info("Extracted embedded web/views to", viewsDir)
|
||||
}
|
||||
}
|
||||
|
||||
func extractFS(efs embed.FS, root string, destDir string) {
|
||||
fs.WalkDir(efs, ".", func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
targetPath := filepath.Join(destDir, path)
|
||||
if d.IsDir() {
|
||||
os.MkdirAll(targetPath, 0755)
|
||||
return nil
|
||||
}
|
||||
data, err := efs.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
os.MkdirAll(filepath.Dir(targetPath), 0755)
|
||||
os.WriteFile(targetPath, data, 0644)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
(function (global, factory) {
|
||||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
|
||||
typeof define === 'function' && define.amd ? define(['exports'], factory) :
|
||||
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.zh = {}));
|
||||
}(this, (function (exports) { 'use strict';
|
||||
|
||||
var fp = typeof window !== "undefined" && window.flatpickr !== undefined
|
||||
? window.flatpickr
|
||||
: {
|
||||
l10ns: {},
|
||||
};
|
||||
var Mandarin = {
|
||||
weekdays: {
|
||||
shorthand: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
|
||||
longhand: [
|
||||
"星期日",
|
||||
"星期一",
|
||||
"星期二",
|
||||
"星期三",
|
||||
"星期四",
|
||||
"星期五",
|
||||
"星期六",
|
||||
],
|
||||
},
|
||||
months: {
|
||||
shorthand: [
|
||||
"一月",
|
||||
"二月",
|
||||
"三月",
|
||||
"四月",
|
||||
"五月",
|
||||
"六月",
|
||||
"七月",
|
||||
"八月",
|
||||
"九月",
|
||||
"十月",
|
||||
"十一月",
|
||||
"十二月",
|
||||
],
|
||||
longhand: [
|
||||
"一月",
|
||||
"二月",
|
||||
"三月",
|
||||
"四月",
|
||||
"五月",
|
||||
"六月",
|
||||
"七月",
|
||||
"八月",
|
||||
"九月",
|
||||
"十月",
|
||||
"十一月",
|
||||
"十二月",
|
||||
],
|
||||
},
|
||||
rangeSeparator: " 至 ",
|
||||
weekAbbreviation: "周",
|
||||
scrollTitle: "滚动切换",
|
||||
toggleTitle: "点击切换 12/24 小时时制",
|
||||
};
|
||||
fp.l10ns.zh = Mandarin;
|
||||
var zh = fp.l10ns;
|
||||
|
||||
exports.Mandarin = Mandarin;
|
||||
exports.default = zh;
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
})));
|
||||
Vendored
+2
File diff suppressed because one or more lines are too long
@@ -792,6 +792,16 @@
|
||||
<en-US>Last Online Time</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="word-expiretime">
|
||||
<zh-CN>到期时间</zh-CN>
|
||||
<en-US>Expire Time</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="info-expiretime">
|
||||
<zh-CN>留空表示永不过期,到期后将自动暂停客户端</zh-CN>
|
||||
<en-US>Leave blank for no expiration. The client will be paused automatically when expired.</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="word-ipwhite">
|
||||
<zh-CN>启用IP白名单</zh-CN>
|
||||
<en-US> Enable IP White </en-US>
|
||||
|
||||
@@ -142,6 +142,14 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="expire_time">
|
||||
<label class="control-label font-bold" langtag="word-expiretime"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control flatpickr-expire" type="text" name="expire_time" placeholder="2026-12-31 23:59:59" autocomplete="off">
|
||||
<span class="help-block m-b-none" langtag="info-expiretime"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="hr-line-dashed"></div>
|
||||
<div class="form-group">
|
||||
<div class="col-sm-4 col-sm-offset-2">
|
||||
@@ -170,5 +178,18 @@ $(document).ready(function() {
|
||||
$('#black_ip_list').show();
|
||||
}
|
||||
});
|
||||
|
||||
// 到期时间选择器
|
||||
if (typeof flatpickr !== 'undefined') {
|
||||
flatpickr('.flatpickr-expire', {
|
||||
enableTime: true,
|
||||
enableSeconds: true,
|
||||
time_24hr: true,
|
||||
dateFormat: 'Y-m-d H:i:S',
|
||||
minDate: 'today',
|
||||
allowInput: true,
|
||||
locale: (flatpickr.l10ns && flatpickr.l10ns.zh) ? 'zh' : 'default'
|
||||
});
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -166,6 +166,15 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="expire_time">
|
||||
<label class="control-label font-bold" langtag="word-expiretime"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control flatpickr-expire" value="{{.c.ExpireTime}}" type="text" name="expire_time"
|
||||
placeholder="2026-12-31 23:59:59" autocomplete="off">
|
||||
<span class="help-block m-b-none" langtag="info-expiretime"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="hr-line-dashed"></div>
|
||||
<div class="form-group">
|
||||
<div class="col-sm-4 col-sm-offset-2">
|
||||
@@ -199,5 +208,17 @@
|
||||
$(document).ready(function () {
|
||||
// 页面加载时初始化显示状态
|
||||
changeIpWhite();
|
||||
|
||||
// 到期时间选择器
|
||||
if (typeof flatpickr !== 'undefined') {
|
||||
flatpickr('.flatpickr-expire', {
|
||||
enableTime: true,
|
||||
enableSeconds: true,
|
||||
time_24hr: true,
|
||||
dateFormat: 'Y-m-d H:i:S',
|
||||
allowInput: true,
|
||||
locale: (flatpickr.l10ns && flatpickr.l10ns.zh) ? 'zh' : 'default'
|
||||
});
|
||||
}
|
||||
});
|
||||
</script>
|
||||
@@ -73,11 +73,12 @@
|
||||
+ '<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-lastonlinetime"></b>: ' + row.LastOnlineTime + ' <br/>'
|
||||
+ '<b langtag="word-expiretime"></b>: ' + (row.ExpireTime || '<span langtag="info-unrestricted"></span>') + ' <br/><br/>'
|
||||
+ '<b langtag="word-quicklycommand"></b>: <span>' + encodeToBase64(row.Remark +'|'+'{{.ip}}:{{.p}}|' + row.VerifyKey + '|false') + '</span> <button class="copy btn btn-info btn-xs" onclick="copyCommand(this)" data-clipboard-text="">复制</button><br/>'
|
||||
+ '<b langtag="word-tlsquicklycommand"></b>: <span>' + encodeToBase64(row.Remark +'|'+'{{.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>{{.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>{{.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>"
|
||||
},
|
||||
//表格的列
|
||||
columns: [
|
||||
|
||||
@@ -136,6 +136,20 @@
|
||||
halign: 'center',
|
||||
visible: true//false表示不显示
|
||||
},
|
||||
{
|
||||
field: 'IsClose',//域值
|
||||
title: '<span langtag="word-status"></span>',//内容
|
||||
align: 'center',
|
||||
halign: 'center',
|
||||
visible: true,//false表示不显示
|
||||
formatter: function (value, row, index) {
|
||||
if (!value) {
|
||||
return '<span class="badge badge-primary" langtag="word-open"></span>'
|
||||
} else {
|
||||
return '<span class="badge badge-badge" langtag="word-close"></span>'
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
field: '',//域值
|
||||
title: '<span langtag="word-clientstatus"></span>',//内容
|
||||
@@ -159,6 +173,15 @@
|
||||
visible: true,//false表示不显示
|
||||
formatter: function (value, row, index) {
|
||||
btn_group = '<div class="btn-group">'
|
||||
|
||||
if (!row.IsClose) {
|
||||
btn_group += "<a onclick=\"submitform('stop', '{{.web_base_url}}/index/hoststop', {'id':" + row.Id
|
||||
btn_group += '})" class="btn btn-outline btn-warning"><i class="fa fa-pause"></i></a>'
|
||||
} else {
|
||||
btn_group += "<a onclick=\"submitform('start', '{{.web_base_url}}/index/hoststart', {\'id\':" + row.Id
|
||||
btn_group += '})" class="btn btn-outline btn-primary"><i class="fa fa-play"></i></a>'
|
||||
}
|
||||
|
||||
btn_group += "<a onclick=\"submitform('delete', '{{.web_base_url}}/index/delhost', {'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/edithost?id=' + row.Id
|
||||
|
||||
@@ -79,16 +79,16 @@
|
||||
+ '<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
|
||||
+ '<b langtag="word-commandaccessp2p"></b>: ' + "<code>{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.Client.VerifyKey
|
||||
+ " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -target=" + row.Target.TargetStr + "</code>" + "<br/><br>"
|
||||
+ '<b langtag="word-commandaccessp2ps"></b>: ' + "<code>./npc{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.Client.VerifyKey
|
||||
+ '<b langtag="word-commandaccessp2ps"></b>: ' + "<code>{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.Client.VerifyKey
|
||||
+ " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -local_type=p2ps" + "</code>" + "<br/><br>"
|
||||
+ '<b langtag="word-commandaccessp2pt"></b>: ' + "<code>./npc{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.Client.VerifyKey
|
||||
+ '<b langtag="word-commandaccessp2pt"></b>: ' + "<code>{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.Client.VerifyKey
|
||||
+ " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -local_type=p2pt" + "</code>"
|
||||
|
||||
}
|
||||
if (row.Mode == "secret") {
|
||||
return tmp + "<br/><br>" + '<b langtag="word-commandaccess"></b>: ' + "<code>./npc{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.Client.VerifyKey
|
||||
return tmp + "<br/><br>" + '<b langtag="word-commandaccess"></b>: ' + "<code>{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.Client.VerifyKey
|
||||
+ " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -local_type=secret" + "</code>"
|
||||
}
|
||||
return tmp
|
||||
|
||||
@@ -10,16 +10,16 @@
|
||||
|
||||
<!-- Mainly scripts -->
|
||||
<!-- Latest compiled and minified CSS -->
|
||||
<link href="{{.web_base_url}}/static/css/fontawesome.min.css" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/solid.min.css" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/style.css" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/fontawesome.min.css?v={{.version}}" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/solid.min.css?v={{.version}}" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/bootstrap.min.css?v={{.version}}" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/style.css?v={{.version}}" rel="stylesheet">
|
||||
|
||||
<!-- Latest compiled and minified JavaScript -->
|
||||
<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>
|
||||
<script src="{{.web_base_url}}/static/js/jquery-3.4.1.min.js?v={{.version}}"></script>
|
||||
<script src="{{.web_base_url}}/static/js/bootstrap.min.js?v={{.version}}"></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?v={{.version}}" type="text/javascript"></script>
|
||||
|
||||
</head>
|
||||
|
||||
|
||||
@@ -10,16 +10,16 @@
|
||||
|
||||
<!-- Mainly scripts -->
|
||||
<!-- Latest compiled and minified CSS -->
|
||||
<link href="{{.web_base_url}}/static/css/fontawesome.min.css" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/solid.min.css" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/style.css" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/fontawesome.min.css?v={{.version}}" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/solid.min.css?v={{.version}}" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/bootstrap.min.css?v={{.version}}" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/style.css?v={{.version}}" rel="stylesheet">
|
||||
|
||||
<!-- Latest compiled and minified JavaScript -->
|
||||
<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>
|
||||
<script src="{{.web_base_url}}/static/js/jquery-3.4.1.min.js?v={{.version}}"></script>
|
||||
<script src="{{.web_base_url}}/static/js/bootstrap.min.js?v={{.version}}"></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?v={{.version}}" type="text/javascript"></script>
|
||||
|
||||
</head>
|
||||
|
||||
|
||||
@@ -11,25 +11,28 @@
|
||||
|
||||
<!-- Mainly scripts -->
|
||||
<!-- Latest compiled and minified CSS -->
|
||||
<link href="{{.web_base_url}}/static/css/toastr.min.css" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/fontawesome.min.css" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/solid.min.css" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/bootstrap-table.min.css" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/style.css" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/toastr.min.css?v={{.version}}" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/fontawesome.min.css?v={{.version}}" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/solid.min.css?v={{.version}}" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/bootstrap.min.css?v={{.version}}" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/bootstrap-table.min.css?v={{.version}}" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/style.css?v={{.version}}" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/flatpickr.min.css?v={{.version}}" rel="stylesheet">
|
||||
|
||||
<!-- Latest compiled and minified JavaScript -->
|
||||
<script src="{{.web_base_url}}/static/js/jquery-3.4.1.min.js"></script>
|
||||
<script src="{{.web_base_url}}/static/js/clipboard.min.js"></script>
|
||||
<script src="{{.web_base_url}}/static/js/toastr.min.js"></script>
|
||||
<script src="{{.web_base_url}}/static/js/popper.min.js"></script>
|
||||
<script src="{{.web_base_url}}/static/js/bootstrap.min.js"></script>
|
||||
<script src="{{.web_base_url}}/static/js/bootstrap-table.min.js"></script>
|
||||
<script src="{{.web_base_url}}/static/js/bootstrap-table-locale-all.min.js"></script>
|
||||
<script src="{{.web_base_url}}/static/js/echarts.min.js"></script>
|
||||
<script src="{{.web_base_url}}/static/js/inspinia.js"></script>
|
||||
<script src="{{.web_base_url}}/static/js/jquery-3.4.1.min.js?v={{.version}}"></script>
|
||||
<script src="{{.web_base_url}}/static/js/clipboard.min.js?v={{.version}}"></script>
|
||||
<script src="{{.web_base_url}}/static/js/toastr.min.js?v={{.version}}"></script>
|
||||
<script src="{{.web_base_url}}/static/js/popper.min.js?v={{.version}}"></script>
|
||||
<script src="{{.web_base_url}}/static/js/bootstrap.min.js?v={{.version}}"></script>
|
||||
<script src="{{.web_base_url}}/static/js/bootstrap-table.min.js?v={{.version}}"></script>
|
||||
<script src="{{.web_base_url}}/static/js/bootstrap-table-locale-all.min.js?v={{.version}}"></script>
|
||||
<script src="{{.web_base_url}}/static/js/echarts.min.js?v={{.version}}"></script>
|
||||
<script src="{{.web_base_url}}/static/js/inspinia.js?v={{.version}}"></script>
|
||||
<script src="{{.web_base_url}}/static/js/flatpickr.min.js?v={{.version}}"></script>
|
||||
<script src="{{.web_base_url}}/static/js/flatpickr-l10n-zh.js?v={{.version}}"></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?v={{.version}}" type="text/javascript"></script>
|
||||
|
||||
|
||||
</head>
|
||||
|
||||
Reference in New Issue
Block a user