Compare commits

...
35 Commits
Author SHA1 Message Date
yisier dd16ce6659 Web 面板languages.xml使用 NPS 版本号作为缓存标识 2026-08-09 15:27:47 +08:00
yisier 16381ce7e0 配置 allow_ports 后随机生成端口问题 2026-08-09 15:20:41 +08:00
yisier 3e9cccb86e 客户端、隧道、域名解析修改接口支持修改流量数据 2026-08-08 20:13:51 +08:00
yisier f91156a0cb NPC 安装到系统服务失败 BUG 2026-08-08 15:05:29 +08:00
yisier 7231be3944 解决客户端/服务端在线更新失败问题 2026-07-12 22:51:56 -06:00
yisier 1ebbee14a5 back tar.gz 2026-07-12 22:31:56 -06:00
yisier f2fe889a7c 将打包格式从 tar.gz 改为 zip 2026-07-12 22:17:54 -06:00
yisier e19af0a4d1 解决客户端建连失败后的半连接假死问题 2026-07-12 22:00:52 -06:00
yisier c62a3424bc 修复HTTP正向代理和SOCKS5认证问题 2026-07-12 21:31:06 -06:00
yisier 8508c9bd5e 解决私密代理和P2P连接的TLS启用问题 2026-07-12 19:37:53 -06:00
yisier 253c58f3c8 Web 管理端客户端/隧道/域名列表业务字段支持服务端排序(备注、状态、在线等) 2026-07-12 19:28:00 -06:00
yisier 0a096ffef4 解决握手过程中的连接超时和资源堆积问题 2026-07-12 19:05:52 -06:00
yisier b45dfe048e 新增客户端内网地址上报功能 2026-07-12 18:38:47 -06:00
yisier 3c848e5216 nps -server 安装成功后 web_port 未正常显示BUG 2026-07-12 18:20:19 -06:00
yisier 0d77cd92d5 管理界面完全从可执行文件内嵌资源加载 2026-07-12 18:04:09 -06:00
yisier b9642cc9c3 修复 Android 构建脚本中的 Fyne 工具安装路径 2026-07-04 23:50:26 -06:00
yisier c6a70c53a0 添加批量删除功能 2026-07-04 23:27:32 -06:00
yisier 70a50254d6 决 MIPS 架构运行时出现非法指令错误 2026-07-04 23:16:35 -06:00
yisier 8aacbc7bc5 解决新增编辑隧道时重复提交问题 2026-07-04 23:10:14 -06:00
yisier 67cefe1278 修复HTTP代理在SVN客户端无法正常检出的问题 2026-07-04 22:39:37 -06:00
yisier c972af584c doc 2026-06-08 15:33:12 -06:00
yisier 8e889710d7 Update README.md 2026-06-08 15:18:07 -06:00
yisier af6f9243ff md 2026-06-08 15:11:18 -06:00
yisier 9a56ea5d51 doc 2026-06-08 15:06:48 -06:00
yisier 173eeba97f md 2026-06-08 15:02:08 -06:00
yisier ca6371edb1 doc 2026-06-08 14:49:43 -06:00
yisier f57b2b7b34 doc 2026-06-08 00:29:40 -06:00
yisier e263b062c5 docs 2026-06-08 00:19:52 -06:00
yisier 29b064d65f docs 2026-06-08 00:18:04 -06:00
yisier bf6b762371 docs 2026-06-08 00:16:42 -06:00
yisier 2b5aefd1e8 doc 2026-06-08 00:11:12 -06:00
yisier 438d5084c9 doc 2026-06-07 23:46:21 -06:00
yisier e3ed556f0f doc 2026-06-07 22:35:49 -06:00
yisier cfb53ca703 doc 2026-06-07 11:04:50 -06:00
yisier 0afd382e6c doc 2026-06-07 11:03:11 -06:00
116 changed files with 3308 additions and 1885 deletions
+60
View File
@@ -0,0 +1,60 @@
name: Deploy Docs to GitHub Pages
on:
push:
branches: [master]
paths:
- 'docs/**'
- '.github/workflows/docs.yml'
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
# 并发:同一时刻只允许一次部署,新的提交会取消上一个未完成的运行
concurrency:
group: pages
cancel-in-progress: false
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0 # lastUpdated 需要完整 git 历史
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Install dependencies
working-directory: docs
run: npm install --legacy-peer-deps
- name: Build VuePress site
working-directory: docs
run: npm run docs:build
- name: Setup Pages
uses: actions/configure-pages@v4
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: docs/.vuepress/dist
deploy:
needs: build
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
+28 -1
View File
@@ -1,2 +1,29 @@
.idea
nps
nps
# Go build outputs
/npc
/nps.exe
/npc.exe
# Node.js / VuePress
node_modules/
yarn.lock
pnpm-lock.yaml
# VuePress build artifacts
docs/.vuepress/.cache/
docs/.vuepress/.temp/
docs/.vuepress/dist/
# VuePress dev runtime
docs/vuepress-dev.log
docs/vuepress-dev.err.log
docs/vuepress-dev.pid
docs/node_modules/
docs/yarn.lock
docs/.vscode
# OS
.DS_Store
Thumbs.db
+35 -35
View File
@@ -17,41 +17,41 @@ deploy:
token: ${GH_TOKEN}
cleanup: false
file:
- freebsd_386_client.tar.gz
- freebsd_386_server.tar.gz
- freebsd_amd64_client.tar.gz
- freebsd_amd64_server.tar.gz
- freebsd_arm_client.tar.gz
- freebsd_arm_server.tar.gz
- linux_386_client.tar.gz
- linux_386_server.tar.gz
- linux_amd64_client.tar.gz
- linux_amd64_server.tar.gz
- linux_arm64_client.tar.gz
- linux_arm64_server.tar.gz
- linux_arm_v5_client.tar.gz
- linux_arm_v6_client.tar.gz
- linux_arm_v7_client.tar.gz
- linux_arm_v5_server.tar.gz
- linux_arm_v6_server.tar.gz
- linux_arm_v7_server.tar.gz
- linux_mips64le_client.tar.gz
- linux_mips64le_server.tar.gz
- linux_mips64_client.tar.gz
- linux_mips64_server.tar.gz
- linux_mipsle_client.tar.gz
- linux_mipsle_server.tar.gz
- linux_mips_client.tar.gz
- linux_mips_server.tar.gz
- darwin_amd64_client.tar.gz
- darwin_amd64_server.tar.gz
- windows_386_client.tar.gz
- windows_386_server.tar.gz
- windows_amd64_client.tar.gz
- windows_amd64_server.tar.gz
- npc_syno.spk
- npc_sdk.tar.gz
- android_client.apk
- freebsd_386_client.tar.gz
- freebsd_386_server.tar.gz
- freebsd_amd64_client.tar.gz
- freebsd_amd64_server.tar.gz
- freebsd_arm_client.tar.gz
- freebsd_arm_server.tar.gz
- linux_386_client.tar.gz
- linux_386_server.tar.gz
- linux_amd64_client.tar.gz
- linux_amd64_server.tar.gz
- linux_arm64_client.tar.gz
- linux_arm64_server.tar.gz
- linux_arm_v5_client.tar.gz
- linux_arm_v6_client.tar.gz
- linux_arm_v7_client.tar.gz
- linux_arm_v5_server.tar.gz
- linux_arm_v6_server.tar.gz
- linux_arm_v7_server.tar.gz
- linux_mips64le_client.tar.gz
- linux_mips64le_server.tar.gz
- linux_mips64_client.tar.gz
- linux_mips64_server.tar.gz
- linux_mipsle_client.tar.gz
- linux_mipsle_server.tar.gz
- linux_mips_client.tar.gz
- linux_mips_server.tar.gz
- darwin_amd64_client.tar.gz
- darwin_amd64_server.tar.gz
- windows_386_client.tar.gz
- windows_386_server.tar.gz
- windows_amd64_client.tar.gz
- windows_amd64_server.tar.gz
- npc_syno.spk
- npc_sdk.tar.gz
- android_client.apk
on:
tags: true
all_branches: true
+54 -253
View File
@@ -1,274 +1,75 @@
# NPS
[新特性文档](https://dqg9t9eulqq.feishu.cn/wiki/FmVVwDcEGiTZxekYJl5ccuFanlg?from=from_copylink)
[原版文档](https://ehang.io/nps/documents)
# 说明
由于nps已经停更多年,存留了不少bug和未完善的功能。
此版本基于 nps 0.26.10的基础上二次开发而来。
### 交流
聊天灌水QQ群:619833483,热心群主可提供免费远程协助👍👍👍
![Version](https://img.shields.io/badge/version-v0.26.37-blue)
![License](https://img.shields.io/badge/license-GPL--3.0-green)
![Go](https://img.shields.io/badge/Go-%3E%3D1.22-00ADD8?logo=go)
***DockerHub***: [NPS](https://hub.docker.com/r/yisier1/nps) [NPC](https://hub.docker.com/r/yisier1/npc)
> 一款轻量级、高性能、功能强大的内网穿透代理服务器,基于 [ehang-io/nps](https://github.com/ehang-io/nps) 0.26.10 二次开发 —— 修复大量 bug,持续更新中。
> 💬 聊天灌水 QQ 群:**619833483**(热心群主可提供免费远程协助)
***宝塔面板***:[宝塔面板 Docker](docs/bt.md)
### 📖 在线文档
<small>[完整文档](https://yisier.github.io/nps) · [更新日志](https://yisier.github.io/nps/changelog/) · [程序安装](https://yisier.github.io/nps/install/#%E7%A8%8B%E5%BA%8F%E5%AE%89%E8%A3%85) · [宝塔面板](https://yisier.github.io/nps/install/#%E5%AE%9D%E5%A1%94%E9%9D%A2%E6%9D%BF-%E4%B8%80%E9%94%AE%E9%83%A8%E7%BD%B2) · [Docker安装](https://yisier.github.io/nps/install/#docker-%E5%AE%89%E8%A3%85)</small>
强烈推荐使用无配置文件模式启动客户端(删除掉npc.exe 目录下的`conf`文件夹即可),所有数据应该在服务端保存和配置,而客户端只做连接转发。客户端配置文件对小白极不友好,配置繁琐,容易出错。
0.26.21 版本后的客户端,无需再通过命令行方式启动、安装、卸载客户端,直接双击运行,按照提示输入指令即可完成,非常方便。
---
## 💰 赞助 / 推荐
#### ☁️ [雨云 — 国内便宜稳定的云服务器,首月 5 折](https://www.rainyun.com/MjY0MzY1_)
500M 带宽,高仿物理机,云服务器**15 元起**,通过此链接注册首月 5 折。
# 广告
[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_)。
#### 🚀 [NATNPS 云穿透 — 免费 3M 带宽 / 2 条隧道](https://natnps.com/register?utm_from=MQ==)
无需自备服务器,注册即用。免费版 3M 带宽 2 条隧道;6.8 元 12M 带宽 10 条隧道;13.8 元 24M 带宽 20 条隧道。
# 快速上手
***服务端启动/安装:***`./npc(.exe) -server`
---
## 🚀 快速开始
![img.png](image/new/server.png)
### 下载
***客户端启动/安装:*** `./npc(.exe)`
从 [releases](https://github.com/yisier/nps/releases) 下载对应平台版本。服务端 `nps` 和客户端 `npc` 是独立的压缩包。
![image](image/new/cmd.png)
### 服务端
```shell
./nps -server # 交互菜单:安装/卸载/启动/停止/更新
```
首次启动自动生成 `conf/nps.conf`,随机生成 `web_password`、`auth_key`、`auth_crypt_key`,请从启动日志或 `nps.conf` 获取。
![img](https://raw.githubusercontent.com/yisier/nps/master/docs/.vuepress/public/image/new/server.png)
### 客户端
```shell
./npc # 直接双击运行,按提示输入即可
```
在 Web 后台复制【快捷启动命令】,客户端粘贴即可注册系统服务、启停或卸载。
![image](https://raw.githubusercontent.com/yisier/nps/master/docs/.vuepress/public/image/new/cmd.png)
# 更新日志
- 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)
```shell
npc -server=ip:8024 -vkey=xxx # 标准
npc -server=ip:8025 -vkey=xxx -tls_enable=true # TLS 桥接
npc -server=ip:8024 -vkey=vkey1,vkey2 # 多隧道
```
---
## ☕ 请作者喝杯咖啡
> 如果这个项目帮到了你,可以请作者喝杯咖啡 ☕ 感谢支持!
![微信/支付宝扫码赞赏](docs/.vuepress/public/image/payme.png)
- 2026-03-12 v0.26.30
修复:
- http 协议 websocket 错误,感谢[xiaozonglong](https://github.com/xiaozonglong) 提供的 home assistant 环境 ,[#268](https://github.com/yisier/nps/issues/268),[#296](https://github.com/yisier/nps/issues/296)
- 域名解析中,主机url点击无法跳转非80端口 [311](https://github.com/yisier/nps/issues/311)
- 新增的主机配置页面,客户端ID异常 [#310](https://github.com/yisier/nps/issues/310)
- 自动 HTTPS(301) 按照 `https_proxy_port` 配置的端口号跳转
- 2026-01-24 v0.26.29
新增:
GUI 客户端,基于 Wails 开发,[点击查看了解更多](https://github.com/yisier/nps/blob/master/cmd/npc/npc-gui/README.md),需要 WebView2 运行时,可通过两种方式添加客户端。
方式1:直接输入快捷启动命令即可
方式2:手动添加客户端,输入-server -vkey等参数
![img.png](image/new/gui.png)
修复:
Android 包未构建到 Release [72](https://github.com/yisier/nps/issues/72)
---
- 2025-12-06 v0.26.28
-【全局参数】页面新增`服务地址`配置项,用于客户端命令地址显示、隧道访问地址显示 [293](https://github.com/yisier/nps/issues/293)
-【IP授权功能优化】,通过穿透的端口去提交 IP 认证,感谢 [Aqamoe](https://github.com/Aqamoe) 的建议 [291](https://github.com/yisier/nps/issues/291)
-【重构限速器实现】提升性能和准确性
## 📈 Star History
[![Star History Chart](https://api.star-history.com/svg?repos=yisier/nps&type=Date)](https://star-history.com/#yisier/nps&Date)
- 2025-11-05 v0.26.27
新增:
- 1.客户端新增【IP白名单】,可通过两种方式添加IP:
- 方式1️⃣:在【客户端】新建/修改页面,配置IP授权密码,不在IP白名单的外网访问将被跳转到 IP 授权页面,输入正确的授权密码,即可完成添加 IP。
- 方式2️⃣:在【客户端】新建/修改页面,直接添加IP到白名单中。
![img.png](image/new/ip.png)
- 2.客户端配置移除【压缩】和【加密】功能,此功能会显著提高内存和CPU占用率,"利大于弊"。
- 3.客户端默认不再提供配置文件,***强烈推荐使用无配置文件模式启动客户端***
---
## 📃 License
- 2025-08-15 v0.26.26
修复:
- windows注册服务 使用tls无法连接 [269](https://github.com/yisier/nps/issues/269)
- 域名解析自动HTTPS逻辑bug [273](https://github.com/yisier/nps/issues/273)
- 2025-05-28 v0.26.25
新增:
- nps增加`nps(.exe) -server` 命令,用于管理NPS服务,安装和卸载服务在 Linux 下需要有 sudo 权限,Windows 下需要有管理员权限。
![img.png](image/new/server.png)
- 增加【TLS快捷启动命令】,可用于在tls模式下,快速启动客户端。 [257](https://github.com/yisier/nps/issues/257)
- 2025-04-16 v0.26.24
新增:
- 隧道支持复制功能,在隧道页面增加复制按钮,除了端口号为随机生成外,其他参数全部拷贝。[251](https://github.com/yisier/nps/issues/251)
修复:
- 私密代理连接时服务端会报错退出,[250](https://github.com/yisier/nps/issues/250)
- 2025-04-11 v0.26.23
新增:
- TCP 隧道支持 Proxy Protocol 协议来传递经过请求的真实 IP。![img.png](image/new/protocol.png)
修复:
- 客户端较多时,协程增长过快,感谢 [@huanglei288766](https://github.com/yisier/nps/pull/244) 的PR
- 2025-01-23 v0.26.22
优化:
- 客户端注册系统服务时,(新版客户端注册方式,非 install 命令) 将按照 `npc-[vkey].log` 格式保存日志,每个客户端VKEY单独一个日志文件,windows 日志位于 `npc.exe` 同级目录下,linux 位于 `/var/log/`目录。
- 域名模式,HTTPS证书支持上传文件和文件路径,系统将自动识别路径还是证书内容。 [#175](https://github.com/yisier/nps/issues/175)
修复:
- ipv6地址显示不全 [#237](https://github.com/yisier/nps/issues/237)
- 2025-01-07 v0.26.21
新增:
- 客户端列表页面新增【快捷启动命令】,此命令为连接地址+链接秘钥的base64编码,方便一键启动、一键安装客户端。
- 域名解析和隧道列表增加访问地址,可以点击隧道链接,直接网页打开。 [#234](https://github.com/yisier/nps/issues/234)
优化:
- 修改vkey生成方式,由16位缩短至10位,截取uuid前10位,避免重复。
- 优化客户端启动方式,当npc文件目录下无配置文件时,可直接双击运行客户端,输入命令完成启动、安装、卸载客户端,直接启动和安装服务时需要输入【快捷启动命令】,卸载服务、启动服务、停止服务时,只需输入隧道秘钥【vkey】即可。安装服务以 nps-client-vkey 方式命名 ,实现注册多个服务。
![image](image/new/cmd.png)
**注意**
强烈推荐使用无配置文件模式启动客户端,所有数据应该在服务端保存和配置,而客户端只做连接转发。客户端配置文件对小白极不友好,配置繁琐,容易出错。
- 2024-11-07 v0.26.20
新增:
- 客户端增加创建时间
修复:
- 客户端限速单位不统一 [#185](https://github.com/yisier/nps/issues/185)
- 增加从下拉选择客户端,隧道列表排序,新增编辑后不会刷新界面 [#183](https://github.com/yisier/nps/issues/183)
- 隧道数量限制无法统计域名映射 [#209](https://github.com/yisier/nps/issues/209)
- 2024-06-01 v0.26.19
- golang 版本升级到 1.22.
- 增加自动https,自动将http 重定向(301)到 https.
- 客户端命令行方式启动支持多个隧道ID,使用逗号拼接,示例:`npc -server=xxx:8024 -vkey=ytkpyr0er676m0r7,iwnbjfbvygvzyzzt` .
- 移除 nps.conf 参数 `https_just_proxy` , 调整 https 处理逻辑,如果上传了 https 证书,则由nps负责SSL (此方式可以获取真实IP),
否则走端口转发模式(使用本地证书,nps 获取不到真实IP), 如下图所示。
![image](image/new/https.png)
- 2024-02-27 v0.26.18
***新增***:nps.conf 新增 `tls_bridge_port=8025` 参数,当 `tls_enable=true` 时,nps 会监听8025端口,作为 tls 的连接端口。
客户端可以选择连接 tls 端口或者非 tls 端口: `npc.exe -server=xxx:8024 -vkey=xxx` 或 `npc.exe -server=xxx:8025 -vkey=xxx -tls_enable=true`
- 2024-01-31 v0.26.17
***说明***:考虑到 npc 历史版本客户端众多,版本号不同旧版本客户端无法连接,为了兼容,仓库版本号将继续沿用 0.26.xx
- 2024-01-02 v0.27.01 (已作废,功能移动到v0.26.17 版本)
***新增***:tls 流量加密,(客户端忽略证书校验,谨慎使用,客户端与服务端需要同时开启,或同时关闭),使用方式:
服务端:nps.conf `tls_enable=true`;
客户端:npc.conf `tls_enable=true` 或者 `npc.exe -server=xxx -vkey=xxx -tls_enable=true`
- 2023-06-01 v0.26.16
***修复***:https 流量不统计 Bug 修复。
***新增***:新增全局黑名单IP,用于防止被肉鸡扫描端口或被恶意攻击。
***新增***:新增客户端上次在线时间。
- 2023-02-24 v0.26.15
***修复***:更新程序 url 更改到当前仓库中
***修复***:nps 在外部路径启动时找不到配置文件
***新增***:增加 nps 启动参数,`-conf_path=D:\test\nps`,可用于加载指定nps配置文件和web文件目录。
***window 使用示例:***
直接启动:`nps.exe -conf_path=D:\test\nps`
安装:`nps.exe install -conf_path=D:\test\nps`
安装启动:`nps.exe start`
***linux 使用示例:***
直接启动:`./nps -conf_path=/app/nps`
安装:`./nps install -conf_path=/app/nps`
安装启动:`nps start -conf_path=/app/nps`
- 2022-12-30 v0.26.14
***修复***:API 鉴权漏洞修复
- 2022-12-19
***修复***:某些场景下丢包导致服务端意外退出
***优化***:新增隧道时,不指定服务端口时,将自动生成端口号
***优化***:API返回ID, `/client/add/, /index/addhost/,/index/add/ `
***优化***:域名解析、隧道页面,增加[唯一验证密钥],方便搜查
- 2022-10-30
***新增***:在管理面板中新增客户端时,可以配置多个黑名单IP,用于防止被肉鸡扫描端口或被恶意攻击。
***优化***:0.26.12 版本还原了注册系统功能,使用方式和以前一样。无论是否注册了系统服务,直接执行 nps 时只会读取当前目录下的配置文件。
- 2022-10-27
***新增***:在管理面板登录时开启验证码校验,开启方式:nps.conf `open_captcha=true`,感谢 [@dongFangTuring](https://github.com/dongFangTuring) 提供的PR
- 2022-10-24:
***修复***:HTTP协议支持WebSocket(稳定性待测试)
- 2022-10-21:
***修复***:HTTP协议下实时统计流量,能够精准的限制住流量(上下行对等)
***优化***:删除HTTP隧道时,客户端已用流量不再清空
- 2022-10-19:
***BUG***:在TCP协议下,流量统计有问题,只有当连接断开时才会统计流量。例如,限制客户端流量20m,当传输100m的文件时,也能传输成功。
***修复***:TCP协议下实时统计流量,能够精准的限制住流量(上下行对等)
***优化***:删除TCP隧道时,客户端已用流量不再清空
![image](image/new/tcp_limit.png)
- 2022-09-14:
修改NPS工作目录为当前可执行文件目录(即配置文件和nps可执行文件放在同一目录下,直接执行nps文件即可),去除注册系统服务,启动、停止、升级等命令
# 捐赠
![image](image/new/payCode.png)
GPL-3.0 License — 基于 [ehang-io/nps](https://github.com/ehang-io/nps) 0.26.10 二次开发。
+46 -6
View File
@@ -117,6 +117,37 @@ func (s *Bridge) StartTunnel() error {
return nil
}
// requestClientLocalAddr asks the client for private/LAN IPs on the main signal conn.
// New clients reply with WriteLenContent; old clients ignore the flag and we time out.
func (s *Bridge) requestClientLocalAddr(id int, c *conn.Conn) {
if c == nil || c.Conn == nil {
return
}
if _, err := c.Write([]byte(common.REPORT_LOCAL_IP)); err != nil {
return
}
_ = c.Conn.SetReadDeadline(time.Now().Add(2 * time.Second))
defer func() {
// clear deadline so health / later reads are not affected
_ = c.Conn.SetReadDeadline(time.Time{})
}()
b, err := c.GetShortLenContent()
if err != nil {
logs.Trace("clientId %d did not report local addr (old client or timeout): %v", id, err)
return
}
localAddr := strings.TrimSpace(string(b))
if localAddr == "" {
return
}
if client, err := file.GetDb().GetClient(id); err == nil {
client.Lock()
client.LocalAddr = localAddr
client.Unlock()
logs.Info("clientId %d local addr: %s", id, localAddr)
}
}
// get health information form client
func (s *Bridge) GetHealthFromClient(id int, c *conn.Conn) {
for {
@@ -185,6 +216,7 @@ func (s *Bridge) GetHealthFromClient(id int, c *conn.Conn) {
// 验证失败,返回错误验证flag,并且关闭连接
func (s *Bridge) verifyError(c *conn.Conn) {
c.Write([]byte(common.VERIFY_EER))
c.Close()
}
func (s *Bridge) verifySuccess(c *conn.Conn) {
@@ -192,16 +224,19 @@ func (s *Bridge) verifySuccess(c *conn.Conn) {
}
func (s *Bridge) cliProcess(c *conn.Conn) {
// 握手 10s 超时:扫描/半开连接不会一直占着 goroutine;成功后清掉
_ = c.SetReadDeadline(time.Now().Add(10 * time.Second))
//read test flag
if _, err := c.GetShortContent(3); err != nil {
logs.Info("The client %s connect error", c.Conn.RemoteAddr(), err.Error())
c.Close()
return
}
//version check
if b, err := c.GetShortLenContent(); err != nil || string(b) != version.GetVersion() {
//logs.Info("The client %s version does not match", c.Conn.RemoteAddr())
//c.Close()
//return
//version check(版本不匹配仍兼容放行;读失败则断开)
if _, err := c.GetShortLenContent(); err != nil {
c.Close()
return
}
//version get
var vs []byte
@@ -213,7 +248,7 @@ func (s *Bridge) cliProcess(c *conn.Conn) {
}
//write server version to client
c.Write([]byte(crypt.Md5(version.GetVersion())))
c.SetReadDeadlineBySecond(5)
_ = c.SetReadDeadline(time.Now().Add(10 * time.Second))
var buf []byte
//get vKey from client
if buf, err = c.GetShortContent(32); err != nil {
@@ -230,9 +265,12 @@ func (s *Bridge) cliProcess(c *conn.Conn) {
s.verifySuccess(c)
}
if flag, err := c.ReadFlag(); err == nil {
// 握手完成,交给 typeDeal 做长连接
_ = c.SetReadDeadline(time.Time{})
s.typeDeal(flag, c, id, string(vs))
} else {
logs.Warn(err, flag)
c.Close()
}
return
}
@@ -285,6 +323,8 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int, vs string) {
oldSignal.WriteClose()
}
}
// Request private/LAN IPs from client. Old clients ignore the flag; short timeout keeps compatibility.
s.requestClientLocalAddr(id, c)
go s.GetHealthFromClient(id, c)
logs.Info("clientId %d connection succeeded, address:%s ", id, c.Conn.RemoteAddr())
case common.WORK_CHAN:
+1 -1
View File
@@ -18,7 +18,7 @@ export PATH="/usr/local/go/bin:$PATH"
export GOTOOLCHAIN=auto
go version
GO111MODULE=on go install fyne.io/fyne/v2/cmd/fyne@latest
GO111MODULE=on go install fyne.io/tools/cmd/fyne@latest
export PATH="$PATH:$(go env GOPATH)/bin"
#mkdir -p /go/src/fyne.io
#cd src/fyne.io
+25 -25
View File
@@ -8,79 +8,79 @@ tar -czvf npc_sdk.tar.gz npc_sdk.dll npc_sdk.so npc_sdk.h
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_amd64_client.tar.gz npc
tar -czvf linux_amd64_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_386_client.tar.gz npc
tar -czvf linux_386_client.tar.gz npc
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_386_client.tar.gz npc
tar -czvf freebsd_386_client.tar.gz npc
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_amd64_client.tar.gz npc
tar -czvf freebsd_amd64_client.tar.gz npc
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_arm_client.tar.gz npc
tar -czvf freebsd_arm_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v7_client.tar.gz npc
tar -czvf linux_arm_v7_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v6_client.tar.gz npc
tar -czvf linux_arm_v6_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v5_client.tar.gz npc
tar -czvf linux_arm_v5_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm64_client.tar.gz npc
tar -czvf linux_arm64_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 GOMIPS64=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips64_client.tar.gz npc
tar -czvf linux_mips64_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le GOMIPS64=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips64le_client.tar.gz npc
tar -czvf linux_mips64le_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle GOMIPS=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mipsle_client.tar.gz npc
tar -czvf linux_mipsle_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mips go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
CGO_ENABLED=0 GOOS=linux GOARCH=mips GOMIPS=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips_client.tar.gz npc
tar -czvf linux_mips_client.tar.gz npc
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf windows_386_client.tar.gz npc.exe
tar -czvf windows_386_client.tar.gz npc.exe
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf windows_amd64_client.tar.gz npc.exe
tar -czvf windows_amd64_client.tar.gz npc.exe
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf darwin_amd64_client.tar.gz npc
tar -czvf darwin_amd64_client.tar.gz npc
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf darwin_arm64_client.tar.gz npc
tar -czvf darwin_arm64_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
@@ -125,22 +125,22 @@ 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
CGO_ENABLED=0 GOOS=linux GOARCH=mips GOMIPS=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
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
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 GOMIPS64=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
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
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le GOMIPS64=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
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
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle GOMIPS=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_mipsle_server.tar.gz nps
+26 -26
View File
@@ -1,5 +1,5 @@
#/bash/sh
export VERSION=0.26.33
export VERSION=0.26.37
export GOPROXY=direct
sudo apt-get update
@@ -13,71 +13,71 @@ tar -xvf upx-3.95-amd64_linux.tar.xz
cp upx-3.95-amd64_linux/upx ./
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_amd64_client.tar.gz npc
tar -czvf linux_amd64_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_386_client.tar.gz npc
tar -czvf linux_386_client.tar.gz npc
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_386_client.tar.gz npc
tar -czvf freebsd_386_client.tar.gz npc
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_amd64_client.tar.gz npc
tar -czvf freebsd_amd64_client.tar.gz npc
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_arm_client.tar.gz npc
tar -czvf freebsd_arm_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v7_client.tar.gz npc
tar -czvf linux_arm_v7_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v6_client.tar.gz npc
tar -czvf linux_arm_v6_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v5_client.tar.gz npc
tar -czvf linux_arm_v5_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm64_client.tar.gz npc
tar -czvf linux_arm64_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips64_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 GOMIPS64=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips64_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips64le_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le GOMIPS64=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips64le_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mipsle_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle GOMIPS=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mipsle_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mips go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mips GOMIPS=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips_client.tar.gz npc
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf windows_386_client.tar.gz npc.exe
tar -czvf windows_386_client.tar.gz npc.exe
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf windows_amd64_client.tar.gz npc.exe
tar -czvf windows_amd64_client.tar.gz npc.exe
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf darwin_amd64_client.tar.gz npc
tar -czvf darwin_amd64_client.tar.gz npc
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf darwin_arm64_client.tar.gz npc
tar -czvf darwin_arm64_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
@@ -116,19 +116,19 @@ CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags "-s -w -extldflags -st
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
CGO_ENABLED=0 GOOS=linux GOARCH=mips go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
CGO_ENABLED=0 GOOS=linux GOARCH=mips GOMIPS=softfloat 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
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 GOMIPS64=softfloat 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
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le GOMIPS64=softfloat 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
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle GOMIPS=softfloat 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
+31 -9
View File
@@ -34,6 +34,7 @@ type TRPClient struct {
cnf *config.Config
disconnectTime int
once sync.Once
closeCh chan struct{} // closed when client is shutting down; stops ping
logger *logs.BeeLogger // 每个客户端独立的 logger
}
@@ -48,6 +49,7 @@ func NewRPClient(svraddr string, vKey string, bridgeConnType string, proxyUrl st
cnf: cnf,
disconnectTime: disconnectTime,
once: sync.Once{},
closeCh: make(chan struct{}),
logger: nil, // 默认使用全局 logger,可通过 SetLogger 设置
}
}
@@ -134,6 +136,7 @@ retry:
// handle main connection
func (s *TRPClient) handleMain() {
mainLoop:
for {
flags, err := s.signal.ReadFlag()
if err != nil {
@@ -141,11 +144,19 @@ func (s *TRPClient) handleMain() {
break
}
switch flags {
case common.REPORT_LOCAL_IP:
// server requests private/LAN IPs (new nps); ignore failures so main loop continues
localIPs := common.GetLocalIPs(s.signal.Conn)
if err := s.signal.WriteLenContent([]byte(localIPs)); err != nil {
s.logWarn("report local ip failed: %s", err.Error())
} else {
s.logInfo("reported local addr: %s", localIPs)
}
case common.NEW_UDP_CONN:
//read server udp addr and password
if lAddr, err := s.signal.GetShortLenContent(); err != nil {
s.logWarn(err.Error())
return
break mainLoop
} else if pwd, err := s.signal.GetShortLenContent(); err == nil {
var localAddr string
//The local port remains unchanged for a certain period of time
@@ -153,7 +164,7 @@ func (s *TRPClient) handleMain() {
tmpConn, err := common.GetLocalUdpAddr()
if err != nil {
s.logError(err.Error())
return
break mainLoop
}
localAddr = tmpConn.LocalAddr().String()
} else {
@@ -203,7 +214,10 @@ func (s *TRPClient) newUdpConn(localAddr, rAddr string, md5Password string) {
func (s *TRPClient) newChan() {
tunnel, err := NewConn(s.bridgeConnType, s.vKey, s.svrAddr, common.WORK_CHAN, s.proxyUrl)
if err != nil {
s.logError("connect to %s error: %v", s.svrAddr, err)
// WORK_MAIN may already be up; without Close the client stays half-connected
// (handleMain blocks, outer reconnect loop never runs). See #115.
s.logError("connect to %s error: %v, client will reconnect", s.svrAddr, err)
s.Close()
return
}
s.tunnel = nps_mux.NewMux(tunnel.Conn, s.bridgeConnType, s.disconnectTime)
@@ -239,8 +253,9 @@ func (s *TRPClient) handleChan(src net.Conn) {
srcConn.Close()
targetConn.Close()
}()
br := bufio.NewReader(srcConn)
for {
if r, err := http.ReadRequest(bufio.NewReader(srcConn)); err != nil {
if r, err := http.ReadRequest(br); err != nil {
srcConn.Close()
targetConn.Close()
break
@@ -375,14 +390,18 @@ func (s *TRPClient) handleUdp(serverConn net.Conn) {
// Whether the monitor channel is closed
func (s *TRPClient) ping() {
s.ticker = time.NewTicker(time.Second * 5)
loop:
defer s.ticker.Stop()
for {
select {
case <-s.ticker.C:
// tunnel still nil: newChan failed or still connecting; if Close already ran, closeCh fires.
// tunnel established then closed: tear down so outer loop can reconnect.
if s.tunnel != nil && s.tunnel.IsClose() {
s.Close()
break loop
return
}
case <-s.closeCh:
return
}
}
}
@@ -394,13 +413,16 @@ func (s *TRPClient) Close() {
func (s *TRPClient) closing() {
CloseClient = true
NowStatus = 0
// unblock ping; safe: closing runs only once via once.Do
select {
case <-s.closeCh:
default:
close(s.closeCh)
}
if s.tunnel != nil {
_ = s.tunnel.Close()
}
if s.signal != nil {
_ = s.signal.Close()
}
if s.ticker != nil {
s.ticker.Stop()
}
}
+1 -1
View File
@@ -14,7 +14,7 @@
},
"info": {
"productName": "NPS Client",
"productVersion": "0.26.33",
"productVersion": "0.26.37",
"companyName": "NPS",
"copyright": "Copyright © 2026 NPS"
},
+2
View File
@@ -213,6 +213,8 @@ func run() {
common.InitPProfFromArg(*pprofAddr)
//p2p or secret command
if *password != "" {
client.SetTlsEnable(*tlsEnable)
logs.Info("the version of client is %s, the core version of client is %s,tls enable is %t", version.VERSION, version.GetVersion(), client.GetTlsEnable())
commonConfig := new(config.CommonConfig)
commonConfig.Server = *serverAddr
commonConfig.VKey = *verifyKey
+20 -4
View File
@@ -26,7 +26,6 @@ import (
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/crypt"
"ehang.io/nps/web"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
@@ -52,6 +51,7 @@ func main() {
return
}
if *serverCmd {
_ = logs.SetLogger(logs.AdapterConsole, `{"level":7,"color":true}`)
printSlogan()
inputCmd()
return
@@ -270,7 +270,15 @@ func inputCmd() {
_ = service.Control(s, "uninstall")
binPath := install.InstallNpsToCurrentDir()
beego.LoadAppConfig("ini", filepath.Join(common.GetAppPath(), "conf", "nps.conf"))
// Ensure conf exists (same as normal startup), then load it for display.
// Previously LoadAppConfig error was ignored and web_port could be empty,
// printing "127.0.0.1:" with no port. See #317.
confDir := filepath.Join(common.GetAppPath(), "conf")
initConfig(confDir)
if err := beego.LoadAppConfig("ini", filepath.Join(confDir, "nps.conf")); err != nil {
fmt.Println("加载配置文件失败:", err)
break
}
logPath := filepath.Join(common.GetAppPath(), "nps.log")
if common.IsWindows() {
@@ -303,7 +311,16 @@ func inputCmd() {
if err != nil {
fmt.Println("启动NPS服务失败", err)
} else {
fmt.Println("NPS服务已启动,管理面板访问地址:127.0.0.1:" + beego.AppConfig.String("web_port"))
webPort := beego.AppConfig.String("web_port")
if webPort == "" {
fmt.Println("NPS服务已启动(未配置 web_port,管理面板已关闭)")
} else {
scheme := "http"
if beego.AppConfig.DefaultBool("web_open_ssl", false) {
scheme = "https"
}
fmt.Println("NPS服务已启动,管理面板访问地址:" + scheme + "://127.0.0.1:" + webPort)
}
}
break
@@ -472,7 +489,6 @@ func initConfig(confDir string) {
logs.Info("auth_key:", authKey)
logs.Info("auth_crypt_key:", authCryptKey)
}
web.ExtractWebFiles(common.GetRunPath())
}
const defaultNpsConf = `http_proxy_ip=0.0.0.0
+3
View File
@@ -0,0 +1,3 @@
@echo off
cd /d D:\yisi\github\nps\docs
yarn docs:dev > vuepress-dev.log 2> vuepress-dev.err.log
+15
View File
@@ -0,0 +1,15 @@
import { defineClientConfig } from 'vuepress/client'
import { watch } from 'vue'
import { usePageData, useRoute } from 'vuepress/client'
export default defineClientConfig({
setup() {
const page = usePageData()
const route = useRoute()
// eslint-disable-next-line no-console
watch(() => route.path, () => {
// eslint-disable-next-line no-console
console.log('[debug] route:', route.path, 'headers:', JSON.stringify(page.value.headers))
}, { immediate: true })
},
})
+143
View File
@@ -0,0 +1,143 @@
import type { SidebarConfig } from 'vuepress'
import { defineUserConfig } from 'vuepress'
import { viteBundler } from '@vuepress/bundler-vite'
import { defaultTheme } from '@vuepress/theme-default'
import { prismjsPlugin } from '@vuepress/plugin-prismjs'
import { searchPlugin } from '@vuepress/plugin-search'
const serverSidebar: SidebarConfig = [
{ text: '服务端', children: [
{ text: '使用说明', link: '/server/nps_use.html' },
{ text: '配置文件', link: '/server/server_config.html' },
{ text: '增强功能', link: '/server/nps_extend.html' },
]},
]
const clientSidebar: SidebarConfig = [
{ text: '客户端', children: [
{ text: '使用说明', link: '/client/use.html' },
{ text: '增强功能', link: '/client/npc_extend.html' },
{ text: 'SDK', link: '/client/npc_sdk.html' },
]},
]
const extendSidebar: SidebarConfig = [
{ text: '扩展', children: [
{ text: '更多功能', link: '/extend/feature.html' },
{ text: '配置示例', link: '/extend/example.html' },
{ text: 'API接入方式', link: '/extend/api.html' },
{ text: 'API 清单', link: '/extend/webapi.html' },
]},
]
export default defineUserConfig({
base: '/nps/',
bundler: viteBundler(),
lang: 'zh-CN',
title: 'NPS',
description: 'NPS 内网穿透文档 — 服务端、客户端、Web API、增强功能、更新日志',
head: [
['link', { rel: 'icon', href: '/logo.svg' }],
['meta', { name: 'theme-color', content: '#4f46e5' }],
],
plugins: [
prismjsPlugin({
lineNumbers: true,
}),
searchPlugin({}),
],
theme: defaultTheme({
logo: '/logo.svg',
repo: 'yisier/nps',
repoLabel: 'GitHub',
docsRepo: 'https://github.com/yisier/nps',
docsBranch: 'master',
docsDir: 'docs',
editLink: true,
editLinkText: '在 GitHub 上编辑此页',
lastUpdated: true,
lastUpdatedText: '最后更新',
contributors: false,
navbar: [
{ text: '首页', link: '/' },
{ text: '快速上手', link: '/install/' },
{
text: '服务端',
children: [
{ text: '使用说明', link: '/server/nps_use.html' },
{ text: '配置文件', link: '/server/server_config.html' },
{ text: '增强功能', link: '/server/nps_extend.html' },
],
},
{
text: '客户端',
children: [
{ text: '使用说明', link: '/client/use.html' },
{ text: '增强功能', link: '/client/npc_extend.html' },
{ text: 'SDK', link: '/client/npc_sdk.html' },
],
},
{
text: '扩展',
children: [
{ text: '更多功能', link: '/extend/feature.html' },
{ text: '配置示例', link: '/extend/example.html' },
{ text: 'API接入方式', link: '/extend/api.html' },
{ text: 'API 清单', link: '/extend/webapi.html' },
],
},
{ text: '更新日志', link: '/changelog/' },
],
sidebar: {
'/install/': [
{ text: '快速上手', link: '/install/' },
],
'/server/introduction.html': serverSidebar,
'/server/nps_use.html': serverSidebar,
'/server/server_config.html': serverSidebar,
'/server/nps_extend.html': serverSidebar,
'/client/use.html': clientSidebar,
'/client/npc_extend.html': clientSidebar,
'/client/npc_sdk.html': clientSidebar,
'/extend/feature.html': extendSidebar,
'/extend/example.html': extendSidebar,
'/extend/api.html': extendSidebar,
'/extend/webapi.html': extendSidebar,
'/': [
{ text: '首页', link: '/' },
{ text: '快速上手', link: '/install/' },
{
text: '服务端',
children: [
{ text: '使用说明', link: '/server/nps_use.html' },
{ text: '配置文件', link: '/server/server_config.html' },
{ text: '增强功能', link: '/server/nps_extend.html' },
],
},
{
text: '客户端',
children: [
{ text: '使用说明', link: '/client/use.html' },
{ text: '增强功能', link: '/client/npc_extend.html' },
{ text: 'SDK', link: '/client/npc_sdk.html' },
],
},
{
text: '扩展',
children: [
{ text: '功能', link: '/extend/feature.html' },
{ text: '配置示例', link: '/extend/example.html' },
{ text: 'API接入方式', link: '/extend/api.html' },
{ text: 'Web API 详细', link: '/extend/webapi.html' },
],
},
{ text: '更新日志', link: '/changelog/' },
],
},
sidebarDepth: 2,
}),
})

Before

Width:  |  Height:  |  Size: 156 KiB

After

Width:  |  Height:  |  Size: 156 KiB

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Before

Width:  |  Height:  |  Size: 72 KiB

After

Width:  |  Height:  |  Size: 72 KiB

Before

Width:  |  Height:  |  Size: 119 KiB

After

Width:  |  Height:  |  Size: 119 KiB

Before

Width:  |  Height:  |  Size: 276 KiB

After

Width:  |  Height:  |  Size: 276 KiB

Before

Width:  |  Height:  |  Size: 276 KiB

After

Width:  |  Height:  |  Size: 276 KiB

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 34 KiB

Before

Width:  |  Height:  |  Size: 110 KiB

After

Width:  |  Height:  |  Size: 110 KiB

Before

Width:  |  Height:  |  Size: 95 KiB

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 186 KiB

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 32 KiB

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 34 KiB

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Before

Width:  |  Height:  |  Size: 166 KiB

After

Width:  |  Height:  |  Size: 166 KiB

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Before

Width:  |  Height:  |  Size: 61 KiB

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Before

Width:  |  Height:  |  Size: 712 KiB

After

Width:  |  Height:  |  Size: 712 KiB

Before

Width:  |  Height:  |  Size: 97 KiB

After

Width:  |  Height:  |  Size: 97 KiB

Before

Width:  |  Height:  |  Size: 690 KiB

After

Width:  |  Height:  |  Size: 690 KiB

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 49 KiB

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 76 KiB

Before

Width:  |  Height:  |  Size: 290 KiB

After

Width:  |  Height:  |  Size: 290 KiB

Before

Width:  |  Height:  |  Size: 232 KiB

After

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Before

Width:  |  Height:  |  Size: 58 KiB

After

Width:  |  Height:  |  Size: 58 KiB

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

+30 -19
View File
@@ -1,21 +1,32 @@
# nps
![](https://img.shields.io/github/stars/cnlh/nps.svg) ![](https://img.shields.io/github/forks/cnlh/nps.svg)
[![Gitter](https://badges.gitter.im/cnlh-nps/community.svg)](https://gitter.im/cnlh-nps/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
[![Build Status](https://travis-ci.org/ehang-io/nps.svg?branch=master)](https://travis-ci.org/cnlh/nps)
---
home: true
title: NPS 内网穿透
heroImage: /logo.svg
heroText: NPS
tagline: 一款轻量级、高性能、功能强大的内网穿透代理服务器
actions:
- text: 快速上手 →
link: /install/
type: primary
- text: 简介
link: /server/nps_use.html
type: secondary
features:
- title: 全协议支持
details: TCP、UDP、HTTP、HTTPS、SOCKS5、P2P 全覆盖,几乎所有场景一次满足
- title: Web 管理界面
details: 简洁但功能强大的服务端面板,无需配置文件,开箱即用
- title: 全平台兼容
details: Linux / macOS / Windows / Android,一键注册系统服务,桌面 GUI 客户端
- title: TLS 桥接加密
details: 防止流量被防火墙识别拦截,与 KCP / 普通 TCP 三种连接方式自由切换
- title: 进阶能力
details: 流量统计、限速、IP 黑白名单、Proxy Protocol、负载均衡、健康检查
- title: 强大的 API
details: 完整的 REST API,支持 MD5 签名鉴权,方便自动化运维与二次开发
footer: GPL-3.0 License · 基于 ehang-io/nps 0.26.10 二次开发
---
nps是一款轻量级、高性能、功能强大的**内网穿透**代理服务器。目前支持**tcp、udp流量转发**,可支持任何**tcp、udp**上层协议(访问内网网站、本地支付接口调试、ssh访问、远程桌面,内网dns解析等等……),此外还**支持内网http代理、内网socks5代理**、**p2p等**,并带有功能强大的web管理端。
## 加入交流
## 背景
![image](https://github.com/ehang-io/nps/blob/master/image/web.png?raw=true)
1. 做微信公众号开发、小程序开发等----> 域名代理模式
2. 想在外网通过ssh连接内网的机器,做云服务器到内网服务器端口的映射,----> tcp代理模式
3. 在非内网环境下使用内网dns,或者需要通过udp访问内网机器等----> udp代理模式
4. 在外网使用HTTP代理访问内网站点----> http代理模式
5. 搭建一个内网穿透ss,在外网如同使用内网vpn一样访问内网资源或者设备----> socks5代理模式
聊天灌水 QQ 群:**619833483**,热心群主可提供免费远程协助。
-16
View File
@@ -1,16 +0,0 @@
![logo](logo.svg)
# NPS <small>0.26.10</small>
> 一款轻量级、高性能、功能强大的内网穿透代理服务器
- 几乎支持所有协议
- 支持内网http代理、内网socks5代理、p2p等
- 简洁但功能强大的WEB管理界面
- 支持服务端、客户端同时控制
- 扩展功能强大
- 全平台兼容,一键注册为服务
[GitHub](https://github.com/ehang-io/nps/)
[开始使用](#nps)
-3
View File
@@ -1,3 +0,0 @@
* [![GitHub stars](https://img.shields.io/github/stars/ehang-io/nps?style=social)](https://github.com/ehang-io/nps/stargazers)
* [![GitHub forks](https://img.shields.io/github/forks/ehang-io/nps?style=social)](https://github.com/ehang-io/nps/network)
-29
View File
@@ -1,29 +0,0 @@
* 入门
* [安装](install.md)
* [启动](run.md)
* [使用示例](example.md)
* 服务端
* [介绍](introduction.md)
* [使用](nps_use.md)
* [配置文件](server_config.md)
* [增强功能](nps_extend.md)
* 客户端
* [基本使用](use.md)
* [增强功能](npc_extend.md)
* 扩展
* [功能](feature.md)
* [说明](description.md)
* [web api](api.md)
* [sdk](npc_sdk.md)
* 其他
* [FAQ](faq.md)
* [贡献](contribute.md)
* [捐助](donate.md)
* [致谢](thanks.md)
* [交流](discuss.md)
-45
View File
@@ -1,45 +0,0 @@
# web api
需要开启请先去掉`nps.conf`中`auth_key`的注释并配置一个合适的密钥
## webAPI验证说明
- 采用auth_key的验证方式
- 在提交的每个请求后面附带两个参数,`auth_key` 和`timestamp`
```
auth_key的生成方式为:md5(配置文件中的auth_key+当前时间戳)
```
```
timestamp为当前时间戳
```
```
curl --request POST \
--url http://127.0.0.1:8080/client/list \
--data 'auth_key=2a0000d9229e7dbcf79dd0f5e04bb084&timestamp=1553045344&start=0&limit=10'
```
**注意:** 为保证安全,时间戳的有效范围为20秒内,所以每次提交请求必须重新生成。
## 获取服务端时间
由于服务端与api请求的客户端时间差异不能太大,所以提供了一个可以获取服务端时间的接口
```
POST /auth/gettime
```
## 获取服务端authKey
如果想获取authKey,服务端提供获取authKey的接口
```
POST /auth/getauthkey
```
将返回加密后的authKey,采用aes cbc加密,请使用与服务端配置文件中cryptKey相同的密钥进行解密
**注意:** nps配置文件中`auth_crypt_key`需为16位
- 解密密钥长度128
- 偏移量与密钥相同
- 补码方式pkcs5padding
- 解密串编码方式 十六进制
## 详细文档
- **[详见](webapi.md)** (感谢@avengexyz)
+2
View File
@@ -0,0 +1,2 @@
cd ..
yarn add -D vuepress
+2
View File
@@ -0,0 +1,2 @@
cd ..
yarn docs:dev
-42
View File
@@ -1,42 +0,0 @@
# 🐳 宝塔面板 (一键部署)
> 安装宝塔面板,前往宝塔面板官网,选择对应的脚本下载安装,推荐宝塔版本 9.2.0+
![logo](../image/bt/bt1.jpg)
# 安装宝塔面板
1. 安装宝塔面板,前往 [宝塔面板官网](https://www.bt.cn/new/download.html) 进行安装,选择正式版脚本安装。
2. 登录面板,点击左侧 **Docker** 进入 `Docker 管理`。
3. 如提示未安装 Docker / Docker Compose, 可根据上方引导安装。
# 安装NPS服务端
1. 在宝塔面板左侧` Docker 菜单`,进入 **应用商城**,搜索 `NPS`,找到 `NPS 服务端` 并点击 **安装**。
2. 配置NPS,进入安装目录,修改 `conf/nps.conf` 即可(修改后记得重启容器),服务端参数配置详见 [配置文件说明](https://ehang-io.github.io/nps/#/server_config)
![logo](../image/bt/bt2.png)
**注意**:NPS 默认的`WEB端口`为`80,443`, 如果端口被占用,请修改 `nps.conf` 中的 `http_proxy_port`,`https_proxy_port` 为其他端口。
web管理端口默认为`8081`,服务端启动后,输入:`ip:8081` 即可访问。
# 安装NPS客户端
1. 在宝塔面板左侧` Docker 菜单`,进入 **应用商城**,搜索 `NPS`,找到 `NPS 客户端` 并点击 **安装**。
2. 客户端配置有两种方式,1. [无配置文件模式](https://ehang-io.github.io/nps/#/use?id=%e6%97%a0%e9%85%8d%e7%bd%ae%e6%96%87%e4%bb%b6%e6%a8%a1%e5%bc%8f)(推荐),2. [配置文件模式](https://ehang-io.github.io/nps/#/use?id=%e9%85%8d%e7%bd%ae%e6%96%87%e4%bb%b6%e6%a8%a1%e5%bc%8f)。
- **无配置文件模式**:点击安装后,输入`服务地址`、`连接密钥`,即可启动客户端。`连接方式`和`开启TLS`参数,为了避免意外错误,不建议修改。如果需要配置多个客户端,直接安装多个即可(注意名字不要重复)。
- **配置文件模式**: `服务地址`、`连接密钥`不需要填写,直接点击 **安装** ,然后在`安装目录`下找到 `conf/npc.conf`,修改配置文件,再重启容器即可。客户端参数配置详见 [配置文件说明](https://ehang-io.github.io/nps/#/use?id=%e9%85%8d%e7%bd%ae%e6%96%87%e4%bb%b6%e6%a8%a1%e5%bc%8f)。
**注意**:强烈推荐使用无配置文件模式,所有数据应该在服务端保存和配置,而客户端只做连接转发。客户端配置文件对小白极不友好,配置繁琐,容易出错。
![logo](../image/bt/bt3.png)
+240
View File
@@ -0,0 +1,240 @@
# 更新日志
- 2026-08-08 v0.26.37
- 修复:
- NPC 安装到系统服务失败 BUG [#338](https://github.com/yisier/nps/issues/338)
- 隧道实际未运行但面板提示「启动成功」、运行状态始终为关闭的问题 [#339](https://github.com/yisier/nps/issues/339)
- 配置 `allow_ports` 后随机生成端口问题 [#339](https://github.com/yisier/nps/issues/339)
- Web 面板`languages.xml`使用 NPS 版本号作为缓存标识 [#342](https://github.com/yisier/nps/issues/342)
- 新增:
- 客户端、隧道、域名解析修改接口支持修改流量数据 [#341](https://github.com/yisier/nps/issues/341)
- 2026-07-12 v0.26.36
- 新增:
- 新增客户端内网地址上报功能,客户端列表展示 npc 内网地址 [#333](https://github.com/yisier/nps/issues/333)
- Web 管理端客户端/隧道/域名列表业务字段支持服务端排序(备注、状态、在线等)[#254](https://github.com/yisier/nps/issues/254)
- 优化:
- 不再依赖外部 `web` 目录的静态文件
- 修复:
- 客户端/服务端在线更新失败 BUG
- `nps -server` 安装成功后 `web_port` 未正常显示BUG [#317](https://github.com/yisier/nps/issues/317)
- Bridge 握手增加 10s 读超时,校验失败/读失败立即关闭连接,减轻端口扫描导致的连接与 goroutine 堆积 [#281](https://github.com/yisier/nps/issues/281)
- 解决私密代理和P2P连接的TLS启用问题 [#143](https://github.com/yisier/nps/issues/143)
- HTTP 正向代理 Basic 认证 BUG[#133](https://github.com/yisier/nps/issues/133)
- SOCKS5 用户名密码认证 BUG [#133](https://github.com/yisier/nps/issues/133)
- 客户端建连失败后半连接假死、需手动重启 npc BUG [#115](https://github.com/yisier/nps/issues/115)
- 2026-07-04 v0.26.35
- 新增:
- 客户端列表、隧道列表、域名解析列表支持多选批量删除 [#287](https://github.com/yisier/nps/issues/287)
- 修复:
- HTTP 代理在 SVN 客户端无法正常检出 [#336](https://github.com/yisier/nps/issues/336)
- 新增/编辑隧道时无提示且不跳转,重复点击会产生多条记录 [#334](https://github.com/yisier/nps/issues/334)
- mips/mipsle 架构运行出现 Illegal instruction 错误 [#331](https://github.com/yisier/nps/issues/331)
- 优化:
- 隧道、域名解析编辑页的客户端 ID 改为下拉选择 [#334](https://github.com/yisier/nps/issues/334)
- 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
- 修复:
- http 协议 websocket 错误,感谢[xiaozonglong](https://github.com/xiaozonglong) 提供的 home assistant 环境 ,[#268](https://github.com/yisier/nps/issues/268),[#296](https://github.com/yisier/nps/issues/296)
- 域名解析中,主机url点击无法跳转非80端口 [311](https://github.com/yisier/nps/issues/311)
- 新增的主机配置页面,客户端ID异常 [#310](https://github.com/yisier/nps/issues/310)
- 自动 HTTPS(301) 按照 `https_proxy_port` 配置的端口号跳转
- 2026-01-24 v0.26.29
- 新增:
- GUI 客户端,基于 Wails 开发,[点击查看了解更多](https://github.com/yisier/nps/blob/master/cmd/npc/npc-gui/README.md),需要 WebView2 运行时,可通过两种方式添加客户端。
- 方式1:直接输入快捷启动命令即可
- 方式2:手动添加客户端,输入-server -vkey等参数
![img.png](/image/new/gui.png)
- 修复:
- Android 包未构建到 Release [72](https://github.com/yisier/nps/issues/72)
- 2025-12-06 v0.26.28
- 【全局参数】页面新增`服务地址`配置项,用于客户端命令地址显示、隧道访问地址显示 [293](https://github.com/yisier/nps/issues/293)
- 【IP授权功能优化】,通过穿透的端口去提交 IP 认证,感谢 [Aqamoe](https://github.com/Aqamoe) 的建议 [291](https://github.com/yisier/nps/issues/291)
- 【重构限速器实现】提升性能和准确性
- 2025-11-05 v0.26.27
- 新增:
- 客户端新增【IP白名单】,可通过两种方式添加IP:
- 方式1️⃣:在【客户端】新建/修改页面,配置IP授权密码,不在IP白名单的外网访问将被跳转到 IP 授权页面,输入正确的授权密码,即可完成添加 IP。
- 方式2️⃣:在【客户端】新建/修改页面,直接添加IP到白名单中。
![img.png](/image/new/ip.png)
- 客户端配置移除【压缩】和【加密】功能,此功能会显著提高内存和CPU占用率,"利大于弊"。
- 客户端默认不再提供配置文件,***强烈推荐使用无配置文件模式启动客户端***
- 2025-08-15 v0.26.26
- 修复:
- windows注册服务 使用tls无法连接 [269](https://github.com/yisier/nps/issues/269)
- 域名解析自动HTTPS逻辑bug [273](https://github.com/yisier/nps/issues/273)
- 2025-05-28 v0.26.25
- 新增:
- nps增加`nps(.exe) -server` 命令,用于管理NPS服务,安装和卸载服务在 Linux 下需要有 sudo 权限,Windows 下需要有管理员权限。
![img.png](/image/new/server.png)
- 增加【TLS快捷启动命令】,可用于在tls模式下,快速启动客户端。 [257](https://github.com/yisier/nps/issues/257)
- 2025-04-16 v0.26.24
- 新增:
- 隧道支持复制功能,在隧道页面增加复制按钮,除了端口号为随机生成外,其他参数全部拷贝。[251](https://github.com/yisier/nps/issues/251)
- 修复:
- 私密代理连接时服务端会报错退出,[250](https://github.com/yisier/nps/issues/250)
- 2025-04-11 v0.26.23
- 新增:
- TCP 隧道支持 Proxy Protocol 协议来传递经过请求的真实 IP。
![img.png](/image/new/protocol.png)
- 修复:
- 客户端较多时,协程增长过快,感谢 [@huanglei288766](https://github.com/yisier/nps/pull/244) 的PR
- 2025-01-23 v0.26.22
- 优化:
- 客户端注册系统服务时,(新版客户端注册方式,非 install 命令) 将按照 `npc-[vkey].log` 格式保存日志,每个客户端VKEY单独一个日志文件,windows 日志位于 `npc.exe` 同级目录下,linux 位于 `/var/log/`目录。
- 域名模式,HTTPS证书支持上传文件和文件路径,系统将自动识别路径还是证书内容。 [#175](https://github.com/yisier/nps/issues/175)
- 修复:
- ipv6地址显示不全 [#237](https://github.com/yisier/nps/issues/237)
- 2025-01-07 v0.26.21
- 新增:
- 客户端列表页面新增【快捷启动命令】,此命令为连接地址+链接秘钥的base64编码,方便一键启动、一键安装客户端。
- 域名解析和隧道列表增加访问地址,可以点击隧道链接,直接网页打开。 [#234](https://github.com/yisier/nps/issues/234)
- 优化:
- 修改vkey生成方式,由16位缩短至10位,截取uuid前10位,避免重复。
- 优化客户端启动方式,当npc文件目录下无配置文件时,可直接双击运行客户端,输入命令完成启动、安装、卸载客户端,直接启动和安装服务时需要输入【快捷启动命令】,卸载服务、启动服务、停止服务时,只需输入隧道秘钥【vkey】即可。安装服务以 nps-client-vkey 方式命名 ,实现注册多个服务。
![image](/image/new/cmd.png)
> **注意**:强烈推荐使用无配置文件模式启动客户端,所有数据应该在服务端保存和配置,而客户端只做连接转发。客户端配置文件对小白极不友好,配置繁琐,容易出错。
- 2024-11-07 v0.26.20
- 新增:
- 客户端增加创建时间
- 修复:
- 客户端限速单位不统一 [#185](https://github.com/yisier/nps/issues/185)
- 增加从下拉选择客户端,隧道列表排序,新增编辑后不会刷新界面 [#183](https://github.com/yisier/nps/issues/183)
- 隧道数量限制无法统计域名映射 [#209](https://github.com/yisier/nps/issues/209)
- 2024-06-01 v0.26.19
- golang 版本升级到 1.22。
- 增加自动https,自动将http 重定向(301)到 https。
- 客户端命令行方式启动支持多个隧道ID,使用逗号拼接,示例:`npc -server=xxx:8024 -vkey=ytkpyr0er676m0r7,iwnbjfbvygvzyzzt`。
- 移除 nps.conf 参数 `https_just_proxy` ,调整 https 处理逻辑,如果上传了 https 证书,则由nps负责SSL(此方式可以获取真实IP),否则走端口转发模式(使用本地证书,nps 获取不到真实IP),如下图所示。
![image](/image/new/https.png)
- 2024-02-27 v0.26.18
- ***新增***:nps.conf 新增 `tls_bridge_port=8025` 参数,当 `tls_enable=true` 时,nps 会监听8025端口,作为 tls 的连接端口。客户端可以选择连接 tls 端口或者非 tls 端口:`npc.exe -server=xxx:8024 -vkey=xxx` 或 `npc.exe -server=xxx:8025 -vkey=xxx -tls_enable=true`
- 2024-01-31 v0.26.17
- ***说明***:考虑到 npc 历史版本客户端众多,版本号不同旧版本客户端无法连接,为了兼容,仓库版本号将继续沿用 0.26.xx
- 2024-01-02 v0.27.01 (已作废,功能移动到 v0.26.17 版本)
- ***新增***:tls 流量加密,(客户端忽略证书校验,谨慎使用,客户端与服务端需要同时开启,或同时关闭),使用方式:
- 服务端:nps.conf `tls_enable=true`;
- 客户端:npc.conf `tls_enable=true` 或者 `npc.exe -server=xxx -vkey=xxx -tls_enable=true`
- 2023-06-01 v0.26.16
- ***修复***:https 流量不统计 Bug 修复。
- ***新增***:新增全局黑名单IP,用于防止被肉鸡扫描端口或被恶意攻击。
- ***新增***:新增客户端上次在线时间。
- 2023-02-24 v0.26.15
- ***修复***:更新程序 url 更改到当前仓库中
- ***修复***:nps 在外部路径启动时找不到配置文件
- ***新增***:增加 nps 启动参数,`-conf_path=D:\test\nps`,可用于加载指定nps配置文件和web文件目录。
- ***window 使用示例:***
- 直接启动:`nps.exe -conf_path=D:\test\nps`
- 安装:`nps.exe install -conf_path=D:\test\nps`
- 安装启动:`nps.exe start`
- ***linux 使用示例:***
- 直接启动:`./nps -conf_path=/app/nps`
- 安装:`./nps install -conf_path=/app/nps`
- 安装启动:`nps start -conf_path=/app/nps`
- 2022-12-30 v0.26.14
- ***修复***:API 鉴权漏洞修复
- 2022-12-19
- ***修复***:某些场景下丢包导致服务端意外退出
- ***优化***:新增隧道时,不指定服务端口时,将自动生成端口号
- ***优化***:API返回ID,`/client/add/`, `/index/addhost/`, `/index/add/`
- ***优化***:域名解析、隧道页面,增加[唯一验证密钥],方便搜查
- 2022-10-30
- ***新增***:在管理面板中新增客户端时,可以配置多个黑名单IP,用于防止被肉鸡扫描端口或被恶意攻击。
- ***优化***:0.26.12 版本还原了注册系统功能,使用方式和以前一样。无论是否注册了系统服务,直接执行 nps 时只会读取当前目录下的配置文件。
- 2022-10-27
- ***新增***:在管理面板登录时开启验证码校验,开启方式:nps.conf `open_captcha=true`,感谢 [@dongFangTuring](https://github.com/dongFangTuring) 提供的PR
- 2022-10-24
- ***修复***:HTTP协议支持WebSocket(稳定性待测试)
- 2022-10-21
- ***修复***:HTTP协议下实时统计流量,能够精准的限制住流量(上下行对等)
- ***优化***:删除HTTP隧道时,客户端已用流量不再清空
- 2022-10-19
- ***BUG***:在TCP协议下,流量统计有问题,只有当连接断开时才会统计流量。例如,限制客户端流量20m,当传输100m的文件时,也能传输成功。
- ***修复***:TCP协议下实时统计流量,能够精准的限制住流量(上下行对等)
- ***优化***:删除TCP隧道时,客户端已用流量不再清空
![image](/image/new/tcp_limit.png)
- 2022-09-14
- 修改NPS工作目录为当前可执行文件目录(即配置文件和nps可执行文件放在同一目录下,直接执行nps文件即可),去除注册系统服务,启动、停止、升级等命令
@@ -8,21 +8,11 @@
```
./npc status -config=npc配置文件路径
```
## 重载配置文件
```
./npc restart -config=npc配置文件路径
```
## 通过代理连接nps
有时候运行npc的内网机器无法直接访问外网,此时可以可以通过socks5代理连接nps
对于配置文件方式启动,设置
```ini
[common]
proxy_url=socks5://111:222@127.0.0.1:8024
```
对于无配置文件模式,加上参数
```
-proxy=socks5://111:222@127.0.0.1:8024
```
@@ -33,4 +23,5 @@ proxy_url=socks5://111:222@127.0.0.1:8024
或http://username:password@ip:port
## 群晖支持
可在releases中下载spk群晖套件,例如`npc_x64-6.1_0.19.0-1.spk`
添加 `我不是矿神` 套件地址 : https://spk7.imnks.com/,下载npc套件安装后,按照提示输入服务地址和连接密钥即可。
+72
View File
@@ -0,0 +1,72 @@
## 直接运行
直接双击 `npc`/`npc.exe`,无任何参数,按提示输入即可:
| 菜单项 | 输入内容 |
| --- | --- |
| 注册系统服务 | 【快捷启动命令】或【TLS 快捷启动命令】|
| 卸载系统服务 | 隧道密钥 `vkey` |
| 启动 | 隧道密钥 `vkey` |
| 停止 | 隧道密钥 `vkey` |
| 更新客户端 | — |
【快捷启动命令】在 web 后台 → 客户端列表 → 客户端前的小图标里复制,本质是 `服务端地址 + vkey` 的 base64 编码。TLS 模式有独立的【TLS 快捷启动命令】。
服务以 `nps-client-<vkey>` 命名注册,可在同一台机器并存多个客户端实例。
![image](/image/new/cmd.png)
## 直接命令行
```shell
./npc -server=ip:port -vkey=web界面中显示的密钥 # 标准
./npc -server=ip:8025 -vkey=xxx -tls_enable=true # TLS 桥接
./npc -server=ip:8024 -vkey=ytkpyr0er676m0r7,iwnbjfbvygvzyzzt # 同时拉起多个隧道 ID(逗号拼接)
```
## GUI 客户端
> 基于 Wails 开发的桌面 GUI,体积只有 5M,免安装,解压即用。
支持两种添加客户端方式:
1. 粘贴 web 后台的【快捷启动命令】
2. 手动填写 `-server`、`-vkey` 等参数
详细说明请参考 [GUI 客户端 README](https://github.com/yisier/nps/blob/master/cmd/npc/npc-gui/README.md)。
![img](/image/new/gui.png)
## 注册到系统服务
> 实现开机启动、守护进程
```shell
./npc # linux/darwin(需 sudo)
npc.exe # windows(管理员 cmd)
```
按菜单选「注册系统服务」并粘贴【快捷启动命令】或【TLS 快捷启动命令】即可,服务名为 `nps-client-<vkey>`。
> Windows 如果需要当客户端退出时自动重启客户端,请按照如图所示配置
![img](/image/windows_client_service_configuration.png)
## 系统服务日志
注册系统服务后日志按 **每个 vkey 一个文件** 保存,命名为 `npc-<vkey>.log`:
- windows:与 `npc.exe` 同级目录
- linux / darwin:`/var/log/`
## 客户端更新
> 运行客户端,会显示当前客户端版本号。
```shell
./npc # 选择菜单 [5] 更新客户端
```
自动下载并替换 `npc` 二进制。
如果无法成功更新,可以直接下载 releases 压缩包覆盖原有的 `npc` 二进制。
-6
View File
@@ -1,6 +0,0 @@
# 贡献
- 如果遇到bug可以直接提交至dev分支
- 使用遇到问题可以通过issues反馈
- 项目处于开发阶段,还有很多待完善的地方,如果可以贡献代码,请提交 PR 至 dev 分支
- 如果有新的功能特性反馈,可以通过issues或者qq群反馈
-30
View File
@@ -1,30 +0,0 @@
# 说明
## 获取用户真实ip
如需使用需要在`nps.conf`中设置`http_add_origin_header=true`
在域名代理模式中,可以通过request请求 header 中的 X-Forwarded-For 和 X-Real-IP 来获取用户真实 IP。
**本代理前会在每一个http(s)请求中添加了这两个 header。**
## 热更新支持
对于绝大多数配置,在web管理中的修改将实时使用,无需重启客户端或者服务端
## 客户端地址显示
在web管理中将显示客户端的连接地址
## 流量统计
可统计显示每个代理使用的流量,由于压缩和加密等原因,会和实际环境中的略有差异
## 当前客户端带宽
可统计每个客户端当前的带宽,可能和实际有一定差异,仅供参考。
## 客户端与服务端版本对比
为了程序正常运行,客户端与服务端的核心版本必须一致,否则将导致客户端无法成功连接致服务端。
## Linux系统限制
默认情况下linux对连接数量有限制,对于性能好的机器完全可以调整内核参数以处理更多的连接。
`tcp_max_syn_backlog` `somaxconn`
酌情调整参数,增强网络性能
## web管理保护
当一个ip连续登陆失败次数超过10次,将在一分钟内禁止该ip再次尝试。
-3
View File
@@ -1,3 +0,0 @@
# 交流群
![二维码.jpeg](https://i.loli.net/2019/02/15/5c66c32a42074.jpeg)
-7
View File
@@ -1,7 +0,0 @@
# 捐助
如果您觉得nps对你有帮助,欢迎给予我们一定捐助,也是帮助nps更好的发展。
## 支付宝
![image](https://github.com/ehang-io/nps/blob/master/image/donation_zfb.png?raw=true)
## 微信
![image](https://github.com/ehang-io/nps/blob/master/image/donation_wx.png?raw=true)
+115
View File
@@ -0,0 +1,115 @@
# Web API 鉴权
在 `nps.conf` 中配置 `auth_key` 即可启用 API 鉴权(首次启动自动生成)。
## 鉴权方式
每个请求需附带两个参数:
| 参数 | 说明 |
| --- | --- |
| `auth_key` | `md5(配置文件中的 auth_key + 当前时间戳)` |
| `timestamp` | 当前 unix 时间戳(秒) |
时间戳有效范围为 **20 秒**,每次请求须重新生成。
## 获取服务端时间戳
由于客户端与服务端时间可能不一致,可先获取服务端时间:
```
GET /auth/gettime/
```
返回:
```json
{"time": 1717654321}
```
> 此接口无需鉴权。
## 获取服务端 auth_key(加密)
```
GET /auth/getauthkey/
```
返回经 AES-CBC 加密后的 `auth_key`(hex 编码)。
> 此接口无需鉴权。需确保 `nps.conf` 中 `auth_crypt_key` 为 **16 位**。
解密参数:
- 算法:AES-128-CBC
- 密钥:`auth_crypt_key`(16 字节)
- IV:与密钥相同
- 填充:PKCS5Padding
- 密文编码:hex
---
## 接入示例
::: tabs
@tab curl
```bash
# 1. 获取服务端时间戳
ts=$(curl -s http://127.0.0.1:8080/auth/gettime/ | sed 's/.*"time":\([0-9]*\).*/\1/')
# 2. 计算签名(Linux)
sign=$(echo -n "your_auth_key${ts}" | md5sum | awk '{print $1}')
# 或 macOS:
# sign=$(echo -n "your_auth_key${ts}" | md5)
# 3. 调用接口
curl -s -X POST "http://127.0.0.1:8080/client/list/" \
-d "auth_key=${sign}&timestamp=${ts}&search=&order=asc&offset=0&limit=10"
```
@tab Python
```python
import hashlib, requests
host = "http://127.0.0.1:8080"
auth_key = "your_auth_key"
ts = requests.get(f"{host}/auth/gettime/").json()["time"]
sign = hashlib.md5(f"{auth_key}{ts}".encode()).hexdigest()
r = requests.post(f"{host}/client/list/", data={
"auth_key": sign, "timestamp": ts,
"search": "", "order": "asc", "offset": 0, "limit": 10
})
print(r.json())
```
@tab JavaScript
```javascript
const crypto = require("crypto");
const host = "http://127.0.0.1:8080";
const authKey = "your_auth_key";
(async () => {
const ts = (await (await fetch(`${host}/auth/gettime/`)).json()).time;
const sign = crypto.createHash("md5").update(`${authKey}${ts}`).digest("hex");
const r = await fetch(`${host}/client/list/`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ auth_key: sign, timestamp: ts, search: "", order: "asc", offset: 0, limit: 10 }).toString(),
});
console.log(await r.json());
})();
```
:::
---
## 详细接口清单
- [Web API 接口文档](webapi.html)
+3 -3
View File
@@ -1,5 +1,5 @@
# 使用示例
## 统一准备工作(必做)
## 统一准备工作
- 开启服务端,假设公网服务器ip为1.1.1.1,配置文件中`bridge_port`为8024,配置文件中`web_port`为8080
- 访问1.1.1.1:8080
- 在客户端管理中创建一个客户端,记录下验证密钥
@@ -27,7 +27,7 @@
现在访问(http|https://)`a.proxy.com`,`b.proxy.com`即可成功
**https:** 如需使用https请进行相关配置,详见 [使用https](/nps_extend?id=使用https)
**https:** 如需使用https请进行相关配置,详见 [使用https](/server/nps_extend.html#使用-https)
## tcp隧道
@@ -104,7 +104,7 @@
## p2p服务
**适用范围:** 大流量传输场景,流量不经过公网服务器,但是由于p2p穿透和nat类型关系较大,不保证100%成功,支持大部分nat类型。[nat类型检测](/npc_extend?id=nat类型检测)
**适用范围:** 大流量传输场景,流量不经过公网服务器,但是由于p2p穿透和nat类型关系较大,不保证100%成功,支持大部分nat类型。[nat类型检测](/client/npc_extend.html#nat类型检测)
**假设场景:**
+50 -118
View File
@@ -1,23 +1,47 @@
# 扩展功能
## 获取用户真实ip
如需使用需要在`nps.conf`中设置`http_add_origin_header=true`
在域名代理模式中,可以通过request请求 header 中的 X-Forwarded-For 和 X-Real-IP 来获取用户真实 IP。
**本代理前会在每一个http(s)请求中添加了这两个 header。**
## 热更新支持
对于绝大多数配置,在web管理中的修改将实时使用,无需重启客户端或者服务端
## 客户端地址显示
在web管理中将显示客户端的连接地址
## 流量统计
可统计显示每个代理使用的流量,由于压缩和加密等原因,会和实际环境中的略有差异
## 当前客户端带宽
可统计每个客户端当前的带宽,可能和实际有一定差异,仅供参考。
## 客户端与服务端版本对比
为了程序正常运行,客户端与服务端的核心版本必须一致,否则将导致客户端无法成功连接致服务端。
## Linux系统限制
默认情况下linux对连接数量有限制,对于性能好的机器完全可以调整内核参数以处理更多的连接。
`tcp_max_syn_backlog` `somaxconn`
酌情调整参数,增强网络性能
## web管理保护
当一个 ip 连续登陆失败次数超过 10 次,将在一分钟内禁止该 ip 再次尝试。
可在 `nps.conf` 设置 `open_captcha=true` 进一步开启图形验证码
## 缓存支持
对于web站点来说,一些静态文件往往消耗更大的流量,且在内网穿透中,静态文件还需到客户端获取一次,这将导致更大的流量消耗。nps在域名解析代理中支持对静态文件进行缓存。
即假设一个站点有a.css,nps将只需从npc客户端读取一次该文件,然后把该文件的内容放在内存中,下一次将不再对npc客户端进行请求而直接返回内存中的对应内容。该功能默认是关闭的,如需开启请在`nps.conf`中设置`http_cache=true`,并设置`http_cache_length`(缓存文件的个数,消耗内存,不宜过大,0表示不限制个数)
## 数据压缩支持
由于是内网穿透,内网客户端与服务端之间的隧道存在大量的数据交换,为节省流量,加快传输速度,由此本程序支持SNNAPY形式的压缩。
- 所有模式均支持数据压缩
- 在web管理或客户端配置文件中设置
## 加密传输
如果公司内网防火墙对外网访问进行了流量识别与屏蔽,例如禁止了ssh协议等,通过设置 配置文件,将服务端与客户端之间的通信内容加密传输,将会有效防止流量被拦截。
- nps现在默认每次启动时随机生成tls证书,用于加密传输
> 链路加密的新方式:在 `nps.conf` 设置 `tls_enable=true`,客户端连接 `tls_bridge_port`(默认 `8025`)并加 `-tls_enable=true` 参数。详见 [TLS 桥接加密](/server/nps_extend.html#tls-桥接加密v02617)。
> nps 仍会在每次启动时随机生成 TLS 证书用于桥接通道。
## 站点保护
@@ -51,6 +75,18 @@
## 负载均衡
本代理支持域名解析模式和tcp代理的负载均衡,在web域名添加或者编辑中内网目标分行填写多个目标即可实现轮训级别的负载均衡
## 隧道端口自动生成
在 web 后台新增隧道时,**服务端端口留空即可自动生成**未被占用的端口号。
## 隧道复制
隧道列表页提供「复制」按钮:除了服务端端口随机生成,其他参数全部一键拷贝,方便创建多条相似隧道。
## TCP 隧道获取真实 IP
两种方式选一:
1. **[Proxy Protocol](/server/nps_extend.html#tcp-隧道-proxy-protocolv02623)**:在 web 上勾选开关,后端以 PROXY v1/v2 协议解析。
2. **HTTP 域名解析**:使用域名代理模式,配合 `http_add_origin_header=true` 通过 `X-Forwarded-For` / `X-Real-IP` 获取(见 [说明](/extend/description.html#获取用户真实ip))。
## 端口白名单
为了防止服务端上的端口被滥用,可在nps.conf中配置allow_ports限制可开启的端口,忽略或者不填表示端口不受限制,格式:
@@ -90,41 +126,10 @@ target_ip=10.1.50.2
支持域名泛解析,例如将host设置为*.proxy.com,a.proxy.com、b.proxy.com等都将解析到同一目标,在web管理中或客户端配置文件中将host设置为此格式即可。
## URL路由
本代理支持根据URL将同一域名转发到不同的内网服务器,可在web中或客户端配置文件中设置,此参数也可忽略,例如在客户端配置文件中
```ini
[web1]
host=a.proxy.com
target_addr=127.0.0.1:7001
location=/test
[web2]
host=a.proxy.com
target_addr=127.0.0.1:7002
location=/static
```
本代理支持根据URL将同一域名转发到不同的内网服务器,可在web中设置
对于`a.proxy.com/test`将转发到`web1`,对于`a.proxy.com/static`将转发到`web2`
## 限制ip访问
如果将一些危险性高的端口例如ssh端口暴露在公网上,可能会带来一些风险,本代理支持限制ip访问。
**使用方法:** 在配置文件nps.conf中设置`ip_limit`=true,设置后仅通过注册的ip方可访问。
**ip注册**:
**方式一:**
在需要访问的机器上,运行客户端
```
./npc register -server=ip:port -vkey=公钥或客户端密钥 time=2
```
time为有效小时数,例如time=2,在当前时间后的两小时内,本机公网ip都可以访问nps代理.
**方式二:**
此外nps的web登陆也可提供验证的功能,成功登陆nps web admin后将自动为登陆的ip注册两小时的允许访问权限。
**注意:** 本机公网ip并不是一成不变的,请自行注意有效期的设置,同时同一网络下,多人也可能是在公用同一个公网ip。
## 客户端最大连接数
为防止恶意大量长连接,影响服务端程序的稳定性,可以在web或客户端配置文件中为每个客户端设置最大连接数。该功能针对`socks5`、`http正向代理`、`域名代理`、`tcp代理`、`udp代理`、`私密代理`生效,使用该功能需要在`nps.conf`中设置`allow_connection_num_limit=true`,默认是关闭的。
@@ -164,79 +169,6 @@ export NPC_SERVER_VKEY=xxxxx
```
直接执行./npc即可运行
**在配置文件启动模式下:**
```ini
[common]
server_addr={{.NPC_SERVER_ADDR}}
conn_type=tcp
vkey={{.NPC_SERVER_VKEY}}
auto_reconnection=true
[web]
host={{.NPC_WEB_HOST}}
target_addr={{.NPC_WEB_TARGET}}
```
在配置文件中填入相应的环境变量名称,npc将自动进行渲染配置文件替换环境变量
## 健康检查
当客户端以配置文件模式启动时,支持多节点的健康检查。配置示例如下
```ini
[health_check_test1]
health_check_timeout=1
health_check_max_failed=3
health_check_interval=1
health_http_url=/
health_check_type=http
health_check_target=127.0.0.1:8083,127.0.0.1:8082
[health_check_test2]
health_check_timeout=1
health_check_max_failed=3
health_check_interval=1
health_check_type=tcp
health_check_target=127.0.0.1:8083,127.0.0.1:8082
```
**health关键词必须在开头存在**
第一种是http模式,也就是以get的方式请求目标+url,返回状态码为200表示成功
第一种是tcp模式,也就是以tcp的方式与目标建立连接,能成功建立连接表示成功
如果失败次数超过`health_check_max_failed`,nps则会移除该npc下的所有该目标,如果失败后目标重新上线,nps将自动将目标重新加入。
项 | 含义
---|---
health_check_timeout | 健康检查超时时间
health_check_max_failed | 健康检查允许失败次数
health_check_interval | 健康检查间隔
health_check_type | 健康检查类型
health_check_target | 健康检查目标,多个以逗号(,)分隔
health_check_type | 健康检查类型
health_http_url | 健康检查url,仅http模式适用
## 日志输出
日志输出级别
**对于npc:**
```
-log_level=0~7 -log_path=npc.log
```
```
LevelEmergency->0 LevelAlert->1
LevelCritical->2 LevelError->3
LevelWarning->4 LevelNotice->5
LevelInformational->6 LevelDebug->7
```
默认为全输出,级别为0到7
**对于nps:**
在`nps.conf`中设置相关配置即可
## pprof性能分析与调试
+398
View File
@@ -0,0 +1,398 @@
# Web API
> 除 `AuthController` 和 `LoginController` 外,所有接口均需通过鉴权,详见 [API 鉴权说明](api.html)。
## 通用响应格式
| 响应类型 | 格式 |
| --- | --- |
| 成功 | `{"status": 1, "msg": "success"}` |
| 成功(含 id) | `{"status": 1, "msg": "success", "id": 123}` |
| 失败 | `{"status": 0, "msg": "error message"}` |
| 列表 | `{"rows": [...], "total": 100}` |
> 单个查询接口(`GetClient`、`GetOneTunnel`、`GetHost`)返回 `{"code": 1, "data": {...}}` 或 `{"code": 0}`。
---
## Client 客户端管理
### 客户端列表
```
POST /client/list/
```
| 参数 | 含义 |
| --- | --- |
| search | 搜索关键词 |
| sort | 排序字段 |
| order | asc 正序 / desc 倒序 |
| offset | 分页起始 |
| limit | 每页条数 |
返回 `AjaxTable` 格式,额外含 `ip`、`bridgeType`、`bridgePort` 字段。
---
### 获取单个客户端
```
POST /client/getclient/
```
| 参数 | 含义 |
| --- | --- |
| id | 客户端 id |
---
### 添加客户端
```
POST /client/add/
```
| 参数 | 含义 |
| --- | --- |
| remark | 备注 |
| vkey | 客户端验证密钥 |
| u | basic 权限认证用户名 |
| p | basic 权限认证密码 |
| compress | 是否压缩传输,`true` / `false` |
| crypt | 是否加密传输,`true` / `false` |
| config_conn_allow | 是否允许客户端以配置文件模式连接,`true` / `false` |
| rate_limit | 带宽限制,单位 KB/s,留空不限制 |
| flow_limit | 流量限制,单位 M,留空不限制 |
| max_conn | 最大连接数,留空不限制 |
| max_tunnel | 最大隧道数,留空不限制 |
| web_username | web 用户登录用户名 |
| web_password | web 用户登录密码 |
| blackiplist | 黑名单 IP 列表,`\r\n` 分隔 |
| ipwhite | 是否开启 IP 白名单,`true` / `false` |
| ipwhitepass | IP 白名单授权密码 |
| ipwhitelist | 白名单 IP 列表,`\r\n` 分隔 |
| 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` |
---
### 修改客户端
```
POST /client/edit/
```
| 参数 | 含义 |
| --- | --- |
| id | 要修改的客户端 id |
| remark | 备注 |
| vkey | 客户端验证密钥(仅管理员可修改) |
| u | basic 权限认证用户名 |
| p | basic 权限认证密码 |
| compress | 是否压缩传输,`true` / `false` |
| crypt | 是否加密传输,`true` / `false` |
| config_conn_allow | 是否允许客户端以配置文件模式连接,`true` / `false` |
| rate_limit | 带宽限制,单位 KB/s(仅管理员可修改) |
| flow_limit | 流量限制,单位 M(仅管理员可修改) |
| max_conn | 最大连接数(仅管理员可修改) |
| max_tunnel | 最大隧道数(仅管理员可修改) |
| web_username | web 用户登录用户名 |
| web_password | web 用户登录密码 |
| blackiplist | 黑名单 IP 列表,`\r\n` 分隔 |
| ipwhite | 是否开启 IP 白名单,`true` / `false` |
| ipwhitepass | IP 白名单授权密码 |
| ipwhitelist | 白名单 IP 列表,`\r\n` 分隔 |
| expire_time | 到期时间,格式同新增接口 |
| flow_inlet | 入口流量,单位字节,传入则覆盖原值(留空不修改) |
| flow_export | 出口流量,单位字节,传入则覆盖原值(留空不修改) |
---
### 更改客户端状态
```
POST /client/changestatus/
```
| 参数 | 含义 |
| --- | --- |
| id | 客户端 id |
| status | `true` 启用 / `false` 禁用 |
---
### 删除客户端
```
POST /client/del/
```
| 参数 | 含义 |
| --- | --- |
| id | 要删除的客户端 id |
---
## Index 隧道管理
### 隧道列表
```
POST /index/gettunnel/
```
| 参数 | 含义 |
| --- | --- |
| client_id | 客户端 id |
| type | 隧道类型:`tcp`、`udp`、`httpProxy`、`socks5`、`secret`、`p2p`、`file` |
| search | 搜索关键词 |
| sort | 排序字段 |
| order | asc 正序 / desc 倒序 |
| offset | 分页起始 |
| limit | 每页条数 |
---
### 获取单条隧道
```
POST /index/getonetunnel/
```
| 参数 | 含义 |
| --- | --- |
| id | 隧道 id |
---
### 添加隧道
```
POST /index/add/
```
| 参数 | 含义 |
| --- | --- |
| client_id | 客户端 id |
| type | 隧道类型:`tcp`、`udp`、`httpProxy`、`socks5`、`secret`、`p2p`、`file` |
| remark | 备注 |
| port | 服务端端口(端口为 0 或留空时自动分配) |
| server_ip | 绑定的服务端 IP(多 IP 场景) |
| target | 内网目标,格式 `ip:端口` |
| local_proxy | 是否转发到 nps 服务器本地,`true` / `false` |
| password | 隧道密码(secret 模式) |
| local_path | 本地文件路径(file 模式) |
| strip_pre | URL 前缀去除(httpProxy 模式) |
| proto_version | 协议版本 |
---
### 复制隧道
```
POST /index/copy/
```
| 参数 | 含义 |
| --- | --- |
| id | 要复制的源隧道 id |
复制后自动分配新端口和新 id,其他配置沿用源隧道。
---
### 修改隧道
```
POST /index/edit/
```
| 参数 | 含义 |
| --- | --- |
| id | 隧道 id |
| client_id | 客户端 id |
| type | 隧道类型 |
| port | 服务端端口 |
| server_ip | 绑定的服务端 IP |
| target | 内网目标 |
| local_proxy | 是否转发到 nps 服务器本地 |
| remark | 备注 |
| password | 隧道密码 |
| local_path | 本地文件路径 |
| strip_pre | URL 前缀去除 |
| proto_version | 协议版本 |
| flow_inlet | 入口流量,单位字节,传入则覆盖原值(留空不修改) |
| flow_export | 出口流量,单位字节,传入则覆盖原值(留空不修改) |
---
### 停止隧道
```
POST /index/stop/
```
| 参数 | 含义 |
| --- | --- |
| id | 隧道 id |
---
### 启动隧道
```
POST /index/start/
```
| 参数 | 含义 |
| --- | --- |
| id | 隧道 id |
---
### 删除隧道
```
POST /index/del/
```
| 参数 | 含义 |
| --- | --- |
| id | 隧道 id |
---
## Host 域名解析管理
### 域名列表
```
POST /index/hostlist/
```
| 参数 | 含义 |
| --- | --- |
| client_id | 客户端 id |
| search | 搜索关键词(域名/备注) |
| offset | 分页起始 |
| limit | 每页条数 |
---
### 获取单条域名解析
```
POST /index/gethost/
```
| 参数 | 含义 |
| --- | --- |
| id | 域名解析 id |
---
### 添加域名解析
```
POST /index/addhost/
```
| 参数 | 含义 |
| --- | --- |
| client_id | 客户端 id |
| remark | 备注 |
| host | 域名 |
| scheme | 协议类型:`all`、`http`、`https` |
| location | URL 路由,留空不限制 |
| target | 内网目标,格式 `ip:端口` |
| local_proxy | 是否转发到 nps 服务器本地,`true` / `false` |
| header | 自定义 request header |
| hostchange | 修改 request host |
| key_file_path | HTTPS 证书私钥文本或路径 |
| cert_file_path | HTTPS 证书文件文本或路径 |
| AutoHttps | 是否自动 HTTPS(仅 scheme 非 `http` 时生效) |
---
### 修改域名解析
```
POST /index/edithost/
```
| 参数 | 含义 |
| --- | --- |
| id | 域名解析 id |
| client_id | 客户端 id |
| remark | 备注 |
| host | 域名 |
| scheme | 协议类型 |
| location | URL 路由 |
| target | 内网目标 |
| local_proxy | 是否转发到 nps 服务器本地 |
| header | 自定义 request header |
| hostchange | 修改 request host |
| key_file_path | HTTPS 证书私钥文本或路径 |
| cert_file_path | HTTPS 证书文件文本或路径 |
| AutoHttps | 是否自动 HTTPS |
| flow_inlet | 入口流量,单位字节,传入则覆盖原值(留空不修改) |
| flow_export | 出口流量,单位字节,传入则覆盖原值(留空不修改) |
```
POST /index/hoststop/
```
| 参数 | 含义 |
| --- | --- |
| id | 域名解析 id |
---
### 启动域名解析
```
POST /index/hoststart/
```
| 参数 | 含义 |
| --- | --- |
| id | 域名解析 id |
---
### 删除域名解析
```
POST /index/delhost/
```
| 参数 | 含义 |
| --- | --- |
| id | 域名解析 id |
---
## Global 全局设置
### 查看全局设置
```
GET /global/index/
```
返回全局黑名单 IP 列表和服务端 URL。
---
### 保存全局设置
```
POST /global/save/
```
| 参数 | 含义 |
| --- | --- |
| globalBlackIpList | 全局黑名单 IP 列表,`\r\n` 分隔 |
| serverUrl | 服务端访问地址(用于更正显示 IP) |
---
-20
View File
@@ -1,20 +0,0 @@
# FAQ
- 服务端无法启动
```
服务端默认配置启用了8024,8080,80,443端口,端口冲突无法启动,请修改配置
```
- 客户端无法连接服务端
```
请检查配置文件中的所有端口是否在安全组,防火墙放行
请检查vkey是否对应
请检查版本是否对应
```
- 服务端配置文件修改无效
```
install 之后,Linux 配置文件在 /etc/nps
```
- p2p穿透失败 [p2p服务](https://ehang-io.github.io/nps/#/example?id=p2p%e6%9c%8d%e5%8a%a1)
```
双方nat类型都是Symmetric Nat一定不成功,建议先查看nat类型。请按照文档操作(标题上有超链接)
```
-43
View File
@@ -1,43 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="description" content="Description">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<link rel="stylesheet" href="//unpkg.com/docsify/lib/themes/vue.css">
</head>
<body>
<div id="app"></div>
<script src="//unpkg.com/docsify-edit-on-github/index.js"></script>
<script>
window.$docsify = {
name: '',
repo: '',
loadSidebar: true,
coverpage: true,
loadNavbar: true,
subMaxLevel: 2,
maxLevel: 4,
search: {
noData: "没有结果",
paths: 'auto',
placeholder: "搜索",
hideOtherSidebarContent: true, // whether or not to hide other sidebar content
},
plugins: [
EditOnGithubPlugin.create("https://github.com/ehang-io/nps/tree/master/docs/", "", "在github上编辑"),
]
}
</script>
<script src="//unpkg.com/docsify/lib/docsify.min.js"></script>
<script src="//unpkg.com/docsify/lib/plugins/search.min.js"></script>
<script src="//unpkg.com/docsify-copy-code"></script>
</body>
</html>
-18
View File
@@ -1,18 +0,0 @@
# 安装
## 安装包安装
[releases](https://github.com/ehang-io/nps/releases)
下载对应的系统版本即可,服务端和客户端是单独的
## 源码安装
- 安装源码
```go get -u ehang.io/nps```
- 编译
服务端```go build cmd/nps/nps.go```
客户端```go build cmd/npc/npc.go```
## docker安装
> [server](https://hub.docker.com/r/ffdfgdfg/nps)
> [client](https://hub.docker.com/r/ffdfgdfg/npc)
+125
View File
@@ -0,0 +1,125 @@
## 程序安装
从 [releases](https://github.com/yisier/nps/releases) 下载对应系统版本,服务端 (`nps`) 和客户端 (`npc`) 是单独的压缩包。
::: tabs
@tab 服务端
> 首次启动时 `nps` 会在可执行文件同级目录自动生成 `conf/nps.conf`,并随机生成 `web_password`、`auth_key`、`auth_crypt_key`,web 管理界面的访问密码请在conf/nps.conf文件中或启动日志中查看。
`./npc(.exe) -server`
![img.png](/image/new/server.png)
@tab 客户端
> 客户端可直接双击运行,通过交互菜单完成安装、卸载、启动等操作。
`./npc(.exe)`
![image](/image/new/cmd.png)
@tab 客户端(GUI)
> 通过Web 后台的【快捷启动命令】或 手动填写 `-server`、`-vkey` 等参数配置客户端
![img](/image/new/gui.png)
:::
## Docker 安装
::: tabs
@tab 服务端
先拉取镜像:
```shell
docker pull yisier1/nps
```
启动容器,请把 `<本机conf目录>` 替换为实际路径(例如 `/root/nps/conf`):
```shell
docker run -d \
--restart=always \
--name nps \
--net=host \
-v <本机conf目录>:/conf \
-v /etc/localtime:/etc/localtime:ro \
yisier1/nps
```
@tab 客户端
先拉取镜像:
```shell
docker pull yisier1/npc
```
启动容器,请把 `<>` 内的值替换为实际配置:
```shell
docker run -d \
--restart=always \
--name <自定义名称> \
--net=host \
yisier1/npc \
-server=<服务器IP:端口> \
-vkey=<密钥>
```
:::
镜像主页:[NPS](https://hub.docker.com/r/yisier1/nps) | [NPC](https://hub.docker.com/r/yisier1/npc)。
## 宝塔面板(一键部署)
> 推荐宝塔版本 9.2.0+,前往 [宝塔面板官网](https://www.bt.cn/new/download.html) 安装。
![宝塔面板](/image/bt/bt1.jpg)
### 安装宝塔面板
1. 前往 [宝塔面板官网](https://www.bt.cn/new/download.html),选择正式版脚本安装。
2. 登录面板,点击左侧 **Docker** 进入 Docker 管理。
3. 如提示未安装 Docker / Docker Compose,可根据上方引导安装。
### 安装 NPS 服务端
1. 在宝塔面板 Docker 菜单进入 **应用商城**,搜索 `NPS`,找到 **NPS 服务端** 并点击安装。
2. 进入安装目录,修改 `conf/nps.conf` 即可(修改后重启容器)。参数说明详见 [配置文件](/server/server_config.html)。
![配置截图](/image/bt/bt2.png)
> **注意**:NPS 默认占用的端口为 `80`、`443`,如被占用请修改 `nps.conf` 中的 `http_proxy_port` 和 `https_proxy_port`。Web 管理默认端口 `8081`,启动后访问 `http://<IP>:8081`。
### 安装 NPS 客户端
1. 在宝塔面板 Docker 菜单进入 **应用商城**,搜索 `NPS`,找到 **NPS 客户端** 并点击安装。
2. 客户端支持两种配置方式:
- **无配置文件模式(推荐)**:输入 `服务地址`、`连接密钥` 即可启动。如需多个客户端,安装多个即可(名称不要重复)。
- **配置文件模式**:`服务地址`、`连接密钥` 留空直接安装,然后在安装目录下找到 `conf/npc.conf` 修改配置并重启容器。详见 [配置文件说明](/client/use.html#配置文件模式)。
![客户端配置](/image/bt/bt3.png)
> **推荐使用无配置文件模式**,所有数据在服务端保存和配置,客户端只做连接转发。配置文件模式对新手不友好,容易出错。
## 源码安装
需要 Go 1.22 及以上(仓库 `go.mod` 中 `toolchain` 锁定为 `go1.24.9`)。
```shell
git clone https://github.com/yisier/nps.git
cd nps
go build -o nps cmd/nps/nps.go
go build -o npc cmd/npc/npc.go
```
-4
View File
@@ -1,4 +0,0 @@
![image](https://github.com/ehang-io/nps/blob/master/image/web2.png?raw=true)
# 介绍
可在网页上配置和管理各个tcp、udp隧道、内网站点代理,http、https解析等,功能强大,操作方便。
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 614 KiB

-107
View File
@@ -1,107 +0,0 @@
# 增强功能
## 使用https
**方式一:** 类似于nginx实现https的处理
在配置文件中将https_proxy_port设置为443或者其他你想配置的端口,将`https_just_proxy`设置为false,nps 重启后,在web管理界面,域名新增或修改界面中修改域名证书和密钥。
**此外:** 可以在`nps.conf`中设置一个默认的https配置,当遇到未在web中设置https证书的域名解析时,将自动使用默认证书,另还有一种情况就是对于某些请求的clienthello不携带sni扩展信息,nps也将自动使用默认证书
**方式二:** 在内网对应服务器上设置https
在`nps.conf`中将`https_just_proxy`设置为true,并且打开`https_proxy_port`端口,然后nps将直接转发https请求到内网服务器上,由内网服务器进行https处理
## 与nginx配合
有时候我们还需要在云服务器上运行nginx来保证静态文件缓存等,本代理可和nginx配合使用,在配置文件中将httpProxyPort设置为非80端口,并在nginx中配置代理,例如httpProxyPort为8010时
```
server {
listen 80;
server_name *.proxy.com;
location / {
proxy_set_header Host $http_host;
proxy_pass http://127.0.0.1:8010;
}
}
```
如需使用https也可在nginx监听443端口并配置ssl,并将本代理的httpsProxyPort设置为空关闭https即可,例如httpProxyPort为8020时
```
server {
listen 443;
server_name *.proxy.com;
ssl on;
ssl_certificate certificate.crt;
ssl_certificate_key private.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
location / {
proxy_set_header Host $http_host;
proxy_pass http://127.0.0.1:8020;
}
}
```
## web管理使用https
如果web管理需要使用https,可以在配置文件`nps.conf`中设置`web_open_ssl=true`,并配置`web_cert_file`和`web_key_file`
## web使用Caddy代理
如果将web配置到Caddy代理,实现子路径访问nps,可以这样配置.
假设我们想通过 `http://caddy_ip:caddy_port/nps` 来访问后台, Caddyfile 这样配置:
```Caddyfile
caddy_ip:caddy_port/nps {
##server_ip 为 nps 服务器IP
##web_port 为 nps 后台端口
proxy / http://server_ip:web_port/nps {
transparent
}
}
```
nps.conf 修改 `web_base_url` 为 `/nps` 即可
```
web_base_url=/nps
```
## 关闭代理
如需关闭http代理可在配置文件中将http_proxy_port设置为空,如需关闭https代理可在配置文件中将https_proxy_port设置为空。
## 流量数据持久化
服务端支持将流量数据持久化,默认情况下是关闭的,如果有需求可以设置`nps.conf`中的`flow_store_interval`参数,单位为分钟
**注意:** nps不会持久化通过公钥连接的客户端
## 系统信息显示
nps服务端支持在web上显示和统计服务器的相关信息,但默认一些统计图表是关闭的,如需开启请在`nps.conf`中设置`system_info_display=true`
## 自定义客户端连接密钥
web上可以自定义客户端连接的密钥,但是必须具有唯一性
## 关闭公钥访问
可以将`nps.conf`中的`public_vkey`设置为空或者删除
## 关闭web管理
可以将`nps.conf`中的`web_port`设置为空或者删除
## 服务端多用户登陆
如果将`nps.conf`中的`allow_user_login`设置为true,服务端web将支持多用户登陆,登陆用户名为user,默认密码为每个客户端的验证密钥,登陆后可以进入客户端编辑修改web登陆的用户名和密码,默认该功能是关闭的。
## 用户注册功能
nps服务端支持用户注册功能,可将`nps.conf`中的`allow_user_register`设置为true,开启后登陆页将会有有注册功能,
## 监听指定ip
nps支持每个隧道监听不同的服务端端口,在`nps.conf`中设置`allow_multi_ip=true`后,可在web中控制,或者npc配置文件中(可忽略,默认为0.0.0.0)
```ini
server_ip=xxx
```
## 代理到服务端本地
在使用nps监听80或者443端口时,默认是将所有的请求都会转发到内网上,但有时候我们的nps服务器的上一些服务也需要使用这两个端口,nps提供类似于`nginx` `proxy_pass` 的功能,支持将代理到服务器本地,该功能支持域名解析,tcp、udp隧道,默认关闭。
**即:** 假设在nps的vps服务器上有一个服务使用5000端口,这时候nps占用了80端口和443,我们想能使用一个域名通过http(s)访问到5000的服务。
**使用方式:** 在`nps.conf`中设置`allow_local_proxy=true`,然后在web上设置想转发的隧道或者域名然后选择转发到本地选项即可成功。
-47
View File
@@ -1,47 +0,0 @@
# 使用
**提示:使用web模式时,服务端执行文件必须在项目根目录,否则无法正确加载配置文件**
## web管理
进入web界面,公网ip:web界面端口(默认8080),密码默认为123
进入web管理界面,有详细的说明
## 服务端配置文件重载
对于linux、darwin
```shell
sudo nps reload
```
对于windows
```shell
nps.exe reload
```
**说明:** 仅支持部分配置重载,例如`allow_user_login` `auth_crypt_key` `auth_key` `web_username` `web_password` 等,未来将支持更多
## 服务端停止或重启
对于linux、darwin
```shell
sudo nps stop|restart
```
对于windows
```shell
nps.exe stop|restart
```
## 服务端更新
请首先执行 `sudo nps stop` 或者 `nps.exe stop` 停止运行,然后
对于linux
```shell
sudo nps-update update
```
对于windows
```shell
nps-update.exe update
```
更新完成后,执行执行 `sudo nps start` 或者 `nps.exe start` 重新运行即可完成升级
如果无法更新成功,可以直接自行下载releases压缩包然后覆盖原有的nps二进制文件和web目录
注意:`nps install` 之后的 nps 不在原位置,请使用 `whereis nps` 查找具体目录覆盖 nps 二进制文件
+24
View File
@@ -0,0 +1,24 @@
{
"name": "nps-docs",
"version": "1.0.0",
"description": "NPS 内网穿透文档站点 (VuePress 2)",
"private": true,
"scripts": {
"docs:dev": "vuepress dev .",
"docs:build": "vuepress build .",
"docs:clean": "vuepress clean ."
},
"devDependencies": {
"@vuepress/bundler-vite": "2.0.0-rc.30",
"@vuepress/plugin-search": "2.0.0-rc.130",
"@vuepress/plugin-shiki": "2.0.0-rc.130",
"@vuepress/theme-default": "2.0.0-rc.130",
"sass": "1.77.8",
"vite": "^8.0.16",
"vue": "^3.5.34",
"vuepress": "2.0.0-rc.30"
},
"resolutions": {
"@vuepress/plugin-palette": "2.0.0-rc.130"
}
}
-42
View File
@@ -1,42 +0,0 @@
# 启动
## 服务端
下载完服务器压缩包后,解压,然后进入解压后的文件夹
- 执行安装命令
对于linux|darwin ```sudo ./nps install```
对于windows,管理员身份运行cmd,进入安装目录 ```nps.exe install```
- 启动
对于linux|darwin ```sudo nps start```
对于windows,管理员身份运行cmd,进入程序目录 ```nps.exe start```
```安装后windows配置文件位于 C:\Program Files\nps,linux和darwin位于/etc/nps```
停止和重启可用,stop和restart
**如果发现没有启动成功,可以使用`nps(.exe) stop`,然后运行`nps.(exe)`运行调试,或查看日志**(Windows日志文件位于当前运行目录下,linux和darwin位于/var/log/nps.log)
- 访问服务端ip:web服务端口(默认为8080)
- 使用用户名和密码登陆(默认admin/123,正式使用一定要更改)
- 创建客户端
## 客户端
- 下载客户端安装包并解压,进入到解压目录
- 点击web管理中客户端前的+号,复制启动命令
- 执行启动命令,linux直接执行即可,windows将./npc换成npc.exe用**cmd执行**
如果使用`powershell`运行,**请将ip括起来!**
如果需要注册到系统服务可查看[注册到系统服务](/use?id=注册到系统服务)
## 版本检查
- 对客户端以及服务的均可以使用参数`-version`打印版本
- `nps -version`或`./nps -version`
- `npc -version`或`./npc -version`
## 配置
- 客户端连接后,在web中配置对应穿透服务即可
- 可以查看[使用示例](/example)
+195
View File
@@ -0,0 +1,195 @@
# 增强功能
## 使用 https
> nps 会根据域名是否上传了证书自动选择处理方式:
| 是否在 web 上传证书 | 行为 | 真实 IP |
| --- | --- | --- |
| 是 | nps 直接接管 SSL 终结,再转发到内网 | ✅ 可拿到 |
| 否 | nps 透传 TLS(端口转发),由内网服务器自行解密 | ❌ 拿不到 |
![image](/image/new/https.png)
## 自动 HTTPS
在 web 域名编辑页勾选「自动 HTTPS」后,nps 会把对应域名的 http 请求 301 重定向到 https。
重定向会按 `https_proxy_port` 配置的端口跳转(例如 `https_proxy_port=8443` 时会跳到 `https://<host>:8443/...`),方便非标准端口部署。
## HTTPS 证书来源
web 域名编辑页的「证书」/「私钥」字段同时支持:
- **直接粘贴证书 / 私钥内容**
- **填写服务器上的文件路径**(例如 `/etc/letsencrypt/live/proxy.com/fullchain.pem`)
nps 会自动识别是文件路径还是内容。文件路径方式便于配合 acme.sh / certbot 自动续期,无需每次手工拷贝。
## TLS 桥接加密
为防止客户端到服务端的桥接流量被防火墙识别和拦截,可启用 TLS:
```ini
# nps.conf
tls_enable=true
tls_bridge_port=8025 # v0.26.18 引入,与 bridge_port 并存
```
客户端任选一种方式接入:
```shell
npc.exe -server=1.1.1.1:8024 -vkey=xxx # 明文桥接(bridge_port)
npc.exe -server=1.1.1.1:8025 -vkey=xxx -tls_enable=true # TLS 桥接(tls_bridge_port)
```
> 客户端忽略证书校验,请勿暴露在不可信网络里。
## 全局参数
> 未来会在此页面继续扩展更多功能,欢迎提需求。
web 后台 → 全局参数 页面(对应 `conf/global.json`):
| 字段 | 含义 |
| --- | --- |
| 全局 IP 黑名单 | 一行一个 IPv4,不支持范围匹配。命中后所有 TCP/HTTP/HTTPS/UDP 入口请求都会被直接关闭。用于防止扫描和暴力破解 |
| 服务地址 |用于在 web 上生成 [客户端快捷启动命令]、隧道访问 URL 时拼接的服务端地址。留空则使用浏览器当前访问地址 |
## 客户端黑名单
在客户端编辑页可填写多个 IP,命中后该客户端下所有隧道都会拒绝服务,用于针对单个客户端阻断。
## 客户端白名单 + IP 授权
在客户端编辑页:
1. 直接添加 IP 到白名单
2. 或填写「IP 授权密码」。当外网 IP 不在白名单时,会被重定向到 IP 授权页面,输入正确密码即可把该 IP 自动加入白名单。
![img](/image/new/ip.png)
## Proxy Protocol
在 web 上 TCP 隧道编辑页开启「Proxy Protocol」开关,nps 会以 PROXY v1/v2 协议向后端转发原始来源 IP。后端服务(nginx、HAProxy 等)只需正常解析 PROXY 协议即可拿到真实客户端 IP。
![img](/image/new/protocol.png)
## WEB登录验证码
`nps.conf` 中:
```ini
open_captcha=true
```
开启后 web 登录页会要求图形验证码。结合「web 管理保护」(连续 10 次失败封禁 1 分钟,见 [说明](/extend/description.html#web管理保护)),可以有效缓解暴力破解。
## 关闭代理
如需关闭 http 代理,将 `http_proxy_port` 留空;如需关闭 https 代理,将 `https_proxy_port` 留空。
## 流量数据持久化
服务端支持将流量数据持久化,默认关闭。在 `nps.conf` 中设置 `flow_store_interval`(单位分钟)即可开启。
**注意:** nps 不会持久化通过公钥连接的客户端。
## 系统信息显示
nps 服务端支持在 web 上显示和统计服务器相关信息,但默认部分统计图表是关闭的。如需开启请在 `nps.conf` 中设置 `system_info_display=true`。
## 关闭 web 管理
将 `nps.conf` 中的 `web_port` 设置为空或删除。
## 服务端多用户登录
将 `allow_user_login=true`,登录用户名 `user`,密码为对应客户端的验证密钥。登录后可进入客户端编辑修改 web 登录用户名密码。默认关闭。
## 用户注册功能
将 `allow_user_register=true` 后登录页会出现注册入口。
## 监听指定 IP
nps 支持每个隧道监听不同的服务端 IP,`nps.conf` 中设置 `allow_multi_ip=true` 后,可在 web 中控制,或 npc 配置文件中指定:
```ini
server_ip=xxx
```
## 客户端到期时间
在创建 / 修改客户端时可填写「到期时间」(可留空表示永不过期)。到期后该客户端会被**自动暂停**,所有隧道停止服务,直到管理员手工延长或清空到期时间。
支持格式:`2006-01-02 15:04:05` / `2006-01-02 15:04` / `2006-01-02T15:04:05` / `2006-01-02T15:04` / `2006-01-02`。
## 首次启动随机凭据
为避免默认密码被恶意扫描,**首次启动时** `web_username`(默认 `admin`)、`web_password`、`auth_key`、`auth_crypt_key` 全部随机生成,并直接打印到终端:
```text
[INFO] generated random web_password: <xxxxxxxx>
[INFO] generated random auth_key: <xxxxxxxx>
[INFO] generated random auth_crypt_key: <xxxxxxxxxxxxxxxx>
```
请在第一次启动时妥善记录。后续可在 `nps.conf` 中手工修改。
## 与 nginx 配合
有时需要在云服务器上跑 nginx 做静态缓存或多服务复用 80/443。把 `http_proxy_port` 设为非 80 端口(例如 8010),由 nginx 反代:
```
server {
listen 80;
server_name *.proxy.com;
location / {
proxy_set_header Host $http_host;
proxy_pass http://127.0.0.1:8010;
}
}
```
如需 https 也由 nginx 终结,将 `https_proxy_port` 留空关闭,由 nginx 监听 443:
```
server {
listen 443;
server_name *.proxy.com;
ssl on;
ssl_certificate certificate.crt;
ssl_certificate_key private.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
location / {
proxy_set_header Host $http_host;
proxy_pass http://127.0.0.1:8020;
}
}
```
## web 管理使用 https
在 `nps.conf` 中设置 `web_open_ssl=true`,并配置 `web_cert_file` 与 `web_key_file`。
## web 使用 Caddy 代理
实现子路径访问 nps,假设想通过 `http://caddy_ip:caddy_port/nps` 访问后台:
```nginx
caddy_ip:caddy_port/nps {
##server_ip 为 nps 服务器IP
##web_port 为 nps 后台端口
proxy / http://server_ip:web_port/nps {
transparent
}
}
```
`nps.conf` 中设置:
```
web_base_url=/nps
```
+50
View File
@@ -0,0 +1,50 @@
## Web 管理
进入 web 界面:`公网IP:web 端口`(默认 `8081`)。
> **首次启动 `web_username`(默认 `admin`)、`web_password`、`auth_key`、`auth_crypt_key` 均为随机生成**,会打印到终端日志中,请第一时间复制保存。后续如需变更可直接修改 `conf/nps.conf` 后 `nps reload`。
进入 web 管理界面,有详细的说明。
## 服务端管理脚本
```shell
./nps -server # linux/darwin(操作系统服务时需 sudo)
nps.exe -server # windows(操作系统服务时需管理员)
```
交互菜单覆盖了安装、卸载、启停、重启、更新等全部场景。
![img.png](/image/new/server.png)
## 工作目录与配置文件位置
- nps安装系统服务后,配置文件默认在当前目录,目录结构为:
```
nps_dir/
├── conf/
│ └── nps.conf // nps主配置文件
│ └── client.json // 客户端列表配置文件
│ └── tasks.json // 隧道列表配置文件
│ └── hosts.json // 域名解析列表配置文件
│ └── global.json // 全局参数配置文件
├── nps // nps主程序
```
## 更新
```shell
./nps -server # 选择 “更新” 菜单项
```
更新只会替换 `nps` 二进制文件,对配置文件和用户数据无影响,更新完成后重新启动即可。
>如果无法成功更新,可直接下载 releases 压缩包覆盖原有的 `nps` 二进制文件。
## 数据迁移
数据迁移只需迁移 `conf` 目录,该目录包含配置文件以及用户数据(json格式文件),放到 nps(.exe) 的同级目录下,直接启动即可。
+89
View File
@@ -0,0 +1,89 @@
# 服务端配置文件
配置文件路径:`<nps 可执行文件目录>/conf/nps.conf`
> 首次启动时若 `conf/nps.conf` 不存在会**自动生成默认配置**,其中 `web_username`(默认 `admin`)、`web_password`、`auth_key`、`auth_crypt_key` **均为随机值**并打印到终端,请在启动日志或配置文件中查看。
## 通用配置
| 名称 | 含义 | 默认值 |
| --- | --- | --- |
| bridge_type | 客户端与服务端连接方式 `tcp` 或 `kcp` | `tcp` |
| bridge_ip | 桥接监听 IP | `0.0.0.0` |
| bridge_port | 服务端客户端通信端口 | `8024` |
| tls_enable | 是否开启 TLS。开启后客户端可通过 `-tls_enable=true` 连接 `tls_bridge_port` | `true` |
| tls_bridge_port | TLS 桥接端口,默认 `8025`。**与 `bridge_port` 并存**:客户端可分别用 `bridge_port`(明文)或 `tls_bridge_port`(TLS)接入 | `8025` |
| disconnect_timeout | 客户端连接超时,单位为 5s,默认 `60`(即 5 分钟) | `60` |
| flow_store_interval | 流量数据持久化间隔,单位分钟;忽略表示不持久化| `1` |
| log_level | 日志级别 0~7 | `6` |
| log_path | 日志文件路径 | `nps.log` |
| ip_limit | 是否限制 IP 访问,`true` / `false` / 忽略 | - |
## HTTP(S) 代理
| 名称 | 含义 | 默认值 |
| --- | --- | --- |
| http_proxy_ip | http(s) 代理监听 IP,默认 `0.0.0.0` | `0.0.0.0` |
| http_proxy_port | 域名代理 http 监听端口(默认 `80`),留空关闭 | `80` |
| https_proxy_port | 域名代理 https 监听端口(默认 `443`),留空关闭。详见 [使用 https](/server/nps_extend.html#使用-https) | `443` |
| show_http_proxy_port | 域名隧道访问地址是否拼接非 80/443 端口,`true` / `false` | `true` |
| http_add_origin_header | 是否在 http(s) 请求头中追加 `X-Forwarded-For` / `X-Real-IP`,用于内网获取真实 IP | `true` |
| http_cache | 是否开启静态文件缓存 | `false` |
| http_cache_length | 缓存条目数上限,`0` 表示不限制 | `100` |
## Web 管理后台
| 名称 | 含义 | 默认值 |
| --- | --- | --- |
| web_host | web 管理使用的二级域名,端口复用时区分用 | `a.o.com` |
| web_username | web 后台用户名(默认 `admin` | `admin` |
| web_password | web 后台密码 | 首次启动随机生成 |
| web_port | web 管理端口,留空关闭 web | `8081` |
| web_ip | web 管理监听 IP | `0.0.0.0` |
| web_base_url | web 管理子路径,例如 `/nps`,用于反代到子路径时使用 | (空) |
| web_open_ssl | web 管理是否启用 https | `false` |
| web_cert_file | web 管理 https 证书路径 | `conf/server.pem` |
| web_key_file | web 管理 https 私钥路径 | `conf/server.key` |
| open_captcha | 登录是否开启验证码校验 | `false` |
| allow_user_login | 是否允许多用户登录,开启后用户名 `user`,密码为客户端的验证密钥 | `true` |
| allow_user_register | 是否允许从登录页注册账号 | `false` |
| allow_user_change_username | 多用户登录后是否允许修改用户名 | `true` |
## API 鉴权
| 名称 | 含义 | 默认值 |
| --- | --- | --- |
| auth_key | web API 鉴权密钥,详见 [Web API](/nps/extend/api.html) | 首次启动随机生成 |
| auth_crypt_key | `auth/getauthkey` 接口的 AES 加密密钥,**必须 16 位** | 首次启动随机生成 |
## P2P
| 名称 | 含义 | 默认值 |
| --- | --- | --- |
| p2p_ip | 服务端 IP,使用 p2p 模式必填 | - |
| p2p_port | p2p 模式开启的 UDP 起始端口。若设为 `6000`,请额外开放 `6001`、`6002` | - |
## 限制开关
> 这些开关默认关闭。开启后才会在 web 管理中暴露对应字段。
| 名称 | 含义 | 默认值 |
| --- | --- | --- |
| allow_flow_limit | 是否启用客户端流量限制 | `true` |
| allow_rate_limit | 是否启用客户端带宽限制 | `true` |
| allow_tunnel_num_limit | 是否启用客户端最大隧道数限制 | `true` |
| allow_connection_num_limit | 是否启用客户端最大连接数限制 | `true` |
| allow_multi_ip | 是否允许每个隧道监听不同的服务端 IP | `true` |
| allow_local_proxy | 是否允许把隧道目标转发到 nps 所在服务器本地 | `false` |
| allow_ports | 限制可开放的隧道端口范围,例如 `9001-9009,10001,11000-12000`,留空不限制 | (空) |
| system_info_display | 是否在 web 上展示服务器系统监控信息图表 | `true` |
## debug / pprof
| 名称 | 含义 | 默认值 |
| --- | --- | --- |
| pprof_ip | debug pprof 监听 IP | - |
| pprof_port | debug pprof 监听端口 | - |
-24
View File
@@ -1,24 +0,0 @@
# 服务端配置文件
- /etc/nps/conf/nps.conf
名称 | 含义
---|---
web_port | web管理端口
web_password | web界面管理密码
web_username | web界面管理账号
web_base_url | web管理主路径,用于将web管理置于代理子路径后面
bridge_port | 服务端客户端通信端口
https_proxy_port | 域名代理https代理监听端口
http_proxy_port | 域名代理http代理监听端口
auth_key|web api密钥
bridge_type|客户端与服务端连接方式kcp或tcp
public_vkey|客户端以配置文件模式启动时的密钥,设置为空表示关闭客户端配置文件连接模式
ip_limit|是否限制ip访问,true或false或忽略
flow_store_interval|服务端流量数据持久化间隔,单位分钟,忽略表示不持久化
log_level|日志输出级别
auth_crypt_key | 获取服务端authKey时的aes加密密钥,16位
p2p_ip| 服务端Ip,使用p2p模式必填
p2p_port|p2p模式开启的udp端口
pprof_ip|debug pprof 服务端ip
pprof_port|debug pprof 端口
disconnect_timeout|客户端连接超时,单位 5s,默认值 60,即 300s = 5mins
-5
View File
@@ -1,5 +0,0 @@
Thanks [jetbrains](https://www.jetbrains.com/?from=nps) for providing development tools for nps
<html>
<img src="https://ftp.bmp.ovh/imgs/2019/12/6435398b0c7402b1.png" width="300" align=center />
</html>
-225
View File
@@ -1,225 +0,0 @@
# 基本使用
## 无配置文件模式
此模式的各种配置在服务端web管理中完成,客户端除运行一条命令外无需任何其他设置
```
./npc -server=ip:port -vkey=web界面中显示的密钥
```
## 注册到系统服务(开机启动、守护进程)
对于linux、darwin
- 注册:`sudo ./npc install 其他参数(例如-server=xx -vkey=xx或者-config=xxx)`
- 启动:`sudo npc start`
- 停止:`sudo npc stop`
- 如果需要更换命令内容需要先卸载`./npc uninstall`,再重新注册
对于windows,使用管理员身份运行cmd
- 注册:`npc.exe install 其他参数(例如-server=xx -vkey=xx或者-config=xxx)`
- 启动:`npc.exe start`
- 停止:`npc.exe stop`
- 如果需要更换命令内容需要先卸载`npc.exe uninstall`,再重新注册
- 如果需要当客户端退出时自动重启客户端,请按照如图所示配置
![image](https://github.com/ehang-io/nps/blob/master/docs/windows_client_service_configuration.png?raw=true)
注册到服务后,日志文件windows位于当前目录下,linux和darwin位于/var/log/npc.log
## 客户端更新
首先进入到对于的客户端二进制文件目录
请首先执行`sudo npc stop`或者`npc.exe stop`停止运行,然后
对于linux
```shell
sudo npc-update update
```
对于windows
```shell
npc-update.exe update
```
更新完成后,执行执行`sudo npc start`或者`npc.exe start`重新运行即可完成升级
如果无法更新成功,可以直接自行下载releases压缩包然后覆盖原有的npc二进制文件
## 配置文件模式
此模式使用nps的公钥或者客户端私钥验证,各种配置在客户端完成,同时服务端web也可以进行管理
```
./npc -config=npc配置文件路径
```
## 配置文件说明
[示例配置文件](https://github.com/ehang-io/nps/tree/master/conf/npc.conf)
#### 全局配置
```ini
[common]
server_addr=1.1.1.1:8024
conn_type=tcp
vkey=123
username=111
password=222
compress=true
crypt=true
rate_limit=10000
flow_limit=100
remark=test
max_conn=10
#pprof_addr=0.0.0.0:9999
```
项 | 含义
---|---
server_addr | 服务端ip/域名:port
conn_type | 与服务端通信模式(tcp或kcp)
vkey|服务端配置文件中的密钥(非web)
username|socks5或http(s)密码保护用户名(可忽略)
password|socks5或http(s)密码保护密码(可忽略)
compress|是否压缩传输(true或false或忽略)
crypt|是否加密传输(true或false或忽略)
rate_limit|速度限制,可忽略
flow_limit|流量限制,可忽略
remark|客户端备注,可忽略
max_conn|最大连接数,可忽略
pprof_addr|debug pprof ip:port
#### 域名代理
```ini
[common]
server_addr=1.1.1.1:8024
vkey=123
[web1]
host=a.proxy.com
target_addr=127.0.0.1:8080,127.0.0.1:8082
host_change=www.proxy.com
header_set_proxy=nps
```
项 | 含义
---|---
web1 | 备注
host | 域名(http|https都可解析)
target_addr|内网目标,负载均衡时多个目标,逗号隔开
host_change|请求host修改
header_xxx|请求header修改或添加,header_proxy表示添加header proxy:nps
#### tcp隧道模式
```ini
[common]
server_addr=1.1.1.1:8024
vkey=123
[tcp]
mode=tcp
target_addr=127.0.0.1:8080
server_port=9001
```
项 | 含义
---|---
mode | tcp
server_port | 在服务端的代理端口
tartget_addr|内网目标
#### udp隧道模式
```ini
[common]
server_addr=1.1.1.1:8024
vkey=123
[udp]
mode=udp
target_addr=127.0.0.1:8080
server_port=9002
```
项 | 含义
---|---
mode | udp
server_port | 在服务端的代理端口
target_addr|内网目标
#### http代理模式
```ini
[common]
server_addr=1.1.1.1:8024
vkey=123
[http]
mode=httpProxy
server_port=9003
```
项 | 含义
---|---
mode | httpProxy
server_port | 在服务端的代理端口
#### socks5代理模式
```ini
[common]
server_addr=1.1.1.1:8024
vkey=123
[socks5]
mode=socks5
server_port=9004
multi_account=multi_account.conf
```
项 | 含义
---|---
mode | socks5
server_port | 在服务端的代理端口
multi_account | socks5多账号配置文件(可选),配置后使用basic_username和basic_password无法通过认证
#### 私密代理模式
```ini
[common]
server_addr=1.1.1.1:8024
vkey=123
[secret_ssh]
mode=secret
password=ssh2
target_addr=10.1.50.2:22
```
项 | 含义
---|---
mode | secret
password | 唯一密钥
target_addr|内网目标
#### p2p代理模式
```ini
[common]
server_addr=1.1.1.1:8024
vkey=123
[p2p_ssh]
mode=p2p
password=ssh2
target_addr=10.1.50.2:22
```
项 | 含义
---|---
mode | p2p
password | 唯一密钥
target_addr|内网目标
#### 文件访问模式
利用nps提供一个公网可访问的本地文件服务,此模式仅客户端使用配置文件模式方可启动
```ini
[common]
server_addr=1.1.1.1:8024
vkey=123
[file]
mode=file
server_port=9100
local_path=/tmp/
strip_pre=/web/
````
项 | 含义
---|---
mode | file
server_port | 服务端开启的端口
local_path|本地文件目录
strip_pre|前缀
对于`strip_pre`,访问公网`ip:9100/web/`相当于访问`/tmp/`目录
#### 断线重连
```ini
[common]
auto_reconnection=true
```
-235
View File
@@ -1,235 +0,0 @@
获取客户端列表
```
POST /client/list/
```
| 参数 | 含义 |
| --- | --- |
| search | 搜索 |
| order | 排序asc 正序 desc倒序 |
| offset | 分页(第几页) |
| limit | 条数(分页显示的条数) |
***
获取单个客户端
```
POST /client/getclient/
```
| 参数 | 含义 |
| --- | --- |
| id | 客户端id |
***
添加客户端
```
POST /client/add/
```
| 参数 | 含义 |
| --- | --- |
| remark | 备注 |
| u | basic权限认证用户名 |
| p | basic权限认证密码 |
| limit | 条数(分页显示的条数) |
| vkey | 客户端验证密钥 |
| config\_conn\_allow | 是否允许客户端以配置文件模式连接 1允许 0不允许 |
| compress | 压缩1允许 0不允许 |
| crypt | 是否加密(1或者0)1允许 0不允许 |
| rate\_limit | 带宽限制 单位KB/S 空则为不限制 |
| 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` |
***
修改客户端
```
POST /client/edit/
```
| 参数 | 含义 |
| --- | --- |
| remark | 备注 |
| u | basic权限认证用户名 |
| p | basic权限认证密码 |
| limit | 条数(分页显示的条数) |
| vkey | 客户端验证密钥 |
| config\_conn\_allow | 是否允许客户端以配置文件模式连接 1允许 0不允许 |
| compress | 压缩1允许 0不允许 |
| crypt | 是否加密(1或者0)1允许 0不允许 |
| rate\_limit | 带宽限制 单位KB/S 空则为不限制 |
| flow\_limit | 流量限制 单位M 空则为不限制 |
| max\_conn | 客户端最大连接数量 空则为不限制 |
| max\_tunnel | 客户端最大隧道数量 空则为不限制 |
| expire\_time | 到期时间,留空表示永不过期,到期后自动暂停。格式同新增接口 |
| id | 要修改的客户端id |
***
删除客户端
```
POST /client/del/
```
| 参数 | 含义 |
| --- | --- |
| id | 要删除的客户端id |
***
获取域名解析列表
```
POST /index/hostlist/
```
| 参数 | 含义 |
| --- | --- |
| search | 搜索(可以搜域名/备注什么的) |
| offset | 分页(第几页) |
| limit | 条数(分页显示的条数) |
***
添加域名解析
```
POST /index/addhost/
```
| 参数 | 含义 |
| --- | --- |
| remark | 备注 |
| host | 域名 |
| scheme | 协议类型(三种 all http https) |
| location | url路由 空则为不限制 |
| client\_id | 客户端id |
| target | 内网目标(ip:端口) |
| header | request header 请求头 |
| hostchange | request host 请求主机 |
***
修改域名解析
```
POST /index/edithost/
```
| 参数 | 含义 |
| --- | --- |
| remark | 备注 |
| host | 域名 |
| scheme | 协议类型(三种 all http https) |
| location | url路由 空则为不限制 |
| client\_id | 客户端id |
| target | 内网目标(ip:端口) |
| header | request header 请求头 |
| hostchange | request host 请求主机 |
| id | 需要修改的域名解析id |
***
删除域名解析
```
POST /index/delhost/
```
| 参数 | 含义 |
| --- | --- |
| id | 需要删除的域名解析id |
***
获取单条隧道信息
```
POST /index/getonetunnel/
```
| 参数 | 含义 |
| --- | --- |
| id | 隧道的id |
***
获取隧道列表
```
POST /index/gettunnel/
```
| 参数 | 含义 |
| --- | --- |
| client\_id | 穿透隧道的客户端id |
| type | 类型tcp udp httpProx socks5 secret p2p |
| search | 搜索 |
| offset | 分页(第几页) |
| limit | 条数(分页显示的条数) |
***
添加隧道
```
POST /index/add/
```
| 参数 | 含义 |
| --- | --- |
| type | 类型tcp udp httpProx socks5 secret p2p |
| remark | 备注 |
| port | 服务端端口 |
| target | 目标(ip:端口) |
| client\_id | 客户端id |
***
修改隧道
```
POST /index/edit/
```
| 参数 | 含义 |
| --- | --- |
| type | 类型tcp udp httpProx socks5 secret p2p |
| remark | 备注 |
| port | 服务端端口 |
| target | 目标(ip:端口) |
| client\_id | 客户端id |
| id | 隧道id |
***
删除隧道
```
POST /index/del/
```
| 参数 | 含义 |
| --- | --- |
| id | 隧道id |
***
隧道停止工作
```
POST /index/stop/
```
| 参数 | 含义 |
| --- | --- |
| id | 隧道id |
***
隧道开始工作
```
POST /index/start/
```
| 参数 | 含义 |
| --- | --- |
| id | 隧道id |
Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

+10
View File
@@ -21,6 +21,9 @@ const (
RES_MSG = "msg0"
RES_CLOSE = "clse"
NEW_UDP_CONN = "udpc" //p2p udp conn
// REPORT_LOCAL_IP: server requests client local/private IPs on WORK_MAIN.
// New clients reply with WriteLenContent; old clients ignore the flag (server times out).
REPORT_LOCAL_IP = "rlip"
NEW_TASK = "task"
NEW_CONF = "conf"
NEW_HOST = "host"
@@ -32,6 +35,13 @@ Content-Type: text/plain; charset=utf-8
WWW-Authenticate: Basic realm="easyProxy"
401 Unauthorized`
// ProxyAuthRequiredBytes is the challenge for HTTP forward proxy Basic auth (RFC 7235).
// Clients expect 407 + Proxy-Authenticate, not 401 + WWW-Authenticate.
ProxyAuthRequiredBytes = "HTTP/1.1 407 Proxy Authentication Required\r\n" +
"Content-Type: text/plain; charset=utf-8\r\n" +
"Proxy-Authenticate: Basic realm=\"nps\"\r\n" +
"\r\n" +
"407 Proxy Authentication Required"
ConnectionFailBytes = `HTTP/1.1 404 Not Found
`
+93
View File
@@ -482,6 +482,99 @@ func GetIntranetIp() (error, string) {
return errors.New("get intranet ip error"), ""
}
// isUsefulPrivateIPv4 reports whether ip is a usable LAN IPv4 for display:
// RFC1918 private only — excludes loopback, link-local (169.254.0.0/16), public, etc.
func isUsefulPrivateIPv4(ip net.IP) bool {
if ip == nil {
return false
}
v4 := ip.To4()
if v4 == nil {
return false
}
if v4.IsLoopback() || v4.IsLinkLocalUnicast() || v4.IsLinkLocalMulticast() || v4.IsUnspecified() || v4.IsMulticast() {
return false
}
// RFC1918 only (not 169.254, not public)
return v4.IsPrivate()
}
func ipFromAddr(addr net.Addr) net.IP {
if addr == nil {
return nil
}
switch a := addr.(type) {
case *net.TCPAddr:
return a.IP
case *net.UDPAddr:
return a.IP
default:
return net.ParseIP(GetIpByAddr(addr.String()))
}
}
// GetLocalIPs returns private (RFC1918) IPv4 addresses useful for identifying the npc host.
// Prefers the local IP of conn (path toward nps). Falls back to interface scan.
// Link-local 169.254.0.0/16, loopback and public addresses are excluded.
func GetLocalIPs(conn net.Conn) string {
seen := make(map[string]struct{})
ips := make([]string, 0, 4)
add := func(ip net.IP) {
if !isUsefulPrivateIPv4(ip) {
return
}
s := ip.To4().String()
if _, ok := seen[s]; ok {
return
}
seen[s] = struct{}{}
ips = append(ips, s)
}
// 1) Local endpoint of the bridge connection — usually the real LAN IP used to reach nps.
if conn != nil {
add(ipFromAddr(conn.LocalAddr()))
// One correct path IP is enough for most hosts (avoids docker/vm junk alongside).
if len(ips) > 0 {
return ips[0]
}
}
// 2) Outbound interface toward the internet (same idea as GetLocalUdpAddr).
if tmp, err := net.Dial("udp", "114.114.114.114:53"); err == nil {
add(ipFromAddr(tmp.LocalAddr()))
_ = tmp.Close()
if len(ips) > 0 {
return ips[0]
}
}
// 3) Fallback: all up interfaces with private IPv4.
ifaces, err := net.Interfaces()
if err == nil {
for _, iface := range ifaces {
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
continue
}
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok {
add(ipnet.IP)
}
}
}
}
if len(ips) > 1 {
sort.Strings(ips)
}
return strings.Join(ips, ",")
}
func IsPublicIP(IP net.IP) bool {
if IP.IsLoopback() || IP.IsLinkLocalMulticast() || IP.IsLinkLocalUnicast() {
return false
+66 -50
View File
@@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"net/http"
"sort"
"strings"
"sync"
@@ -36,43 +35,42 @@ func GetDb() *DbUtils {
return Db
}
func GetMapKeys(m sync.Map, isSort bool, sortKey, order string) (keys []int) {
if sortKey != "" && isSort {
return sortClientByKey(m, sortKey, order)
}
m.Range(func(key, value interface{}) bool {
keys = append(keys, key.(int))
func (s *DbUtils) GetClientList(start, length int, search, sortField, order string, clientId int) ([]*Client, int) {
all := make([]*Client, 0)
s.JsonDb.Clients.Range(func(key, value interface{}) bool {
v := value.(*Client)
if v.NoDisplay {
return true
}
if clientId != 0 && clientId != v.Id {
return true
}
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.VerifyKey, search) || strings.Contains(v.Remark, search) || strings.Contains(v.Addr, search) || strings.Contains(v.LocalAddr, search)) {
return true
}
all = append(all, v)
return true
})
sort.Ints(keys)
return
SortClients(all, sortField, order)
return paginateClients(all, start, length)
}
func (s *DbUtils) GetClientList(start, length int, search, sort, order string, clientId int) ([]*Client, int) {
list := make([]*Client, 0)
var cnt int
keys := GetMapKeys(s.JsonDb.Clients, true, sort, order)
for _, key := range keys {
if value, ok := s.JsonDb.Clients.Load(key); ok {
v := value.(*Client)
if v.NoDisplay {
continue
}
if clientId != 0 && clientId != v.Id {
continue
}
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.VerifyKey, search) || strings.Contains(v.Remark, search)) {
continue
}
cnt++
if start--; start < 0 {
if length--; length >= 0 {
list = append(list, v)
}
}
}
func paginateClients(all []*Client, start, length int) ([]*Client, int) {
cnt := len(all)
if start < 0 {
start = 0
}
return list, cnt
if length <= 0 {
return []*Client{}, cnt
}
if start >= cnt {
return []*Client{}, cnt
}
end := start + length
if end > cnt {
end = cnt
}
return all[start:end], cnt
}
func (s *DbUtils) GetIdByVerifyKey(vKey string, addr string) (id int, err error) {
@@ -182,27 +180,45 @@ func (s *DbUtils) NewHost(t *Host) error {
return nil
}
func (s *DbUtils) GetHost(start, length int, id int, search string) ([]*Host, int) {
list := make([]*Host, 0)
var cnt int
keys := GetMapKeys(s.JsonDb.Hosts, false, "", "")
for _, key := range keys {
if value, ok := s.JsonDb.Hosts.Load(key); ok {
v := value.(*Host)
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.Host, search) || strings.Contains(v.Remark, search) || strings.Contains(v.Client.VerifyKey, search)) {
continue
func (s *DbUtils) GetHost(start, length int, id int, search, sortField, order string) ([]*Host, int) {
all := make([]*Host, 0)
s.JsonDb.Hosts.Range(func(key, value interface{}) bool {
v := value.(*Host)
if search != "" {
vkey := ""
if v.Client != nil {
vkey = v.Client.VerifyKey
}
if id == 0 || v.Client.Id == id {
cnt++
if start--; start < 0 {
if length--; length >= 0 {
list = append(list, v)
}
}
if !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.Host, search) || strings.Contains(v.Remark, search) || strings.Contains(vkey, search)) {
return true
}
}
if id != 0 && (v.Client == nil || v.Client.Id != id) {
return true
}
all = append(all, v)
return true
})
SortHosts(all, sortField, order)
return paginateHosts(all, start, length)
}
func paginateHosts(all []*Host, start, length int) ([]*Host, int) {
cnt := len(all)
if start < 0 {
start = 0
}
return list, cnt
if length <= 0 {
return []*Host{}, cnt
}
if start >= cnt {
return []*Host{}, cnt
}
end := start + length
if end > cnt {
end = cnt
}
return all[start:end], cnt
}
func (s *DbUtils) DelClient(id int) error {
+3 -1
View File
@@ -35,7 +35,8 @@ type Client struct {
Cnf *Config
Id int //id
VerifyKey string //verify key
Addr string //the ip of client
Addr string // client egress address as seen by server (RemoteAddr)
LocalAddr string // client private/LAN addresses reported by npc
Remark string //remark
Status bool //is allow connect
IsConnect bool //is the client connect
@@ -67,6 +68,7 @@ func NewClient(vKey string, noStore bool, noDisplay bool) *Client {
Id: 0,
VerifyKey: vKey,
Addr: "",
LocalAddr: "",
Remark: "",
Status: true,
IsConnect: false,
+221 -29
View File
@@ -1,41 +1,233 @@
package file
import (
"reflect"
"sort"
"sync"
"strings"
)
// A data structure to hold a key/value pair.
type Pair struct {
key string //sort key
cId int
order string
clientFlow *Flow
}
// A slice of Pairs that implements sort.Interface to sort by Value.
type PairList []*Pair
func (p PairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p PairList) Len() int { return len(p) }
func (p PairList) Less(i, j int) bool {
if p[i].order == "desc" {
return reflect.ValueOf(*p[i].clientFlow).FieldByName(p[i].key).Int() < reflect.ValueOf(*p[j].clientFlow).FieldByName(p[j].key).Int()
func lessBool(a, b bool, asc bool) bool {
if a == b {
return false
}
return reflect.ValueOf(*p[i].clientFlow).FieldByName(p[i].key).Int() > reflect.ValueOf(*p[j].clientFlow).FieldByName(p[j].key).Int()
if asc {
return !a && b // false first
}
return a && !b // true first
}
// A function to turn a map into a PairList, then sort and return it.
func sortClientByKey(m sync.Map, sortKey, order string) (res []int) {
p := make(PairList, 0)
m.Range(func(key, value interface{}) bool {
p = append(p, &Pair{sortKey, value.(*Client).Id, order, value.(*Client).Flow})
return true
func lessInt(a, b int, asc bool) bool {
if asc {
return a < b
}
return a > b
}
func lessInt64(a, b int64, asc bool) bool {
if asc {
return a < b
}
return a > b
}
func lessString(a, b string, asc bool) bool {
if asc {
return strings.ToLower(a) < strings.ToLower(b)
}
return strings.ToLower(a) > strings.ToLower(b)
}
// SortClients sorts clients in-place by the given field (bootstrap-table sort name).
func SortClients(list []*Client, sortField, order string) {
if sortField == "" || len(list) < 2 {
if sortField == "" && len(list) > 1 {
sort.SliceStable(list, func(i, j int) bool { return list[i].Id < list[j].Id })
}
return
}
asc := order != "desc"
sort.SliceStable(list, func(i, j int) bool {
a, b := list[i], list[j]
switch sortField {
case "Id":
return lessInt(a.Id, b.Id, asc)
case "Remark":
return lessString(a.Remark, b.Remark, asc)
case "Version":
return lessString(a.Version, b.Version, asc)
case "VerifyKey":
return lessString(a.VerifyKey, b.VerifyKey, asc)
case "Addr":
return lessString(a.Addr, b.Addr, asc)
case "LocalAddr":
return lessString(a.LocalAddr, b.LocalAddr, asc)
case "InletFlow":
return lessInt64(flowInlet(a), flowInlet(b), asc)
case "ExportFlow":
return lessInt64(flowExport(a), flowExport(b), asc)
case "NowRate":
return lessInt64(nowRate(a), nowRate(b), asc)
case "Status":
return lessBool(a.Status, b.Status, asc)
case "IsConnect":
return lessBool(a.IsConnect, b.IsConnect, asc)
default:
return lessInt(a.Id, b.Id, true)
}
})
sort.Sort(p)
for _, v := range p {
res = append(res, v.cId)
}
func flowInlet(c *Client) int64 {
if c == nil || c.Flow == nil {
return 0
}
return
return c.Flow.InletFlow
}
func flowExport(c *Client) int64 {
if c == nil || c.Flow == nil {
return 0
}
return c.Flow.ExportFlow
}
func nowRate(c *Client) int64 {
if c == nil || c.Rate == nil {
return 0
}
return c.Rate.NowRate
}
// SortTunnels sorts tunnels in-place by the given field.
func SortTunnels(list []*Tunnel, sortField, order string) {
if sortField == "" || len(list) < 2 {
if sortField == "" && len(list) > 1 {
sort.SliceStable(list, func(i, j int) bool { return list[i].Id < list[j].Id })
}
return
}
asc := order != "desc"
sort.SliceStable(list, func(i, j int) bool {
a, b := list[i], list[j]
switch sortField {
case "Id":
return lessInt(a.Id, b.Id, asc)
case "ClientId":
return lessInt(clientIdOfTunnel(a), clientIdOfTunnel(b), asc)
case "Remark":
return lessString(a.Remark, b.Remark, asc)
case "Client.VerifyKey", "VerifyKey":
return lessString(clientVkeyOfTunnel(a), clientVkeyOfTunnel(b), asc)
case "Mode":
return lessString(a.Mode, b.Mode, asc)
case "Port":
return lessInt(a.Port, b.Port, asc)
case "Target":
return lessString(targetStrOfTunnel(a), targetStrOfTunnel(b), asc)
case "Password":
return lessString(a.Password, b.Password, asc)
case "Status":
return lessBool(a.Status, b.Status, asc)
case "RunStatus":
return lessBool(a.RunStatus, b.RunStatus, asc)
case "IsConnect", "Client.IsConnect":
return lessBool(clientConnectOfTunnel(a), clientConnectOfTunnel(b), asc)
default:
return lessInt(a.Id, b.Id, true)
}
})
}
func clientIdOfTunnel(t *Tunnel) int {
if t == nil || t.Client == nil {
return 0
}
return t.Client.Id
}
func clientVkeyOfTunnel(t *Tunnel) string {
if t == nil || t.Client == nil {
return ""
}
return t.Client.VerifyKey
}
func clientConnectOfTunnel(t *Tunnel) bool {
if t == nil || t.Client == nil {
return false
}
return t.Client.IsConnect
}
func targetStrOfTunnel(t *Tunnel) string {
if t == nil || t.Target == nil {
return ""
}
return t.Target.TargetStr
}
// SortHosts sorts hosts in-place by the given field.
func SortHosts(list []*Host, sortField, order string) {
if sortField == "" || len(list) < 2 {
if sortField == "" && len(list) > 1 {
sort.SliceStable(list, func(i, j int) bool { return list[i].Id < list[j].Id })
}
return
}
asc := order != "desc"
sort.SliceStable(list, func(i, j int) bool {
a, b := list[i], list[j]
switch sortField {
case "Id":
return lessInt(a.Id, b.Id, asc)
case "ClientId":
return lessInt(clientIdOfHost(a), clientIdOfHost(b), asc)
case "Remark":
return lessString(a.Remark, b.Remark, asc)
case "Client.VerifyKey", "VerifyKey":
return lessString(clientVkeyOfHost(a), clientVkeyOfHost(b), asc)
case "Host":
return lessString(a.Host, b.Host, asc)
case "Scheme":
return lessString(a.Scheme, b.Scheme, asc)
case "Target":
return lessString(targetStrOfHost(a), targetStrOfHost(b), asc)
case "Location":
return lessString(a.Location, b.Location, asc)
case "IsClose", "Status":
// IsClose: false=open, true=closed — sort by open status for "Status" display
return lessBool(a.IsClose, b.IsClose, asc)
case "IsConnect", "Client.IsConnect":
return lessBool(clientConnectOfHost(a), clientConnectOfHost(b), asc)
default:
return lessInt(a.Id, b.Id, true)
}
})
}
func clientIdOfHost(h *Host) int {
if h == nil || h.Client == nil {
return 0
}
return h.Client.Id
}
func clientVkeyOfHost(h *Host) string {
if h == nil || h.Client == nil {
return ""
}
return h.Client.VerifyKey
}
func clientConnectOfHost(h *Host) bool {
if h == nil || h.Client == nil {
return false
}
return h.Client.IsConnect
}
func targetStrOfHost(h *Host) string {
if h == nil || h.Target == nil {
return ""
}
return h.Target.TargetStr
}
+2 -2
View File
@@ -5,12 +5,12 @@ import (
"fmt"
"io"
"net"
"path/filepath"
"strings"
"sync"
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/file"
"ehang.io/nps/web"
"github.com/astaxie/beego/logs"
"github.com/panjf2000/ants/v2"
)
@@ -64,7 +64,7 @@ func CopyBuffer(dst io.Writer, src io.Reader, flow *file.Flow, task *file.Tunnel
ip := common.GetIpByAddr(remote)
var jsonBytes []byte
errorContent, _ := common.ReadAllFromFile(filepath.Join(common.GetRunPath(), "web", "static", "page", "auth.html"))
errorContent, _ := web.ReadStaticFile("page/auth.html")
authHtml := string(errorContent)
authHtml = strings.ReplaceAll(authHtml, "${ip}", ip)
+215 -126
View File
@@ -137,9 +137,16 @@ WantedBy=multi-user.target
`
func UpdateNps() {
destPath := downloadLatest("server")
destPath, err := downloadLatest("server")
if err != nil {
log.Println("下载更新失败:", err)
return
}
//复制文件到对应目录
copyStaticFile(destPath, "nps")
if _, err := copyStaticFile(destPath, "nps"); err != nil {
log.Println("替换服务端文件失败:", err)
return
}
fmt.Println("Update completed, please restart")
}
@@ -148,16 +155,23 @@ func UpdateNpsNew() {
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"))
fmt.Println("最新版本为:", latest)
if compareVersion(version.VERSION, latest) >= 0 {
fmt.Println("当前已是最新版本,无需更新")
return
}
tempDir := filepath.Join(common.GetAppPath(), "temp")
destPath, err := downloadLatest2("server", tempDir)
if err != nil {
log.Println("下载更新失败:", err)
return
}
//复制文件到对应目录
copyStaticFileReplaceNps(destPath, common.GetAppPath())
if err := copyStaticFileReplaceNps(destPath, common.GetAppPath()); err != nil {
log.Println("替换服务端文件失败:", err)
return
}
fmt.Println("更新成功,请重启服务")
}
@@ -167,6 +181,9 @@ func fetchLatestVersion() (string, error) {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("HTTP %d", resp.StatusCode)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
@@ -175,6 +192,9 @@ func fetchLatestVersion() (string, error) {
if err := json.Unmarshal(b, rl); err != nil {
return "", err
}
if rl.TagName == "" {
return "", errors.New("无法解析最新版本号")
}
return rl.TagName, nil
}
@@ -191,9 +211,16 @@ func compareVersion(a, b string) int {
}
func UpdateNpc() {
destPath := downloadLatest("client")
destPath, err := downloadLatest("client")
if err != nil {
log.Println("下载更新失败:", err)
return
}
//复制文件到对应目录
copyStaticFile(destPath, "npc")
if _, err := copyStaticFile(destPath, "npc"); err != nil {
log.Println("替换客户端文件失败:", err)
return
}
fmt.Println("Update completed, please restart")
}
@@ -202,15 +229,22 @@ func UpdateNpcNew() {
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("最新版本为:", latest)
if compareVersion(version.VERSION, latest) >= 0 {
fmt.Println("当前已是最新版本,无需更新")
return
}
tempDir := filepath.Join(common.GetAppPath(), "temp")
destPath, err := downloadLatest2("client", tempDir)
if err != nil {
log.Println("下载更新失败:", err)
return
}
if err := copyStaticFileReplaceNpc(destPath, common.GetAppPath()); err != nil {
log.Println("替换客户端文件失败:", err)
return
}
fmt.Println("更新成功,请重启客户端")
}
@@ -218,69 +252,52 @@ type release struct {
TagName string `json:"tag_name"`
}
func downloadLatest(bin string) string {
// get version
data, err := http.Get("https://api.github.com/repos/yisier/nps/releases/latest")
if err != nil {
log.Fatal(err.Error())
}
b, err := ioutil.ReadAll(data.Body)
if err != nil {
log.Fatal(err)
}
rl := new(release)
json.Unmarshal(b, &rl)
version := rl.TagName
fmt.Println("the latest version is", version)
filename := runtime.GOOS + "_" + runtime.GOARCH + "_" + bin + ".tar.gz"
// download latest package
downloadUrl := fmt.Sprintf("https://github.com/yisier/nps/releases/download/%s/%s", version, filename)
fmt.Println("download package from ", downloadUrl)
resp, err := http.Get(downloadUrl)
if err != nil {
log.Fatal(err.Error())
}
destPath, err := unpackit.Unpack(resp.Body, "")
if err != nil {
log.Fatal(err)
}
if bin == "server" {
destPath = strings.Replace(destPath, "/web", "", -1)
destPath = strings.Replace(destPath, `\web`, "", -1)
destPath = strings.Replace(destPath, "/views", "", -1)
destPath = strings.Replace(destPath, `\views`, "", -1)
} else {
destPath = strings.Replace(destPath, `\conf`, "", -1)
destPath = strings.Replace(destPath, "/conf", "", -1)
}
return destPath
func downloadLatest(bin string) (string, error) {
return downloadAndUnpack(bin, "")
}
func downloadLatest2(bin string, path string) string {
// get version
func downloadLatest2(bin string, path string) (string, error) {
return downloadAndUnpack(bin, path)
}
// downloadAndUnpack fetches the latest release package for the current OS/arch.
// Releases ship as .tar.gz (see build.assets.sh / release.yml).
func downloadAndUnpack(bin, unpackPath string) (string, error) {
data, err := http.Get("https://api.github.com/repos/yisier/nps/releases/latest")
if err != nil {
log.Fatal(err.Error())
return "", err
}
defer data.Body.Close()
if data.StatusCode != http.StatusOK {
return "", fmt.Errorf("获取版本信息失败: HTTP %d", data.StatusCode)
}
b, err := ioutil.ReadAll(data.Body)
if err != nil {
log.Fatal(err)
return "", err
}
rl := new(release)
json.Unmarshal(b, &rl)
version := rl.TagName
fmt.Println("the latest version is", version)
if err := json.Unmarshal(b, rl); err != nil {
return "", err
}
if rl.TagName == "" {
return "", errors.New("无法解析最新版本号")
}
ver := rl.TagName
fmt.Println("the latest version is", ver)
filename := runtime.GOOS + "_" + runtime.GOARCH + "_" + bin + ".tar.gz"
// download latest package
downloadUrl := fmt.Sprintf("https://github.com/yisier/nps/releases/download/%s/%s", version, filename)
downloadUrl := fmt.Sprintf("https://github.com/yisier/nps/releases/download/%s/%s", ver, filename)
fmt.Println("download package from ", downloadUrl)
resp, err := http.Get(downloadUrl)
if err != nil {
log.Fatal(err.Error())
return "", err
}
destPath, err := unpackit.Unpack(resp.Body, path)
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("下载失败: HTTP %d %s", resp.StatusCode, downloadUrl)
}
destPath, err := unpackit.Unpack(resp.Body, unpackPath)
if err != nil {
log.Fatal(err)
return "", err
}
if bin == "server" {
destPath = strings.Replace(destPath, "/web", "", -1)
@@ -291,70 +308,139 @@ func downloadLatest2(bin string, path string) string {
destPath = strings.Replace(destPath, `\conf`, "", -1)
destPath = strings.Replace(destPath, "/conf", "", -1)
}
return destPath
return destPath, nil
}
func copyStaticFile(srcPath, bin string) string {
path := common.GetInstallPath()
if bin == "nps" {
//复制文件到对应目录
if err := CopyDir(filepath.Join(srcPath, "web", "views"), filepath.Join(path, "web", "views")); err != nil {
log.Fatalln(err)
}
chMod(filepath.Join(path, "web", "views"), 0766)
if err := CopyDir(filepath.Join(srcPath, "web", "static"), filepath.Join(path, "web", "static")); err != nil {
log.Fatalln(err)
}
chMod(filepath.Join(path, "web", "static"), 0766)
}
func copyStaticFile(srcPath, bin string) (string, error) {
// nps web UI is embedded in the binary; no web/ files to copy.
binPath, _ := filepath.Abs(os.Args[0])
srcBin := filepath.Join(srcPath, bin)
if common.IsWindows() {
srcBin += ".exe"
}
if _, err := os.Stat(srcBin); err != nil {
return "", fmt.Errorf("更新包中未找到可执行文件 %s: %w", srcBin, err)
}
if !common.IsWindows() {
if _, err := copyFile(filepath.Join(srcPath, bin), "/usr/bin/"+bin); err != nil {
if _, err := copyFile(filepath.Join(srcPath, bin), "/usr/local/bin/"+bin); err != nil {
log.Fatalln(err)
} else {
copyFile(filepath.Join(srcPath, bin), "/usr/local/bin/"+bin+"-update")
chMod("/usr/local/bin/"+bin+"-update", 0755)
binPath = "/usr/local/bin/" + bin
if _, err := copyFile(srcBin, "/usr/bin/"+bin); err != nil {
if _, err := copyFile(srcBin, "/usr/local/bin/"+bin); err != nil {
return "", err
}
binPath = "/usr/local/bin/" + bin
} else {
copyFile(filepath.Join(srcPath, bin), "/usr/bin/"+bin+"-update")
chMod("/usr/bin/"+bin+"-update", 0755)
binPath = "/usr/bin/" + bin
}
} else {
copyFile(filepath.Join(srcPath, bin+".exe"), filepath.Join(common.GetAppPath(), bin+"-update.exe"))
copyFile(filepath.Join(srcPath, bin+".exe"), filepath.Join(common.GetAppPath(), bin+".exe"))
destBin := filepath.Join(common.GetAppPath(), bin+".exe")
if err := replaceExecutable(srcBin, destBin); err != nil {
return "", err
}
binPath = destBin
}
chMod(binPath, 0755)
return binPath
return binPath, nil
}
func copyStaticFileReplaceNps(srcPath, descPath string) string {
//复制文件到对应目录
os.Rename(filepath.Join(srcPath, "web"), filepath.Join(descPath, "web"))
chMod(filepath.Join(descPath, "web"), 0766)
binPath, _ := filepath.Abs(os.Args[0])
if !common.IsWindows() {
os.Rename(filepath.Join(srcPath, "nps"), filepath.Join(descPath, "nps"))
} else {
os.Rename(filepath.Join(srcPath, "nps.exe"), filepath.Join(descPath, "nps.exe"))
}
chMod(binPath, 0755)
os.RemoveAll(srcPath)
return binPath
func copyStaticFileReplaceNps(srcPath, descPath string) error {
// Web UI is embedded in the binary; only replace the executable.
return replaceBinFromPackage(srcPath, descPath, "nps")
}
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"))
func copyStaticFileReplaceNpc(srcPath, descPath string) error {
return replaceBinFromPackage(srcPath, descPath, "npc")
}
func replaceBinFromPackage(srcPath, descPath, bin string) error {
srcBin := filepath.Join(srcPath, bin)
destBin := filepath.Join(descPath, bin)
if common.IsWindows() {
srcBin += ".exe"
destBin += ".exe"
}
chMod(binPath, 0755)
os.RemoveAll(srcPath)
return binPath
// Prefer replacing the actually running binary when its basename matches.
if exe, err := os.Executable(); err == nil {
if filepath.Base(exe) == filepath.Base(destBin) {
destBin = exe
}
}
if _, err := os.Stat(srcBin); err != nil {
// unpackit may return a nested root dir; search one level if needed
if found, findErr := findBinInDir(srcPath, filepath.Base(srcBin)); findErr == nil {
srcBin = found
} else {
return fmt.Errorf("更新包中未找到可执行文件 %s: %w", srcBin, err)
}
}
if err := replaceExecutable(srcBin, destBin); err != nil {
return err
}
chMod(destBin, 0755)
// Clean temp package; keep parent temp dir if still in use
_ = os.RemoveAll(srcPath)
return nil
}
func findBinInDir(root, name string) (string, error) {
var found string
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil || info == nil || info.IsDir() {
return err
}
if info.Name() == name {
found = path
return errors.New("found")
}
return nil
})
if found != "" {
return found, nil
}
if err != nil {
return "", err
}
return "", os.ErrNotExist
}
// replaceExecutable places srcBin at destBin. On Windows a running executable
// cannot be overwritten, but it can be renamed aside first.
func replaceExecutable(srcBin, destBin string) error {
if _, err := os.Stat(srcBin); err != nil {
return fmt.Errorf("源文件不存在: %s: %w", srcBin, err)
}
if dstFi, err := os.Stat(destBin); err == nil {
if srcFi, err := os.Stat(srcBin); err == nil {
if os.SameFile(srcFi, dstFi) {
return nil
}
}
}
if err := os.MkdirAll(filepath.Dir(destBin), 0755); err != nil {
return err
}
// Move the current binary out of the way when present (required on Windows
// while the process is still running).
if _, err := os.Stat(destBin); err == nil {
bak := destBin + ".old"
_ = os.Remove(bak)
if err := os.Rename(destBin, bak); err != nil {
return fmt.Errorf("无法备份当前程序 %s: %w", destBin, err)
}
}
// Same filesystem: rename is atomic. Fall back to copy across volumes.
if err := os.Rename(srcBin, destBin); err != nil {
if _, copyErr := copyFile(srcBin, destBin); copyErr != nil {
// Best-effort restore of previous binary
bak := destBin + ".old"
if _, statErr := os.Stat(bak); statErr == nil {
_ = os.Rename(bak, destBin)
}
return fmt.Errorf("替换可执行文件失败: %w", copyErr)
}
_ = os.Remove(srcBin)
}
return nil
}
func InstallNpc() {
@@ -365,33 +451,36 @@ func InstallNpc() {
log.Fatal(err)
}
}
copyStaticFile(common.GetAppPath(), "npc")
if _, err := copyStaticFile(common.GetAppPath(), "npc"); err != nil {
log.Fatalln(err)
}
}
func InstallNps() string {
path := common.GetInstallPath()
log.Println("install path:" + path)
if common.FileExists(path) {
MkidrDirAll(path, "web/static", "web/views")
} else {
MkidrDirAll(path, "conf", "web/static", "web/views")
if !common.FileExists(path) {
MkidrDirAll(path, "conf")
// not copy config if the config file is exist
if err := CopyDir(filepath.Join(common.GetAppPath(), "conf"), filepath.Join(path, "conf")); err != nil {
log.Fatalln(err)
}
chMod(filepath.Join(path, "conf"), 0766)
}
binPath := copyStaticFile(common.GetAppPath(), "nps")
binPath, err := copyStaticFile(common.GetAppPath(), "nps")
if err != nil {
log.Fatalln(err)
}
log.Println("install ok!")
log.Println("Static files and configuration files in the current directory will be useless")
log.Println("Web UI is embedded in the nps binary; no web/ directory is required")
log.Println("The new configuration file is located in", path, "you can edit them")
if !common.IsWindows() {
log.Println(`You can start with:
nps start|stop|restart|uninstall|update or nps-update update
nps start|stop|restart|uninstall|update
anywhere!`)
} else {
log.Println(`You can copy executable files to any directory and start working with:
nps.exe start|stop|restart|uninstall|update or nps-update.exe update
nps.exe start|stop|restart|uninstall|update
now!`)
}
chMod(common.GetLogPath(), 0777)
+1 -1
View File
@@ -1,6 +1,6 @@
package version
const VERSION = "0.26.34"
const VERSION = "0.26.37"
// Compulsory minimum version, Minimum downward compatibility to this version
func GetVersion() string {
+12 -3
View File
@@ -64,12 +64,21 @@ func (s *BaseServer) writeConnFail(c net.Conn) {
c.Write(s.errorContent)
}
// auth check
// auth check for reverse-proxy hosts (401 + WWW-Authenticate).
func (s *BaseServer) auth(r *http.Request, c *conn.Conn, u, p string) error {
return s.doAuth(r, c, u, p, common.UnauthorizedBytes, "401 Unauthorized")
}
// proxyAuth check for HTTP forward proxy (407 + Proxy-Authenticate).
func (s *BaseServer) proxyAuth(r *http.Request, c *conn.Conn, u, p string) error {
return s.doAuth(r, c, u, p, common.ProxyAuthRequiredBytes, "407 Proxy Authentication Required")
}
func (s *BaseServer) doAuth(r *http.Request, c *conn.Conn, u, p, failBytes, errMsg string) error {
if u != "" && p != "" && !common.CheckAuth(r, u, p) {
c.Write([]byte(common.UnauthorizedBytes))
c.Write([]byte(failBytes))
c.Close()
return errors.New("401 Unauthorized")
return errors.New(errMsg)
}
return nil
}
+97 -33
View File
@@ -10,7 +10,9 @@ import (
"ehang.io/nps/lib/file"
"ehang.io/nps/lib/goroutine"
"ehang.io/nps/server/connection"
"ehang.io/nps/web"
"encoding/json"
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"io"
@@ -57,7 +59,7 @@ func NewHttp(bridge *bridge.Bridge, c *file.Tunnel, httpPort, httpsPort int, use
func (s *httpServer) Start() error {
var err error
if s.errorContent, err = common.ReadAllFromFile(filepath.Join(common.GetRunPath(), "web", "static", "page", "error.html")); err != nil {
if s.errorContent, err = web.ReadStaticFile("page/error.html"); err != nil {
s.errorContent = []byte("nps 404")
}
if s.httpPort > 0 {
@@ -127,17 +129,18 @@ func (s *httpServer) handleTunneling(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
return
}
c, _, err := hijacker.Hijack()
c, rw, err := hijacker.Hijack()
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
s.handleHttp(conn.NewConn(c), r)
s.handleHttp(conn.NewConn(c), r, rw.Reader)
}
}
func (s *httpServer) handleHttp(c *conn.Conn, r *http.Request) {
func (s *httpServer) handleHttp(c *conn.Conn, r *http.Request, br *bufio.Reader) {
var (
host *file.Host
target net.Conn
@@ -159,6 +162,7 @@ func (s *httpServer) handleHttp(c *conn.Conn, r *http.Request) {
}
c.Close()
}()
firstReq := true
reset:
if isReset {
host.Client.AddConn()
@@ -228,7 +232,7 @@ reset:
return
}
errorContent, _ := common.ReadAllFromFile(filepath.Join(common.GetRunPath(), "web", "static", "page", "auth.html"))
errorContent, _ := web.ReadStaticFile("page/auth.html")
authHtml := string(errorContent)
authHtml = strings.ReplaceAll(authHtml, "${ip}", common.GetIpByAddr(c.RemoteAddr().String()))
s.errorContent, err = []byte(authHtml), err
@@ -262,24 +266,9 @@ reset:
}
}()
err1 := goroutine.CopyBuffer(c, connClient, host.Client.Flow, nil, host, "")
if err1 != nil {
if err1 := goroutine.CopyBuffer(c, connClient, host.Client.Flow, nil, host, ""); err1 != nil {
return
}
resp, err := http.ReadResponse(bufio.NewReader(connClient), r)
if err != nil || resp == nil || r == nil {
// if there got broken pipe, http.ReadResponse will get a nil
//break
return
} else {
lenConn := conn.NewLenConn(c)
if err := resp.Write(lenConn); err != nil {
logs.Error(err)
//break
return
}
}
}()
for {
@@ -309,23 +298,29 @@ reset:
//write
lenConn = conn.NewLenConn(connClient)
//lenConn = conn.LenConn
if err := r.Write(lenConn); err != nil {
logs.Error(err)
break
if firstReq {
if err = writeRequestRaw(lenConn, r, br); err != nil {
logs.Error(err)
break
}
} else {
if err = r.Write(lenConn); err != nil {
logs.Error(err)
break
}
}
firstReq = false
host.Client.Flow.Add(int64(lenConn.Len), int64(lenConn.Len))
host.Flow.Add(int64(lenConn.Len), int64(lenConn.Len))
readReq:
//read req from connection
r, err = http.ReadRequest(bufio.NewReader(c))
r, err = http.ReadRequest(br)
if err != nil {
//break
return
}
r.URL.Scheme = scheme
//What happened ,Why one character less???
r.Method = resetReqMethod(r.Method)
if hostTmp, err := file.GetDb().GetInfoByHost(r.Host, r); err != nil {
logs.Notice("the url %s %s %s can't be parsed!", r.URL.Scheme, r.Host, r.RequestURI)
break
@@ -339,14 +334,83 @@ reset:
wg.Wait()
}
func resetReqMethod(method string) string {
if method == "ET" {
return "GET"
func writeRequestRaw(w io.Writer, r *http.Request, br *bufio.Reader) error {
bw := bufio.NewWriter(w)
if _, err := fmt.Fprintf(bw, "%s %s HTTP/1.1\r\n", r.Method, r.URL.RequestURI()); err != nil {
return err
}
if method == "OST" {
return "POST"
if _, err := fmt.Fprintf(bw, "Host: %s\r\n", r.Host); err != nil {
return err
}
chunked := len(r.TransferEncoding) > 0 && r.TransferEncoding[0] == "chunked"
if chunked {
if _, err := io.WriteString(bw, "Transfer-Encoding: chunked\r\n"); err != nil {
return err
}
}
if err := r.Header.Write(bw); err != nil {
return err
}
if _, err := io.WriteString(bw, "\r\n"); err != nil {
return err
}
if err := bw.Flush(); err != nil {
return err
}
if r.ContentLength > 0 {
if _, err := io.CopyN(w, br, r.ContentLength); err != nil {
return err
}
} else if chunked {
if err := copyRawChunked(w, br); err != nil {
return err
}
}
return nil
}
func copyRawChunked(w io.Writer, br *bufio.Reader) error {
for {
line, err := br.ReadString('\n')
if err != nil {
return err
}
if _, err := io.WriteString(w, line); err != nil {
return err
}
sizeStr := strings.TrimSpace(line)
if i := strings.IndexByte(sizeStr, ';'); i >= 0 {
sizeStr = sizeStr[:i]
}
size, err := strconv.ParseInt(sizeStr, 16, 64)
if err != nil {
return err
}
if size == 0 {
for {
tline, err := br.ReadString('\n')
if err != nil {
return err
}
if _, err := io.WriteString(w, tline); err != nil {
return err
}
if tline == "\r\n" || tline == "\n" {
return nil
}
}
}
if _, err := io.CopyN(w, br, size); err != nil {
return err
}
var crlf [2]byte
if _, err := io.ReadFull(br, crlf[:]); err != nil {
return err
}
if _, err := w.Write(crlf[:]); err != nil {
return err
}
}
return method
}
func (s *httpServer) NewServer(port int, scheme string) *http.Server {
+62 -36
View File
@@ -348,33 +348,62 @@ func (s *Sock5ModeServer) handleConn(c net.Conn) {
c.Close()
return
}
nMethods := buf[1]
nMethods := int(buf[1])
if nMethods == 0 {
logs.Warn("socks5 client offered no auth methods, remote %s", c.RemoteAddr())
c.Close()
return
}
methods := make([]byte, nMethods)
if len, err := c.Read(methods); len != int(nMethods) || err != nil {
if _, err := io.ReadFull(c, methods); err != nil {
logs.Warn("wrong method")
c.Close()
return
}
if (s.task.Client.Cnf.U != "" && s.task.Client.Cnf.P != "") || (s.task.MultiAccount != nil && len(s.task.MultiAccount.AccountMap) > 0) {
buf[1] = UserPassAuth
c.Write(buf)
needAuth := (s.task.Client.Cnf.U != "" && s.task.Client.Cnf.P != "") ||
(s.task.MultiAccount != nil && len(s.task.MultiAccount.AccountMap) > 0)
if needAuth {
if !methodOffered(methods, UserPassAuth) {
// Client cannot authenticate; reply no acceptable methods (RFC 1928).
_, _ = c.Write([]byte{5, 0xFF})
c.Close()
logs.Warn("socks5 client %s does not support username/password auth", c.RemoteAddr())
return
}
if _, err := c.Write([]byte{5, UserPassAuth}); err != nil {
c.Close()
return
}
if err := s.Auth(c); err != nil {
c.Close()
logs.Warn("Validation failed:", err)
logs.Warn("Validation failed: %v, remote %s", err, c.RemoteAddr())
return
}
} else {
buf[1] = 0
c.Write(buf)
if _, err := c.Write([]byte{5, 0}); err != nil {
c.Close()
return
}
}
s.handleRequest(c)
}
// socks5 auth
func methodOffered(methods []byte, method byte) bool {
for _, m := range methods {
if m == method {
return true
}
}
return false
}
// socks5 auth (RFC 1929 username/password)
func (s *Sock5ModeServer) Auth(c net.Conn) error {
header := []byte{0, 0}
if _, err := io.ReadAtLeast(c, header, 2); err != nil {
header := make([]byte, 2)
if _, err := io.ReadFull(c, header); err != nil {
return err
}
if header[0] != userAuthVersion {
@@ -382,46 +411,43 @@ func (s *Sock5ModeServer) Auth(c net.Conn) error {
}
userLen := int(header[1])
user := make([]byte, userLen)
if _, err := io.ReadAtLeast(c, user, userLen); err != nil {
return err
if userLen > 0 {
if _, err := io.ReadFull(c, user); err != nil {
return err
}
}
if _, err := c.Read(header[:1]); err != nil {
plen := make([]byte, 1)
if _, err := io.ReadFull(c, plen); err != nil {
return errors.New("密码长度获取错误")
}
passLen := int(header[0])
passLen := int(plen[0])
pass := make([]byte, passLen)
if _, err := io.ReadAtLeast(c, pass, passLen); err != nil {
return err
if passLen > 0 {
if _, err := io.ReadFull(c, pass); err != nil {
return err
}
}
var U, P string
if s.task.MultiAccount != nil {
// enable multi user auth
U = string(user)
if len(U) == 0 {
return errors.New("验证不通过")
}
var ok bool
P, ok = s.task.MultiAccount.AccountMap[U]
if !ok {
return errors.New("验证不通过")
ok := false
if s.task.MultiAccount != nil && len(s.task.MultiAccount.AccountMap) > 0 {
// multi-user auth
if expected, found := s.task.MultiAccount.AccountMap[string(user)]; found && string(pass) == expected {
ok = true
}
} else {
U = s.task.Client.Cnf.U
P = s.task.Client.Cnf.P
ok = string(user) == s.task.Client.Cnf.U && string(pass) == s.task.Client.Cnf.P
}
if string(user) == U && string(pass) == P {
if ok {
if _, err := c.Write([]byte{userAuthVersion, authSuccess}); err != nil {
return err
}
return nil
} else {
if _, err := c.Write([]byte{userAuthVersion, authFailure}); err != nil {
return err
}
return errors.New("验证不通过")
}
if _, err := c.Write([]byte{userAuthVersion, authFailure}); err != nil {
return err
}
return errors.New("验证不通过")
}
// start
+14 -10
View File
@@ -7,7 +7,6 @@ import (
"errors"
"net"
"net/http"
"path/filepath"
"strconv"
"ehang.io/nps/bridge"
@@ -15,6 +14,7 @@ import (
"ehang.io/nps/lib/conn"
"ehang.io/nps/lib/file"
"ehang.io/nps/server/connection"
"ehang.io/nps/web"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
)
@@ -66,8 +66,8 @@ func (s *WebServer) Start() error {
<-stop
}
beego.BConfig.WebConfig.Session.SessionOn = true
beego.SetStaticPath(beego.AppConfig.String("web_base_url")+"/static", filepath.Join(common.GetRunPath(), "web", "static"))
beego.SetViewsPath(filepath.Join(common.GetRunPath(), "web", "views"))
// Serve management UI from embedded assets only (no disk web/ directory).
web.InitBeegoAssets()
err := errors.New("Web management startup failure ")
var l net.Listener
if l, err = connection.GetWebManagerListener(); err == nil {
@@ -111,20 +111,24 @@ func ProcessTunnel(c *conn.Conn, s *TunnelModeServer) error {
// http proxy
func ProcessHttp(c *conn.Conn, s *TunnelModeServer) error {
_, addr, rb, err, r := c.GetHost()
if err != nil {
c.Close()
logs.Info(err)
return err
}
if r.Method == "CONNECT" {
c.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
rb = nil
}
if err := s.auth(r, c, s.task.Client.Cnf.U, s.task.Client.Cnf.P); err != nil {
// Authenticate before establishing CONNECT tunnel (fixes auth-after-200 bug).
if err := s.proxyAuth(r, c, s.task.Client.Cnf.U, s.task.Client.Cnf.P); err != nil {
logs.Warn("http proxy auth failed, client %d, remote %s: %v", s.task.Client.Id, c.Conn.RemoteAddr(), err)
return err
}
if r.Method == "CONNECT" {
if _, err := c.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n")); err != nil {
c.Close()
return err
}
rb = nil
}
logs.Info("http proxy request, method %s, host %s, client %d, remote %s", r.Method, addr, s.task.Client.Id, c.Conn.RemoteAddr())
return s.DealClient(c, s.task.Client, addr, rb, common.CONN_TCP, nil, s.task.Client.Flow, s.task.Target.LocalProxy, nil, nil)
}
+205
View File
@@ -1,11 +1,15 @@
package proxy
import (
"bufio"
"bytes"
"encoding/base64"
"io"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
@@ -92,3 +96,204 @@ func TestProcessTunnelForwardsBufferedBytesWhenAuthProbeFails(t *testing.T) {
t.Fatal("ProcessTunnel did not exit after connections closed")
}
}
func setupProxyTestConf(t *testing.T) {
t.Helper()
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
})
}
func newHTTPProxyServer(t *testing.T, u, p string, target net.Conn) *TunnelModeServer {
t.Helper()
client := file.NewClient("test", true, true)
client.Id = 1
client.Cnf.U = u
client.Cnf.P = p
task := &file.Tunnel{
Id: 1,
Client: client,
Mode: "httpProxy",
Target: &file.Target{TargetStr: "127.0.0.1:80"},
}
return NewTunnelModeServer(ProcessHttp, &tunnelTestBridge{target: target}, task)
}
func TestProcessHttpConnectAuthBeforeTunnel(t *testing.T) {
setupProxyTestConf(t)
clientConn, serverConn := net.Pipe()
defer clientConn.Close()
defer serverConn.Close()
// target unused: auth must fail before DealClient
targetClient, targetServer := net.Pipe()
defer targetClient.Close()
defer targetServer.Close()
server := newHTTPProxyServer(t, "user", "pass", targetServer)
done := make(chan error, 1)
go func() {
done <- ProcessHttp(conn.NewConn(serverConn), server)
}()
// CONNECT without credentials
req := "CONNECT example.com:443 HTTP/1.1\r\nHost: example.com:443\r\n\r\n"
if _, err := clientConn.Write([]byte(req)); err != nil {
t.Fatal(err)
}
_ = clientConn.SetReadDeadline(time.Now().Add(time.Second))
br := bufio.NewReader(clientConn)
resp, err := http.ReadResponse(br, nil)
if err != nil {
t.Fatalf("read response: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusProxyAuthRequired {
t.Fatalf("expected 407 before CONNECT tunnel, got %d", resp.StatusCode)
}
if got := resp.Header.Get("Proxy-Authenticate"); !strings.Contains(got, "Basic") {
t.Fatalf("expected Proxy-Authenticate Basic challenge, got %q", got)
}
select {
case err := <-done:
if err == nil {
t.Fatal("expected auth error")
}
case <-time.After(time.Second):
t.Fatal("ProcessHttp did not exit after auth failure")
}
}
func TestProcessHttpConnectWithProxyAuth(t *testing.T) {
setupProxyTestConf(t)
clientConn, serverConn := net.Pipe()
defer clientConn.Close()
defer serverConn.Close()
targetClient, targetServer := net.Pipe()
defer targetClient.Close()
defer targetServer.Close()
server := newHTTPProxyServer(t, "user", "pass", targetServer)
done := make(chan error, 1)
go func() {
done <- ProcessHttp(conn.NewConn(serverConn), server)
}()
token := base64.StdEncoding.EncodeToString([]byte("user:pass"))
req := "CONNECT example.com:443 HTTP/1.1\r\n" +
"Host: example.com:443\r\n" +
"Proxy-Authorization: Basic " + token + "\r\n\r\n"
if _, err := clientConn.Write([]byte(req)); err != nil {
t.Fatal(err)
}
_ = clientConn.SetReadDeadline(time.Now().Add(time.Second))
br := bufio.NewReader(clientConn)
// First line of CONNECT success is not always a full http.Response parse-friendly body;
// read status line.
statusLine, err := br.ReadString('\n')
if err != nil {
t.Fatalf("read status: %v", err)
}
if !strings.Contains(statusLine, "200") {
t.Fatalf("expected 200 Connection established after auth, got %q", statusLine)
}
// consume remaining headers
for {
line, err := br.ReadString('\n')
if err != nil {
t.Fatal(err)
}
if line == "\r\n" || line == "\n" {
break
}
}
// After tunnel is up, write application data and ensure it reaches target.
payload := []byte("hello-tls")
if _, err := clientConn.Write(payload); err != nil {
t.Fatal(err)
}
_ = targetClient.SetReadDeadline(time.Now().Add(time.Second))
got := make([]byte, len(payload))
if _, err := io.ReadFull(targetClient, got); err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, payload) {
t.Fatalf("expected %q, got %q", payload, got)
}
clientConn.Close()
targetClient.Close()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("ProcessHttp did not exit")
}
}
func TestProcessHttpPlainGetWithProxyAuth(t *testing.T) {
setupProxyTestConf(t)
clientConn, serverConn := net.Pipe()
defer clientConn.Close()
defer serverConn.Close()
targetClient, targetServer := net.Pipe()
defer targetClient.Close()
defer targetServer.Close()
server := newHTTPProxyServer(t, "user", "pass", targetServer)
done := make(chan error, 1)
go func() {
done <- ProcessHttp(conn.NewConn(serverConn), server)
}()
token := base64.StdEncoding.EncodeToString([]byte("user:pass"))
req := "GET http://example.com/ HTTP/1.1\r\n" +
"Host: example.com\r\n" +
"Proxy-Authorization: Basic " + token + "\r\n\r\n"
if _, err := clientConn.Write([]byte(req)); err != nil {
t.Fatal(err)
}
// Absolute-form request is forwarded (buffered) to the tunnel target.
_ = targetClient.SetReadDeadline(time.Now().Add(time.Second))
buf := make([]byte, 512)
n, err := targetClient.Read(buf)
if err != nil {
t.Fatal(err)
}
if !bytes.Contains(buf[:n], []byte("GET ")) {
t.Fatalf("expected forwarded GET, got %q", buf[:n])
}
clientConn.Close()
targetClient.Close()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("ProcessHttp did not exit")
}
}
+53 -66
View File
@@ -5,7 +5,6 @@ import (
"errors"
"math"
"os"
"sort"
"strconv"
"strings"
"sync"
@@ -260,13 +259,15 @@ func AddTask(t *file.Tunnel) error {
// start task
func StartTask(id int) error {
if t, err := file.GetDb().GetTask(id); err != nil {
t, err := file.GetDb().GetTask(id)
if err != nil {
return err
} else {
AddTask(t)
t.Status = true
file.GetDb().UpdateTask(t)
}
if err := AddTask(t); err != nil {
return err
}
t.Status = true
file.GetDb().UpdateTask(t)
return nil
}
@@ -283,84 +284,70 @@ func DelTask(id int) error {
// get task list by page num
func GetTunnel(start, length int, typeVal string, clientId int, search string, sortField string, order string) ([]*file.Tunnel, int) {
all_list := make([]*file.Tunnel, 0) //store all Tunnel
list := make([]*file.Tunnel, 0)
var cnt int
all_list := make([]*file.Tunnel, 0)
// 单次遍历收集所有符合条件的 Tunnel(修复原代码双重遍历 sync.Map 的性能问题)
// collect + fill runtime fields before sort/paginate
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
}
if search != "" {
targetStr := ""
if v.Target != nil {
targetStr = v.Target.TargetStr
}
if !(v.Id == common.GetIntNoErrByStr(search) || v.Port == common.GetIntNoErrByStr(search) || strings.Contains(v.Password, search) || strings.Contains(v.Remark, search) || strings.Contains(targetStr, search)) {
return true
}
}
if v.Client != nil {
if _, ok := Bridge.Client.Load(v.Client.Id); ok {
v.Client.IsConnect = true
} else {
v.Client.IsConnect = false
}
}
if _, ok := RunList.Load(v.Id); ok {
v.RunStatus = true
} else {
v.RunStatus = false
}
all_list = append(all_list, v)
return true
})
//sort by Id, Remark, TargetStr, Port, asc or desc
if sortField == "Id" {
if order == "asc" {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Id < all_list[j].Id })
} else {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Id > all_list[j].Id })
}
} else if sortField == "ClientId" {
if order == "asc" {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Client.Id < all_list[j].Client.Id })
} else {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Client.Id > all_list[j].Client.Id })
}
} else if sortField == "Remark" {
if order == "asc" {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Remark < all_list[j].Remark })
} else {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Remark > all_list[j].Remark })
}
} else if sortField == "Client.VerifyKey" {
if order == "asc" {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Client.VerifyKey < all_list[j].Client.VerifyKey })
} else {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Client.VerifyKey > all_list[j].Client.VerifyKey })
}
} else if sortField == "Target" {
if order == "asc" {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Target.TargetStr < all_list[j].Target.TargetStr })
} else {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Target.TargetStr > all_list[j].Target.TargetStr })
}
}
//search 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)
}
}
file.SortTunnels(all_list, sortField, order)
cnt := len(all_list)
if start < 0 {
start = 0
}
return list, cnt
if length <= 0 || start >= cnt {
return []*file.Tunnel{}, cnt
}
end := start + length
if end > cnt {
end = cnt
}
return all_list[start:end], cnt
}
// get client list
func GetClientList(start, length int, search, sort, order string, clientId int) (list []*file.Client, cnt int) {
list, cnt = file.GetDb().GetClientList(start, length, search, sort, order, clientId)
func GetClientList(start, length int, search, sortField, order string, clientId int) (list []*file.Client, cnt int) {
// fill IsConnect / Version before sort so IsConnect ordering is correct
dealClientData()
list, cnt = file.GetDb().GetClientList(start, length, search, sortField, order, clientId)
return
}
// GetHostList returns hosts with client online status filled before sort/pagination.
func GetHostList(start, length int, clientId int, search, sortField, order string) ([]*file.Host, int) {
// ensure Client.IsConnect is current for sort and display
dealClientData()
return file.GetDb().GetHost(start, length, clientId, search, sortField, order)
}
func dealClientData() {
file.GetDb().JsonDb.Clients.Range(func(key, value interface{}) bool {
+14
View File
@@ -56,6 +56,20 @@ func TestServerPort(p int, m string) (b bool) {
}
func GenerateServerPort(m string) int {
// allow_ports 已配置:在允许范围内随机选取,打乱顺序后逐个尝试以避免重复命中已占用端口
if len(ports) != 0 {
shuffled := make([]int, len(ports))
copy(shuffled, ports)
rand.Shuffle(len(shuffled), func(i, j int) {
shuffled[i], shuffled[j] = shuffled[j], shuffled[i]
})
for _, p := range shuffled {
if TestServerPort(p, m) {
return p
}
}
return 0
}
for i := 0; i < 1000; i++ {
//生成随机数 1024 - 65535
serverPort := rand.Intn(65535)

Some files were not shown because too many files have changed in this diff Show More