Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fbbd4bace2 | ||
|
|
0492268190 | ||
|
|
01fca7d568 | ||
|
|
0711b9befb | ||
|
|
2c13a02bdc | ||
|
|
6788f24821 | ||
|
|
e65ab33749 | ||
|
|
7f94b3871a | ||
|
|
aa5b869da9 | ||
|
|
f7898e019e | ||
|
|
ca04f19275 | ||
|
|
db43405237 | ||
|
|
750ecb824a | ||
|
|
2c608ddb7f | ||
|
|
934402e97d | ||
|
|
6fe69bc6b1 | ||
|
|
dab51c32a2 | ||
|
|
48c7309973 | ||
|
|
f2329f72f6 | ||
|
|
9f03c2f6eb |
+8
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="WEB_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
@@ -41,10 +41,14 @@ go语言编写,无第三方依赖,各个平台都已经编译在release中
|
||||
* [udp隧道](#udp隧道)
|
||||
* [socks5代理](#socks5代理)
|
||||
* [http正向代理](#http正向代理)
|
||||
* [私密代理](#私密代理)
|
||||
* [使用https](#使用https)
|
||||
* [与nginx配合](#与nginx配合)
|
||||
* [关闭http|https代理](#关闭代理)
|
||||
* [将nps安装到系统](#将nps安装到系统)
|
||||
* [流量数据持久化](#流量数据持久化)
|
||||
* [自定义客户端连接密钥](#自定义客户端连接密钥)
|
||||
* [关闭公钥访问](#关闭公钥访问)
|
||||
* [客户端](#客户端)
|
||||
* [客户端启动](#客户端启动)
|
||||
* [无配置文件模式](#无配置文件模式)
|
||||
@@ -52,14 +56,16 @@ go语言编写,无第三方依赖,各个平台都已经编译在release中
|
||||
* [配置文件说明](#配置文件说明)
|
||||
* [全局配置](#全局配置)
|
||||
* [域名代理](#域名代理)
|
||||
* [tcp隧道模式](#tcp隧道模式)
|
||||
* [udp隧道模式](#udp隧道模式)
|
||||
* [http代理模式](#http代理模式)
|
||||
* [socks5模式](#socks5模式)
|
||||
* [tcp隧道](#tcp隧道模式)
|
||||
* [udp隧道](#udp隧道模式)
|
||||
* [http正向代理](#http代理模式)
|
||||
* [socks5代理](#socks5代理模式)
|
||||
* [私密代理](#私密代理)
|
||||
* [断线重连](#断线重连)
|
||||
* [状态检查](#状态检查)
|
||||
* [重载配置文件](#重载配置文件)
|
||||
* [通过代理连接nps](#通过代理连接nps)
|
||||
* [日志输出级别](#日志输出级别)
|
||||
|
||||
* [相关功能](#相关功能)
|
||||
* [数据压缩支持](#数据压缩支持)
|
||||
@@ -73,16 +79,19 @@ go语言编写,无第三方依赖,各个平台都已经编译在release中
|
||||
* [负载均衡](#负载均衡)
|
||||
* [端口白名单](#端口白名单)
|
||||
* [端口范围映射](#端口范围映射)
|
||||
* [端口范围映射到其他机器](#端口范围映射到其他机器)
|
||||
* [守护进程](#守护进程)
|
||||
* [KCP协议支持](#KCP协议支持)
|
||||
* [域名泛解析](#域名泛解析)
|
||||
* [URL路由](#URL路由)
|
||||
* [限制ip访问](#限制ip访问)
|
||||
* [客户端最大连接数限制](#客户端最大连接数)
|
||||
* [相关说明](#相关说明)
|
||||
* [流量统计](#流量统计)
|
||||
* [热更新支持](#热更新支持)
|
||||
* [获取用户真实ip](#获取用户真实ip)
|
||||
* [客户端地址显示](#客户端地址显示)
|
||||
* [客户端与服务端版本对比](#客户端与服务端版本对比)
|
||||
* [简单的性能测试](#简单的性能测试)
|
||||
* [qps](#qps)
|
||||
* [速度测试](#速度测试)
|
||||
@@ -103,7 +112,7 @@ go语言编写,无第三方依赖,各个平台都已经编译在release中
|
||||
|
||||
### 源码安装
|
||||
- 安装源码
|
||||
> go get github.com/cnlh/nps
|
||||
> go get -u github.com/cnlh/nps...
|
||||
- 编译
|
||||
> go build cmd/nps/nps.go
|
||||
|
||||
@@ -123,12 +132,12 @@ go语言编写,无第三方依赖,各个平台都已经编译在release中
|
||||
|
||||
|
||||
#### 服务端测试
|
||||
```
|
||||
```shell
|
||||
./nps test
|
||||
```
|
||||
如有错误请及时修改配置文件,无错误可继续进行下去
|
||||
#### 服务端启动
|
||||
```
|
||||
```shell
|
||||
./nps start
|
||||
```
|
||||
如果无需daemon运行,去掉start即可
|
||||
@@ -141,12 +150,12 @@ go语言编写,无第三方依赖,各个平台都已经编译在release中
|
||||
|
||||
#### 服务端停止或重启
|
||||
如果是daemon启动
|
||||
```
|
||||
```shell
|
||||
./nps stop|restart
|
||||
```
|
||||
|
||||
### 服务端配置文件
|
||||
- /conf/app.conf
|
||||
- /conf/nps.conf
|
||||
|
||||
名称 | 含义
|
||||
---|---
|
||||
@@ -161,6 +170,8 @@ authip|web api免验证IP地址
|
||||
bridgeType|客户端与服务端连接方式kcp或tcp
|
||||
publicVkey|客户端以配置文件模式启动时的密钥,设置为空表示关闭客户端配置文件连接模式
|
||||
ipLimit|是否限制ip访问,true或false或忽略
|
||||
flowStoreInterval|服务端流量数据持久化间隔,单位分钟,忽略表示不持久化
|
||||
logLevel|日志输出级别
|
||||
|
||||
### 详细说明
|
||||
|
||||
@@ -172,18 +183,18 @@ ipLimit|是否限制ip访问,true或false或忽略
|
||||
- 有一个域名proxy.com,有一台公网机器ip为1.1.1.1
|
||||
- 两个内网开发站点127.0.0.1:81,127.0.0.1:82
|
||||
- 想通过(http|https://)a.proxy.com访问127.0.0.1:81,通过(http|https://)b.proxy.com访问127.0.0.1:82
|
||||
- 例如配置文件中tcpport为8284
|
||||
- 例如配置文件中bridgePort为8284
|
||||
|
||||
**使用步骤**
|
||||
- 将*.proxy.com解析到公网服务器1.1.1.1
|
||||
- 在客户端管理中创建一个客户端,记录下验证密钥
|
||||
- 点击该客户端的域名管理,添加两条规则规则:1、域名:a.proxy.com,内网目标:127.0.0.1:81,2、域名:b.proxy.com,内网目标:127.0.0.1:82
|
||||
- 点击该客户端的域名管理,添加两条规则规则:1、域名:`a.proxy.com`,内网目标:`127.0.0.1:81`,2、域名:`b.proxy.com`,内网目标:`127.0.0.1:82`
|
||||
- 内网客户端运行
|
||||
|
||||
```
|
||||
```shell
|
||||
./npc -server=1.1.1.1:8284 -vkey=客户端的密钥
|
||||
```
|
||||
现在访问(http|https://)a.proxy.com,b.proxy.com即可成功
|
||||
现在访问(http|https://)`a.proxy.com`,`b.proxy.com`即可成功
|
||||
|
||||
**https:** 如需使用https请在配置文件中将https端口设置为443,和将对应的证书文件路径添加到配置文件中,上面添加的这条记录将会把http、https都转发到内网目标
|
||||
|
||||
@@ -193,16 +204,16 @@ ipLimit|是否限制ip访问,true或false或忽略
|
||||
**适用范围:** ssh、远程桌面等tcp连接场景
|
||||
|
||||
**假设场景:**
|
||||
想通过访问公网服务器1.1.1.1的8001端口,连接内网机器10.1.50.101的22端口,实现ssh连接,例如配置文件中tcpport为8284
|
||||
想通过访问公网服务器1.1.1.1的8001端口,连接内网机器10.1.50.101的22端口,实现ssh连接,例如配置文件中bridgePort为8284
|
||||
|
||||
**使用步骤**
|
||||
- 在客户端管理中创建一个客户端,记录下验证密钥
|
||||
- -内网客户端运行
|
||||
```
|
||||
```shell
|
||||
./npc -server=1.1.1.1:8284 -vkey=客户端的密钥
|
||||
```
|
||||
- 在该客户端隧道管理中添加一条tcp隧道,填写监听的端口(8001)、内网目标ip和目标端口(10.1.50.101:22),选择压缩方式,保存。
|
||||
- 访问公网服务器ip(127.0.0.1),填写的监听端口(8001),相当于访问内网ip(10.1.50.101):目标端口(22),例如:ssh -p 8001 root@127.0.0.1
|
||||
- 访问公网服务器ip(127.0.0.1),填写的监听端口(8001),相当于访问内网ip(10.1.50.101):目标端口(22),例如:`ssh -p 8001 root@127.0.0.1`
|
||||
|
||||
#### udp隧道
|
||||
|
||||
@@ -211,12 +222,12 @@ ipLimit|是否限制ip访问,true或false或忽略
|
||||
**适用范围:** 内网dns解析等udp连接场景
|
||||
|
||||
**假设场景:**
|
||||
内网有一台dns(10.1.50.102:53),在非内网环境下想使用该dns,公网服务器为1.1.1.1,例如配置文件中tcpport为8284
|
||||
内网有一台dns(10.1.50.102:53),在非内网环境下想使用该dns,公网服务器为1.1.1.1,例如配置文件中bridgePort为8284
|
||||
|
||||
**使用步骤**
|
||||
- 在客户端管理中创建一个客户端,记录下验证密钥
|
||||
- -内网客户端运行
|
||||
```
|
||||
```shell
|
||||
./npc -server=1.1.1.1:8284 -vkey=客户端的密钥
|
||||
```
|
||||
- 在该客户端的隧道管理中添加一条udp隧道,填写监听的端口(53)、内网目标ip和目标端口(10.1.50.102:53),选择压缩方式,保存。
|
||||
@@ -228,12 +239,12 @@ ipLimit|是否限制ip访问,true或false或忽略
|
||||
**适用范围:** 在外网环境下如同使用vpn一样访问内网设备或者资源
|
||||
|
||||
**假设场景:**
|
||||
想将公网服务器1.1.1.1的8003端口作为socks5代理,达到访问内网任意设备或者资源的效果,例如配置文件中tcpport为8284
|
||||
想将公网服务器1.1.1.1的8003端口作为socks5代理,达到访问内网任意设备或者资源的效果,例如配置文件中bridgePort为8284
|
||||
|
||||
**使用步骤**
|
||||
- 在客户端管理中创建一个客户端,记录下验证密钥
|
||||
- -内网客户端运行
|
||||
```
|
||||
```shell
|
||||
./npc -server=1.1.1.1:8284 -vkey=客户端的密钥
|
||||
```
|
||||
- 在该客户端隧道管理中添加一条socks5代理,填写监听的端口(8003),验证用户名和密码自行选择(建议先不填,部分客户端不支持,proxifer支持),选择压缩方式,保存。
|
||||
@@ -244,25 +255,55 @@ ipLimit|是否限制ip访问,true或false或忽略
|
||||
**适用范围:** 在外网环境下使用http代理访问内网站点
|
||||
|
||||
**假设场景:**
|
||||
想将公网服务器1.1.1.1的8004端口作为http代理,访问内网网站,例如配置文件中tcpport为8284
|
||||
想将公网服务器1.1.1.1的8004端口作为http代理,访问内网网站,例如配置文件中bridgePort为8284
|
||||
|
||||
**使用步骤**
|
||||
- 在客户端管理中创建一个客户端,记录下验证密钥
|
||||
- -内网客户端运行
|
||||
```
|
||||
```shell
|
||||
./npc -server=1.1.1.1:8284 -vkey=客户端的密钥
|
||||
```
|
||||
- 在该客户端隧道管理中添加一条http代理,填写监听的端口(8004),选择压缩方式,保存。
|
||||
- 在外网环境的本机配置http代理,ip为公网服务器ip(127.0.0.1),端口为填写的监听端口(8004),即可访问了
|
||||
|
||||
#### 私密代理
|
||||
|
||||
**适用范围:** 无需占用多余的端口、安全性要求较高可以防止其他人连接的TCP服务,例如ssh。
|
||||
|
||||
**假设场景:**
|
||||
无需新增多的端将映射内网服务器10.1.50.2的22端口
|
||||
|
||||
**使用步骤**
|
||||
- 在客户端管理中创建一个客户端,记录下验证密钥
|
||||
- 内网客户端运行
|
||||
```
|
||||
./npc -server=1.1.1.1:8284 -vkey=客户端的密钥
|
||||
```
|
||||
- 添加一条私密代理,并设置唯一密钥和内网目标10.1.50.2:22
|
||||
- 在需要连接ssh的机器上以配置文件模式启动客户端,内容如下
|
||||
|
||||
```ini
|
||||
[common]
|
||||
server=127.0.0.1:8284
|
||||
tp=tcp
|
||||
vkey=123
|
||||
[secret_ssh]
|
||||
password=1111
|
||||
port=1000
|
||||
```
|
||||
**注意:** secret前缀必须存在,password为web管理上添加的唯一密钥
|
||||
|
||||
假设用户名为root,现在执行`ssh -p 1000 root@127.0.0.1`即可访问ssh
|
||||
|
||||
|
||||
|
||||
### 使用https
|
||||
|
||||
在配置文件中将httpsProxyPort设置为443或者其他你想配置的端口,和将对应的证书文件路径添加到配置文件中,然后就和http代理一样了,例如
|
||||
|
||||
- 需要访问https://a.proxy.com 对应内网127.0.0.1:80
|
||||
- 需要访问`https://a.proxy.com` 对应内网`127.0.0.1:80`
|
||||
|
||||
- 在域名代理中添加a.proxy.com 内网目标127.0.0.1:80 即可将所有到达本代理的http(s)请求都转发到127.0.0.1:80
|
||||
- 在域名代理中添加`a.proxy.com` 内网目标`127.0.0.1:80` 即可将所有到达本代理的http(s)请求都转发到127.0.0.1:80
|
||||
|
||||
### 与nginx配合
|
||||
|
||||
@@ -272,6 +313,7 @@ server {
|
||||
listen 80;
|
||||
server_name *.proxy.com;
|
||||
location / {
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_pass http://127.0.0.1:8024;
|
||||
}
|
||||
}
|
||||
@@ -290,6 +332,7 @@ server {
|
||||
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:8024;
|
||||
}
|
||||
}
|
||||
@@ -315,6 +358,16 @@ nps test|start|stop|restart|status
|
||||
nps.exe test|start|stop|restart|status
|
||||
```
|
||||
|
||||
### 流量数据持久化
|
||||
服务端支持将流量数据持久化,默认情况下是关闭的,如果有需求可以设置`nps.conf`中的`flowStoreInterval`参数,单位为分钟
|
||||
|
||||
**注意:** nps不会持久化通过公钥连接的客户端
|
||||
|
||||
### 自定义客户端连接密钥
|
||||
web上可以自定义客户端连接的密钥,但是必须具有唯一性
|
||||
### 关闭公钥访问
|
||||
可以将`nps.conf`中的`publicVkey`设置为空或者删除
|
||||
|
||||
## 客户端
|
||||
|
||||
### 客户端启动
|
||||
@@ -331,7 +384,7 @@ nps.exe test|start|stop|restart|status
|
||||
#### 配置文件说明
|
||||
[示例配置文件](https://github.com/cnlh/nps/tree/master/conf/npc.conf)
|
||||
##### 全局配置
|
||||
```
|
||||
```ini
|
||||
[common]
|
||||
server=127.0.0.1:8284
|
||||
tp=tcp
|
||||
@@ -340,6 +393,10 @@ username=111
|
||||
password=222
|
||||
compress=snappy
|
||||
crypt=true
|
||||
rate_limit=10000
|
||||
flow_limit=100
|
||||
remark=test
|
||||
max_conn=10
|
||||
```
|
||||
项 | 含义
|
||||
---|---
|
||||
@@ -350,9 +407,13 @@ username|socks5或http(s)密码保护用户名(可忽略)
|
||||
username|socks5或http(s)密码保护密码(可忽略)
|
||||
compress|是否压缩传输(snappy或空或忽略)
|
||||
crypt|是否加密传输(true或false或忽略)
|
||||
rate_limit|速度限制,可忽略
|
||||
flow_limit|流量限制,可忽略
|
||||
remark|客户端备注,可忽略
|
||||
max_conn|最大连接数,可忽略
|
||||
##### 域名代理
|
||||
|
||||
```
|
||||
```ini
|
||||
[web1]
|
||||
host=a.o.com
|
||||
target=127.0.0.1:8080,127.0.0.1:8082
|
||||
@@ -369,7 +430,7 @@ header_xxx|请求header修改或添加,header_proxy表示添加header proxy:np
|
||||
|
||||
##### tcp隧道模式
|
||||
|
||||
```
|
||||
```ini
|
||||
[tcp]
|
||||
mode=tcpServer
|
||||
target=127.0.0.1:8080
|
||||
@@ -383,7 +444,7 @@ target|内网目标
|
||||
|
||||
##### udp隧道模式
|
||||
|
||||
```
|
||||
```ini
|
||||
[udp]
|
||||
mode=udpServer
|
||||
target=127.0.0.1:8080
|
||||
@@ -396,7 +457,7 @@ port | 在服务端的代理端口
|
||||
target|内网目标
|
||||
##### http代理模式
|
||||
|
||||
```
|
||||
```ini
|
||||
[http]
|
||||
mode=httpProxyServer
|
||||
port=9003
|
||||
@@ -407,7 +468,7 @@ mode | httpProxyServer
|
||||
port | 在服务端的代理端口
|
||||
##### socks5代理模式
|
||||
|
||||
```
|
||||
```ini
|
||||
[socks5]
|
||||
mode=socks5Server
|
||||
port=9004
|
||||
@@ -416,9 +477,22 @@ port=9004
|
||||
---|---
|
||||
mode | socks5Server
|
||||
port | 在服务端的代理端口
|
||||
##### 私密代理模式
|
||||
|
||||
```ini
|
||||
[secret_ssh]
|
||||
mode=secretServer
|
||||
password=ssh2
|
||||
target=10.1.50.2:22
|
||||
```
|
||||
项 | 含义
|
||||
---|---
|
||||
mode | secretServer
|
||||
password | 唯一密钥
|
||||
target|内网目标
|
||||
|
||||
#### 断线重连
|
||||
```
|
||||
```ini
|
||||
[common]
|
||||
auto_reconnection=true
|
||||
```
|
||||
@@ -427,7 +501,7 @@ auto_reconnection=true
|
||||
```
|
||||
./npc status -config=npc配置文件路径
|
||||
```
|
||||
#### 配置文件重载
|
||||
#### 重载配置文件
|
||||
```
|
||||
./npc restart -config=npc配置文件路径
|
||||
```
|
||||
@@ -436,7 +510,7 @@ auto_reconnection=true
|
||||
有时候运行npc的内网机器无法直接访问外网,此时可以可以通过socks5代理连接nps
|
||||
|
||||
对于配置文件方式启动,设置
|
||||
```
|
||||
```ini
|
||||
[common]
|
||||
proxy_socks5_url=socks5://111:222@127.0.0.1:8024
|
||||
```
|
||||
@@ -447,6 +521,20 @@ proxy_socks5_url=socks5://111:222@127.0.0.1:8024
|
||||
```
|
||||
即socks5://username:password@ip:port
|
||||
|
||||
#### 日志输出级别
|
||||
```
|
||||
-log_level=0~7
|
||||
```
|
||||
```
|
||||
LevelEmergency->0 LevelAlert->1
|
||||
|
||||
LevelCritical->2 LevelError->3
|
||||
|
||||
LevelWarning->4 LevelNotice->5
|
||||
|
||||
LevelInformational->6 LevelDebug->7
|
||||
```
|
||||
默认为全输出,级别为0到7
|
||||
## 相关功能
|
||||
|
||||
### 数据压缩支持
|
||||
@@ -501,16 +589,16 @@ proxy_socks5_url=socks5://111:222@127.0.0.1:8024
|
||||
本代理支持域名解析模式的负载均衡,在web域名添加或者编辑中内网目标分行填写多个目标即可实现轮训级别的负载均衡
|
||||
|
||||
### 端口白名单
|
||||
为了防止服务端上的端口被滥用,可在app.conf中配置allowPorts限制可开启的端口,忽略或者不填表示端口不受限制,格式:
|
||||
为了防止服务端上的端口被滥用,可在nps.conf中配置allowPorts限制可开启的端口,忽略或者不填表示端口不受限制,格式:
|
||||
|
||||
```
|
||||
```ini
|
||||
allowPorts=9001-9009,10001,11000-12000
|
||||
```
|
||||
|
||||
### 端口范围映射
|
||||
当客户端以配置文件的方式启动时,可以将本地的端口进行范围映射,仅支持tcp和udp模式,例如:
|
||||
|
||||
```
|
||||
```ini
|
||||
[tcp]
|
||||
mode=tcpServer
|
||||
port=9001-9009,10001,11000-12000
|
||||
@@ -518,6 +606,15 @@ target=8001-8009,10002,13000-14000
|
||||
```
|
||||
|
||||
逗号分隔,可单个或者范围,注意上下端口的对应关系,无法一一对应将不能成功
|
||||
### 端口范围映射到其他机器
|
||||
```ini
|
||||
[tcp]
|
||||
mode=tcpServer
|
||||
port=9001-9009,10001,11000-12000
|
||||
target=8001-8009,10002,13000-14000
|
||||
targetAddr=10.1.50.2
|
||||
```
|
||||
填写targetAddr后则表示映射的该地址机器的端口,忽略则便是映射本地127.0.0.1,仅范围映射时有效
|
||||
### 守护进程
|
||||
本代理支持守护进程,使用示例如下,服务端客户端所有模式通用,支持linux,darwin,windows。
|
||||
```
|
||||
@@ -528,7 +625,7 @@ target=8001-8009,10002,13000-14000
|
||||
```
|
||||
### KCP协议支持
|
||||
|
||||
KCP 是一个快速可靠协议,能以比 TCP浪费10%-20%的带宽的代价,换取平均延迟降低 30%-40%,在弱网环境下对性能能有一定的提升。可在app.conf中修改bridgeType为kcp
|
||||
KCP 是一个快速可靠协议,能以比 TCP浪费10%-20%的带宽的代价,换取平均延迟降低 30%-40%,在弱网环境下对性能能有一定的提升。可在nps.conf中修改bridgeType为kcp
|
||||
,设置后本代理将开启udp端口(bridgePort)
|
||||
|
||||
注意:当服务端为kcp时,客户端连接时也需要使用相同配置,无配置文件模式加上参数type=kcp,配置文件模式在配置文件中设置tp=kcp
|
||||
@@ -539,7 +636,7 @@ KCP 是一个快速可靠协议,能以比 TCP浪费10%-20%的带宽的代价
|
||||
### URL路由
|
||||
本代理支持根据URL将同一域名转发到不同的内网服务器,可在web中或客户端配置文件中设置,此参数也可忽略,例如在客户端配置文件中
|
||||
|
||||
```
|
||||
```ini
|
||||
[web1]
|
||||
host=a.proxy.com
|
||||
target=127.0.0.1:7001
|
||||
@@ -549,12 +646,12 @@ host=a.proxy.com
|
||||
target=127.0.0.1:7002
|
||||
location=/static
|
||||
```
|
||||
对于a.proxy.com/test将转发到web1,对于a.proxy.com/static将转发到web2
|
||||
对于`a.proxy.com/test`将转发到`web1`,对于`a.proxy.com/static`将转发到`web2`
|
||||
|
||||
### 限制ip访问
|
||||
如果将一些危险性高的端口例如ssh端口暴露在公网上,可能会带来一些风险,本代理支持限制ip访问。
|
||||
|
||||
**使用方法:** 在配置文件app.conf中设置ipLimit=true,设置后仅通过注册的ip方可访问。
|
||||
**使用方法:** 在配置文件nps.conf中设置ipLimit=true,设置后仅通过注册的ip方可访问。
|
||||
|
||||
**ip注册**: 在需要访问的机器上,运行客户端
|
||||
|
||||
@@ -565,6 +662,8 @@ location=/static
|
||||
time为有效小时数,例如time=2,在当前时间后的两小时内,本机公网ip都可以访问nps代理.
|
||||
|
||||
**注意:** 本机公网ip并不是一成不变的,请自行注意有效期的设置,同时同一网络下,多人也可能是在公用同一个公网ip。
|
||||
### 客户端最大连接数
|
||||
为防止恶意大量长连接,影响服务端程序的稳定性,可以在web或客户端配置文件中为每个客户端设置最大连接数。该功能针对`socks5`、`http正向代理`、`域名代理`、`tcp代理`、`私密代理`生效。
|
||||
|
||||
## 相关说明
|
||||
|
||||
@@ -583,7 +682,10 @@ time为有效小时数,例如time=2,在当前时间后的两小时内,本
|
||||
### 流量统计
|
||||
可统计显示每个代理使用的流量,由于压缩和加密等原因,会和实际环境中的略有差异
|
||||
|
||||
## 简单性能测试
|
||||
### 客户端与服务端版本对比
|
||||
为了程序正常运行,客户端与服务端的版本必须一致,否则将导致客户端无法成功连接致服务端。
|
||||
|
||||
## 简单的性能测试
|
||||
|
||||
### qps
|
||||

|
||||
|
||||
+126
-41
@@ -8,11 +8,11 @@ import (
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/lib/pool"
|
||||
"github.com/cnlh/nps/lib/version"
|
||||
"github.com/cnlh/nps/server/tool"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/vender/github.com/xtaci/kcp"
|
||||
"log"
|
||||
"net"
|
||||
"strconv"
|
||||
"sync"
|
||||
@@ -22,19 +22,21 @@ import (
|
||||
type Client struct {
|
||||
tunnel *conn.Conn
|
||||
signal *conn.Conn
|
||||
msg *conn.Conn
|
||||
linkMap map[int]*conn.Link
|
||||
linkStatusMap map[int]bool
|
||||
stop chan bool
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func NewClient(t *conn.Conn, s *conn.Conn) *Client {
|
||||
func NewClient(t *conn.Conn, s *conn.Conn, m *conn.Conn) *Client {
|
||||
return &Client{
|
||||
linkMap: make(map[int]*conn.Link),
|
||||
stop: make(chan bool),
|
||||
linkStatusMap: make(map[int]bool),
|
||||
signal: s,
|
||||
tunnel: t,
|
||||
msg: m,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +48,7 @@ type Bridge struct {
|
||||
tunnelType string //bridge type kcp or tcp
|
||||
OpenTask chan *file.Tunnel
|
||||
CloseClient chan int
|
||||
SecretChan chan *conn.Secret
|
||||
clientLock sync.RWMutex
|
||||
Register map[string]time.Time
|
||||
registerLock sync.RWMutex
|
||||
@@ -63,10 +66,12 @@ func NewTunnel(tunnelPort int, tunnelType string, ipVerify bool, runList map[int
|
||||
t.Register = make(map[string]time.Time)
|
||||
t.ipVerify = ipVerify
|
||||
t.runList = runList
|
||||
t.SecretChan = make(chan *conn.Secret)
|
||||
return t
|
||||
}
|
||||
|
||||
func (s *Bridge) StartTunnel() error {
|
||||
go s.linkCleanSession()
|
||||
var err error
|
||||
if s.tunnelType == "kcp" {
|
||||
s.kcpListener, err = kcp.ListenWithOptions(":"+strconv.Itoa(s.TunnelPort), nil, 150, 3)
|
||||
@@ -78,7 +83,7 @@ func (s *Bridge) StartTunnel() error {
|
||||
c, err := s.kcpListener.AcceptKCP()
|
||||
conn.SetUdpSession(c)
|
||||
if err != nil {
|
||||
lg.Println(err)
|
||||
logs.Warn(err)
|
||||
continue
|
||||
}
|
||||
go s.cliProcess(conn.NewConn(c))
|
||||
@@ -93,7 +98,7 @@ func (s *Bridge) StartTunnel() error {
|
||||
for {
|
||||
c, err := s.tcpListener.Accept()
|
||||
if err != nil {
|
||||
lg.Println(err)
|
||||
logs.Warn(err)
|
||||
continue
|
||||
}
|
||||
go s.cliProcess(conn.NewConn(c))
|
||||
@@ -114,6 +119,12 @@ func (s *Bridge) verifySuccess(c *conn.Conn) {
|
||||
}
|
||||
|
||||
func (s *Bridge) cliProcess(c *conn.Conn) {
|
||||
if b, err := c.ReadLen(32); err != nil || string(b) != crypt.Md5(version.GetVersion()) {
|
||||
logs.Info("The client %s version does not match", c.Conn.RemoteAddr())
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
c.Write([]byte(crypt.Md5(version.GetVersion())))
|
||||
c.SetReadDeadline(5, s.tunnelType)
|
||||
var buf []byte
|
||||
var err error
|
||||
@@ -124,7 +135,7 @@ func (s *Bridge) cliProcess(c *conn.Conn) {
|
||||
//验证
|
||||
id, err := file.GetCsvDb().GetIdByVerifyKey(string(buf), c.Conn.RemoteAddr().String())
|
||||
if err != nil {
|
||||
lg.Println("当前客户端连接校验错误,关闭此客户端:", c.Conn.RemoteAddr())
|
||||
logs.Info("Current client connection validation error, close this client:", c.Conn.RemoteAddr())
|
||||
s.verifyError(c)
|
||||
return
|
||||
} else {
|
||||
@@ -134,7 +145,7 @@ func (s *Bridge) cliProcess(c *conn.Conn) {
|
||||
if flag, err := c.ReadFlag(); err == nil {
|
||||
s.typeDeal(flag, c, id)
|
||||
} else {
|
||||
log.Println(err, flag)
|
||||
logs.Warn(err, flag)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -150,6 +161,17 @@ func (s *Bridge) closeClient(id int) {
|
||||
delete(s.Client, id)
|
||||
}
|
||||
}
|
||||
func (s *Bridge) delClient(id int) {
|
||||
s.clientLock.Lock()
|
||||
defer s.clientLock.Unlock()
|
||||
if v, ok := s.Client[id]; ok {
|
||||
if c, err := file.GetCsvDb().GetClient(id); err == nil && c.NoStore {
|
||||
s.CloseClient <- c.Id
|
||||
}
|
||||
v.signal.Close()
|
||||
delete(s.Client, id)
|
||||
}
|
||||
}
|
||||
|
||||
//tcp连接类型区分
|
||||
func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int) {
|
||||
@@ -166,10 +188,10 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int) {
|
||||
v.signal = c
|
||||
v.Unlock()
|
||||
} else {
|
||||
s.Client[id] = NewClient(nil, c)
|
||||
s.Client[id] = NewClient(nil, c, nil)
|
||||
s.clientLock.Unlock()
|
||||
}
|
||||
lg.Printf("clientId %d connection succeeded, address:%s ", id, c.Conn.RemoteAddr())
|
||||
logs.Info("clientId %d connection succeeded, address:%s ", id, c.Conn.RemoteAddr())
|
||||
go s.GetStatus(id)
|
||||
case common.WORK_CHAN:
|
||||
s.clientLock.Lock()
|
||||
@@ -179,7 +201,7 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int) {
|
||||
v.tunnel = c
|
||||
v.Unlock()
|
||||
} else {
|
||||
s.Client[id] = NewClient(c, nil)
|
||||
s.Client[id] = NewClient(c, nil, nil)
|
||||
s.clientLock.Unlock()
|
||||
}
|
||||
go s.clientCopy(id)
|
||||
@@ -187,11 +209,48 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int) {
|
||||
go s.GetConfig(c)
|
||||
case common.WORK_REGISTER:
|
||||
go s.register(c)
|
||||
case common.WORD_SECRET:
|
||||
if b, err := c.ReadLen(32); err == nil {
|
||||
s.SecretChan <- conn.NewSecret(string(b), c)
|
||||
}
|
||||
case common.WORK_SEND_STATUS:
|
||||
s.clientLock.Lock()
|
||||
if v, ok := s.Client[id]; ok {
|
||||
s.clientLock.Unlock()
|
||||
v.Lock()
|
||||
v.msg = c
|
||||
v.Unlock()
|
||||
} else {
|
||||
s.Client[id] = NewClient(nil, nil, c)
|
||||
s.clientLock.Unlock()
|
||||
}
|
||||
go s.getMsgStatus(id)
|
||||
}
|
||||
c.SetAlive(s.tunnelType)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Bridge) getMsgStatus(clientId int) {
|
||||
s.clientLock.Lock()
|
||||
client := s.Client[clientId]
|
||||
s.clientLock.Unlock()
|
||||
|
||||
if client == nil {
|
||||
return
|
||||
}
|
||||
for {
|
||||
if id, err := client.msg.GetLen(); err != nil {
|
||||
s.closeClient(clientId)
|
||||
return
|
||||
} else {
|
||||
client.Lock()
|
||||
if v, ok := client.linkMap[id]; ok {
|
||||
v.StatusCh <- true
|
||||
}
|
||||
client.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *Bridge) register(c *conn.Conn) {
|
||||
var hour int32
|
||||
if err := binary.Read(c, binary.LittleEndian, &hour); err == nil {
|
||||
@@ -247,26 +306,28 @@ func (s *Bridge) SendLinkInfo(clientId int, link *conn.Link, linkAddr string) (t
|
||||
|
||||
v.signal.SendLinkInfo(link)
|
||||
if err != nil {
|
||||
lg.Println("send link information error:", err, link.Id)
|
||||
logs.Warn("send link information error:", err, link.Id)
|
||||
s.DelClient(clientId)
|
||||
return
|
||||
}
|
||||
|
||||
if v.tunnel == nil {
|
||||
err = errors.New("get tunnel connection error")
|
||||
return
|
||||
} else {
|
||||
tunnel = v.tunnel
|
||||
}
|
||||
link.MsgConn = v.msg
|
||||
v.Lock()
|
||||
v.linkMap[link.Id] = link
|
||||
v.Unlock()
|
||||
if !s.waitStatus(clientId, link.Id) {
|
||||
err = errors.New("connect fail")
|
||||
err = errors.New(fmt.Sprintf("connect target %s fail", link.Host))
|
||||
return
|
||||
}
|
||||
} else {
|
||||
s.clientLock.Unlock()
|
||||
err = errors.New("the connection is not connect")
|
||||
err = errors.New(fmt.Sprintf("the client %d is not connect", clientId))
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -280,6 +341,7 @@ func (s *Bridge) DelClient(id int) {
|
||||
func (s *Bridge) GetConfig(c *conn.Conn) {
|
||||
var client *file.Client
|
||||
var fail bool
|
||||
|
||||
for {
|
||||
flag, err := c.ReadFlag()
|
||||
if err != nil {
|
||||
@@ -309,20 +371,19 @@ func (s *Bridge) GetConfig(c *conn.Conn) {
|
||||
binary.Write(c, binary.LittleEndian, []byte(str))
|
||||
}
|
||||
case common.NEW_CONF:
|
||||
//new client ,Set the client not to store to the file
|
||||
client = file.NewClient(crypt.GetRandomString(16), true, false)
|
||||
client.Remark = "public veky"
|
||||
//Send the key to the client
|
||||
file.GetCsvDb().NewClient(client)
|
||||
c.Write([]byte(client.VerifyKey))
|
||||
|
||||
if config, err := c.GetConfigInfo(); err != nil {
|
||||
var err error
|
||||
if client, err = c.GetConfigInfo(); err != nil {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break
|
||||
} else {
|
||||
client.Cnf = config
|
||||
if err = file.GetCsvDb().NewClient(client); err != nil {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break
|
||||
}
|
||||
c.WriteAddOk()
|
||||
c.Write([]byte(client.VerifyKey))
|
||||
}
|
||||
case common.NEW_HOST:
|
||||
if h, err := c.GetHostInfo(); err != nil {
|
||||
@@ -332,6 +393,7 @@ func (s *Bridge) GetConfig(c *conn.Conn) {
|
||||
} else if file.GetCsvDb().IsHostExist(h) {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break
|
||||
} else {
|
||||
h.Client = client
|
||||
file.GetCsvDb().NewHost(h)
|
||||
@@ -349,6 +411,13 @@ func (s *Bridge) GetConfig(c *conn.Conn) {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break
|
||||
} else if t.Mode == "secretServer" {
|
||||
ports = append(ports, 0)
|
||||
}
|
||||
if len(ports) == 0 {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break
|
||||
}
|
||||
for i := 0; i < len(ports); i++ {
|
||||
tl := new(file.Tunnel)
|
||||
@@ -359,17 +428,24 @@ func (s *Bridge) GetConfig(c *conn.Conn) {
|
||||
tl.Remark = t.Remark
|
||||
} else {
|
||||
tl.Remark = t.Remark + "_" + strconv.Itoa(tl.Port)
|
||||
tl.Target = strconv.Itoa(targets[i])
|
||||
tl.Target = t.TargetAddr + ":" + strconv.Itoa(targets[i])
|
||||
}
|
||||
tl.Id = file.GetCsvDb().GetTaskId()
|
||||
tl.Status = true
|
||||
tl.Flow = new(file.Flow)
|
||||
tl.NoStore = true
|
||||
tl.Client = client
|
||||
file.GetCsvDb().NewTask(tl)
|
||||
if b := tool.TestServerPort(tl.Port, tl.Mode); !b {
|
||||
tl.Password = t.Password
|
||||
if err := file.GetCsvDb().NewTask(tl); err != nil {
|
||||
logs.Notice("Add task error ", err.Error())
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break
|
||||
}
|
||||
if b := tool.TestServerPort(tl.Port, tl.Mode); !b && t.Mode != "secretServer" {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break
|
||||
} else {
|
||||
s.OpenTask <- tl
|
||||
}
|
||||
@@ -412,7 +488,8 @@ func (s *Bridge) clientCopy(clientId int) {
|
||||
|
||||
for {
|
||||
if id, err := client.tunnel.GetLen(); err != nil {
|
||||
s.closeClient(clientId)
|
||||
logs.Info("read msg content length error close client")
|
||||
s.delClient(clientId)
|
||||
break
|
||||
} else {
|
||||
client.Lock()
|
||||
@@ -420,23 +497,11 @@ func (s *Bridge) clientCopy(clientId int) {
|
||||
client.Unlock()
|
||||
if content, err := client.tunnel.GetMsgContent(link); err != nil {
|
||||
pool.PutBufPoolCopy(content)
|
||||
s.closeClient(clientId)
|
||||
lg.Println("read msg content error", err, "close client")
|
||||
s.delClient(clientId)
|
||||
logs.Notice("read msg content error", err, "close client")
|
||||
break
|
||||
} else {
|
||||
if len(content) == len(common.IO_EOF) && string(content) == common.IO_EOF {
|
||||
if link.Conn != nil {
|
||||
link.Conn.Close()
|
||||
}
|
||||
} else {
|
||||
if link.UdpListener != nil && link.UdpRemoteAddr != nil {
|
||||
link.UdpListener.WriteToUDP(content, link.UdpRemoteAddr)
|
||||
} else {
|
||||
link.Conn.Write(content)
|
||||
}
|
||||
link.Flow.Add(0, len(content))
|
||||
}
|
||||
pool.PutBufPoolCopy(content)
|
||||
link.MsgCh <- content
|
||||
}
|
||||
} else {
|
||||
client.Unlock()
|
||||
@@ -445,3 +510,23 @@ func (s *Bridge) clientCopy(clientId int) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Bridge) linkCleanSession() {
|
||||
ticker := time.NewTicker(time.Minute * 5)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
s.clientLock.Lock()
|
||||
for _, v := range s.Client {
|
||||
v.Lock()
|
||||
for _, vv := range v.linkMap {
|
||||
if vv.FinishUse {
|
||||
delete(v.linkMap, vv.Id)
|
||||
}
|
||||
}
|
||||
v.Unlock()
|
||||
}
|
||||
s.clientLock.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+59
-134
@@ -1,18 +1,12 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/config"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/lib/pool"
|
||||
"github.com/cnlh/nps/vender/github.com/xtaci/kcp"
|
||||
"github.com/cnlh/nps/vender/golang.org/x/net/proxy"
|
||||
"io/ioutil"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"net"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
@@ -21,6 +15,7 @@ type TRPClient struct {
|
||||
svrAddr string
|
||||
linkMap map[int]*conn.Link
|
||||
tunnel *conn.Conn
|
||||
msgTunnel *conn.Conn
|
||||
bridgeConnType string
|
||||
stop chan bool
|
||||
proxyUrl string
|
||||
@@ -43,14 +38,15 @@ func NewRPClient(svraddr string, vKey string, bridgeConnType string, proxyUrl st
|
||||
|
||||
//start
|
||||
func (s *TRPClient) Start() {
|
||||
go s.linkCleanSession()
|
||||
retry:
|
||||
c, err := NewConn(s.bridgeConnType, s.vKey, s.svrAddr, common.WORK_MAIN, s.proxyUrl)
|
||||
if err != nil {
|
||||
lg.Println("The connection server failed and will be reconnected in five seconds")
|
||||
logs.Error("The connection server failed and will be reconnected in five seconds")
|
||||
time.Sleep(time.Second * 5)
|
||||
goto retry
|
||||
}
|
||||
lg.Printf("Successful connection with server %s", s.svrAddr)
|
||||
logs.Info("Successful connection with server %s", s.svrAddr)
|
||||
s.processor(c)
|
||||
}
|
||||
|
||||
@@ -67,15 +63,17 @@ func (s *TRPClient) Close() {
|
||||
//处理
|
||||
func (s *TRPClient) processor(c *conn.Conn) {
|
||||
go s.dealChan()
|
||||
go s.getMsgStatus()
|
||||
for {
|
||||
flags, err := c.ReadFlag()
|
||||
if err != nil {
|
||||
lg.Printf("Accept server data error %s, end this service", err.Error())
|
||||
logs.Error("Accept server data error %s, end this service", err.Error())
|
||||
break
|
||||
}
|
||||
switch flags {
|
||||
case common.VERIFY_EER:
|
||||
lg.Fatalf("VKey:%s is incorrect, the server refuses to connect, please check", s.vKey)
|
||||
logs.Error("VKey:%s is incorrect, the server refuses to connect, please check", s.vKey)
|
||||
os.Exit(0)
|
||||
case common.NEW_CONN:
|
||||
if link, err := c.GetLinkInfo(); err != nil {
|
||||
break
|
||||
@@ -83,15 +81,18 @@ func (s *TRPClient) processor(c *conn.Conn) {
|
||||
s.Lock()
|
||||
s.linkMap[link.Id] = link
|
||||
s.Unlock()
|
||||
link.MsgConn = s.msgTunnel
|
||||
go s.linkProcess(link, c)
|
||||
link.Run(false)
|
||||
}
|
||||
case common.RES_CLOSE:
|
||||
lg.Fatalln("The authentication key is connected by another client or the server closes the client.")
|
||||
logs.Error("The authentication key is connected by another client or the server closes the client.")
|
||||
os.Exit(0)
|
||||
case common.RES_MSG:
|
||||
lg.Println("Server-side return error")
|
||||
logs.Error("Server-side return error")
|
||||
break
|
||||
default:
|
||||
lg.Println("The error could not be resolved")
|
||||
logs.Warn("The error could not be resolved")
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -106,12 +107,10 @@ func (s *TRPClient) linkProcess(link *conn.Link, c *conn.Conn) {
|
||||
|
||||
if err != nil {
|
||||
c.WriteFail(link.Id)
|
||||
lg.Println("connect to ", link.Host, "error:", err)
|
||||
logs.Warn("connect to ", link.Host, "error:", err)
|
||||
return
|
||||
}
|
||||
|
||||
c.WriteSuccess(link.Id)
|
||||
|
||||
link.Conn = conn.NewConn(server)
|
||||
buf := pool.BufPoolCopy.Get().([]byte)
|
||||
for {
|
||||
@@ -123,24 +122,50 @@ func (s *TRPClient) linkProcess(link *conn.Link, c *conn.Conn) {
|
||||
c.Close()
|
||||
break
|
||||
}
|
||||
lg.Println("send ok", link.Id)
|
||||
if link.ConnType == common.CONN_UDP {
|
||||
break
|
||||
}
|
||||
}
|
||||
<-link.StatusCh
|
||||
}
|
||||
pool.PutBufPoolCopy(buf)
|
||||
s.Lock()
|
||||
delete(s.linkMap, link.Id)
|
||||
s.Unlock()
|
||||
}
|
||||
|
||||
func (s *TRPClient) getMsgStatus() {
|
||||
var err error
|
||||
s.msgTunnel, err = NewConn(s.bridgeConnType, s.vKey, s.svrAddr, common.WORK_SEND_STATUS, s.proxyUrl)
|
||||
if err != nil {
|
||||
logs.Error("connect to ", s.svrAddr, "error:", err)
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
for {
|
||||
if id, err := s.msgTunnel.GetLen(); err != nil {
|
||||
break
|
||||
} else {
|
||||
s.Lock()
|
||||
if v, ok := s.linkMap[id]; ok {
|
||||
s.Unlock()
|
||||
v.StatusCh <- true
|
||||
} else {
|
||||
s.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
<-s.stop
|
||||
}
|
||||
|
||||
//隧道模式处理
|
||||
func (s *TRPClient) dealChan() {
|
||||
var err error
|
||||
s.tunnel, err = NewConn(s.bridgeConnType, s.vKey, s.svrAddr, common.WORK_CHAN, s.proxyUrl)
|
||||
if err != nil {
|
||||
lg.Println("connect to ", s.svrAddr, "error:", err)
|
||||
logs.Error("connect to ", s.svrAddr, "error:", err)
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
for {
|
||||
if id, err := s.tunnel.GetLen(); err != nil {
|
||||
@@ -150,16 +175,10 @@ func (s *TRPClient) dealChan() {
|
||||
if v, ok := s.linkMap[id]; ok {
|
||||
s.Unlock()
|
||||
if content, err := s.tunnel.GetMsgContent(v); err != nil {
|
||||
lg.Println("get msg content error:", err, id)
|
||||
pool.PutBufPoolCopy(content)
|
||||
break
|
||||
} else {
|
||||
if len(content) == len(common.IO_EOF) && string(content) == common.IO_EOF {
|
||||
v.Conn.Close()
|
||||
} else if v.Conn != nil {
|
||||
v.Conn.Write(content)
|
||||
}
|
||||
pool.PutBufPoolCopy(content)
|
||||
v.MsgCh <- content
|
||||
}
|
||||
} else {
|
||||
s.Unlock()
|
||||
@@ -170,112 +189,18 @@ func (s *TRPClient) dealChan() {
|
||||
<-s.stop
|
||||
}
|
||||
|
||||
var errAdd = errors.New("The server returned an error, which port or host may have been occupied or not allowed to open.")
|
||||
|
||||
func StartFromFile(path string) {
|
||||
first := true
|
||||
cnf, err := config.NewConfig(path)
|
||||
if err != nil {
|
||||
lg.Fatalln(err)
|
||||
}
|
||||
lg.Printf("Loading configuration file %s successfully", path)
|
||||
re:
|
||||
if first || cnf.CommonConfig.AutoReconnection {
|
||||
if !first {
|
||||
lg.Println("Reconnecting...")
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
} else {
|
||||
return
|
||||
}
|
||||
first = false
|
||||
c, err := NewConn(cnf.CommonConfig.Tp, cnf.CommonConfig.VKey, cnf.CommonConfig.Server, common.WORK_CONFIG, cnf.CommonConfig.ProxyUrl)
|
||||
if err != nil {
|
||||
lg.Println(err)
|
||||
goto re
|
||||
}
|
||||
if _, err := c.SendConfigInfo(cnf.CommonConfig.Cnf); err != nil {
|
||||
lg.Println(err)
|
||||
goto re
|
||||
}
|
||||
var b []byte
|
||||
if b, err = c.ReadLen(16); err != nil {
|
||||
lg.Println(err)
|
||||
goto re
|
||||
} else {
|
||||
ioutil.WriteFile(filepath.Join(common.GetTmpPath(), "npc_vkey.txt"), []byte(string(b)), 0600)
|
||||
}
|
||||
if !c.GetAddStatus() {
|
||||
lg.Println(errAdd)
|
||||
goto re
|
||||
}
|
||||
for _, v := range cnf.Hosts {
|
||||
if _, err := c.SendHostInfo(v); err != nil {
|
||||
lg.Println(err)
|
||||
goto re
|
||||
}
|
||||
if !c.GetAddStatus() {
|
||||
lg.Println(errAdd, v.Host)
|
||||
goto re
|
||||
}
|
||||
}
|
||||
for _, v := range cnf.Tasks {
|
||||
if _, err := c.SendTaskInfo(v); err != nil {
|
||||
lg.Println(err)
|
||||
goto re
|
||||
}
|
||||
if !c.GetAddStatus() {
|
||||
lg.Println(errAdd, v.Ports)
|
||||
goto re
|
||||
}
|
||||
}
|
||||
|
||||
c.Close()
|
||||
|
||||
NewRPClient(cnf.CommonConfig.Server, string(b), cnf.CommonConfig.Tp, cnf.CommonConfig.ProxyUrl).Start()
|
||||
goto re
|
||||
}
|
||||
|
||||
//Create a new connection with the server and verify it
|
||||
func NewConn(tp string, vkey string, server string, connType string, proxyUrl string) (*conn.Conn, error) {
|
||||
var err error
|
||||
var connection net.Conn
|
||||
var sess *kcp.UDPSession
|
||||
if tp == "tcp" {
|
||||
if proxyUrl != "" {
|
||||
u, er := url.Parse(proxyUrl)
|
||||
if er != nil {
|
||||
return nil, er
|
||||
func (s *TRPClient) linkCleanSession() {
|
||||
ticker := time.NewTicker(time.Minute * 5)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
s.Lock()
|
||||
for _, v := range s.linkMap {
|
||||
if v.FinishUse {
|
||||
delete(s.linkMap, v.Id)
|
||||
}
|
||||
}
|
||||
n, er := proxy.FromURL(u, nil)
|
||||
if er != nil {
|
||||
return nil, er
|
||||
}
|
||||
connection, err = n.Dial("tcp", server)
|
||||
} else {
|
||||
connection, err = net.Dial("tcp", server)
|
||||
s.Unlock()
|
||||
}
|
||||
} else {
|
||||
sess, err = kcp.DialWithOptions(server, nil, 10, 3)
|
||||
conn.SetUdpSession(sess)
|
||||
connection = sess
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := conn.NewConn(connection)
|
||||
if _, err := c.Write([]byte(common.Getverifyval(vkey))); err != nil {
|
||||
lg.Println(err)
|
||||
}
|
||||
if s, err := c.ReadFlag(); err != nil {
|
||||
lg.Println(err)
|
||||
} else if s == common.VERIFY_EER {
|
||||
lg.Fatalf("Validation key %s incorrect", vkey)
|
||||
}
|
||||
if _, err := c.Write([]byte(connType)); err != nil {
|
||||
lg.Println(err)
|
||||
}
|
||||
c.SetAlive(tp)
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/config"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/version"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/vender/github.com/xtaci/kcp"
|
||||
"github.com/cnlh/nps/vender/golang.org/x/net/proxy"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func GetTaskStatus(path string) {
|
||||
cnf, err := config.NewConfig(path)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
c, err := NewConn(cnf.CommonConfig.Tp, cnf.CommonConfig.VKey, cnf.CommonConfig.Server, common.WORK_CONFIG, cnf.CommonConfig.ProxyUrl)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
if _, err := c.Write([]byte(common.WORK_STATUS)); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
if f, err := common.ReadAllFromFile(filepath.Join(common.GetTmpPath(), "npc_vkey.txt")); err != nil {
|
||||
log.Fatalln(err)
|
||||
} else if _, err := c.Write([]byte(string(f))); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
if l, err := c.GetLen(); err != nil {
|
||||
log.Fatalln(err)
|
||||
} else if b, err := c.ReadLen(l); err != nil {
|
||||
log.Fatalln(err)
|
||||
} else {
|
||||
arr := strings.Split(string(b), common.CONN_DATA_SEQ)
|
||||
for _, v := range cnf.Hosts {
|
||||
if common.InStrArr(arr, v.Remark) {
|
||||
log.Println(v.Remark, "ok")
|
||||
} else {
|
||||
log.Println(v.Remark, "not running")
|
||||
}
|
||||
}
|
||||
for _, v := range cnf.Tasks {
|
||||
ports := common.GetPorts(v.Ports)
|
||||
if v.Mode == "secretServer" {
|
||||
ports = append(ports, 0)
|
||||
}
|
||||
for _, vv := range ports {
|
||||
var remark string
|
||||
if len(ports) > 1 {
|
||||
remark = v.Remark + "_" + strconv.Itoa(vv)
|
||||
} else {
|
||||
remark = v.Remark
|
||||
}
|
||||
if common.InStrArr(arr, remark) {
|
||||
log.Println(remark, "ok")
|
||||
} else {
|
||||
log.Println(remark, "not running")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
var errAdd = errors.New("The server returned an error, which port or host may have been occupied or not allowed to open.")
|
||||
|
||||
func StartFromFile(path string) {
|
||||
first := true
|
||||
cnf, err := config.NewConfig(path)
|
||||
if err != nil || cnf.CommonConfig == nil {
|
||||
logs.Error("Config file %s loading error", path)
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
logs.Info("Loading configuration file %s successfully", path)
|
||||
re:
|
||||
if first || cnf.CommonConfig.AutoReconnection {
|
||||
if !first {
|
||||
logs.Info("Reconnecting...")
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
} else {
|
||||
return
|
||||
}
|
||||
first = false
|
||||
c, err := NewConn(cnf.CommonConfig.Tp, cnf.CommonConfig.VKey, cnf.CommonConfig.Server, common.WORK_CONFIG, cnf.CommonConfig.ProxyUrl)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
goto re
|
||||
}
|
||||
if _, err := c.SendConfigInfo(cnf.CommonConfig); err != nil {
|
||||
logs.Error(err)
|
||||
goto re
|
||||
}
|
||||
if !c.GetAddStatus() {
|
||||
logs.Error(errAdd)
|
||||
goto re
|
||||
}
|
||||
var b []byte
|
||||
if b, err = c.ReadLen(16); err != nil {
|
||||
logs.Error(err)
|
||||
goto re
|
||||
} else {
|
||||
ioutil.WriteFile(filepath.Join(common.GetTmpPath(), "npc_vkey.txt"), []byte(string(b)), 0600)
|
||||
}
|
||||
for _, v := range cnf.Hosts {
|
||||
if _, err := c.SendHostInfo(v); err != nil {
|
||||
logs.Error(err)
|
||||
goto re
|
||||
}
|
||||
if !c.GetAddStatus() {
|
||||
logs.Error(errAdd, v.Host)
|
||||
goto re
|
||||
}
|
||||
}
|
||||
for _, v := range cnf.Tasks {
|
||||
if _, err := c.SendTaskInfo(v); err != nil {
|
||||
logs.Error(err)
|
||||
goto re
|
||||
}
|
||||
if !c.GetAddStatus() {
|
||||
logs.Error(errAdd, v.Ports)
|
||||
goto re
|
||||
}
|
||||
}
|
||||
for _, v := range cnf.LocalServer {
|
||||
go StartLocalServer(v, cnf.CommonConfig)
|
||||
}
|
||||
c.Close()
|
||||
NewRPClient(cnf.CommonConfig.Server, string(b), cnf.CommonConfig.Tp, cnf.CommonConfig.ProxyUrl).Start()
|
||||
CloseLocalServer()
|
||||
goto re
|
||||
}
|
||||
|
||||
//Create a new connection with the server and verify it
|
||||
func NewConn(tp string, vkey string, server string, connType string, proxyUrl string) (*conn.Conn, error) {
|
||||
var err error
|
||||
var connection net.Conn
|
||||
var sess *kcp.UDPSession
|
||||
if tp == "tcp" {
|
||||
if proxyUrl != "" {
|
||||
u, er := url.Parse(proxyUrl)
|
||||
if er != nil {
|
||||
return nil, er
|
||||
}
|
||||
n, er := proxy.FromURL(u, nil)
|
||||
if er != nil {
|
||||
return nil, er
|
||||
}
|
||||
connection, err = n.Dial("tcp", server)
|
||||
} else {
|
||||
connection, err = net.Dial("tcp", server)
|
||||
}
|
||||
} else {
|
||||
sess, err = kcp.DialWithOptions(server, nil, 10, 3)
|
||||
conn.SetUdpSession(sess)
|
||||
connection = sess
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := conn.NewConn(connection)
|
||||
if _, err := c.Write([]byte(crypt.Md5(version.GetVersion()))); err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
if b, err := c.ReadLen(32); err != nil || crypt.Md5(version.GetVersion()) != string(b) {
|
||||
logs.Error("The client does not match the server version. The current version of the client is", version.GetVersion())
|
||||
os.Exit(0)
|
||||
}
|
||||
if _, err := c.Write([]byte(common.Getverifyval(vkey))); err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
if s, err := c.ReadFlag(); err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
} else if s == common.VERIFY_EER {
|
||||
logs.Error("Validation key %s incorrect", vkey)
|
||||
os.Exit(0)
|
||||
}
|
||||
if _, err := c.Write([]byte(connType)); err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
c.SetAlive(tp)
|
||||
|
||||
return c, nil
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/config"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var LocalServer []*net.TCPListener
|
||||
|
||||
func CloseLocalServer() {
|
||||
for _, v := range LocalServer {
|
||||
v.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func StartLocalServer(l *config.LocalServer, config *config.CommonConfig) error {
|
||||
listener, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), l.Port, ""})
|
||||
if err != nil {
|
||||
logs.Error("Local listener startup failed port %d, error %s", l.Port, err.Error())
|
||||
return err
|
||||
}
|
||||
LocalServer = append(LocalServer, listener)
|
||||
logs.Info("Successful start-up of local monitoring, port", l.Port)
|
||||
for {
|
||||
c, err := listener.AcceptTCP()
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "use of closed network connection") {
|
||||
break
|
||||
}
|
||||
logs.Info(err)
|
||||
continue
|
||||
}
|
||||
go process(c, config, l)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func process(conn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
|
||||
c, err := NewConn(config.Tp, config.VKey, config.Server, common.WORD_SECRET, config.ProxyUrl)
|
||||
if err != nil {
|
||||
logs.Error("Local connection server failed ", err.Error())
|
||||
}
|
||||
if _, err := c.Write([]byte(crypt.Md5(l.Password))); err != nil {
|
||||
logs.Error("Local connection server failed ", err.Error())
|
||||
}
|
||||
go common.CopyBuffer(c, conn)
|
||||
common.CopyBuffer(conn, c)
|
||||
c.Close()
|
||||
conn.Close()
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/config"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func GetTaskStatus(path string) {
|
||||
cnf, err := config.NewConfig(path)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
c, err := NewConn(cnf.CommonConfig.Tp, cnf.CommonConfig.VKey, cnf.CommonConfig.Server, common.WORK_CONFIG, cnf.CommonConfig.ProxyUrl)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
if _, err := c.Write([]byte(common.WORK_STATUS)); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
if f, err := common.ReadAllFromFile(filepath.Join(common.GetTmpPath(), "npc_vkey.txt")); err != nil {
|
||||
log.Fatalln(err)
|
||||
} else if _, err := c.Write([]byte(string(f))); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
if l, err := c.GetLen(); err != nil {
|
||||
log.Fatalln(err)
|
||||
} else if b, err := c.ReadLen(l); err != nil {
|
||||
lg.Fatalln(err)
|
||||
} else {
|
||||
arr := strings.Split(string(b), common.CONN_DATA_SEQ)
|
||||
for _, v := range cnf.Hosts {
|
||||
if common.InArr(arr, v.Remark) {
|
||||
log.Println(v.Remark, "ok")
|
||||
} else {
|
||||
log.Println(v.Remark, "not running")
|
||||
}
|
||||
}
|
||||
for _, v := range cnf.Tasks {
|
||||
ports := common.GetPorts(v.Ports)
|
||||
for _, vv := range ports {
|
||||
var remark string
|
||||
if len(ports) > 1 {
|
||||
remark = v.Remark + "_" + strconv.Itoa(vv)
|
||||
} else {
|
||||
remark = v.Remark
|
||||
}
|
||||
if common.InArr(arr, remark) {
|
||||
log.Println(remark, "ok")
|
||||
} else {
|
||||
log.Println(remark, "not running")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
+7
-7
@@ -5,14 +5,12 @@ import (
|
||||
"github.com/cnlh/nps/client"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/daemon"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const VERSION = "v0.0.15"
|
||||
|
||||
var (
|
||||
serverAddr = flag.String("server", "", "Server addr (ip:port)")
|
||||
configPath = flag.String("config", "npc.conf", "Configuration file path")
|
||||
@@ -20,9 +18,9 @@ var (
|
||||
logType = flag.String("log", "stdout", "Log output mode(stdout|file)")
|
||||
connType = flag.String("type", "tcp", "Connection type with the server(kcp|tcp)")
|
||||
proxyUrl = flag.String("proxy", "", "proxy socks5 url(eg:socks5://111:222@127.0.0.1:9007)")
|
||||
logLevel = flag.String("log_level", "7", "log level 0~7")
|
||||
registerTime = flag.Int("time", 2, "register time long /h")
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
if len(os.Args) > 2 {
|
||||
@@ -36,15 +34,17 @@ func main() {
|
||||
}
|
||||
}
|
||||
daemon.InitDaemon("npc", common.GetRunPath(), common.GetTmpPath())
|
||||
logs.EnableFuncCallDepth(true)
|
||||
logs.SetLogFuncCallDepth(3)
|
||||
if *logType == "stdout" {
|
||||
lg.InitLogFile("npc", true, common.GetLogPath())
|
||||
logs.SetLogger(logs.AdapterConsole, `{"level":`+*logLevel+`,"color":true}`)
|
||||
} else {
|
||||
lg.InitLogFile("npc", false, common.GetLogPath())
|
||||
logs.SetLogger(logs.AdapterFile, `{"level":`+*logLevel+`,"filename":"npc_log.log"}`)
|
||||
}
|
||||
if *verifyKey != "" && *serverAddr != "" {
|
||||
for {
|
||||
client.NewRPClient(*serverAddr, *verifyKey, *connType, *proxyUrl).Start()
|
||||
lg.Println("It will be reconnected in five seconds")
|
||||
logs.Info("It will be reconnected in five seconds")
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
} else {
|
||||
|
||||
+13
-8
@@ -6,25 +6,24 @@ import (
|
||||
"github.com/cnlh/nps/lib/daemon"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/install"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/server"
|
||||
"github.com/cnlh/nps/server/test"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
_ "github.com/cnlh/nps/web/routers"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
const VERSION = "v0.0.15"
|
||||
|
||||
var (
|
||||
level string
|
||||
logType = flag.String("log", "stdout", "Log output mode(stdout|file)")
|
||||
)
|
||||
|
||||
func main() {
|
||||
log.SetFlags(log.Lshortfile)
|
||||
flag.Parse()
|
||||
beego.LoadAppConfig("ini", filepath.Join(common.GetRunPath(), "conf", "nps.conf"))
|
||||
if len(os.Args) > 1 {
|
||||
switch os.Args[1] {
|
||||
case "test":
|
||||
@@ -38,18 +37,24 @@ func main() {
|
||||
return
|
||||
}
|
||||
}
|
||||
if level = beego.AppConfig.String("logLevel"); level == "" {
|
||||
level = "7"
|
||||
}
|
||||
logs.Reset()
|
||||
logs.EnableFuncCallDepth(true)
|
||||
logs.SetLogFuncCallDepth(3)
|
||||
if *logType == "stdout" {
|
||||
lg.InitLogFile("nps", true, common.GetLogPath())
|
||||
logs.SetLogger(logs.AdapterConsole, `{"level":`+level+`,"color":true}`)
|
||||
} else {
|
||||
lg.InitLogFile("nps", false, common.GetLogPath())
|
||||
logs.SetLogger(logs.AdapterFile, `{"level":`+level+`,"filename":"nps_log.log"}`)
|
||||
}
|
||||
task := &file.Tunnel{
|
||||
Mode: "webServer",
|
||||
}
|
||||
bridgePort, err := beego.AppConfig.Int("bridgePort")
|
||||
if err != nil {
|
||||
lg.Fatalln("Getting bridgePort error", err)
|
||||
logs.Error("Getting bridgePort error", err)
|
||||
os.Exit(0)
|
||||
}
|
||||
beego.LoadAppConfig("ini", filepath.Join(common.GetRunPath(), "conf", "app.conf"))
|
||||
server.StartNewServer(bridgePort, task, beego.AppConfig.String("bridgeType"))
|
||||
}
|
||||
|
||||
+4
-1
@@ -1 +1,4 @@
|
||||
7,7hv3avgeg2ldzvx7,,true,,,0,,0,0
|
||||
7,7hv3avgeg2ldzvx7,,true,,,1,,0,999,10
|
||||
10,213123dsd,,true,,,0,,0,0,0
|
||||
11,213123dsd2,,true,,,0,,0,0,0
|
||||
15,wx1wdhjmpmntowc8,,true,,,0,,0,0,0
|
||||
|
||||
|
@@ -0,0 +1 @@
|
||||
b.o.com,127.0.0.1:8082,7,,,,/,3,12995709,38827
|
||||
|
||||
|
+15
-13
@@ -2,11 +2,8 @@
|
||||
server=127.0.0.1:8284
|
||||
tp=tcp
|
||||
vkey=123
|
||||
compress=snappy
|
||||
crypt=true
|
||||
auto_reconnection=true
|
||||
username=111
|
||||
password=222
|
||||
|
||||
[web1]
|
||||
host=a.o.com
|
||||
host_change=www.proxy.com
|
||||
@@ -14,25 +11,30 @@ target=127.0.0.1:8080
|
||||
location=/
|
||||
|
||||
[web2]
|
||||
host=a.proxy.com
|
||||
target=127.0.0.1:8080,127.0.0.1:8082
|
||||
host=127.0.0.1
|
||||
host_change=www.proxy.com
|
||||
header_set_proxy=nps
|
||||
target=127.0.0.1:8080
|
||||
location=/cdn
|
||||
|
||||
[ssh_1118]
|
||||
mode=secretServer
|
||||
password=1111
|
||||
target=123.206.77.88:22
|
||||
|
||||
[tcp]
|
||||
mode=tcpServer
|
||||
target=8001-8005,8006
|
||||
port=9001-9005,9006
|
||||
target=127.0.0.1:8080
|
||||
port=9006
|
||||
|
||||
[socks5]
|
||||
mode=socks5Server
|
||||
port=9007
|
||||
port=9005
|
||||
|
||||
[http]
|
||||
mode=httpProxyServer
|
||||
port=9008
|
||||
port=9004
|
||||
|
||||
[udp]
|
||||
mode=udpServer
|
||||
port=9009
|
||||
target=114.114.114.114:53
|
||||
port=9003
|
||||
target=114.114.114.53
|
||||
@@ -36,4 +36,15 @@ bridgeType=tcp
|
||||
# After the connection, the server will be able to open relevant ports and parse related domain names according to its own configuration file.
|
||||
publicVkey=123
|
||||
|
||||
#Traffic data persistence interval(minute)
|
||||
#Ignorance means no persistence
|
||||
#flowStoreInterval=1
|
||||
|
||||
#log level
|
||||
#LevelEmergency->0 LevelAlert->1 LevelCritical->2 LevelError->3 LevelWarning->4
|
||||
#LevelNotice->5 LevelInformational->6 LevelDebug->7
|
||||
#logLevel=7
|
||||
|
||||
#Whether to restrict IP access, true or false or ignore
|
||||
#ipLimit=true
|
||||
|
||||
+3
-1
@@ -1 +1,3 @@
|
||||
9010,socks5Server,,1,27,7,
|
||||
9010,socks5Server,,1,27,7,,0,0,
|
||||
9002,tcpServer,127.0.0.1:8082,1,28,7,,9175971,17054,
|
||||
0,secretServer,123.206.77.88:22,1,30,7,私密隧道测试,15620,12628,tests
|
||||
|
||||
|
+16
-15
@@ -6,21 +6,22 @@ const (
|
||||
COMPRESS_NONE_DECODE
|
||||
COMPRESS_SNAPY_ENCODE
|
||||
COMPRESS_SNAPY_DECODE
|
||||
VERIFY_EER = "vkey"
|
||||
VERIFY_SUCCESS = "sucs"
|
||||
WORK_MAIN = "main"
|
||||
WORK_CHAN = "chan"
|
||||
WORK_CONFIG = "conf"
|
||||
WORK_REGISTER = "rgst"
|
||||
WORK_STATUS = "stus"
|
||||
RES_SIGN = "sign"
|
||||
RES_MSG = "msg0"
|
||||
RES_CLOSE = "clse"
|
||||
NEW_CONN = "conn" //新连接标志
|
||||
NEW_TASK = "task" //新连接标志
|
||||
NEW_CONF = "conf" //新连接标志
|
||||
NEW_HOST = "host" //新连接标志
|
||||
|
||||
VERIFY_EER = "vkey"
|
||||
VERIFY_SUCCESS = "sucs"
|
||||
WORK_MAIN = "main"
|
||||
WORK_CHAN = "chan"
|
||||
WORK_SEND_STATUS = "sdst"
|
||||
WORK_CONFIG = "conf"
|
||||
WORK_REGISTER = "rgst"
|
||||
WORD_SECRET = "sert"
|
||||
WORK_STATUS = "stus"
|
||||
RES_SIGN = "sign"
|
||||
RES_MSG = "msg0"
|
||||
RES_CLOSE = "clse"
|
||||
NEW_CONN = "conn" //新连接标志
|
||||
NEW_TASK = "task" //新连接标志
|
||||
NEW_CONF = "conf" //新连接标志
|
||||
NEW_HOST = "host" //新连接标志
|
||||
CONN_TCP = "tcp"
|
||||
CONN_UDP = "udp"
|
||||
UnauthorizedBytes = `HTTP/1.1 401 Unauthorized
|
||||
|
||||
+12
-3
@@ -5,7 +5,8 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/lib/pool"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
@@ -23,7 +24,7 @@ func GetCompressType(compress string) (int, int) {
|
||||
case "snappy":
|
||||
return COMPRESS_SNAPY_DECODE, COMPRESS_SNAPY_ENCODE
|
||||
default:
|
||||
lg.Fatalln("数据压缩格式错误")
|
||||
return COMPRESS_NONE_DECODE, COMPRESS_NONE_ENCODE
|
||||
}
|
||||
return COMPRESS_NONE_DECODE, COMPRESS_NONE_ENCODE
|
||||
}
|
||||
@@ -184,7 +185,7 @@ func BinaryWrite(raw *bytes.Buffer, v ...string) {
|
||||
binary.Write(raw, binary.LittleEndian, buffer.Bytes())
|
||||
}
|
||||
|
||||
func InArr(arr []string, val string) bool {
|
||||
func InStrArr(arr []string, val string) bool {
|
||||
for _, v := range arr {
|
||||
if v == val {
|
||||
return true
|
||||
@@ -224,6 +225,7 @@ func GetPorts(p string) []int {
|
||||
}
|
||||
return ps
|
||||
}
|
||||
|
||||
func IsPort(p string) bool {
|
||||
pi, err := strconv.Atoi(p)
|
||||
if err != nil {
|
||||
@@ -246,3 +248,10 @@ func GetIpByAddr(addr string) string {
|
||||
arr := strings.Split(addr, ":")
|
||||
return arr[0]
|
||||
}
|
||||
|
||||
func CopyBuffer(dst io.Writer, src io.Reader) (written int64, err error) {
|
||||
buf := pool.BufPoolCopy.Get().([]byte)
|
||||
io.CopyBuffer(dst, src, buf)
|
||||
pool.PutBufPoolCopy(buf)
|
||||
return written, err
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"regexp"
|
||||
@@ -14,6 +15,11 @@ type CommonConfig struct {
|
||||
AutoReconnection bool
|
||||
Cnf *file.Config
|
||||
ProxyUrl string
|
||||
Client *file.Client
|
||||
}
|
||||
type LocalServer struct {
|
||||
Port int
|
||||
Password string
|
||||
}
|
||||
type Config struct {
|
||||
content string
|
||||
@@ -21,6 +27,7 @@ type Config struct {
|
||||
CommonConfig *CommonConfig
|
||||
Hosts []*file.Host
|
||||
Tasks []*file.Tunnel
|
||||
LocalServer []*LocalServer
|
||||
}
|
||||
|
||||
func NewConfig(path string) (c *Config, err error) {
|
||||
@@ -44,6 +51,11 @@ func NewConfig(path string) (c *Config, err error) {
|
||||
nextIndex = len(c.content)
|
||||
}
|
||||
nowContent = c.content[nowIndex:nextIndex]
|
||||
|
||||
if strings.Index(getTitleContent(c.title[i]), "secret") == 0 {
|
||||
c.LocalServer = append(c.LocalServer, delLocalService(nowContent))
|
||||
continue
|
||||
}
|
||||
switch c.title[i] {
|
||||
case "[common]":
|
||||
c.CommonConfig = dealCommon(nowContent)
|
||||
@@ -68,9 +80,11 @@ func getTitleContent(s string) string {
|
||||
re, _ := regexp.Compile(`[\[\]]`)
|
||||
return re.ReplaceAllString(s, "")
|
||||
}
|
||||
|
||||
func dealCommon(s string) *CommonConfig {
|
||||
c := &CommonConfig{}
|
||||
c.Cnf = new(file.Config)
|
||||
c.Client = file.NewClient("", true, true)
|
||||
for _, v := range strings.Split(s, "\n") {
|
||||
item := strings.Split(v, "=")
|
||||
if len(item) == 0 {
|
||||
@@ -97,10 +111,19 @@ func dealCommon(s string) *CommonConfig {
|
||||
c.Cnf.Crypt = common.GetBoolByStr(item[1])
|
||||
case "proxy_socks5_url":
|
||||
c.ProxyUrl = item[1]
|
||||
case "rate_limit":
|
||||
c.Client.RateLimit = common.GetIntNoErrByStr(item[1])
|
||||
case "flow_limit":
|
||||
c.Client.Flow.FlowLimit = int64(common.GetIntNoErrByStr(item[1]))
|
||||
case "max_conn":
|
||||
c.Client.MaxConn = common.GetIntNoErrByStr(item[1])
|
||||
case "remark":
|
||||
c.Client.Remark = item[1]
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func dealHost(s string) *file.Host {
|
||||
h := &file.Host{}
|
||||
var headerChange string
|
||||
@@ -146,12 +169,35 @@ func dealTunnel(s string) *file.Tunnel {
|
||||
t.Mode = item[1]
|
||||
case "target":
|
||||
t.Target = item[1]
|
||||
case "targetAddr":
|
||||
t.TargetAddr = item[1]
|
||||
case "password":
|
||||
t.Password = item[1]
|
||||
}
|
||||
}
|
||||
return t
|
||||
|
||||
}
|
||||
|
||||
func delLocalService(s string) *LocalServer {
|
||||
l := new(LocalServer)
|
||||
for _, v := range strings.Split(s, "\n") {
|
||||
item := strings.Split(v, "=")
|
||||
if len(item) == 0 {
|
||||
continue
|
||||
} else if len(item) == 1 {
|
||||
item = append(item, "")
|
||||
}
|
||||
switch item[0] {
|
||||
case "port":
|
||||
l.Port = common.GetIntNoErrByStr(item[1])
|
||||
case "password":
|
||||
l.Password = item[1]
|
||||
}
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
func getAllTitle(content string) (arr []string, err error) {
|
||||
var re *regexp.Regexp
|
||||
re, err = regexp.Compile(`\[.+?\]`)
|
||||
@@ -159,5 +205,13 @@ func getAllTitle(content string) (arr []string, err error) {
|
||||
return
|
||||
}
|
||||
arr = re.FindAllString(content, -1)
|
||||
m := make(map[string]bool)
|
||||
for _, v := range arr {
|
||||
if _, ok := m[v]; ok {
|
||||
err = errors.New("Item names are not allowed to be duplicated")
|
||||
return
|
||||
}
|
||||
m[v] = true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
+33
-25
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/config"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/pool"
|
||||
"github.com/cnlh/nps/lib/rate"
|
||||
@@ -74,12 +75,12 @@ func (s *Conn) ReadLen(cLen int) ([]byte, error) {
|
||||
return nil, errors.New("长度错误" + strconv.Itoa(cLen))
|
||||
}
|
||||
var buf []byte
|
||||
if cLen <= pool.PoolSizeSmall {
|
||||
if cLen < pool.PoolSizeSmall {
|
||||
buf = pool.BufPoolSmall.Get().([]byte)[:cLen]
|
||||
defer pool.BufPoolSmall.Put(buf)
|
||||
defer pool.PutBufPoolSmall(buf)
|
||||
} else {
|
||||
buf = pool.BufPoolMax.Get().([]byte)[:cLen]
|
||||
defer pool.BufPoolMax.Put(buf)
|
||||
defer pool.PutBufPoolMax(buf)
|
||||
}
|
||||
if n, err := io.ReadFull(s, buf); err != nil || n != cLen {
|
||||
return buf, errors.New("Error reading specified length " + err.Error())
|
||||
@@ -89,11 +90,9 @@ func (s *Conn) ReadLen(cLen int) ([]byte, error) {
|
||||
|
||||
//read length or id (content length=4)
|
||||
func (s *Conn) GetLen() (int, error) {
|
||||
val, err := s.ReadLen(4)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return GetLenByBytes(val)
|
||||
var l int32
|
||||
err := binary.Read(s, binary.LittleEndian, &l)
|
||||
return int(l), err
|
||||
}
|
||||
|
||||
//read flag
|
||||
@@ -190,14 +189,10 @@ func (s *Conn) SendMsg(content []byte, link *Link) (n int, err error) {
|
||||
*/
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
binary.Write(raw, binary.LittleEndian, int32(link.Id))
|
||||
if n, err = s.Write(raw.Bytes()); err != nil {
|
||||
if err = binary.Write(s.Conn, binary.LittleEndian, int32(link.Id)); err != nil {
|
||||
return
|
||||
}
|
||||
raw.Reset()
|
||||
binary.Write(raw, binary.LittleEndian, content)
|
||||
n, err = s.WriteTo(raw.Bytes(), link.En, link.Crypt, link.Rate)
|
||||
n, err = s.WriteTo(content, link.En, link.Crypt, link.Rate)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -206,7 +201,7 @@ func (s *Conn) GetMsgContent(link *Link) (content []byte, err error) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
buf := pool.BufPoolCopy.Get().([]byte)
|
||||
if n, err := s.ReadFrom(buf, link.De, link.Crypt, link.Rate); err == nil && n > 4 {
|
||||
if n, err := s.ReadFrom(buf, link.De, link.Crypt, link.Rate); err == nil {
|
||||
content = buf[:n]
|
||||
}
|
||||
return
|
||||
@@ -260,6 +255,8 @@ func (s *Conn) GetLinkInfo() (lk *Link, err error) {
|
||||
lk.En = common.GetIntNoErrByStr(string(buf[11+hostLen]))
|
||||
lk.De = common.GetIntNoErrByStr(string(buf[12+hostLen]))
|
||||
lk.Crypt = common.GetBoolByStr(string(buf[13+hostLen]))
|
||||
lk.MsgCh = make(chan []byte)
|
||||
lk.StatusCh = make(chan bool)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -321,7 +318,7 @@ func (s *Conn) GetHostInfo() (h *file.Host, err error) {
|
||||
}
|
||||
|
||||
//send task info
|
||||
func (s *Conn) SendConfigInfo(c *file.Config) (int, error) {
|
||||
func (s *Conn) SendConfigInfo(c *config.CommonConfig) (int, error) {
|
||||
/*
|
||||
The task info is formed as follows:
|
||||
+----+-----+---------+
|
||||
@@ -332,14 +329,15 @@ func (s *Conn) SendConfigInfo(c *file.Config) (int, error) {
|
||||
*/
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
binary.Write(raw, binary.LittleEndian, []byte(common.NEW_CONF))
|
||||
common.BinaryWrite(raw, c.U, c.P, common.GetStrByBool(c.Crypt), c.Compress)
|
||||
common.BinaryWrite(raw, c.Cnf.U, c.Cnf.P, common.GetStrByBool(c.Cnf.Crypt), c.Cnf.Compress, strconv.Itoa(c.Client.RateLimit),
|
||||
strconv.Itoa(int(c.Client.Flow.FlowLimit)), strconv.Itoa(c.Client.MaxConn), c.Client.Remark)
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
return s.Write(raw.Bytes())
|
||||
}
|
||||
|
||||
//get task info
|
||||
func (s *Conn) GetConfigInfo() (c *file.Config, err error) {
|
||||
func (s *Conn) GetConfigInfo() (c *file.Client, err error) {
|
||||
var l int
|
||||
var b []byte
|
||||
if l, err = s.GetLen(); err != nil {
|
||||
@@ -348,12 +346,16 @@ func (s *Conn) GetConfigInfo() (c *file.Config, err error) {
|
||||
return
|
||||
} else {
|
||||
arr := strings.Split(string(b), common.CONN_DATA_SEQ)
|
||||
c = new(file.Config)
|
||||
c.U = arr[0]
|
||||
c.P = arr[1]
|
||||
c.Crypt = common.GetBoolByStr(arr[2])
|
||||
c.Compress = arr[3]
|
||||
c.CompressDecode, c.CompressDecode = common.GetCompressType(arr[3])
|
||||
c = file.NewClient("", true, false)
|
||||
c.Cnf.U = arr[0]
|
||||
c.Cnf.P = arr[1]
|
||||
c.Cnf.Crypt = common.GetBoolByStr(arr[2])
|
||||
c.Cnf.Compress = arr[3]
|
||||
c.RateLimit = common.GetIntNoErrByStr(arr[4])
|
||||
c.Flow.FlowLimit = int64(common.GetIntNoErrByStr(arr[5]))
|
||||
c.MaxConn = common.GetIntNoErrByStr(arr[6])
|
||||
c.Remark = arr[7]
|
||||
c.Cnf.CompressDecode, c.Cnf.CompressDecode = common.GetCompressType(arr[3])
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -370,7 +372,7 @@ func (s *Conn) SendTaskInfo(t *file.Tunnel) (int, error) {
|
||||
*/
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
binary.Write(raw, binary.LittleEndian, []byte(common.NEW_TASK))
|
||||
common.BinaryWrite(raw, t.Mode, t.Ports, t.Target, t.Remark)
|
||||
common.BinaryWrite(raw, t.Mode, t.Ports, t.Target, t.Remark, t.TargetAddr, t.Password)
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
return s.Write(raw.Bytes())
|
||||
@@ -394,11 +396,17 @@ func (s *Conn) GetTaskInfo() (t *file.Tunnel, err error) {
|
||||
t.Status = true
|
||||
t.Flow = new(file.Flow)
|
||||
t.Remark = arr[3]
|
||||
t.TargetAddr = arr[4]
|
||||
t.Password = arr[5]
|
||||
t.NoStore = true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Conn) WriteWriteSuccess(id int) error {
|
||||
return binary.Write(s.Conn, binary.LittleEndian, int32(id))
|
||||
}
|
||||
|
||||
//write connect success
|
||||
func (s *Conn) WriteSuccess(id int) (int, error) {
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
|
||||
@@ -1,11 +1,25 @@
|
||||
package conn
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/pool"
|
||||
"github.com/cnlh/nps/lib/rate"
|
||||
"net"
|
||||
)
|
||||
|
||||
type Secret struct {
|
||||
Password string
|
||||
Conn *Conn
|
||||
}
|
||||
|
||||
func NewSecret(p string, conn *Conn) *Secret {
|
||||
return &Secret{
|
||||
Password: p,
|
||||
Conn: conn,
|
||||
}
|
||||
}
|
||||
|
||||
type Link struct {
|
||||
Id int //id
|
||||
ConnType string //连接类型
|
||||
@@ -18,6 +32,10 @@ type Link struct {
|
||||
UdpListener *net.UDPConn
|
||||
Rate *rate.Rate
|
||||
UdpRemoteAddr *net.UDPAddr
|
||||
MsgCh chan []byte
|
||||
MsgConn *Conn
|
||||
StatusCh chan bool
|
||||
FinishUse bool
|
||||
}
|
||||
|
||||
func NewLink(id int, connType string, host string, en, de int, crypt bool, c *Conn, flow *file.Flow, udpListener *net.UDPConn, rate *rate.Rate, UdpRemoteAddr *net.UDPAddr) *Link {
|
||||
@@ -33,5 +51,41 @@ func NewLink(id int, connType string, host string, en, de int, crypt bool, c *Co
|
||||
UdpListener: udpListener,
|
||||
Rate: rate,
|
||||
UdpRemoteAddr: UdpRemoteAddr,
|
||||
MsgCh: make(chan []byte),
|
||||
StatusCh: make(chan bool),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Link) Run(flow bool) {
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case content := <-s.MsgCh:
|
||||
if len(content) == len(common.IO_EOF) && string(content) == common.IO_EOF {
|
||||
s.FinishUse = true
|
||||
if s.Conn != nil {
|
||||
s.Conn.Close()
|
||||
}
|
||||
return
|
||||
} else {
|
||||
if s.Conn == nil {
|
||||
return
|
||||
}
|
||||
if s.UdpListener != nil && s.UdpRemoteAddr != nil {
|
||||
s.UdpListener.WriteToUDP(content, s.UdpRemoteAddr)
|
||||
} else {
|
||||
s.Conn.Write(content)
|
||||
}
|
||||
if flow {
|
||||
s.Flow.Add(0, len(content))
|
||||
}
|
||||
if s.ConnType == common.CONN_UDP {
|
||||
return
|
||||
}
|
||||
s.MsgConn.WriteWriteSuccess(s.Id)
|
||||
}
|
||||
pool.PutBufPoolCopy(content)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
+7
-29
@@ -1,41 +1,29 @@
|
||||
package conn
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/lib/pool"
|
||||
"github.com/cnlh/nps/lib/rate"
|
||||
"github.com/cnlh/nps/vender/github.com/golang/snappy"
|
||||
"log"
|
||||
"net"
|
||||
)
|
||||
|
||||
type SnappyConn struct {
|
||||
w *snappy.Writer
|
||||
r *snappy.Reader
|
||||
crypt bool
|
||||
rate *rate.Rate
|
||||
w *snappy.Writer
|
||||
r *snappy.Reader
|
||||
rate *rate.Rate
|
||||
}
|
||||
|
||||
func NewSnappyConn(conn net.Conn, crypt bool, rate *rate.Rate) *SnappyConn {
|
||||
c := new(SnappyConn)
|
||||
c.w = snappy.NewBufferedWriter(conn)
|
||||
c.r = snappy.NewReader(conn)
|
||||
c.crypt = crypt
|
||||
c.rate = rate
|
||||
return c
|
||||
}
|
||||
|
||||
//snappy压缩写 包含加密
|
||||
//snappy压缩写
|
||||
func (s *SnappyConn) Write(b []byte) (n int, err error) {
|
||||
n = len(b)
|
||||
if s.crypt {
|
||||
if b, err = crypt.AesEncrypt(b, []byte(cryptKey)); err != nil {
|
||||
lg.Println("encode crypt error:", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if _, err = s.w.Write(b); err != nil {
|
||||
if n, err = s.w.Write(b); err != nil {
|
||||
return
|
||||
}
|
||||
if err = s.w.Flush(); err != nil {
|
||||
@@ -47,24 +35,14 @@ func (s *SnappyConn) Write(b []byte) (n int, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
//snappy压缩读 包含解密
|
||||
//snappy压缩读
|
||||
func (s *SnappyConn) Read(b []byte) (n int, err error) {
|
||||
buf := pool.BufPool.Get().([]byte)
|
||||
defer pool.BufPool.Put(buf)
|
||||
if n, err = s.r.Read(buf); err != nil {
|
||||
return
|
||||
}
|
||||
var bs []byte
|
||||
if s.crypt {
|
||||
if bs, err = crypt.AesDecrypt(buf[:n], []byte(cryptKey)); err != nil {
|
||||
log.Println("decode crypt error:", err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
bs = buf[:n]
|
||||
}
|
||||
n = len(bs)
|
||||
copy(b, bs)
|
||||
copy(b, buf[:n])
|
||||
if s.rate != nil {
|
||||
s.rate.Get(int64(n))
|
||||
}
|
||||
|
||||
+3
-1
@@ -14,7 +14,9 @@ var (
|
||||
func GetCsvDb() *Csv {
|
||||
once.Do(func() {
|
||||
CsvDb = NewCsv(common.GetRunPath())
|
||||
CsvDb.Init()
|
||||
CsvDb.LoadClientFromCsv()
|
||||
CsvDb.LoadTaskFromCsv()
|
||||
CsvDb.LoadHostFromCsv()
|
||||
})
|
||||
return CsvDb
|
||||
}
|
||||
|
||||
+77
-24
@@ -3,9 +3,11 @@ package file
|
||||
import (
|
||||
"encoding/csv"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/rate"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -33,17 +35,11 @@ type Csv struct {
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
func (s *Csv) Init() {
|
||||
s.LoadClientFromCsv()
|
||||
s.LoadTaskFromCsv()
|
||||
s.LoadHostFromCsv()
|
||||
}
|
||||
|
||||
func (s *Csv) StoreTasksToCsv() {
|
||||
// 创建文件
|
||||
csvFile, err := os.Create(filepath.Join(s.RunPath, "conf", "tasks.csv"))
|
||||
if err != nil {
|
||||
lg.Fatalf(err.Error())
|
||||
logs.Error(err.Error())
|
||||
}
|
||||
defer csvFile.Close()
|
||||
writer := csv.NewWriter(csvFile)
|
||||
@@ -59,10 +55,13 @@ func (s *Csv) StoreTasksToCsv() {
|
||||
strconv.Itoa(task.Id),
|
||||
strconv.Itoa(task.Client.Id),
|
||||
task.Remark,
|
||||
strconv.Itoa(int(task.Flow.ExportFlow)),
|
||||
strconv.Itoa(int(task.Flow.InletFlow)),
|
||||
task.Password,
|
||||
}
|
||||
err := writer.Write(record)
|
||||
if err != nil {
|
||||
lg.Fatalf(err.Error())
|
||||
logs.Error(err.Error())
|
||||
}
|
||||
}
|
||||
writer.Flush()
|
||||
@@ -90,20 +89,24 @@ func (s *Csv) LoadTaskFromCsv() {
|
||||
path := filepath.Join(s.RunPath, "conf", "tasks.csv")
|
||||
records, err := s.openFile(path)
|
||||
if err != nil {
|
||||
lg.Fatalln("配置文件打开错误:", path)
|
||||
logs.Error("Profile Opening Error:", path)
|
||||
os.Exit(0)
|
||||
}
|
||||
var tasks []*Tunnel
|
||||
// 将每一行数据保存到内存slice中
|
||||
for _, item := range records {
|
||||
post := &Tunnel{
|
||||
Port: common.GetIntNoErrByStr(item[0]),
|
||||
Mode: item[1],
|
||||
Target: item[2],
|
||||
Status: common.GetBoolByStr(item[3]),
|
||||
Id: common.GetIntNoErrByStr(item[4]),
|
||||
Remark: item[6],
|
||||
Port: common.GetIntNoErrByStr(item[0]),
|
||||
Mode: item[1],
|
||||
Target: item[2],
|
||||
Status: common.GetBoolByStr(item[3]),
|
||||
Id: common.GetIntNoErrByStr(item[4]),
|
||||
Remark: item[6],
|
||||
Password: item[9],
|
||||
}
|
||||
post.Flow = new(Flow)
|
||||
post.Flow.ExportFlow = int64(common.GetIntNoErrByStr(item[7]))
|
||||
post.Flow.InletFlow = int64(common.GetIntNoErrByStr(item[8]))
|
||||
if post.Client, err = s.GetClient(common.GetIntNoErrByStr(item[5])); err != nil {
|
||||
continue
|
||||
}
|
||||
@@ -142,10 +145,16 @@ func (s *Csv) GetIdByVerifyKey(vKey string, addr string) (int, error) {
|
||||
return 0, errors.New("not found")
|
||||
}
|
||||
|
||||
func (s *Csv) NewTask(t *Tunnel) {
|
||||
func (s *Csv) NewTask(t *Tunnel) error {
|
||||
for _, v := range s.Tasks {
|
||||
if v.Mode == "secretServer" && v.Password == t.Password {
|
||||
return errors.New(fmt.Sprintf("Secret mode keys %s must be unique", t.Password))
|
||||
}
|
||||
}
|
||||
t.Flow = new(Flow)
|
||||
s.Tasks = append(s.Tasks, t)
|
||||
s.StoreTasksToCsv()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Csv) UpdateTask(t *Tunnel) error {
|
||||
@@ -157,7 +166,7 @@ func (s *Csv) UpdateTask(t *Tunnel) error {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errors.New("不存在")
|
||||
return errors.New("the task is not exist")
|
||||
}
|
||||
|
||||
func (s *Csv) DelTask(id int) error {
|
||||
@@ -171,6 +180,16 @@ func (s *Csv) DelTask(id int) error {
|
||||
return errors.New("不存在")
|
||||
}
|
||||
|
||||
//md5 password
|
||||
func (s *Csv) GetSecretTask(p string) *Tunnel {
|
||||
for _, v := range s.Tasks {
|
||||
if crypt.Md5(v.Password) == p {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Csv) GetTask(id int) (v *Tunnel, err error) {
|
||||
for _, v = range s.Tasks {
|
||||
if v.Id == id {
|
||||
@@ -205,6 +224,8 @@ func (s *Csv) StoreHostToCsv() {
|
||||
host.Remark,
|
||||
host.Location,
|
||||
strconv.Itoa(host.Id),
|
||||
strconv.Itoa(int(host.Flow.ExportFlow)),
|
||||
strconv.Itoa(int(host.Flow.InletFlow)),
|
||||
}
|
||||
err1 := writer.Write(record)
|
||||
if err1 != nil {
|
||||
@@ -219,7 +240,8 @@ func (s *Csv) LoadClientFromCsv() {
|
||||
path := filepath.Join(s.RunPath, "conf", "clients.csv")
|
||||
records, err := s.openFile(path)
|
||||
if err != nil {
|
||||
lg.Fatalln("配置文件打开错误:", path)
|
||||
logs.Error("Profile Opening Error:", path)
|
||||
os.Exit(0)
|
||||
}
|
||||
var clients []*Client
|
||||
// 将每一行数据保存到内存slice中
|
||||
@@ -236,6 +258,7 @@ func (s *Csv) LoadClientFromCsv() {
|
||||
Crypt: common.GetBoolByStr(item[6]),
|
||||
Compress: item[7],
|
||||
},
|
||||
MaxConn: common.GetIntNoErrByStr(item[10]),
|
||||
}
|
||||
if post.Id > s.ClientIncreaseId {
|
||||
s.ClientIncreaseId = post.Id
|
||||
@@ -255,7 +278,8 @@ func (s *Csv) LoadHostFromCsv() {
|
||||
path := filepath.Join(s.RunPath, "conf", "hosts.csv")
|
||||
records, err := s.openFile(path)
|
||||
if err != nil {
|
||||
lg.Fatalln("配置文件打开错误:", path)
|
||||
logs.Error("Profile Opening Error:", path)
|
||||
os.Exit(0)
|
||||
}
|
||||
var hosts []*Host
|
||||
// 将每一行数据保存到内存slice中
|
||||
@@ -273,6 +297,8 @@ func (s *Csv) LoadHostFromCsv() {
|
||||
continue
|
||||
}
|
||||
post.Flow = new(Flow)
|
||||
post.Flow.ExportFlow = int64(common.GetIntNoErrByStr(item[8]))
|
||||
post.Flow.InletFlow = int64(common.GetIntNoErrByStr(item[9]))
|
||||
hosts = append(hosts, post)
|
||||
if post.Id > s.HostIncreaseId {
|
||||
s.HostIncreaseId = post.Id
|
||||
@@ -346,15 +372,39 @@ func (s *Csv) DelClient(id int) error {
|
||||
return errors.New("不存在")
|
||||
}
|
||||
|
||||
func (s *Csv) NewClient(c *Client) {
|
||||
func (s *Csv) NewClient(c *Client) error {
|
||||
var isNotSet bool
|
||||
reset:
|
||||
if c.VerifyKey == "" || isNotSet {
|
||||
isNotSet = true
|
||||
c.VerifyKey = crypt.GetRandomString(16)
|
||||
}
|
||||
if !s.VerifyVkey(c.VerifyKey, c.id) {
|
||||
if isNotSet {
|
||||
goto reset
|
||||
}
|
||||
return errors.New("Vkey duplicate, please reset")
|
||||
}
|
||||
if c.Id == 0 {
|
||||
c.Id = s.GetClientId()
|
||||
}
|
||||
c.Flow = new(Flow)
|
||||
if c.Flow == nil {
|
||||
c.Flow = new(Flow)
|
||||
}
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.Clients = append(s.Clients, c)
|
||||
s.StoreClientsToCsv()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Csv) VerifyVkey(vkey string, id int) bool {
|
||||
for _, v := range s.Clients {
|
||||
if v.VerifyKey == vkey && v.Id != id {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Csv) GetClientId() int {
|
||||
@@ -433,6 +483,8 @@ func (s *Csv) GetHostById(id int) (h *Host, err error) {
|
||||
//get key by host from x
|
||||
func (s *Csv) GetInfoByHost(host string, r *http.Request) (h *Host, err error) {
|
||||
var hosts []*Host
|
||||
//Handling Ported Access
|
||||
host = common.GetIpByAddr(host)
|
||||
for _, v := range s.Hosts {
|
||||
//Remove http(s) http(s)://a.proxy.com
|
||||
//*.proxy.com *.a.proxy.com Do some pan-parsing
|
||||
@@ -467,7 +519,7 @@ func (s *Csv) StoreClientsToCsv() {
|
||||
// 创建文件
|
||||
csvFile, err := os.Create(filepath.Join(s.RunPath, "conf", "clients.csv"))
|
||||
if err != nil {
|
||||
lg.Fatalln(err.Error())
|
||||
logs.Error(err.Error())
|
||||
}
|
||||
defer csvFile.Close()
|
||||
writer := csv.NewWriter(csvFile)
|
||||
@@ -486,10 +538,11 @@ func (s *Csv) StoreClientsToCsv() {
|
||||
client.Cnf.Compress,
|
||||
strconv.Itoa(client.RateLimit),
|
||||
strconv.Itoa(int(client.Flow.FlowLimit)),
|
||||
strconv.Itoa(int(client.MaxConn)),
|
||||
}
|
||||
err := writer.Write(record)
|
||||
if err != nil {
|
||||
lg.Fatalln(err.Error())
|
||||
logs.Error(err.Error())
|
||||
}
|
||||
}
|
||||
writer.Flush()
|
||||
|
||||
+39
-24
@@ -2,6 +2,7 @@ package file
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/rate"
|
||||
"math"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
@@ -33,6 +34,8 @@ type Client struct {
|
||||
Rate *rate.Rate //速度控制
|
||||
NoStore bool
|
||||
NoDisplay bool
|
||||
MaxConn int //客户端最大连接数
|
||||
NowConn int //当前连接数
|
||||
id int
|
||||
sync.RWMutex
|
||||
}
|
||||
@@ -50,7 +53,6 @@ func NewClient(vKey string, noStore bool, noDisplay bool) *Client {
|
||||
Flow: new(Flow),
|
||||
Rate: nil,
|
||||
NoStore: noStore,
|
||||
id: GetCsvDb().GetClientId(),
|
||||
RWMutex: sync.RWMutex{},
|
||||
NoDisplay: noDisplay,
|
||||
}
|
||||
@@ -58,22 +60,47 @@ func NewClient(vKey string, noStore bool, noDisplay bool) *Client {
|
||||
func (s *Client) GetId() int {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
if s.id == math.MaxInt32 {
|
||||
s.id = 0
|
||||
}
|
||||
s.id++
|
||||
return s.id
|
||||
}
|
||||
|
||||
func (s *Client) CutConn() {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.NowConn++
|
||||
}
|
||||
|
||||
func (s *Client) AddConn() {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.NowConn--
|
||||
}
|
||||
|
||||
func (s *Client) GetConn() bool {
|
||||
if s.MaxConn == 0 || s.NowConn < s.MaxConn {
|
||||
s.CutConn()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type Tunnel struct {
|
||||
Id int //Id
|
||||
Port int //服务端监听端口
|
||||
Mode string //启动方式
|
||||
Target string //目标
|
||||
Status bool //设置是否开启
|
||||
RunStatus bool //当前运行状态
|
||||
Client *Client //所属客户端id
|
||||
Ports string //客户端与服务端传递
|
||||
Flow *Flow
|
||||
Remark string //备注
|
||||
NoStore bool
|
||||
Id int //Id
|
||||
Port int //服务端监听端口
|
||||
Mode string //启动方式
|
||||
Target string //目标
|
||||
Status bool //设置是否开启
|
||||
RunStatus bool //当前运行状态
|
||||
Client *Client //所属客户端id
|
||||
Ports string //客户端与服务端传递
|
||||
Flow *Flow
|
||||
Password string //私密模式密码,唯一
|
||||
Remark string //备注
|
||||
TargetAddr string
|
||||
NoStore bool
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
@@ -114,15 +141,3 @@ func (s *Host) GetRandomTarget() string {
|
||||
}
|
||||
return s.TargetArr[s.NowIndex]
|
||||
}
|
||||
|
||||
//深拷贝Config
|
||||
func DeepCopyConfig(c *Config) *Config {
|
||||
return &Config{
|
||||
U: c.U,
|
||||
P: c.P,
|
||||
Compress: c.Compress,
|
||||
Crypt: c.Crypt,
|
||||
CompressEncode: c.CompressEncode,
|
||||
CompressDecode: c.CompressDecode,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
package lg
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
var Log *log.Logger
|
||||
|
||||
func InitLogFile(f string, isStdout bool, logPath string) {
|
||||
var prefix string
|
||||
if !isStdout {
|
||||
logFile, err := os.OpenFile(filepath.Join(logPath, f+"_log.txt"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
|
||||
if err != nil {
|
||||
log.Fatalln("open file error !", err)
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
prefix = "\r\n"
|
||||
}
|
||||
Log = log.New(logFile, prefix, log.Ldate|log.Ltime)
|
||||
} else {
|
||||
Log = log.New(os.Stdout, "", log.Ldate|log.Ltime)
|
||||
}
|
||||
}
|
||||
|
||||
func Println(v ...interface{}) {
|
||||
Log.Println(v...)
|
||||
}
|
||||
|
||||
func Fatalln(v ...interface{}) {
|
||||
Log.SetPrefix("error ")
|
||||
Log.Fatalln(v...)
|
||||
Log.SetPrefix("")
|
||||
}
|
||||
func Fatalf(format string, v ...interface{}) {
|
||||
Log.SetPrefix("error ")
|
||||
Log.Fatalf(format, v...)
|
||||
Log.SetPrefix("")
|
||||
}
|
||||
|
||||
func Printf(format string, v ...interface{}) {
|
||||
Log.Printf(format, v...)
|
||||
}
|
||||
+15
-3
@@ -36,14 +36,26 @@ var BufPoolCopy = sync.Pool{
|
||||
},
|
||||
}
|
||||
|
||||
func PutBufPoolUdp(buf []byte) {
|
||||
if cap(buf) == PoolSizeUdp {
|
||||
BufPoolUdp.Put(buf[:PoolSizeUdp])
|
||||
}
|
||||
}
|
||||
|
||||
func PutBufPoolCopy(buf []byte) {
|
||||
if cap(buf) == PoolSizeCopy {
|
||||
BufPoolCopy.Put(buf[:PoolSizeCopy])
|
||||
}
|
||||
}
|
||||
|
||||
func PutBufPoolUdp(buf []byte) {
|
||||
if cap(buf) == PoolSizeUdp {
|
||||
BufPoolUdp.Put(buf[:PoolSizeUdp])
|
||||
func PutBufPoolSmall(buf []byte) {
|
||||
if cap(buf) == PoolSizeSmall {
|
||||
BufPoolSmall.Put(buf[:PoolSizeSmall])
|
||||
}
|
||||
}
|
||||
|
||||
func PutBufPoolMax(buf []byte) {
|
||||
if cap(buf) == PoolSize {
|
||||
BufPoolMax.Put(buf[:PoolSize])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package version
|
||||
|
||||
const VERSION = "0.0.16"
|
||||
|
||||
func GetVersion() string {
|
||||
return VERSION
|
||||
}
|
||||
+39
-8
@@ -12,8 +12,13 @@ import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
//server base struct
|
||||
type server struct {
|
||||
type Service interface {
|
||||
Start() error
|
||||
Close() error
|
||||
}
|
||||
|
||||
//Server BaseServer struct
|
||||
type BaseServer struct {
|
||||
id int
|
||||
bridge *bridge.Bridge
|
||||
task *file.Tunnel
|
||||
@@ -21,27 +26,37 @@ type server struct {
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
func (s *server) FlowAdd(in, out int64) {
|
||||
func NewBaseServer(bridge *bridge.Bridge, task *file.Tunnel) *BaseServer {
|
||||
return &BaseServer{
|
||||
bridge: bridge,
|
||||
task: task,
|
||||
errorContent: nil,
|
||||
Mutex: sync.Mutex{},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *BaseServer) FlowAdd(in, out int64) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.task.Flow.ExportFlow += out
|
||||
s.task.Flow.InletFlow += in
|
||||
}
|
||||
|
||||
func (s *server) FlowAddHost(host *file.Host, in, out int64) {
|
||||
func (s *BaseServer) FlowAddHost(host *file.Host, in, out int64) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
host.Flow.ExportFlow += out
|
||||
host.Flow.InletFlow += in
|
||||
}
|
||||
|
||||
func (s *server) linkCopy(link *conn.Link, c *conn.Conn, rb []byte, tunnel *conn.Conn, flow *file.Flow) {
|
||||
func (s *BaseServer) linkCopy(link *conn.Link, c *conn.Conn, rb []byte, tunnel *conn.Conn, flow *file.Flow) {
|
||||
if rb != nil {
|
||||
if _, err := tunnel.SendMsg(rb, link); err != nil {
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
flow.Add(len(rb), 0)
|
||||
<-link.StatusCh
|
||||
}
|
||||
|
||||
buf := pool.BufPoolCopy.Get().([]byte)
|
||||
@@ -60,17 +75,19 @@ func (s *server) linkCopy(link *conn.Link, c *conn.Conn, rb []byte, tunnel *conn
|
||||
}
|
||||
flow.Add(n, 0)
|
||||
}
|
||||
<-link.StatusCh
|
||||
}
|
||||
s.task.Client.AddConn()
|
||||
pool.PutBufPoolCopy(buf)
|
||||
}
|
||||
|
||||
func (s *server) writeConnFail(c net.Conn) {
|
||||
func (s *BaseServer) writeConnFail(c net.Conn) {
|
||||
c.Write([]byte(common.ConnectionFailBytes))
|
||||
c.Write(s.errorContent)
|
||||
}
|
||||
|
||||
//权限认证
|
||||
func (s *server) auth(r *http.Request, c *conn.Conn, u, p string) error {
|
||||
func (s *BaseServer) auth(r *http.Request, c *conn.Conn, u, p string) error {
|
||||
if u != "" && p != "" && !common.CheckAuth(r, u, p) {
|
||||
c.Write([]byte(common.UnauthorizedBytes))
|
||||
c.Close()
|
||||
@@ -79,9 +96,23 @@ func (s *server) auth(r *http.Request, c *conn.Conn, u, p string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *server) checkFlow() error {
|
||||
func (s *BaseServer) checkFlow() error {
|
||||
if s.task.Client.Flow.FlowLimit > 0 && (s.task.Client.Flow.FlowLimit<<20) < (s.task.Client.Flow.ExportFlow+s.task.Client.Flow.InletFlow) {
|
||||
return errors.New("Traffic exceeded")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//与客户端建立通道
|
||||
func (s *BaseServer) DealClient(c *conn.Conn, addr string, rb []byte) error {
|
||||
link := conn.NewLink(s.task.Client.GetId(), common.CONN_TCP, addr, s.task.Client.Cnf.CompressEncode, s.task.Client.Cnf.CompressDecode, s.task.Client.Cnf.Crypt, c, s.task.Flow, nil, s.task.Client.Rate, nil)
|
||||
|
||||
if tunnel, err := s.bridge.SendLinkInfo(s.task.Client.Id, link, c.Conn.RemoteAddr().String()); err != nil {
|
||||
c.Close()
|
||||
return err
|
||||
} else {
|
||||
link.Run(true)
|
||||
s.linkCopy(link, c, rb, tunnel, s.task.Flow)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
+46
-20
@@ -7,18 +7,18 @@ import (
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
"log"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type httpServer struct {
|
||||
server
|
||||
BaseServer
|
||||
httpPort int //http端口
|
||||
httpsPort int //https监听端口
|
||||
pemPath string
|
||||
@@ -32,7 +32,7 @@ func NewHttp(bridge *bridge.Bridge, c *file.Tunnel) *httpServer {
|
||||
pemPath := beego.AppConfig.String("pemPath")
|
||||
keyPath := beego.AppConfig.String("keyPath")
|
||||
return &httpServer{
|
||||
server: server{
|
||||
BaseServer: BaseServer{
|
||||
task: c,
|
||||
bridge: bridge,
|
||||
Mutex: sync.Mutex{},
|
||||
@@ -55,26 +55,30 @@ func (s *httpServer) Start() error {
|
||||
if s.httpPort > 0 {
|
||||
http = s.NewServer(s.httpPort)
|
||||
go func() {
|
||||
lg.Println("Start http listener, port is", s.httpPort)
|
||||
logs.Info("Start http listener, port is", s.httpPort)
|
||||
err := http.ListenAndServe()
|
||||
if err != nil {
|
||||
lg.Fatalln(err)
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
}()
|
||||
}
|
||||
if s.httpsPort > 0 {
|
||||
if !common.FileExists(s.pemPath) {
|
||||
lg.Fatalf("ssl certFile %s is not exist", s.pemPath)
|
||||
logs.Error("ssl certFile %s is not exist", s.pemPath)
|
||||
os.Exit(0)
|
||||
}
|
||||
if !common.FileExists(s.keyPath) {
|
||||
lg.Fatalf("ssl keyFile %s exist", s.keyPath)
|
||||
logs.Error("ssl keyFile %s exist", s.keyPath)
|
||||
os.Exit(0)
|
||||
}
|
||||
https = s.NewServer(s.httpsPort)
|
||||
go func() {
|
||||
lg.Println("Start https listener, port is", s.httpsPort)
|
||||
logs.Info("Start https listener, port is", s.httpsPort)
|
||||
err := https.ListenAndServeTLS(s.pemPath, s.keyPath)
|
||||
if err != nil {
|
||||
lg.Fatalln(err)
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -90,8 +94,9 @@ func (s *httpServer) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *httpServer) Close() {
|
||||
func (s *httpServer) Close() error {
|
||||
s.stop <- true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *httpServer) handleTunneling(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -118,9 +123,14 @@ func (s *httpServer) process(c *conn.Conn, r *http.Request) {
|
||||
err error
|
||||
)
|
||||
if host, err = file.GetCsvDb().GetInfoByHost(r.Host, r); err != nil {
|
||||
lg.Printf("the url %s %s can't be parsed!", r.Host, r.RequestURI)
|
||||
logs.Notice("the url %s %s can't be parsed!", r.Host, r.RequestURI)
|
||||
goto end
|
||||
} else if !host.Client.GetConn() {
|
||||
logs.Notice("Connections exceed the current client %d limit", host.Client.Id)
|
||||
c.Close()
|
||||
return
|
||||
} else {
|
||||
logs.Trace("New http(s) connection,clientId %d,host %s,url %s,remote address %s", host.Client.Id, r.Host, r.URL, r.RemoteAddr)
|
||||
lastHost = host
|
||||
}
|
||||
for {
|
||||
@@ -137,21 +147,24 @@ func (s *httpServer) process(c *conn.Conn, r *http.Request) {
|
||||
}
|
||||
lk = conn.NewLink(host.Client.GetId(), common.CONN_TCP, host.GetRandomTarget(), host.Client.Cnf.CompressEncode, host.Client.Cnf.CompressDecode, host.Client.Cnf.Crypt, c, host.Flow, nil, host.Client.Rate, nil)
|
||||
if tunnel, err = s.bridge.SendLinkInfo(host.Client.Id, lk, c.Conn.RemoteAddr().String()); err != nil {
|
||||
log.Println(err)
|
||||
logs.Notice(err)
|
||||
break
|
||||
}
|
||||
lk.Run(true)
|
||||
isConn = false
|
||||
} else {
|
||||
r, err = http.ReadRequest(bufio.NewReader(c))
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
logs.Trace("New http(s) connection,clientId %d,host %s,url %s,remote address %s", host.Client.Id, r.Host, r.URL, r.RemoteAddr)
|
||||
if host, err = file.GetCsvDb().GetInfoByHost(r.Host, r); err != nil {
|
||||
lg.Printf("the url %s %s is not found !", r.Host, r.RequestURI)
|
||||
logs.Notice("the url %s %s can't be parsed!", r.Host, r.RequestURI)
|
||||
break
|
||||
} else if host != lastHost {
|
||||
lastHost = host
|
||||
isConn = true
|
||||
host.Client.AddConn()
|
||||
goto start
|
||||
}
|
||||
}
|
||||
@@ -161,10 +174,22 @@ func (s *httpServer) process(c *conn.Conn, r *http.Request) {
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
host.Flow.Add(len(b), 0)
|
||||
if _, err := tunnel.SendMsg(b, lk); err != nil {
|
||||
c.Close()
|
||||
break
|
||||
l := len(b)
|
||||
var start int
|
||||
host.Flow.Add(l, 0)
|
||||
for {
|
||||
if l-start > 32*1024 {
|
||||
_, err = tunnel.SendMsg(b[start:start+32*1024], lk)
|
||||
start += 32 * 1024
|
||||
<-lk.StatusCh
|
||||
} else {
|
||||
_, err = tunnel.SendMsg(b[start:l], lk)
|
||||
<-lk.StatusCh
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
end:
|
||||
@@ -173,9 +198,10 @@ end:
|
||||
} else {
|
||||
tunnel.SendMsg([]byte(common.IO_EOF), lk)
|
||||
}
|
||||
|
||||
c.Close()
|
||||
|
||||
if host != nil {
|
||||
host.Client.AddConn()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *httpServer) NewServer(port int) *http.Server {
|
||||
|
||||
+17
-11
@@ -7,7 +7,7 @@ import (
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
@@ -48,7 +48,7 @@ const (
|
||||
)
|
||||
|
||||
type Sock5ModeServer struct {
|
||||
server
|
||||
BaseServer
|
||||
listener net.Listener
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ func (s *Sock5ModeServer) handleRequest(c net.Conn) {
|
||||
_, err := io.ReadFull(c, header)
|
||||
|
||||
if err != nil {
|
||||
lg.Println("illegal request", err)
|
||||
logs.Warn("illegal request", err)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
@@ -148,6 +148,7 @@ func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) {
|
||||
return
|
||||
} else {
|
||||
s.sendReply(c, succeeded)
|
||||
link.Run(true)
|
||||
s.linkCopy(link, conn.NewConn(c), nil, tunnel, s.task.Flow)
|
||||
}
|
||||
return
|
||||
@@ -164,7 +165,6 @@ func (s *Sock5ModeServer) handleBind(c net.Conn) {
|
||||
|
||||
//udp
|
||||
func (s *Sock5ModeServer) handleUDP(c net.Conn) {
|
||||
lg.Println("UDP Associate")
|
||||
/*
|
||||
+----+------+------+----------+----------+----------+
|
||||
|RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA |
|
||||
@@ -177,7 +177,7 @@ func (s *Sock5ModeServer) handleUDP(c net.Conn) {
|
||||
// relay udp datagram silently, without any notification to the requesting client
|
||||
if buf[2] != 0 {
|
||||
// does not support fragmentation, drop it
|
||||
lg.Println("does not support fragmentation, drop")
|
||||
logs.Warn("does not support fragmentation, drop")
|
||||
dummy := make([]byte, maxUDPPacketSize)
|
||||
c.Read(dummy)
|
||||
}
|
||||
@@ -189,13 +189,13 @@ func (s *Sock5ModeServer) handleUDP(c net.Conn) {
|
||||
func (s *Sock5ModeServer) handleConn(c net.Conn) {
|
||||
buf := make([]byte, 2)
|
||||
if _, err := io.ReadFull(c, buf); err != nil {
|
||||
lg.Println("negotiation err", err)
|
||||
logs.Warn("negotiation err", err)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
|
||||
if version := buf[0]; version != 5 {
|
||||
lg.Println("only support socks5, request from: ", c.RemoteAddr())
|
||||
logs.Warn("only support socks5, request from: ", c.RemoteAddr())
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
@@ -203,7 +203,7 @@ func (s *Sock5ModeServer) handleConn(c net.Conn) {
|
||||
|
||||
methods := make([]byte, nMethods)
|
||||
if len, err := c.Read(methods); len != int(nMethods) || err != nil {
|
||||
lg.Println("wrong method")
|
||||
logs.Warn("wrong method")
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
@@ -212,7 +212,7 @@ func (s *Sock5ModeServer) handleConn(c net.Conn) {
|
||||
c.Write(buf)
|
||||
if err := s.Auth(c); err != nil {
|
||||
c.Close()
|
||||
lg.Println("Validation failed:", err)
|
||||
logs.Warn("Validation failed:", err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
@@ -270,9 +270,15 @@ func (s *Sock5ModeServer) Start() error {
|
||||
if strings.Contains(err.Error(), "use of closed network connection") {
|
||||
break
|
||||
}
|
||||
lg.Fatalln("accept error: ", err)
|
||||
logs.Warn("accept error: ", err)
|
||||
}
|
||||
if s.task.Client.GetConn() {
|
||||
logs.Trace("New socks5 connection,client %d,remote address %s", s.task.Client.Id, conn.RemoteAddr())
|
||||
go s.handleConn(conn)
|
||||
} else {
|
||||
logs.Warn("Connections exceed the current client %d limit", s.task.Client.Id)
|
||||
conn.Close()
|
||||
}
|
||||
go s.handleConn(conn)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
+24
-25
@@ -6,15 +6,16 @@ import (
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type TunnelModeServer struct {
|
||||
server
|
||||
BaseServer
|
||||
process process
|
||||
listener *net.TCPListener
|
||||
}
|
||||
@@ -41,23 +42,16 @@ func (s *TunnelModeServer) Start() error {
|
||||
if strings.Contains(err.Error(), "use of closed network connection") {
|
||||
break
|
||||
}
|
||||
lg.Println(err)
|
||||
logs.Info(err)
|
||||
continue
|
||||
}
|
||||
go s.process(conn.NewConn(c), s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//与客户端建立通道
|
||||
func (s *TunnelModeServer) dealClient(c *conn.Conn, cnf *file.Config, addr string, method string, rb []byte) error {
|
||||
link := conn.NewLink(s.task.Client.GetId(), common.CONN_TCP, addr, cnf.CompressEncode, cnf.CompressDecode, cnf.Crypt, c, s.task.Flow, nil, s.task.Client.Rate, nil)
|
||||
|
||||
if tunnel, err := s.bridge.SendLinkInfo(s.task.Client.Id, link, c.Conn.RemoteAddr().String()); err != nil {
|
||||
c.Close()
|
||||
return err
|
||||
} else {
|
||||
s.linkCopy(link, c, rb, tunnel, s.task.Flow)
|
||||
if s.task.Client.GetConn() {
|
||||
logs.Trace("New tcp connection,client %d,remote address %s", s.task.Client.Id, c.RemoteAddr())
|
||||
go s.process(conn.NewConn(c), s)
|
||||
} else {
|
||||
logs.Info("Connections exceed the current client %d limit", s.task.Client.Id)
|
||||
c.Close()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -69,23 +63,28 @@ func (s *TunnelModeServer) Close() error {
|
||||
|
||||
//web管理方式
|
||||
type WebServer struct {
|
||||
server
|
||||
BaseServer
|
||||
}
|
||||
|
||||
//开始
|
||||
func (s *WebServer) Start() error {
|
||||
p, _ := beego.AppConfig.Int("httpport")
|
||||
if !common.TestTcpPort(p) {
|
||||
lg.Fatalf("Web management port %d is occupied", p)
|
||||
logs.Error("Web management port %d is occupied", p)
|
||||
os.Exit(0)
|
||||
}
|
||||
beego.BConfig.WebConfig.Session.SessionOn = true
|
||||
lg.Println("Web management start, access port is", p)
|
||||
logs.Info("Web management start, access port is", p)
|
||||
beego.SetStaticPath("/static", filepath.Join(common.GetRunPath(), "web", "static"))
|
||||
beego.SetViewsPath(filepath.Join(common.GetRunPath(), "web", "views"))
|
||||
beego.Run()
|
||||
return errors.New("Web management startup failure")
|
||||
}
|
||||
|
||||
func (s *WebServer) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
//new
|
||||
func NewWebServer(bridge *bridge.Bridge) *WebServer {
|
||||
s := new(WebServer)
|
||||
@@ -97,23 +96,23 @@ type process func(c *conn.Conn, s *TunnelModeServer) error
|
||||
|
||||
//tcp隧道模式
|
||||
func ProcessTunnel(c *conn.Conn, s *TunnelModeServer) error {
|
||||
return s.dealClient(c, s.task.Client.Cnf, s.task.Target, "", nil)
|
||||
return s.DealClient(c, s.task.Target, nil)
|
||||
}
|
||||
|
||||
//http代理模式
|
||||
func ProcessHttp(c *conn.Conn, s *TunnelModeServer) error {
|
||||
method, addr, rb, err, r := c.GetHost()
|
||||
_, addr, rb, err, r := c.GetHost()
|
||||
if err != nil {
|
||||
c.Close()
|
||||
lg.Println(err)
|
||||
logs.Info(err)
|
||||
return err
|
||||
}
|
||||
if r.Method == "CONNECT" {
|
||||
c.Write([]byte("HTTP/1.1 200 Connection Established\r\n"))
|
||||
rb = nil //reset
|
||||
rb = nil
|
||||
}
|
||||
if err := s.auth(r, c, s.task.Client.Cnf.U, s.task.Client.Cnf.P); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.dealClient(c, s.task.Client.Cnf, addr, method, rb)
|
||||
return s.DealClient(c, addr, rb)
|
||||
}
|
||||
|
||||
+4
-1
@@ -6,12 +6,13 @@ import (
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/pool"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type UdpModeServer struct {
|
||||
server
|
||||
BaseServer
|
||||
listener *net.UDPConn
|
||||
udpMap map[string]*conn.Conn
|
||||
}
|
||||
@@ -40,6 +41,7 @@ func (s *UdpModeServer) Start() error {
|
||||
}
|
||||
continue
|
||||
}
|
||||
logs.Trace("New ydo connection,client %d,remote address %s", s.task.Client.Id, addr)
|
||||
go s.process(addr, buf[:n])
|
||||
}
|
||||
return nil
|
||||
@@ -56,6 +58,7 @@ func (s *UdpModeServer) process(addr *net.UDPAddr, data []byte) {
|
||||
s.task.Flow.Add(len(data), 0)
|
||||
tunnel.SendMsg(data, link)
|
||||
pool.PutBufPoolUdp(data)
|
||||
link.Run(true)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+72
-29
@@ -5,11 +5,12 @@ import (
|
||||
"github.com/cnlh/nps/bridge"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/server/proxy"
|
||||
"github.com/cnlh/nps/server/tool"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
"reflect"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -32,11 +33,11 @@ func InitFromCsv() {
|
||||
//Initialize services in server-side files
|
||||
for _, v := range file.GetCsvDb().Tasks {
|
||||
if v.Status {
|
||||
lg.Println("task start info: mode:", v.Mode, "port:", v.Port)
|
||||
AddTask(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func DealBridgeTask() {
|
||||
for {
|
||||
select {
|
||||
@@ -45,6 +46,22 @@ func DealBridgeTask() {
|
||||
case id := <-Bridge.CloseClient:
|
||||
DelTunnelAndHostByClientId(id)
|
||||
file.GetCsvDb().DelClient(id)
|
||||
case s := <-Bridge.SecretChan:
|
||||
logs.Trace("New secret connection, addr", s.Conn.Conn.RemoteAddr())
|
||||
if t := file.GetCsvDb().GetSecretTask(s.Password); t != nil {
|
||||
if !t.Client.GetConn() {
|
||||
logs.Info("Connections exceed the current client %d limit", t.Client.Id)
|
||||
s.Conn.Close()
|
||||
} else if t.Status {
|
||||
go proxy.NewBaseServer(Bridge, t).DealClient(s.Conn, t.Target, nil)
|
||||
} else {
|
||||
s.Conn.Close()
|
||||
logs.Trace("This key %s cannot be processed,status is close", s.Password)
|
||||
}
|
||||
} else {
|
||||
logs.Trace("This key %s cannot be processed", s.Password)
|
||||
s.Conn.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,33 +70,34 @@ func DealBridgeTask() {
|
||||
func StartNewServer(bridgePort int, cnf *file.Tunnel, bridgeType string) {
|
||||
Bridge = bridge.NewTunnel(bridgePort, bridgeType, common.GetBoolByStr(beego.AppConfig.String("ipLimit")), RunList)
|
||||
if err := Bridge.StartTunnel(); err != nil {
|
||||
lg.Fatalln("服务端开启失败", err)
|
||||
logs.Error("服务端开启失败", err)
|
||||
os.Exit(0)
|
||||
} else {
|
||||
lg.Printf("Server startup, the bridge type is %s, the bridge port is %d", bridgeType, bridgePort)
|
||||
logs.Info("Server startup, the bridge type is %s, the bridge port is %d", bridgeType, bridgePort)
|
||||
}
|
||||
go DealBridgeTask()
|
||||
if svr := NewMode(Bridge, cnf); svr != nil {
|
||||
RunList[cnf.Id] = svr
|
||||
err := reflect.ValueOf(svr).MethodByName("Start").Call(nil)[0]
|
||||
if err.Interface() != nil {
|
||||
lg.Fatalln(err)
|
||||
if err := svr.Start(); err != nil {
|
||||
logs.Error(err)
|
||||
}
|
||||
RunList[cnf.Id] = svr
|
||||
} else {
|
||||
lg.Fatalln("启动模式%s不正确", cnf.Mode)
|
||||
logs.Error("Incorrect startup mode %s", cnf.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
//new a server by mode name
|
||||
func NewMode(Bridge *bridge.Bridge, c *file.Tunnel) interface{} {
|
||||
func NewMode(Bridge *bridge.Bridge, c *file.Tunnel) proxy.Service {
|
||||
var service proxy.Service
|
||||
switch c.Mode {
|
||||
case "tcpServer":
|
||||
return proxy.NewTunnelModeServer(proxy.ProcessTunnel, Bridge, c)
|
||||
service = proxy.NewTunnelModeServer(proxy.ProcessTunnel, Bridge, c)
|
||||
case "socks5Server":
|
||||
return proxy.NewSock5ModeServer(Bridge, c)
|
||||
service = proxy.NewSock5ModeServer(Bridge, c)
|
||||
case "httpProxyServer":
|
||||
return proxy.NewTunnelModeServer(proxy.ProcessHttp, Bridge, c)
|
||||
service = proxy.NewTunnelModeServer(proxy.ProcessHttp, Bridge, c)
|
||||
case "udpServer":
|
||||
return proxy.NewUdpModeServer(Bridge, c)
|
||||
service = proxy.NewUdpModeServer(Bridge, c)
|
||||
case "webServer":
|
||||
InitFromCsv()
|
||||
t := &file.Tunnel{
|
||||
@@ -89,26 +107,27 @@ func NewMode(Bridge *bridge.Bridge, c *file.Tunnel) interface{} {
|
||||
Status: true,
|
||||
}
|
||||
AddTask(t)
|
||||
return proxy.NewWebServer(Bridge)
|
||||
service = proxy.NewWebServer(Bridge)
|
||||
case "httpHostServer":
|
||||
return proxy.NewHttp(Bridge, c)
|
||||
service = proxy.NewHttp(Bridge, c)
|
||||
}
|
||||
return nil
|
||||
return service
|
||||
}
|
||||
|
||||
//stop server
|
||||
func StopServer(id int) error {
|
||||
if v, ok := RunList[id]; ok {
|
||||
if reflect.ValueOf(v).IsValid() {
|
||||
//TODO 错误处理
|
||||
reflect.ValueOf(v).MethodByName("Close").Call(nil)
|
||||
if t, err := file.GetCsvDb().GetTask(id); err != nil {
|
||||
if svr, ok := v.(proxy.Service); ok {
|
||||
if err := svr.Close(); err != nil {
|
||||
return err
|
||||
} else {
|
||||
t.Status = false
|
||||
file.GetCsvDb().UpdateTask(t)
|
||||
}
|
||||
}
|
||||
if t, err := file.GetCsvDb().GetTask(id); err != nil {
|
||||
return err
|
||||
} else {
|
||||
t.Status = false
|
||||
file.GetCsvDb().UpdateTask(t)
|
||||
}
|
||||
delete(RunList, id)
|
||||
return nil
|
||||
}
|
||||
@@ -117,16 +136,24 @@ func StopServer(id int) error {
|
||||
|
||||
//add task
|
||||
func AddTask(t *file.Tunnel) error {
|
||||
if t.Mode == "secretServer" {
|
||||
logs.Info("secret task %s start ", t.Remark)
|
||||
RunList[t.Id] = nil
|
||||
return nil
|
||||
}
|
||||
if b := tool.TestServerPort(t.Port, t.Mode); !b && t.Mode != "httpHostServer" {
|
||||
lg.Printf("taskId %d start error Port %d Open Failed", t.Id, t.Port)
|
||||
logs.Error("taskId %d start error port %d open failed", t.Id, t.Port)
|
||||
return errors.New("the port open error")
|
||||
}
|
||||
if minute, err := beego.AppConfig.Int("flowStoreInterval"); err == nil && minute > 0 {
|
||||
go flowSession(time.Minute * time.Duration(minute))
|
||||
}
|
||||
if svr := NewMode(Bridge, t); svr != nil {
|
||||
logs.Info("tunnel task %s start mode:%s port %d", t.Remark, t.Mode, t.Port)
|
||||
RunList[t.Id] = svr
|
||||
go func() {
|
||||
err := reflect.ValueOf(svr).MethodByName("Start").Call(nil)[0]
|
||||
if err.Interface() != nil {
|
||||
lg.Println("clientId %d taskId %d start error %s", t.Client.Id, t.Id, err)
|
||||
if err := svr.Start(); err != nil {
|
||||
logs.Error("clientId %d taskId %d start error %s", t.Client.Id, t.Id, err)
|
||||
delete(RunList, t.Id)
|
||||
return
|
||||
}
|
||||
@@ -272,5 +299,21 @@ func GetDashboardData() map[string]int {
|
||||
data["udpServerCount"] += 1
|
||||
}
|
||||
}
|
||||
tcpCount := 0
|
||||
for _, v := range file.GetCsvDb().Clients {
|
||||
tcpCount += v.NowConn
|
||||
}
|
||||
data["tcpCount"] = tcpCount
|
||||
return data
|
||||
}
|
||||
|
||||
func flowSession(m time.Duration) {
|
||||
ticker := time.NewTicker(m)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
file.GetCsvDb().StoreHostToCsv()
|
||||
file.GetCsvDb().StoreTasksToCsv()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,9 @@ func init() {
|
||||
}
|
||||
|
||||
func TestServerPort(p int, m string) (b bool) {
|
||||
if p > 65535 || p < 0 {
|
||||
return false
|
||||
}
|
||||
if len(ports) != 0 {
|
||||
if !common.InIntArr(ports, p) {
|
||||
return false
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/rate"
|
||||
"github.com/cnlh/nps/server"
|
||||
@@ -31,7 +30,7 @@ func (s *ClientController) Add() {
|
||||
s.display()
|
||||
} else {
|
||||
t := &file.Client{
|
||||
VerifyKey: crypt.GetRandomString(16),
|
||||
VerifyKey: s.GetString("vkey"),
|
||||
Id: file.GetCsvDb().GetClientId(),
|
||||
Status: true,
|
||||
Remark: s.GetString("remark"),
|
||||
@@ -42,6 +41,7 @@ func (s *ClientController) Add() {
|
||||
Crypt: s.GetBoolNoErr("crypt"),
|
||||
},
|
||||
RateLimit: s.GetIntNoErr("rate_limit"),
|
||||
MaxConn: s.GetIntNoErr("max_conn"),
|
||||
Flow: &file.Flow{
|
||||
ExportFlow: 0,
|
||||
InletFlow: 0,
|
||||
@@ -52,7 +52,9 @@ func (s *ClientController) Add() {
|
||||
t.Rate = rate.NewRate(int64(t.RateLimit * 1024))
|
||||
t.Rate.Start()
|
||||
}
|
||||
file.GetCsvDb().NewClient(t)
|
||||
if err := file.GetCsvDb().NewClient(t); err != nil {
|
||||
s.AjaxErr(err.Error())
|
||||
}
|
||||
s.AjaxOk("添加成功")
|
||||
}
|
||||
}
|
||||
@@ -87,6 +89,10 @@ func (s *ClientController) Edit() {
|
||||
if c, err := file.GetCsvDb().GetClient(id); err != nil {
|
||||
s.error()
|
||||
} else {
|
||||
if !file.GetCsvDb().VerifyVkey(s.GetString("vkey"), c.Id) {
|
||||
s.AjaxErr("Vkey duplicate, please reset")
|
||||
}
|
||||
c.VerifyKey = s.GetString("vkey")
|
||||
c.Remark = s.GetString("remark")
|
||||
c.Cnf.U = s.GetString("u")
|
||||
c.Cnf.P = s.GetString("p")
|
||||
@@ -94,6 +100,7 @@ func (s *ClientController) Edit() {
|
||||
c.Cnf.Crypt = s.GetBoolNoErr("crypt")
|
||||
c.Flow.FlowLimit = int64(s.GetIntNoErr("flow_limit"))
|
||||
c.RateLimit = s.GetIntNoErr("rate_limit")
|
||||
c.MaxConn = s.GetIntNoErr("max_conn")
|
||||
if c.Rate != nil {
|
||||
c.Rate.Stop()
|
||||
}
|
||||
|
||||
@@ -44,6 +44,12 @@ func (s *IndexController) Http() {
|
||||
s.display("index/list")
|
||||
}
|
||||
|
||||
func (s *IndexController) Secret() {
|
||||
s.SetInfo("私密代理管理")
|
||||
s.SetType("secretServer")
|
||||
s.display("index/list")
|
||||
}
|
||||
|
||||
func (s *IndexController) Host() {
|
||||
s.SetInfo("host模式管理")
|
||||
s.SetType("hostServer")
|
||||
@@ -74,13 +80,14 @@ func (s *IndexController) Add() {
|
||||
s.display()
|
||||
} else {
|
||||
t := &file.Tunnel{
|
||||
Port: s.GetIntNoErr("port"),
|
||||
Mode: s.GetString("type"),
|
||||
Target: s.GetString("target"),
|
||||
Id: file.GetCsvDb().GetTaskId(),
|
||||
Status: true,
|
||||
Remark: s.GetString("remark"),
|
||||
Flow: &file.Flow{},
|
||||
Port: s.GetIntNoErr("port"),
|
||||
Mode: s.GetString("type"),
|
||||
Target: s.GetString("target"),
|
||||
Id: file.GetCsvDb().GetTaskId(),
|
||||
Status: true,
|
||||
Remark: s.GetString("remark"),
|
||||
Password: s.GetString("password"),
|
||||
Flow: &file.Flow{},
|
||||
}
|
||||
if !tool.TestServerPort(t.Port, t.Mode) {
|
||||
s.AjaxErr("The port cannot be opened because it may has been occupied or is no longer allowed.")
|
||||
@@ -126,8 +133,8 @@ func (s *IndexController) Edit() {
|
||||
t.Port = s.GetIntNoErr("port")
|
||||
t.Mode = s.GetString("type")
|
||||
t.Target = s.GetString("target")
|
||||
t.Password = s.GetString("password")
|
||||
t.Id = id
|
||||
t.Client.Id = s.GetIntNoErr("client_id")
|
||||
t.Remark = s.GetString("remark")
|
||||
if t.Client, err = file.GetCsvDb().GetClient(s.GetIntNoErr("client_id")); err != nil {
|
||||
s.AjaxErr("修改失败")
|
||||
|
||||
@@ -16,6 +16,10 @@
|
||||
<label class="control-label">速度限制(单位:KB,为空不限制)</label>
|
||||
<input class="form-control" type="text" name="rate_limit" placeholder="为空不限制">
|
||||
</div>
|
||||
<div class="form-group" id="max_conn">
|
||||
<label class="control-label">最大客户端连接数</label>
|
||||
<input class="form-control" type="text" name="max_conn" placeholder="为空不限制">
|
||||
</div>
|
||||
<div class="form-group" id="u">
|
||||
<label class="control-label">验证用户名(仅socks5,web穿透支持)</label>
|
||||
<input class="form-control" type="text" name="u" placeholder="不填则无需验证">
|
||||
@@ -24,6 +28,10 @@
|
||||
<label class="control-label">验证密码(仅socks5,web穿透支持)</label>
|
||||
<input class="form-control" type="text" name="p" placeholder="不填则无需验证">
|
||||
</div>
|
||||
<div class="form-group" id="vkey">
|
||||
<label class="control-label">客户端连接密钥(唯一、不填将会自动生成)</label>
|
||||
<input class="form-control" type="text" name="vkey" placeholder="客户端连接密钥">
|
||||
</div>
|
||||
<div class="form-group" id="compress">
|
||||
<label class="control-label">数据压缩方式</label>
|
||||
<select class="form-control" name="compress">
|
||||
|
||||
@@ -19,6 +19,11 @@
|
||||
<input class="form-control" value="{{.c.RateLimit}}" type="text" name="rate_limit"
|
||||
placeholder="为空不限制">
|
||||
</div>
|
||||
<div class="form-group" id="max_conn">
|
||||
<label class="control-label">最大客户端连接数</label>
|
||||
<input class="form-control" value="{{.c.MaxConn}}" type="text" name="max_conn"
|
||||
placeholder="为空不限制">
|
||||
</div>
|
||||
<div class="form-group" id="u">
|
||||
<label class="control-label">验证用户名(仅socks5,web穿透支持)</label>
|
||||
<input class="form-control" value="{{.c.Cnf.U}}" type="text" name="u"
|
||||
@@ -29,6 +34,11 @@
|
||||
<input class="form-control" value="{{.c.Cnf.P}}" type="text" name="p"
|
||||
placeholder="不填则无需验证">
|
||||
</div>
|
||||
<div class="form-group" id="vkey">
|
||||
<label class="control-label">客户端连接密钥(唯一、不填将会自动生成)</label>
|
||||
<input class="form-control" value="{{.c.VerifyKey}}" type="text" name="vkey"
|
||||
placeholder="客户端连接密钥">
|
||||
</div>
|
||||
<div class="form-group" id="compress">
|
||||
<label class="control-label">数据压缩方式(所有模式均支持)</label>
|
||||
<select class="form-control" name="compress">
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
<option {{if eq "udpServer" .type}}selected{{end}} value="udpServer">udp隧道</option>
|
||||
<option {{if eq "socks5Server" .type}}selected{{end}} value="socks5Server">socks5代理</option>
|
||||
<option {{if eq "httpProxyServer" .type}}selected{{end}} value="httpProxyServer">http代理
|
||||
<option {{if eq "secretServer" .type}}selected{{end}} value="secretServer">私密代理
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
@@ -30,6 +31,11 @@
|
||||
<input value="{{.client_id}}" class="form-control" type="text" name="client_id"
|
||||
placeholder="客户端id">
|
||||
</div>
|
||||
<div class="form-group" id="password">
|
||||
<label class="control-label">私密模式唯一密钥</label>
|
||||
<input class="form-control" type="text" name="password"
|
||||
placeholder="私密模式唯一密钥">
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="tile-footer">
|
||||
@@ -48,6 +54,7 @@
|
||||
arr["udpServer"] = ["type", "port", "target", "compress", "udp隧道模式,提供一条udp隧道,适用于dns、内网dns访问等,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,访问公网服务器的设定端口,则相当于访问内网目标地址的udp目标端口"]
|
||||
arr["socks5Server"] = ["type", "port", "compress", "u", "p", "socks5代理模式,内网socks5代理,配合proxifer,可如同使用vpn一样访问内网设备或资源,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,在外网环境下本机配置socks5代理,即访问内网设备或者资源 "]
|
||||
arr["httpProxyServer"] = ["type", "port", "compress", "u", "p", " http代理模式,内网http代理,可访问内网网站,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,在外网环境下本机配置http代理,即访问内网站点"]
|
||||
arr["secretServer"] = ["type", "target", "compress", "password", "u", "p", " http代理模式,内网http代理,可访问内网网站,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,在外网环境下本机配置http代理,即访问内网站点"]
|
||||
arrClientHide = ["compress", "u", "p", "crypt", "mux"]
|
||||
|
||||
function resetForm() {
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
<option {{if eq "socks5Server" .t.Mode}}selected{{end}} value="socks5Server">socks5代理
|
||||
</option>
|
||||
<option {{if eq "httpProxyServer" .t.Mode}}selected{{end}} value="httpProxyServer">http代理
|
||||
<option {{if eq "secretServer" .t.Mode}}selected{{end}} value="secretServer">私密代理
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
@@ -34,6 +35,11 @@
|
||||
<input class="form-control" value="{{.t.Client.Id}}" type="text" name="client_id"
|
||||
placeholder="客户端id">
|
||||
</div>
|
||||
<div class="form-group" id="password">
|
||||
<label class="control-label">私密模式唯一密钥</label>
|
||||
<input class="form-control" value="{{.t.Password}}" type="text" name="password"
|
||||
placeholder="私密模式唯一密钥">
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="tile-footer">
|
||||
@@ -52,6 +58,7 @@
|
||||
arr["udpServer"] = ["type", "port", "target", "compress"]
|
||||
arr["socks5Server"] = ["type", "port", "compress", "u", "p"]
|
||||
arr["httpProxyServer"] = ["type", "port", "compress", "u", "p"]
|
||||
arr["secretServer"] = ["type", "target", "compress", "u", "p","password"]
|
||||
arrClientHide = ["compress", "u", "p", "crypt", "mux"]
|
||||
|
||||
function resetForm() {
|
||||
|
||||
@@ -10,8 +10,8 @@
|
||||
<div class="col-md-3">
|
||||
<div class="widget-small danger coloured-icon"><i class="icon fa fa-home fa-3x"></i>
|
||||
<div class="info">
|
||||
<h4>域名解析数</h4>
|
||||
<p><b>{{.data.hostCount}}</b></p>
|
||||
<h4>当前TCP连接总数</h4>
|
||||
<p><b>{{.data.tcpCount}}</b></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -51,9 +51,11 @@
|
||||
<li><a class="app-menu__item {{if eq "udp" .menu}}active{{end}}" href="/index/udp"><i
|
||||
class="app-menu__icon fa fa-laptop"></i><span class="app-menu__label">udp隧道管理</span></a></li>
|
||||
<li><a class="app-menu__item {{if eq "socks5" .menu}}active{{end}}" href="/index/socks5"><i
|
||||
class="app-menu__icon fa fa-lightbulb-o"></i><span class="app-menu__label">socks5代理</span></a></li>
|
||||
class="app-menu__icon fa fa-lightbulb-o"></i><span class="app-menu__label">socks5代理管理</span></a></li>
|
||||
<li><a class="app-menu__item {{if eq "http" .menu}}active{{end}}" href="/index/http"><i
|
||||
class="app-menu__icon fa fa-magic"></i><span class="app-menu__label">http代理</span></a></li>
|
||||
class="app-menu__icon fa fa-magic"></i><span class="app-menu__label">http代理管理</span></a></li>
|
||||
<li><a class="app-menu__item {{if eq "secret" .menu}}active{{end}}" href="/index/secret"><i
|
||||
class="app-menu__icon fa fa-dashcube"></i><span class="app-menu__label">私密代理管理</span></a></li>
|
||||
<li><a class="app-menu__item {{if eq "help" .menu}}active{{end}}" href="/index/help"><i
|
||||
class="app-menu__icon fa fa-question-circle"></i><span class="app-menu__label">使用说明</span></a></li>
|
||||
</ul>
|
||||
|
||||
Reference in New Issue
Block a user