Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
45521d5680 | ||
|
|
89f1e72c50 | ||
|
|
4a7a0a7b75 | ||
|
|
6a978515ca | ||
|
|
0cc0e82c5d | ||
|
|
c01c61fc6b | ||
|
|
4831e17b38 | ||
|
|
3cb104cd1b | ||
|
|
60c8b0c7bf | ||
|
|
16c97a3c36 | ||
|
|
1e8180014d | ||
|
|
2330935b90 | ||
|
|
7ea9001aa4 | ||
|
|
694ebc5477 | ||
|
|
824b12a2f8 | ||
|
|
0c87b4119a |
@@ -49,11 +49,14 @@ nps是一款轻量级、高性能、功能强大的**内网穿透**代理服务
|
||||
* [关闭http|https代理](#关闭代理)
|
||||
* [将nps安装到系统](#将nps安装到系统)
|
||||
* [流量数据持久化](#流量数据持久化)
|
||||
* [系统信息显示](#系统信息显示)
|
||||
* [自定义客户端连接密钥](#自定义客户端连接密钥)
|
||||
* [关闭公钥访问](#关闭公钥访问)
|
||||
* [关闭web管理](#关闭web管理)
|
||||
* [服务端多用户登陆](#服务端多用户登陆)
|
||||
* [用户注册功能](#用户注册功能)
|
||||
* [监听指定ip](#监听指定ip)
|
||||
* [代理到服务端本地](#代理到服务端本地)
|
||||
* [客户端](#客户端)
|
||||
* [客户端启动](#客户端启动)
|
||||
* [无配置文件模式](#无配置文件模式)
|
||||
@@ -69,13 +72,14 @@ nps是一款轻量级、高性能、功能强大的**内网穿透**代理服务
|
||||
* [p2p服务](#p2p代理)
|
||||
* [文件访问代理](#文件访问模式)
|
||||
* [断线重连](#断线重连)
|
||||
* [nat类型检测](#nat类型检测)
|
||||
* [状态检查](#状态检查)
|
||||
* [重载配置文件](#重载配置文件)
|
||||
* [通过代理连接nps](#通过代理连接nps)
|
||||
* [日志输出级别](#日志输出级别)
|
||||
* [群晖支持](#群晖支持)
|
||||
|
||||
* [相关功能](#相关功能)
|
||||
* [缓存支持](#缓存支持)
|
||||
* [数据压缩支持](#数据压缩支持)
|
||||
* [站点密码保护](#站点保护)
|
||||
* [加密传输](#加密传输)
|
||||
@@ -94,11 +98,12 @@ nps是一款轻量级、高性能、功能强大的**内网穿透**代理服务
|
||||
* [URL路由](#URL路由)
|
||||
* [限制ip访问](#限制ip访问)
|
||||
* [客户端最大连接数限制](#客户端最大连接数)
|
||||
* [客户端最大隧道数限制](#客户端最大隧道数限制)
|
||||
* [端口复用](#端口复用)
|
||||
* [多路复用](#多路复用)
|
||||
* [环境变量渲染](#环境变量渲染)
|
||||
* [健康检查](#健康检查)
|
||||
|
||||
* [日志输出](#日志输出)
|
||||
* [相关说明](#相关说明)
|
||||
* [流量统计](#流量统计)
|
||||
* [当前客户端带宽](#当前客户端带宽)
|
||||
@@ -118,7 +123,7 @@ nps是一款轻量级、高性能、功能强大的**内网穿透**代理服务
|
||||
### releases安装
|
||||
> [releases](https://github.com/cnlh/nps/releases)
|
||||
|
||||
下载对应的系统版本即可,服务端和客户端是单独的,go语言开发,无需任何第三方依赖
|
||||
下载对应的系统版本即可,服务端和客户端是单独的
|
||||
|
||||
### 源码安装
|
||||
- 安装源码
|
||||
@@ -131,7 +136,7 @@ nps是一款轻量级、高性能、功能强大的**内网穿透**代理服务
|
||||
## 使用示例
|
||||
|
||||
### 统一准备工作(必做)
|
||||
- 开启服务端,假设公网服务器ip为1.1.1.1,配置文件中`bridgePort`为8284,配置文件中`web_port`为8080
|
||||
- 开启服务端,假设公网服务器ip为1.1.1.1,配置文件中`bridge_port`为8284,配置文件中`web_port`为8080
|
||||
- 访问1.1.1.1:8080
|
||||
- 在客户端管理中创建一个客户端,记录下验证密钥
|
||||
- 内网客户端运行(windows使用cmd运行加.exe)
|
||||
@@ -190,7 +195,7 @@ nps是一款轻量级、高性能、功能强大的**内网穿透**代理服务
|
||||
|
||||
**使用步骤**
|
||||
- 在刚才创建的客户端隧道管理中添加一条socks5代理,填写监听的端口(8003),保存。
|
||||
- 在外网环境的本机配置socks5代理,ip为公网服务器ip(1.1.1.1),端口为填写的监听端口(8003),即可畅享内网了
|
||||
- 在外网环境的本机配置socks5代理(例如使用proxifier进行全局代理),ip为公网服务器ip(1.1.1.1),端口为填写的监听端口(8003),即可畅享内网了
|
||||
|
||||
### http正向代理
|
||||
|
||||
@@ -198,6 +203,7 @@ nps是一款轻量级、高性能、功能强大的**内网穿透**代理服务
|
||||
|
||||
**假设场景:**
|
||||
想将公网服务器1.1.1.1的8004端口作为http代理,访问内网网站
|
||||
|
||||
**使用步骤**
|
||||
|
||||
- 在刚才创建的客户端隧道管理中添加一条http代理,填写监听的端口(8004),保存。
|
||||
@@ -211,49 +217,41 @@ nps是一款轻量级、高性能、功能强大的**内网穿透**代理服务
|
||||
无需新增多的端口实现访问内网服务器10.1.50.2的22端口
|
||||
|
||||
**使用步骤**
|
||||
- 在刚才创建的客户端中添加一条私密代理,并设置唯一密钥和内网目标10.1.50.2:22
|
||||
- 在需要连接ssh的机器上以配置文件模式启动客户端,内容如下
|
||||
- 在刚才创建的客户端中添加一条私密代理,并设置唯一密钥secrettest和内网目标10.1.50.2:22
|
||||
- 在需要连接ssh的机器上以执行命令
|
||||
|
||||
```ini
|
||||
[common]
|
||||
server=1.1.1.1:8284
|
||||
tp=tcp
|
||||
vkey=123
|
||||
[secret_ssh]
|
||||
password=1111
|
||||
port=1000
|
||||
```
|
||||
**注意:** secret前缀必须存在,password为web管理上添加的唯一密钥
|
||||
./npc -server=1.1.1.1:8284 -vkey=vkey -type=tcp -password=secrettest -local_type=secret
|
||||
```
|
||||
如需指定本地端口可加参数`-local_port=xx`,默认为2000
|
||||
|
||||
**注意:** password为web管理上添加的唯一密钥,具体命令可查看web管理上的命令提示
|
||||
|
||||
假设10.1.50.2用户名为root,现在执行`ssh -p 2000 root@1.1.1.1`即可访问ssh
|
||||
|
||||
假设用户名为root,现在执行`ssh -p 1000 root@127.0.0.1`即可访问ssh
|
||||
|
||||
### p2p服务
|
||||
|
||||
**适用范围:** 大流量传输场景,流量不经过公网服务器,但是由于p2p穿透和nat类型关系较大,成功率一般,可穿透所有非对称型nat。
|
||||
**适用范围:** 大流量传输场景,流量不经过公网服务器,但是由于p2p穿透和nat类型关系较大,不保证100%成功,支持大部分nat类型。[nat类型检测](#nat类型检测)
|
||||
|
||||
**假设场景:**
|
||||
内网1机器ip为10.1.50.2 内网2机器ip为10.2.50.2
|
||||
内网1机器ip为10.1.50.2 内网2机器2 ip为10.2.50.2
|
||||
|
||||
想通过访问机器1的2001端口---->访问到内网2机器的22端口
|
||||
想通过访问内网1机器1的2000端口---->访问到内网2机器3 10.2.50.3的22端口
|
||||
|
||||
**使用步骤**
|
||||
- 在`nps.conf`中设置`p2p_ip`和`p2p_port`
|
||||
- 在`nps.conf`中设置`p2p_ip`(nps服务器ip)和`p2p_port`(nps服务器udp端口)
|
||||
- 在刚才刚才创建的客户端中添加一条p2p代理,并设置唯一密钥p2pssh
|
||||
- 在需要连接的机器上(即机器1)以配置文件模式启动客户端,内容如下
|
||||
- 在机器1执行命令
|
||||
|
||||
```ini
|
||||
[common]
|
||||
server=1.1.1.1:8284
|
||||
tp=tcp
|
||||
vkey=123
|
||||
[p2p_ssh]
|
||||
password=p2pssh
|
||||
port=2001
|
||||
```
|
||||
**注意:** p2p前缀必须存在,password为web管理上添加的唯一密钥
|
||||
./npc -server=1.1.1.1:8284 -vkey=123 -password=p2pssh -target=10.2.50.3:22
|
||||
```
|
||||
如需指定本地端口可加参数`-local_port=xx`,默认为2000
|
||||
|
||||
假设机器2用户名为root,现在在机器1上执行`ssh -p 2001 root@127.0.0.1`即可访问机器2的ssh
|
||||
**注意:** password为web管理上添加的唯一密钥,具体命令可查看web管理上的命令提示
|
||||
|
||||
假设机器3用户名为root,现在在机器1上执行`ssh -p 2000 root@127.0.0.1`即可访问机器2的ssh
|
||||
|
||||
|
||||
|
||||
@@ -279,7 +277,7 @@ port=2001
|
||||
```shell
|
||||
./nps start
|
||||
```
|
||||
如果无需daemon运行,去掉start即可
|
||||
**如果无需daemon运行或者打开后无法正常访问web管理,去掉start查看日志运行即可**
|
||||
|
||||
#### web管理
|
||||
|
||||
@@ -392,6 +390,8 @@ nps.exe test|start|stop|restart|status
|
||||
服务端支持将流量数据持久化,默认情况下是关闭的,如果有需求可以设置`nps.conf`中的`flow_store_interval`参数,单位为分钟
|
||||
|
||||
**注意:** nps不会持久化通过公钥连接的客户端
|
||||
### 系统信息显示
|
||||
nps服务端支持在web上显示和统计服务器的相关信息,但默认一些统计图表是关闭的,如需开启请在`nps.conf`中设置`system_info_display=true`
|
||||
|
||||
### 自定义客户端连接密钥
|
||||
web上可以自定义客户端连接的密钥,但是必须具有唯一性
|
||||
@@ -404,13 +404,21 @@ web上可以自定义客户端连接的密钥,但是必须具有唯一性
|
||||
### 服务端多用户登陆
|
||||
如果将`nps.conf`中的`allow_user_login`设置为true,服务端web将支持多用户登陆,登陆用户名为user,默认密码为每个客户端的验证密钥,登陆后可以进入客户端编辑修改web登陆的用户名和密码,默认该功能是关闭的。
|
||||
|
||||
### 用户注册功能
|
||||
nps服务端支持用户注册功能,可将`nps.conf`中的`allow_user_register`设置为true,开启后登陆页将会有有注册功能,
|
||||
|
||||
### 监听指定ip
|
||||
|
||||
nps支持每个隧道监听不同的服务端端口,可在web中控制,或者npc配置文件中(可忽略,默认为0.0.0.0)
|
||||
nps支持每个隧道监听不同的服务端端口,在`nps.conf`中设置`allow_multi_ip=true`后,可在web中控制,或者npc配置文件中(可忽略,默认为0.0.0.0)
|
||||
```ini
|
||||
server_ip=xxx
|
||||
```
|
||||
### 代理到服务端本地
|
||||
在使用nps监听80或者443端口时,默认是将所有的请求都会转发到内网上,但有时候我们的nps服务器的上一些服务也需要使用这两个端口,nps提供类似于`nginx` `proxy_pass` 的功能,支持将代理到服务器本地,该功能支持域名解析,tcp、udp隧道,默认关闭。
|
||||
|
||||
**即:** 假设在nps的vps服务器上有一个服务使用5000端口,这时候nps占用了80端口和443,我们想能使用一个域名通过http(s)访问到5000的服务。
|
||||
|
||||
**使用方式:** 在`nps.conf`中设置`allow_local_proxy=true`,然后在web上设置想转发的隧道或者域名然后选择转发到本地选项即可成功。
|
||||
## 客户端
|
||||
|
||||
### 客户端启动
|
||||
@@ -598,7 +606,11 @@ strip_pre|前缀
|
||||
[common]
|
||||
auto_reconnection=true
|
||||
```
|
||||
|
||||
#### nat类型检测
|
||||
```
|
||||
./npc nat
|
||||
```
|
||||
如果p2p双方都是Symmetic Nat,肯定不能成功,其他组合都有较大成功率。
|
||||
#### 状态检查
|
||||
```
|
||||
./npc status -config=npc配置文件路径
|
||||
@@ -627,25 +639,15 @@ proxy_url=socks5://111:222@127.0.0.1:8024
|
||||
|
||||
或http://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
|
||||
|
||||
#### 群晖支持
|
||||
可在releases中下载spk群晖套件,例如`npc_x64-6.1_0.19.0-1.spk`
|
||||
## 相关功能
|
||||
|
||||
### 缓存支持
|
||||
对于web站点来说,一些静态文件往往消耗更大的流量,且在内网穿透中,静态文件还需到客户端获取一次,这将导致更大的流量消耗。nps在域名解析代理中支持对静态文件进行缓存。
|
||||
|
||||
即假设一个站点有a.css,nps将只需从npc客户端读取一次该文件,然后把该文件的内容放在内存中,下一次将不再对npc客户端进行请求而直接返回内存中的对应内容。该功能默认是关闭的,如需开启请在`nps.conf`中设置`http_cache=true`,并设置`http_cache_length`(缓存文件的个数,消耗内存,不宜过大,0表示不限制个数)
|
||||
|
||||
### 数据压缩支持
|
||||
|
||||
由于是内网穿透,内网客户端与服务端之间的隧道存在大量的数据交换,为节省流量,加快传输速度,由此本程序支持SNNAPY形式的压缩。
|
||||
@@ -685,11 +687,11 @@ LevelInformational->6 LevelDebug->7
|
||||
### 流量限制
|
||||
|
||||
支持客户端级流量限制,当该客户端入口流量与出口流量达到设定的总量后会拒绝服务
|
||||
,域名代理会返回404页面,其他代理会拒绝连接
|
||||
,域名代理会返回404页面,其他代理会拒绝连接,使用该功能需要在`nps.conf`中设置`allow_flow_limit`,默认是关闭的。
|
||||
|
||||
### 带宽限制
|
||||
|
||||
支持客户端级带宽限制,带宽计算方式为入口和出口总和,权重均衡
|
||||
支持客户端级带宽限制,带宽计算方式为入口和出口总和,权重均衡,使用该功能需要在`nps.conf`中设置`allow_rate_limit`,默认是关闭的。
|
||||
|
||||
### 负载均衡
|
||||
本代理支持域名解析模式和tcp代理的负载均衡,在web域名添加或者编辑中内网目标分行填写多个目标即可实现轮训级别的负载均衡
|
||||
@@ -776,8 +778,10 @@ time为有效小时数,例如time=2,在当前时间后的两小时内,本
|
||||
|
||||
**注意:** 本机公网ip并不是一成不变的,请自行注意有效期的设置,同时同一网络下,多人也可能是在公用同一个公网ip。
|
||||
### 客户端最大连接数
|
||||
为防止恶意大量长连接,影响服务端程序的稳定性,可以在web或客户端配置文件中为每个客户端设置最大连接数。该功能针对`socks5`、`http正向代理`、`域名代理`、`tcp代理`、`udp代理`、`私密代理`生效。
|
||||
为防止恶意大量长连接,影响服务端程序的稳定性,可以在web或客户端配置文件中为每个客户端设置最大连接数。该功能针对`socks5`、`http正向代理`、`域名代理`、`tcp代理`、`udp代理`、`私密代理`生效,使用该功能需要在`nps.conf`中设置`allow_connection_num_limit=true`,默认是关闭的。
|
||||
|
||||
### 客户端最大隧道数限制
|
||||
nps支持对客户端的隧道数量进行限制,该功能默认是关闭的,如需开启,请在`nps.conf`中设置`allow_tunnel_num_limit=true`。
|
||||
### 端口复用
|
||||
在一些严格的网络环境中,对端口的个数等限制较大,nps支持强大端口复用功能。将`bridge_port`、 `http_proxy_port`、 `https_proxy_port` 、`web_port`都设置为同一端口,也能正常使用。
|
||||
|
||||
@@ -850,6 +854,28 @@ health_check_target | 健康检查目标,多个以逗号(,)分隔
|
||||
health_check_type | 健康检查类型
|
||||
health_http_url | 健康检查url,仅http模式适用
|
||||
|
||||
### 日志输出
|
||||
|
||||
#### 日志输出级别
|
||||
|
||||
**对于npc:**
|
||||
```
|
||||
-log_level=0~7 -log_path=npc.log
|
||||
```
|
||||
```
|
||||
LevelEmergency->0 LevelAlert->1
|
||||
|
||||
LevelCritical->2 LevelError->3
|
||||
|
||||
LevelWarning->4 LevelNotice->5
|
||||
|
||||
LevelInformational->6 LevelDebug->7
|
||||
```
|
||||
默认为全输出,级别为0到7
|
||||
|
||||
**对于nps:**
|
||||
|
||||
在`nps.conf`中设置相关配置即可
|
||||
|
||||
## 相关说明
|
||||
|
||||
@@ -872,7 +898,7 @@ health_http_url | 健康检查url,仅http模式适用
|
||||
可统计每个客户端当前的带宽,可能和实际有一定差异,仅供参考。
|
||||
|
||||
### 客户端与服务端版本对比
|
||||
为了程序正常运行,客户端与服务端的版本必须一致,否则将导致客户端无法成功连接致服务端。
|
||||
为了程序正常运行,客户端与服务端的核心版本必须一致,否则将导致客户端无法成功连接致服务端。
|
||||
|
||||
## webAPI
|
||||
|
||||
|
||||
+11
-5
@@ -152,7 +152,6 @@ func (s *Bridge) GetHealthFromClient(id int, c *conn.Conn) {
|
||||
//验证失败,返回错误验证flag,并且关闭连接
|
||||
func (s *Bridge) verifyError(c *conn.Conn) {
|
||||
c.Write([]byte(common.VERIFY_EER))
|
||||
c.Conn.Close()
|
||||
}
|
||||
|
||||
func (s *Bridge) verifySuccess(c *conn.Conn) {
|
||||
@@ -249,6 +248,8 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int) {
|
||||
case common.WORK_SECRET:
|
||||
if b, err := c.GetShortContent(32); err == nil {
|
||||
s.SecretChan <- conn.NewSecret(string(b), c)
|
||||
} else {
|
||||
logs.Error("secret error, failed to match the key successfully")
|
||||
}
|
||||
case common.WORK_FILE:
|
||||
muxConn := mux.NewMux(c.Conn, s.tunnelType)
|
||||
@@ -258,9 +259,9 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int) {
|
||||
case common.WORK_P2P:
|
||||
//read md5 secret
|
||||
if b, err := c.GetShortContent(32); err != nil {
|
||||
return
|
||||
logs.Error("p2p error,", err.Error())
|
||||
} else if t := file.GetDb().GetTaskByMd5Password(string(b)); t == nil {
|
||||
return
|
||||
logs.Error("p2p error, failed to match the key successfully")
|
||||
} else {
|
||||
if v, ok := s.Client.Load(t.Client.Id); !ok {
|
||||
return
|
||||
@@ -291,11 +292,16 @@ func (s *Bridge) register(c *conn.Conn) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Bridge) SendLinkInfo(clientId int, link *conn.Link, linkAddr string, t *file.Tunnel) (target net.Conn, err error) {
|
||||
func (s *Bridge) SendLinkInfo(clientId int, link *conn.Link, t *file.Tunnel) (target net.Conn, err error) {
|
||||
//if the proxy type is local
|
||||
if link.LocalProxy {
|
||||
target, err = net.Dial(link.ConnType, link.Host)
|
||||
return
|
||||
}
|
||||
if v, ok := s.Client.Load(clientId); ok {
|
||||
//If ip is restricted to do ip verification
|
||||
if s.ipVerify {
|
||||
ip := common.GetIpByAddr(linkAddr)
|
||||
ip := common.GetIpByAddr(link.RemoteAddr)
|
||||
if v, ok := s.Register.Load(ip); !ok {
|
||||
return nil, errors.New(fmt.Sprintf("The ip %s is not in the validation list", ip))
|
||||
} else {
|
||||
|
||||
+27
-86
@@ -8,7 +8,6 @@ import (
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/vender/github.com/xtaci/kcp"
|
||||
"net"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -43,106 +42,47 @@ retry:
|
||||
time.Sleep(time.Second * 5)
|
||||
goto retry
|
||||
}
|
||||
|
||||
logs.Info("Successful connection with server %s", s.svrAddr)
|
||||
//monitor the connection
|
||||
go s.ping()
|
||||
s.processor(c)
|
||||
}
|
||||
|
||||
//处理
|
||||
func (s *TRPClient) processor(c *conn.Conn) {
|
||||
s.signal = c
|
||||
go s.dealChan()
|
||||
//start a channel connection
|
||||
go s.newChan()
|
||||
//start health check if the it's open
|
||||
if s.cnf != nil && len(s.cnf.Healths) > 0 {
|
||||
go heathCheck(s.cnf.Healths, s.signal)
|
||||
}
|
||||
//msg connection, eg udp
|
||||
s.handleMain()
|
||||
}
|
||||
|
||||
//handle main connection
|
||||
func (s *TRPClient) handleMain() {
|
||||
for {
|
||||
flags, err := c.ReadFlag()
|
||||
flags, err := s.signal.ReadFlag()
|
||||
if err != nil {
|
||||
logs.Error("Accept server data error %s, end this service", err.Error())
|
||||
break
|
||||
}
|
||||
switch flags {
|
||||
case common.VERIFY_EER:
|
||||
logs.Error("VKey:%s is incorrect, the server refuses to connect, please check", s.vKey)
|
||||
os.Exit(0)
|
||||
case common.RES_CLOSE:
|
||||
logs.Error("The authentication key is connected by another client or the server closes the client.")
|
||||
os.Exit(0)
|
||||
case common.RES_MSG:
|
||||
logs.Error("Server-side return error")
|
||||
break
|
||||
case common.NEW_UDP_CONN:
|
||||
//读取服务端地址、密钥 继续做处理
|
||||
if lAddr, err := c.GetShortLenContent(); err != nil {
|
||||
//read server udp addr and password
|
||||
if lAddr, err := s.signal.GetShortLenContent(); err != nil {
|
||||
logs.Warn(err)
|
||||
return
|
||||
} else if pwd, err := c.GetShortLenContent(); err == nil {
|
||||
} else if pwd, err := s.signal.GetShortLenContent(); err == nil {
|
||||
go s.newUdpConn(string(lAddr), string(pwd))
|
||||
}
|
||||
default:
|
||||
logs.Warn("The error could not be resolved")
|
||||
break
|
||||
}
|
||||
}
|
||||
c.Close()
|
||||
s.Close()
|
||||
}
|
||||
|
||||
func (s *TRPClient) newUdpConn(rAddr string, md5Password string) {
|
||||
tmpConn, err := common.GetLocalUdpAddr()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
localAddr, _ := net.ResolveUDPAddr("udp", tmpConn.LocalAddr().String())
|
||||
localConn, err := net.ListenUDP("udp", localAddr)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
localKcpConn, err := kcp.NewConn(rAddr, nil, 150, 3, localConn)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
conn.SetUdpSession(localKcpConn)
|
||||
localToolConn := conn.NewConn(localKcpConn)
|
||||
//写入密钥、provider身份
|
||||
if _, err := localToolConn.Write([]byte(md5Password)); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
if _, err := localToolConn.Write([]byte(common.WORK_P2P_PROVIDER)); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
//接收服务端传的visitor地址
|
||||
var b []byte
|
||||
if b, err = localToolConn.GetShortLenContent(); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
//向visitor地址发送测试消息
|
||||
visitorAddr, err := net.ResolveUDPAddr("udp", string(b))
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
//向目标IP发送探测包
|
||||
if _, err := localConn.WriteTo([]byte("test"), visitorAddr); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
//给服务端发反馈
|
||||
if _, err := localToolConn.Write([]byte(common.VERIFY_SUCCESS)); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
//关闭与服务端的连接
|
||||
localConn.Close()
|
||||
//关闭与服务端udp conn,建立新的监听
|
||||
if localConn, err = net.ListenUDP("udp", localAddr); err != nil {
|
||||
var localConn net.PacketConn
|
||||
var err error
|
||||
var remoteAddress string
|
||||
if remoteAddress, localConn, err = handleP2PUdp(rAddr, md5Password, common.WORK_P2P_PROVIDER); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
@@ -151,6 +91,7 @@ func (s *TRPClient) newUdpConn(rAddr string, md5Password string) {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
logs.Trace("start local p2p udp listen, local address", localConn.LocalAddr().String())
|
||||
//接收新的监听,得到conn,
|
||||
for {
|
||||
udpTunnel, err := l.AcceptKCP()
|
||||
@@ -159,23 +100,24 @@ func (s *TRPClient) newUdpConn(rAddr string, md5Password string) {
|
||||
l.Close()
|
||||
return
|
||||
}
|
||||
if udpTunnel.RemoteAddr().String() == string(b) {
|
||||
if udpTunnel.RemoteAddr().String() == string(remoteAddress) {
|
||||
conn.SetUdpSession(udpTunnel)
|
||||
//读取link,设置msgCh 设置msgConn消息回传响应机制
|
||||
logs.Trace("successful connection with client ,address %s", udpTunnel.RemoteAddr().String())
|
||||
//read link info from remote
|
||||
l := mux.NewMux(udpTunnel, s.bridgeConnType)
|
||||
for {
|
||||
connMux, err := l.Accept()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
go s.srcProcess(connMux)
|
||||
go s.handleChan(connMux)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//mux tunnel
|
||||
func (s *TRPClient) dealChan() {
|
||||
func (s *TRPClient) newChan() {
|
||||
tunnel, err := NewConn(s.bridgeConnType, s.vKey, s.svrAddr, common.WORK_CHAN, s.proxyUrl)
|
||||
if err != nil {
|
||||
logs.Error("connect to ", s.svrAddr, "error:", err)
|
||||
@@ -189,11 +131,11 @@ func (s *TRPClient) dealChan() {
|
||||
s.Close()
|
||||
break
|
||||
}
|
||||
go s.srcProcess(src)
|
||||
go s.handleChan(src)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TRPClient) srcProcess(src net.Conn) {
|
||||
func (s *TRPClient) handleChan(src net.Conn) {
|
||||
lk, err := conn.NewConn(src).GetLinkInfo()
|
||||
if err != nil {
|
||||
src.Close()
|
||||
@@ -218,9 +160,8 @@ loop:
|
||||
for {
|
||||
select {
|
||||
case <-s.ticker.C:
|
||||
if s.tunnel.IsClose {
|
||||
if s.tunnel != nil && s.tunnel.IsClose {
|
||||
s.Close()
|
||||
s.ticker.Stop()
|
||||
break loop
|
||||
}
|
||||
}
|
||||
|
||||
+155
-1
@@ -10,6 +10,7 @@ import (
|
||||
"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/ccding/go-stun/stun"
|
||||
"github.com/cnlh/nps/vender/github.com/xtaci/kcp"
|
||||
"github.com/cnlh/nps/vender/golang.org/x/net/proxy"
|
||||
"io/ioutil"
|
||||
@@ -210,6 +211,8 @@ func NewConn(tp string, vkey string, server string, connType string, proxyUrl st
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
connection.SetDeadline(time.Now().Add(time.Second * 10))
|
||||
defer connection.SetDeadline(time.Time{})
|
||||
c := conn.NewConn(connection)
|
||||
if _, err := c.Write([]byte(common.CONN_TEST)); err != nil {
|
||||
return nil, err
|
||||
@@ -219,7 +222,7 @@ func NewConn(tp string, vkey string, server string, connType string, proxyUrl st
|
||||
}
|
||||
if b, err := c.GetShortContent(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)
|
||||
return nil, err
|
||||
}
|
||||
if _, err := c.Write([]byte(common.Getverifyval(vkey))); err != nil {
|
||||
return nil, err
|
||||
@@ -238,6 +241,7 @@ func NewConn(tp string, vkey string, server string, connType string, proxyUrl st
|
||||
return c, nil
|
||||
}
|
||||
|
||||
//http proxy connection
|
||||
func NewHttpProxyConn(url *url.URL, remoteAddr string) (net.Conn, error) {
|
||||
req := &http.Request{
|
||||
Method: "CONNECT",
|
||||
@@ -266,7 +270,157 @@ func NewHttpProxyConn(url *url.URL, remoteAddr string) (net.Conn, error) {
|
||||
return proxyConn, nil
|
||||
}
|
||||
|
||||
//get a basic auth string
|
||||
func basicAuth(username, password string) string {
|
||||
auth := username + ":" + password
|
||||
return base64.StdEncoding.EncodeToString([]byte(auth))
|
||||
}
|
||||
|
||||
func handleP2PUdp(rAddr, md5Password, role string) (remoteAddress string, c net.PacketConn, err error) {
|
||||
tmpConn, err := common.GetLocalUdpAddr()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
localConn, err := newUdpConnByAddr(tmpConn.LocalAddr().String())
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
localKcpConn, err := kcp.NewConn(rAddr, nil, 150, 3, localConn)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
conn.SetUdpSession(localKcpConn)
|
||||
localToolConn := conn.NewConn(localKcpConn)
|
||||
//get local nat type
|
||||
//localNatType, host, err := stun.NewClient().Discover()
|
||||
//if err != nil || host == nil {
|
||||
// err = errors.New("get nat type error")
|
||||
// return
|
||||
//}
|
||||
localNatType := stun.NATRestricted
|
||||
//write password
|
||||
if _, err = localToolConn.Write([]byte(md5Password)); err != nil {
|
||||
return
|
||||
}
|
||||
//write role
|
||||
if _, err = localToolConn.Write([]byte(role)); err != nil {
|
||||
return
|
||||
}
|
||||
if err = binary.Write(localToolConn, binary.LittleEndian, int32(localNatType)); err != nil {
|
||||
return
|
||||
}
|
||||
//get another type address and nat type from server
|
||||
var remoteAddr []byte
|
||||
var remoteNatType int32
|
||||
if remoteAddr, err = localToolConn.GetShortLenContent(); err != nil {
|
||||
return
|
||||
}
|
||||
if err = binary.Read(localToolConn, binary.LittleEndian, &remoteNatType); err != nil {
|
||||
return
|
||||
}
|
||||
localConn.Close()
|
||||
//logs.Trace("remote nat type %d,local nat type %s", remoteNatType, localNatType)
|
||||
if remoteAddress, err = sendP2PTestMsg(string(remoteAddr), tmpConn.LocalAddr().String()); err != nil {
|
||||
return
|
||||
}
|
||||
c, err = newUdpConnByAddr(tmpConn.LocalAddr().String())
|
||||
return
|
||||
}
|
||||
|
||||
func handleP2P(natType1, natType2 int, addr1, addr2 string, role string) (string, error) {
|
||||
switch natType1 {
|
||||
case int(stun.NATFull):
|
||||
return sendP2PTestMsg(addr2, addr1)
|
||||
case int(stun.NATRestricted):
|
||||
switch natType2 {
|
||||
case int(stun.NATFull), int(stun.NATRestricted), int(stun.NATPortRestricted), int(stun.NATSymetric):
|
||||
return sendP2PTestMsg(addr2, addr1)
|
||||
}
|
||||
case int(stun.NATPortRestricted):
|
||||
switch natType2 {
|
||||
case int(stun.NATFull), int(stun.NATRestricted), int(stun.NATPortRestricted):
|
||||
return sendP2PTestMsg(addr2, addr1)
|
||||
}
|
||||
case int(stun.NATSymetric):
|
||||
switch natType2 {
|
||||
case int(stun.NATFull), int(stun.NATRestricted):
|
||||
return sendP2PTestMsg(addr2, addr1)
|
||||
}
|
||||
}
|
||||
return "", errors.New("not support p2p")
|
||||
}
|
||||
|
||||
func sendP2PTestMsg(remoteAddr string, localAddr string) (string, error) {
|
||||
remoteUdpAddr, err := net.ResolveUDPAddr("udp", remoteAddr)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
localConn, err := newUdpConnByAddr(localAddr)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer localConn.Close()
|
||||
ticker := time.NewTicker(time.Millisecond * 500)
|
||||
go func(ticker *time.Ticker) {
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
logs.Trace("try send test packet to target %s", remoteAddr)
|
||||
if _, err := localConn.WriteTo([]byte(common.WORK_P2P_CONNECT), remoteUdpAddr); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}(ticker)
|
||||
buf := make([]byte, 10)
|
||||
for {
|
||||
localConn.SetReadDeadline(time.Now().Add(time.Second * 30))
|
||||
n, addr, err := localConn.ReadFromUDP(buf)
|
||||
localConn.SetReadDeadline(time.Time{})
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
switch string(buf[:n]) {
|
||||
case common.WORK_P2P_SUCCESS:
|
||||
for i := 20; i > 0; i-- {
|
||||
if _, err = localConn.WriteTo([]byte(common.WORK_P2P_END), addr); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
return addr.String(), nil
|
||||
case common.WORK_P2P_END:
|
||||
logs.Trace("Remotely Address %s Reply Packet Successfully Received", addr.String())
|
||||
return addr.String(), nil
|
||||
case common.WORK_P2P_CONNECT:
|
||||
go func() {
|
||||
for i := 20; i > 0; i-- {
|
||||
logs.Trace("try send receive success packet to target %s", remoteAddr)
|
||||
if _, err = localConn.WriteTo([]byte(common.WORK_P2P_SUCCESS), addr); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
}()
|
||||
default:
|
||||
continue
|
||||
}
|
||||
ticker.Stop()
|
||||
}
|
||||
ticker.Stop()
|
||||
return "", errors.New("connect to the target failed, maybe the nat type is not support p2p")
|
||||
}
|
||||
|
||||
func newUdpConnByAddr(addr string) (*net.UDPConn, error) {
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
udpConn, err := net.ListenUDP("udp", udpAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return udpConn, nil
|
||||
}
|
||||
|
||||
+42
-55
@@ -11,12 +11,17 @@ import (
|
||||
"github.com/cnlh/nps/vender/github.com/xtaci/kcp"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var LocalServer []*net.TCPListener
|
||||
var udpConn net.Conn
|
||||
var muxSession *mux.Mux
|
||||
var fileServer []*http.Server
|
||||
var (
|
||||
LocalServer []*net.TCPListener
|
||||
udpConn net.Conn
|
||||
muxSession *mux.Mux
|
||||
fileServer []*http.Server
|
||||
lock sync.Mutex
|
||||
hasP2PTry bool
|
||||
)
|
||||
|
||||
func CloseLocalServer() {
|
||||
for _, v := range LocalServer {
|
||||
@@ -39,7 +44,7 @@ func startLocalFileServer(config *config.CommonConfig, t *file.Tunnel, vkey stri
|
||||
logs.Info("start local file system, local path %s, strip prefix %s ,remote port %s ", t.LocalPath, t.StripPre, t.Ports)
|
||||
fileServer = append(fileServer, srv)
|
||||
listener := mux.NewMux(remoteConn.Conn, common.CONN_TCP)
|
||||
logs.Warn(srv.Serve(listener))
|
||||
logs.Error(srv.Serve(listener))
|
||||
}
|
||||
|
||||
func StartLocalServer(l *config.LocalServer, config *config.CommonConfig) error {
|
||||
@@ -52,15 +57,15 @@ func StartLocalServer(l *config.LocalServer, config *config.CommonConfig) error
|
||||
logs.Info("successful start-up of local monitoring, port", l.Port)
|
||||
conn.Accept(listener, func(c net.Conn) {
|
||||
if l.Type == "secret" {
|
||||
processSecret(c, config, l)
|
||||
handleSecret(c, config, l)
|
||||
} else {
|
||||
processP2P(c, config, l)
|
||||
handleP2PVisitor(c, config, l)
|
||||
}
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func processSecret(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
|
||||
func handleSecret(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
|
||||
remoteConn, err := NewConn(config.Tp, config.VKey, config.Server, common.WORK_SECRET, config.ProxyUrl)
|
||||
if err != nil {
|
||||
logs.Error("Local connection server failed ", err.Error())
|
||||
@@ -73,21 +78,34 @@ func processSecret(localTcpConn net.Conn, config *config.CommonConfig, l *config
|
||||
conn.CopyWaitGroup(remoteConn.Conn, localTcpConn, false, false, nil, nil, false, nil)
|
||||
}
|
||||
|
||||
func processP2P(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
|
||||
func handleP2PVisitor(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
|
||||
restart:
|
||||
lock.Lock()
|
||||
if udpConn == nil {
|
||||
newUdpConn(config, l)
|
||||
if !hasP2PTry {
|
||||
hasP2PTry = true
|
||||
newUdpConn(config, l)
|
||||
}
|
||||
if udpConn == nil {
|
||||
lock.Unlock()
|
||||
logs.Notice("new conn, P2P can not penetrate successfully, traffic will be transferred through the server")
|
||||
handleSecret(localTcpConn, config, l)
|
||||
return
|
||||
} else {
|
||||
muxSession = mux.NewMux(udpConn, "kcp")
|
||||
}
|
||||
muxSession = mux.NewMux(udpConn, "kcp")
|
||||
}
|
||||
lock.Unlock()
|
||||
logs.Trace("start trying to connect with the server")
|
||||
nowConn, err := muxSession.NewConn()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
udpConn = nil
|
||||
logs.Error(err, "reconnect......")
|
||||
goto restart
|
||||
return
|
||||
}
|
||||
//TODO just support compress now because there is not tls file in client packages
|
||||
link := conn.NewLink(common.CONN_TCP, l.Target, false, config.Client.Cnf.Compress, localTcpConn.LocalAddr().String())
|
||||
link := conn.NewLink(common.CONN_TCP, l.Target, false, config.Client.Cnf.Compress, localTcpConn.LocalAddr().String(), false)
|
||||
if _, err := conn.NewConn(nowConn).SendInfo(link, ""); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
@@ -111,49 +129,18 @@ func newUdpConn(config *config.CommonConfig, l *config.LocalServer) {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
//与服务端udp建立连接
|
||||
tmpConn, err := common.GetLocalUdpAddr()
|
||||
if err != nil {
|
||||
var localConn net.PacketConn
|
||||
var remoteAddress string
|
||||
if remoteAddress, localConn, err = handleP2PUdp(string(rAddr), crypt.Md5(l.Password), common.WORK_P2P_VISITOR); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
udpTunnel, err := kcp.NewConn(remoteAddress, nil, 150, 3, localConn)
|
||||
if err != nil || udpTunnel == nil {
|
||||
logs.Warn(err)
|
||||
return
|
||||
}
|
||||
//与服务端建立udp连接
|
||||
localAddr, _ := net.ResolveUDPAddr("udp", tmpConn.LocalAddr().String())
|
||||
localConn, err := net.ListenUDP("udp", localAddr)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
localKcpConn, err := kcp.NewConn(string(rAddr), nil, 150, 3, localConn)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
conn.SetUdpSession(localKcpConn)
|
||||
//写入密钥、provider身份
|
||||
if _, err := localKcpConn.Write([]byte(crypt.Md5(l.Password))); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
if _, err := localKcpConn.Write([]byte(common.WORK_P2P_VISITOR)); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
//接收服务端传的visitor地址
|
||||
if b, err := conn.NewConn(localKcpConn).GetShortLenContent(); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
} else {
|
||||
//关闭与服务端连接
|
||||
localConn.Close()
|
||||
//建立新的连接
|
||||
localConn, err = net.ListenUDP("udp", localAddr)
|
||||
udpTunnel, err := kcp.NewConn(string(b), nil, 150, 3, localConn)
|
||||
if err != nil || udpTunnel == nil {
|
||||
logs.Warn(err)
|
||||
return
|
||||
}
|
||||
conn.SetUdpSession(udpTunnel)
|
||||
udpConn = udpTunnel
|
||||
}
|
||||
logs.Trace("successful create a connection with server", remoteAddress)
|
||||
conn.SetUdpSession(udpTunnel)
|
||||
udpConn = udpTunnel
|
||||
}
|
||||
|
||||
+40
-5
@@ -2,11 +2,15 @@ package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/cnlh/nps/client"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/config"
|
||||
"github.com/cnlh/nps/lib/daemon"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/version"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/vender/github.com/ccding/go-stun/stun"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -21,18 +25,33 @@ var (
|
||||
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")
|
||||
localPort = flag.Int("local_port", 2000, "p2p local port")
|
||||
password = flag.String("password", "", "p2p password flag")
|
||||
target = flag.String("target", "", "p2p target")
|
||||
localType = flag.String("local_type", "p2p", "p2p target")
|
||||
logPath = flag.String("log_path", "npc.log", "npc log path")
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
if len(os.Args) > 2 {
|
||||
if len(os.Args) >= 2 {
|
||||
switch os.Args[1] {
|
||||
case "status":
|
||||
path := strings.Replace(os.Args[2], "-config=", "", -1)
|
||||
client.GetTaskStatus(path)
|
||||
if len(os.Args) > 2 {
|
||||
path := strings.Replace(os.Args[2], "-config=", "", -1)
|
||||
client.GetTaskStatus(path)
|
||||
}
|
||||
case "register":
|
||||
flag.CommandLine.Parse(os.Args[2:])
|
||||
client.RegisterLocalIp(*serverAddr, *verifyKey, *connType, *proxyUrl, *registerTime)
|
||||
case "nat":
|
||||
nat, host, err := stun.NewClient().Discover()
|
||||
if err != nil || host == nil {
|
||||
logs.Error("get nat type error", err)
|
||||
return
|
||||
}
|
||||
fmt.Printf("nat type: %s \npublic address: %s\n", nat.String(), host.String())
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
daemon.InitDaemon("npc", common.GetRunPath(), common.GetTmpPath())
|
||||
@@ -41,7 +60,23 @@ func main() {
|
||||
if *logType == "stdout" {
|
||||
logs.SetLogger(logs.AdapterConsole, `{"level":`+*logLevel+`,"color":true}`)
|
||||
} else {
|
||||
logs.SetLogger(logs.AdapterFile, `{"level":`+*logLevel+`,"filename":"npc_log.log","daily":false,"color":true}`)
|
||||
logs.SetLogger(logs.AdapterFile, `{"level":`+*logLevel+`,"filename":"`+*logPath+`","daily":false,"color":true}`)
|
||||
}
|
||||
//p2p or secret command
|
||||
if *password != "" {
|
||||
commonConfig := new(config.CommonConfig)
|
||||
commonConfig.Server = *serverAddr
|
||||
commonConfig.VKey = *verifyKey
|
||||
commonConfig.Tp = *connType
|
||||
localServer := new(config.LocalServer)
|
||||
localServer.Type = *localType
|
||||
localServer.Password = *password
|
||||
localServer.Target = *target
|
||||
localServer.Port = *localPort
|
||||
commonConfig.Client = new(file.Client)
|
||||
commonConfig.Client.Cnf = new(file.Config)
|
||||
client.StartLocalServer(localServer, commonConfig)
|
||||
return
|
||||
}
|
||||
env := common.GetEnvMap()
|
||||
if *serverAddr == "" {
|
||||
@@ -50,7 +85,7 @@ func main() {
|
||||
if *verifyKey == "" {
|
||||
*verifyKey, _ = env["NPC_SERVER_VKEY"]
|
||||
}
|
||||
logs.Info("the version of client is %s", version.VERSION)
|
||||
logs.Info("the version of client is %s, the core version of client is %s", version.VERSION, version.GetVersion())
|
||||
if *verifyKey != "" && *serverAddr != "" && *configPath == "" {
|
||||
for {
|
||||
client.NewRPClient(*serverAddr, *verifyKey, *connType, *proxyUrl, nil).Start()
|
||||
|
||||
+3
-2
@@ -50,7 +50,7 @@ func main() {
|
||||
if *logType == "stdout" {
|
||||
logs.SetLogger(logs.AdapterConsole, `{"level":`+level+`,"color":true}`)
|
||||
} else {
|
||||
logs.SetLogger(logs.AdapterFile, `{"level":`+level+`,"filename":"nps_log.log","daily":false,"color":true}`)
|
||||
logs.SetLogger(logs.AdapterFile, `{"level":`+level+`,"filename":"`+beego.AppConfig.String("log_path")+`","daily":false,"color":true}`)
|
||||
}
|
||||
task := &file.Tunnel{
|
||||
Mode: "webServer",
|
||||
@@ -62,7 +62,8 @@ func main() {
|
||||
}
|
||||
logs.Info("the version of server is %s ,allow client version to be %s", version.VERSION, version.GetVersion())
|
||||
connection.InitConnectionService()
|
||||
crypt.InitTls(filepath.Join(beego.AppPath, "conf", "server.pem"), filepath.Join(beego.AppPath, "conf", "server.key"))
|
||||
crypt.InitTls(filepath.Join(common.GetRunPath(), "conf", "server.pem"), filepath.Join(common.GetRunPath(), "conf", "server.key"))
|
||||
tool.InitAllowPort()
|
||||
tool.StartSystemInfo()
|
||||
server.StartNewServer(bridgePort, task, beego.AppConfig.String("bridge_type"))
|
||||
}
|
||||
|
||||
+1
-1
@@ -44,7 +44,7 @@ server_port=19009
|
||||
[file]
|
||||
mode=file
|
||||
server_port=19008
|
||||
local_path=./
|
||||
local_path=/Users/liuhe/Downloads
|
||||
strip_pre=/web/
|
||||
|
||||
[http]
|
||||
|
||||
+21
-2
@@ -1,6 +1,6 @@
|
||||
appname = nps
|
||||
#Boot mode(dev|pro)
|
||||
runmode = pro
|
||||
runmode = dev
|
||||
|
||||
#HTTP(S) proxy port, no startup if empty
|
||||
http_proxy_ip=0.0.0.0
|
||||
@@ -26,6 +26,7 @@ public_vkey=123
|
||||
|
||||
# log level LevelEmergency->0 LevelAlert->1 LevelCritical->2 LevelError->3 LevelWarning->4 LevelNotice->5 LevelInformational->6 LevelDebug->7
|
||||
log_level=7
|
||||
log_path=nps.log
|
||||
|
||||
#Whether to restrict IP access, true or false or ignore
|
||||
#ip_limit=true
|
||||
@@ -48,4 +49,22 @@ auth_crypt_key =1234567812345678
|
||||
#allow_ports=9001-9009,10001,11000-12000
|
||||
|
||||
#Web management multi-user login
|
||||
#allow_user_login=true
|
||||
allow_user_login=false
|
||||
allow_user_register=false
|
||||
allow_user_change_username=false
|
||||
|
||||
|
||||
#extension
|
||||
allow_flow_limit=false
|
||||
allow_rate_limit=false
|
||||
allow_tunnel_num_limit=false
|
||||
allow_local_proxy=false
|
||||
allow_connection_num_limit=false
|
||||
allow_multi_ip=false
|
||||
system_info_display=false
|
||||
|
||||
#cache
|
||||
http_cache=false
|
||||
http_cache_length=100
|
||||
|
||||
|
||||
|
||||
Vendored
+102
@@ -0,0 +1,102 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Cache is an LRU cache. It is safe for concurrent access.
|
||||
type Cache struct {
|
||||
// MaxEntries is the maximum number of cache entries before
|
||||
// an item is evicted. Zero means no limit.
|
||||
MaxEntries int
|
||||
|
||||
//Execute this callback function when an element is culled
|
||||
OnEvicted func(key Key, value interface{})
|
||||
|
||||
ll *list.List //list
|
||||
cache sync.Map
|
||||
}
|
||||
|
||||
// A Key may be any value that is comparable. See http://golang.org/ref/spec#Comparison_operators
|
||||
type Key interface{}
|
||||
|
||||
type entry struct {
|
||||
key Key
|
||||
value interface{}
|
||||
}
|
||||
|
||||
// New creates a new Cache.
|
||||
// If maxEntries is 0, the cache has no length limit.
|
||||
// that eviction is done by the caller.
|
||||
func New(maxEntries int) *Cache {
|
||||
return &Cache{
|
||||
MaxEntries: maxEntries,
|
||||
ll: list.New(),
|
||||
//cache: make(map[interface{}]*list.Element),
|
||||
}
|
||||
}
|
||||
|
||||
// If the key value already exists, move the key to the front
|
||||
func (c *Cache) Add(key Key, value interface{}) {
|
||||
if ee, ok := c.cache.Load(key); ok {
|
||||
c.ll.MoveToFront(ee.(*list.Element)) // move to the front
|
||||
ee.(*list.Element).Value.(*entry).value = value
|
||||
return
|
||||
}
|
||||
ele := c.ll.PushFront(&entry{key, value})
|
||||
c.cache.Store(key, ele)
|
||||
if c.MaxEntries != 0 && c.ll.Len() > c.MaxEntries { // Remove the oldest element if the limit is exceeded
|
||||
c.RemoveOldest()
|
||||
}
|
||||
}
|
||||
|
||||
// Get looks up a key's value from the cache.
|
||||
func (c *Cache) Get(key Key) (value interface{}, ok bool) {
|
||||
if ele, hit := c.cache.Load(key); hit {
|
||||
c.ll.MoveToFront(ele.(*list.Element))
|
||||
return ele.(*list.Element).Value.(*entry).value, true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Remove removes the provided key from the cache.
|
||||
func (c *Cache) Remove(key Key) {
|
||||
if ele, hit := c.cache.Load(key); hit {
|
||||
c.removeElement(ele.(*list.Element))
|
||||
}
|
||||
}
|
||||
|
||||
// RemoveOldest removes the oldest item from the cache.
|
||||
func (c *Cache) RemoveOldest() {
|
||||
ele := c.ll.Back()
|
||||
if ele != nil {
|
||||
c.removeElement(ele)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cache) removeElement(e *list.Element) {
|
||||
c.ll.Remove(e)
|
||||
kv := e.Value.(*entry)
|
||||
c.cache.Delete(kv.key)
|
||||
if c.OnEvicted != nil {
|
||||
c.OnEvicted(kv.key, kv.value)
|
||||
}
|
||||
}
|
||||
|
||||
// Len returns the number of items in the cache.
|
||||
func (c *Cache) Len() int {
|
||||
return c.ll.Len()
|
||||
}
|
||||
|
||||
// Clear purges all stored items from the cache.
|
||||
func (c *Cache) Clear() {
|
||||
if c.OnEvicted != nil {
|
||||
c.cache.Range(func(key, value interface{}) bool {
|
||||
kv := value.(*list.Element).Value.(*entry)
|
||||
c.OnEvicted(kv.key, kv.value)
|
||||
return true
|
||||
})
|
||||
}
|
||||
c.ll = nil
|
||||
}
|
||||
@@ -13,6 +13,10 @@ const (
|
||||
WORK_P2P = "p2pm"
|
||||
WORK_P2P_VISITOR = "p2pv"
|
||||
WORK_P2P_PROVIDER = "p2pp"
|
||||
WORK_P2P_CONNECT = "p2pc"
|
||||
WORK_P2P_SUCCESS = "p2ps"
|
||||
WORK_P2P_END = "p2pe"
|
||||
WORK_P2P_LAST = "p2pl"
|
||||
WORK_STATUS = "stus"
|
||||
RES_MSG = "msg0"
|
||||
RES_CLOSE = "clse"
|
||||
|
||||
@@ -218,6 +218,7 @@ func GetPorts(p string) []int {
|
||||
return ps
|
||||
}
|
||||
|
||||
//is the string a port
|
||||
func IsPort(p string) bool {
|
||||
pi, err := strconv.Atoi(p)
|
||||
if err != nil {
|
||||
@@ -229,6 +230,7 @@ func IsPort(p string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
//if the s is just a port,return 127.0.0.1:s
|
||||
func FormatAddress(s string) string {
|
||||
if strings.Contains(s, ":") {
|
||||
return s
|
||||
@@ -236,6 +238,7 @@ func FormatAddress(s string) string {
|
||||
return "127.0.0.1:" + s
|
||||
}
|
||||
|
||||
//get address from the complete address
|
||||
func GetIpByAddr(addr string) string {
|
||||
arr := strings.Split(addr, ":")
|
||||
return arr[0]
|
||||
@@ -279,6 +282,7 @@ func GetLocalUdpAddr() (net.Conn, error) {
|
||||
return tmpConn, tmpConn.Close()
|
||||
}
|
||||
|
||||
//parse template
|
||||
func ParseStr(str string) (string, error) {
|
||||
tmp := template.New("npc")
|
||||
var err error
|
||||
@@ -305,6 +309,7 @@ func GetEnvMap() map[string]string {
|
||||
return m
|
||||
}
|
||||
|
||||
//throw the empty element of the string array
|
||||
func TrimArr(arr []string) []string {
|
||||
newArr := make([]string, 0)
|
||||
for _, v := range arr {
|
||||
@@ -315,6 +320,7 @@ func TrimArr(arr []string) []string {
|
||||
return newArr
|
||||
}
|
||||
|
||||
//
|
||||
func IsArrContains(arr []string, val string) bool {
|
||||
if arr == nil {
|
||||
return false
|
||||
@@ -327,6 +333,7 @@ func IsArrContains(arr []string, val string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
//remove value from string array
|
||||
func RemoveArrVal(arr []string, val string) []string {
|
||||
for k, v := range arr {
|
||||
if v == val {
|
||||
@@ -337,6 +344,7 @@ func RemoveArrVal(arr []string, val string) []string {
|
||||
return arr
|
||||
}
|
||||
|
||||
//convert bytes to num
|
||||
func BytesToNum(b []byte) int {
|
||||
var str string
|
||||
for i := 0; i < len(b); i++ {
|
||||
@@ -346,6 +354,7 @@ func BytesToNum(b []byte) int {
|
||||
return int(x)
|
||||
}
|
||||
|
||||
//get the length of the sync map
|
||||
func GeSynctMapLen(m sync.Map) int {
|
||||
var c int
|
||||
m.Range(func(key, value interface{}) bool {
|
||||
@@ -354,3 +363,12 @@ func GeSynctMapLen(m sync.Map) int {
|
||||
})
|
||||
return c
|
||||
}
|
||||
|
||||
func GetExtFromPath(path string) string {
|
||||
s := strings.Split(path, ".")
|
||||
re, err := regexp.Compile(`(\w+)`)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(re.Find([]byte(s[0])))
|
||||
}
|
||||
|
||||
@@ -384,3 +384,17 @@ func GetConn(conn net.Conn, cpt, snappy bool, rt *rate.Rate, isServer bool) (io.
|
||||
}
|
||||
return rate.NewRateConn(conn, rt)
|
||||
}
|
||||
|
||||
type LenConn struct {
|
||||
conn io.Writer
|
||||
Len int
|
||||
}
|
||||
|
||||
func NewLenConn(conn io.Writer) *LenConn {
|
||||
return &LenConn{conn: conn}
|
||||
}
|
||||
func (c *LenConn) Write(p []byte) (n int, err error) {
|
||||
n, err = c.conn.Write(p)
|
||||
c.Len += n
|
||||
return
|
||||
}
|
||||
|
||||
+3
-1
@@ -17,15 +17,17 @@ type Link struct {
|
||||
Host string //目标
|
||||
Crypt bool //加密
|
||||
Compress bool
|
||||
LocalProxy bool
|
||||
RemoteAddr string
|
||||
}
|
||||
|
||||
func NewLink(connType string, host string, crypt bool, compress bool, remoteAddr string) *Link {
|
||||
func NewLink(connType string, host string, crypt bool, compress bool, remoteAddr string, localProxy bool) *Link {
|
||||
return &Link{
|
||||
RemoteAddr: remoteAddr,
|
||||
ConnType: connType,
|
||||
Host: host,
|
||||
Crypt: crypt,
|
||||
Compress: compress,
|
||||
LocalProxy: localProxy,
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -64,7 +64,7 @@ func (s *DbUtils) GetClientList(start, length int, search, sort, order string, c
|
||||
}
|
||||
cnt++
|
||||
if start--; start < 0 {
|
||||
if length--; length > 0 {
|
||||
if length--; length >= 0 {
|
||||
list = append(list, v)
|
||||
}
|
||||
}
|
||||
@@ -187,7 +187,7 @@ func (s *DbUtils) GetHost(start, length int, id int, search string) ([]*Host, in
|
||||
if id == 0 || v.Client.Id == id {
|
||||
cnt++
|
||||
if start--; start < 0 {
|
||||
if length--; length > 0 {
|
||||
if length--; length >= 0 {
|
||||
list = append(list, v)
|
||||
}
|
||||
}
|
||||
|
||||
+16
-3
@@ -48,6 +48,7 @@ type Client struct {
|
||||
WebUserName string //the username of web login
|
||||
WebPassword string //the password of web login
|
||||
ConfigConnAllow bool //is allow connected by config file
|
||||
MaxTunnelNum int
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
@@ -97,6 +98,17 @@ func (s *Client) HasTunnel(t *Tunnel) (exist bool) {
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Client) GetTunnelNum() (num int) {
|
||||
GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
v := value.(*Tunnel)
|
||||
if v.Client.Id == s.Id {
|
||||
num++
|
||||
}
|
||||
return true
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Client) HasHost(h *Host) bool {
|
||||
var has bool
|
||||
GetDb().JsonDb.Hosts.Range(func(key, value interface{}) bool {
|
||||
@@ -164,9 +176,10 @@ type Host struct {
|
||||
}
|
||||
|
||||
type Target struct {
|
||||
nowIndex int
|
||||
TargetStr string
|
||||
TargetArr []string
|
||||
nowIndex int
|
||||
TargetStr string
|
||||
TargetArr []string
|
||||
LocalProxy bool
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package version
|
||||
|
||||
const VERSION = "0.21.2"
|
||||
const VERSION = "0.22.5"
|
||||
|
||||
// Compulsory minimum version, Minimum downward compatibility to this version
|
||||
func GetVersion() string {
|
||||
|
||||
+10
-6
@@ -17,7 +17,7 @@ type Service interface {
|
||||
Close() error
|
||||
}
|
||||
|
||||
//Server BaseServer struct
|
||||
//BaseServer struct
|
||||
type BaseServer struct {
|
||||
id int
|
||||
bridge *bridge.Bridge
|
||||
@@ -35,6 +35,7 @@ func NewBaseServer(bridge *bridge.Bridge, task *file.Tunnel) *BaseServer {
|
||||
}
|
||||
}
|
||||
|
||||
//add the flow
|
||||
func (s *BaseServer) FlowAdd(in, out int64) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
@@ -42,6 +43,7 @@ func (s *BaseServer) FlowAdd(in, out int64) {
|
||||
s.task.Flow.InletFlow += in
|
||||
}
|
||||
|
||||
//change the flow
|
||||
func (s *BaseServer) FlowAddHost(host *file.Host, in, out int64) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
@@ -49,12 +51,13 @@ func (s *BaseServer) FlowAddHost(host *file.Host, in, out int64) {
|
||||
host.Flow.InletFlow += in
|
||||
}
|
||||
|
||||
//write fail bytes to the connection
|
||||
func (s *BaseServer) writeConnFail(c net.Conn) {
|
||||
c.Write([]byte(common.ConnectionFailBytes))
|
||||
c.Write(s.errorContent)
|
||||
}
|
||||
|
||||
//权限认证
|
||||
//auth check
|
||||
func (s *BaseServer) auth(r *http.Request, c *conn.Conn, u, p string) error {
|
||||
if u != "" && p != "" && !common.CheckAuth(r, u, p) {
|
||||
c.Write([]byte(common.UnauthorizedBytes))
|
||||
@@ -64,6 +67,7 @@ func (s *BaseServer) auth(r *http.Request, c *conn.Conn, u, p string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
//check flow limit of the client ,and decrease the allow num of client
|
||||
func (s *BaseServer) CheckFlowAndConnNum(client *file.Client) error {
|
||||
if client.Flow.FlowLimit > 0 && (client.Flow.FlowLimit<<20) < (client.Flow.ExportFlow+client.Flow.InletFlow) {
|
||||
return errors.New("Traffic exceeded")
|
||||
@@ -74,10 +78,10 @@ func (s *BaseServer) CheckFlowAndConnNum(client *file.Client) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
//与客户端建立通道
|
||||
func (s *BaseServer) DealClient(c *conn.Conn, client *file.Client, addr string, rb []byte, tp string, f func(), flow *file.Flow) error {
|
||||
link := conn.NewLink(tp, addr, client.Cnf.Crypt, client.Cnf.Compress, c.Conn.RemoteAddr().String())
|
||||
if target, err := s.bridge.SendLinkInfo(client.Id, link, c.Conn.RemoteAddr().String(), s.task); err != nil {
|
||||
//create a new connection and start bytes copying
|
||||
func (s *BaseServer) DealClient(c *conn.Conn, client *file.Client, addr string, rb []byte, tp string, f func(), flow *file.Flow, localProxy bool) error {
|
||||
link := conn.NewLink(tp, addr, client.Cnf.Crypt, client.Cnf.Compress, c.Conn.RemoteAddr().String(), localProxy)
|
||||
if target, err := s.bridge.SendLinkInfo(client.Id, link, s.task); err != nil {
|
||||
logs.Warn("get connection from client id %d error %s", client.Id, err.Error())
|
||||
c.Close()
|
||||
return err
|
||||
|
||||
+78
-32
@@ -4,11 +4,11 @@ import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"github.com/cnlh/nps/bridge"
|
||||
"github.com/cnlh/nps/lib/cache"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/server/connection"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"io"
|
||||
"net"
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
@@ -27,12 +28,13 @@ type httpServer struct {
|
||||
httpServer *http.Server
|
||||
httpsServer *http.Server
|
||||
httpsListener net.Listener
|
||||
useCache bool
|
||||
cache *cache.Cache
|
||||
cacheLen int
|
||||
}
|
||||
|
||||
func NewHttp(bridge *bridge.Bridge, c *file.Tunnel) *httpServer {
|
||||
httpPort, _ := beego.AppConfig.Int("http_proxy_port")
|
||||
httpsPort, _ := beego.AppConfig.Int("https_proxy_port")
|
||||
return &httpServer{
|
||||
func NewHttp(bridge *bridge.Bridge, c *file.Tunnel, httpPort, httpsPort int, useCache bool, cacheLen int) *httpServer {
|
||||
httpServer := &httpServer{
|
||||
BaseServer: BaseServer{
|
||||
task: c,
|
||||
bridge: bridge,
|
||||
@@ -40,7 +42,13 @@ func NewHttp(bridge *bridge.Bridge, c *file.Tunnel) *httpServer {
|
||||
},
|
||||
httpPort: httpPort,
|
||||
httpsPort: httpsPort,
|
||||
useCache: useCache,
|
||||
cacheLen: cacheLen,
|
||||
}
|
||||
if useCache {
|
||||
httpServer.cache = cache.New(cacheLen)
|
||||
}
|
||||
return httpServer
|
||||
}
|
||||
|
||||
func (s *httpServer) Start() error {
|
||||
@@ -71,7 +79,7 @@ func (s *httpServer) Start() error {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
logs.Error(NewHttpsServer(s.httpsListener, s.bridge).Start())
|
||||
logs.Error(NewHttpsServer(s.httpsListener, s.bridge, s.useCache, s.cacheLen).Start())
|
||||
}()
|
||||
}
|
||||
return nil
|
||||
@@ -100,12 +108,12 @@ func (s *httpServer) handleTunneling(w http.ResponseWriter, r *http.Request) {
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
||||
}
|
||||
s.process(conn.NewConn(c), r)
|
||||
s.httpHandle(conn.NewConn(c), r)
|
||||
}
|
||||
|
||||
func (s *httpServer) process(c *conn.Conn, r *http.Request) {
|
||||
func (s *httpServer) httpHandle(c *conn.Conn, r *http.Request) {
|
||||
var (
|
||||
isConn = true
|
||||
isConn = false
|
||||
host *file.Host
|
||||
target net.Conn
|
||||
lastHost *file.Host
|
||||
@@ -114,7 +122,8 @@ func (s *httpServer) process(c *conn.Conn, r *http.Request) {
|
||||
scheme = r.URL.Scheme
|
||||
lk *conn.Link
|
||||
targetAddr string
|
||||
wg sync.WaitGroup
|
||||
readReq bool
|
||||
reqCh = make(chan *http.Request)
|
||||
)
|
||||
if host, err = file.GetDb().GetInfoByHost(r.Host, r); err != nil {
|
||||
logs.Notice("the url %s %s %s can't be parsed!", r.URL.Scheme, r.Host, r.RequestURI)
|
||||
@@ -126,7 +135,6 @@ func (s *httpServer) process(c *conn.Conn, r *http.Request) {
|
||||
return
|
||||
}
|
||||
defer host.Client.AddConn()
|
||||
logs.Trace("new %s connection,clientId %d,host %s,url %s,remote address %s", r.URL.Scheme, host.Client.Id, r.Host, r.URL, r.RemoteAddr)
|
||||
lastHost = host
|
||||
for {
|
||||
start:
|
||||
@@ -139,22 +147,42 @@ func (s *httpServer) process(c *conn.Conn, r *http.Request) {
|
||||
logs.Warn(err.Error())
|
||||
break
|
||||
}
|
||||
lk = conn.NewLink(common.CONN_TCP, targetAddr, host.Client.Cnf.Crypt, host.Client.Cnf.Compress, r.RemoteAddr)
|
||||
if target, err = s.bridge.SendLinkInfo(host.Client.Id, lk, c.Conn.RemoteAddr().String(), nil); err != nil {
|
||||
lk = conn.NewLink(common.CONN_TCP, targetAddr, host.Client.Cnf.Crypt, host.Client.Cnf.Compress, r.RemoteAddr, host.Target.LocalProxy)
|
||||
if target, err = s.bridge.SendLinkInfo(host.Client.Id, lk, nil); err != nil {
|
||||
logs.Notice("connect to target %s error %s", lk.Host, err)
|
||||
break
|
||||
}
|
||||
connClient = conn.GetConn(target, lk.Crypt, lk.Compress, host.Client.Rate, true)
|
||||
isConn = false
|
||||
go func() {
|
||||
wg.Add(1)
|
||||
w, _ := common.CopyBuffer(c, connClient)
|
||||
host.Flow.Add(0, w)
|
||||
c.Close()
|
||||
target.Close()
|
||||
wg.Done()
|
||||
defer connClient.Close()
|
||||
defer c.Close()
|
||||
for {
|
||||
if resp, err := http.ReadResponse(bufio.NewReader(connClient), r); err != nil {
|
||||
return
|
||||
} else {
|
||||
r := <-reqCh
|
||||
//if the cache is start and the response is in the extension,store the response to the cache list
|
||||
if s.useCache && strings.Contains(r.URL.Path, ".") {
|
||||
b, err := httputil.DumpResponse(resp, true)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.Write(b)
|
||||
host.Flow.Add(0, int64(len(b)))
|
||||
s.cache.Add(filepath.Join(host.Host, r.URL.Path), b)
|
||||
} else {
|
||||
lenConn := conn.NewLenConn(c)
|
||||
if err := resp.Write(lenConn); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
host.Flow.Add(0, int64(lenConn.Len))
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
} else if readReq {
|
||||
r, err = http.ReadRequest(bufio.NewReader(c))
|
||||
if err != nil {
|
||||
break
|
||||
@@ -167,7 +195,6 @@ func (s *httpServer) process(c *conn.Conn, r *http.Request) {
|
||||
if r.Method == "OST" {
|
||||
r.Method = "POST"
|
||||
}
|
||||
logs.Trace("new %s connection,clientId %d,host %s,url %s,remote address %s", r.URL.Scheme, host.Client.Id, r.Host, r.URL, r.RemoteAddr)
|
||||
if hostTmp, err := file.GetDb().GetInfoByHost(r.Host, r); err != nil {
|
||||
logs.Notice("the url %s %s %s can't be parsed!", r.URL.Scheme, r.Host, r.RequestURI)
|
||||
break
|
||||
@@ -178,30 +205,49 @@ func (s *httpServer) process(c *conn.Conn, r *http.Request) {
|
||||
goto start
|
||||
}
|
||||
}
|
||||
//if the cache start and the request is in the cache list, return the cache
|
||||
if s.useCache {
|
||||
if v, ok := s.cache.Get(filepath.Join(host.Host, r.URL.Path)); ok {
|
||||
n, err := c.Write(v.([]byte))
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
logs.Trace("%s request, method %s, host %s, url %s, remote address %s, return cache", r.URL.Scheme, r.Method, r.Host, r.URL.Path, c.RemoteAddr().String())
|
||||
host.Flow.Add(0, int64(n))
|
||||
//if return cache and does not create a new conn with client and Connection is not set or close, close the connection.
|
||||
if connClient == nil && (strings.ToLower(r.Header.Get("Connection")) == "close" || strings.ToLower(r.Header.Get("Connection")) == "") {
|
||||
c.Close()
|
||||
break
|
||||
}
|
||||
readReq = true
|
||||
goto start
|
||||
}
|
||||
}
|
||||
if connClient == nil {
|
||||
isConn = true
|
||||
goto start
|
||||
}
|
||||
readReq = true
|
||||
//change the host and header and set proxy setting
|
||||
common.ChangeHostAndHeader(r, host.HostChange, host.HeaderChange, c.Conn.RemoteAddr().String())
|
||||
b, err := httputil.DumpRequest(r, false)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
logs.Trace("%s request, method %s, host %s, url %s, remote address %s, target %s", r.URL.Scheme, r.Method, r.Host, r.RequestURI, r.RemoteAddr, lk.Host)
|
||||
logs.Trace("%s request, method %s, host %s, url %s, remote address %s, target %s", r.URL.Scheme, r.Method, r.Host, r.URL.Path, c.RemoteAddr().String(), lk.Host)
|
||||
//write
|
||||
connClient.Write(b)
|
||||
if bodyLen, err := common.CopyBuffer(connClient, r.Body); err != nil {
|
||||
lenConn := conn.NewLenConn(connClient)
|
||||
if err := r.Write(lenConn); err != nil {
|
||||
logs.Error(err)
|
||||
break
|
||||
} else {
|
||||
host.Flow.Add(int64(len(b))+bodyLen, 0)
|
||||
}
|
||||
host.Flow.Add(int64(lenConn.Len), 0)
|
||||
reqCh <- r
|
||||
}
|
||||
end:
|
||||
if isConn {
|
||||
if !readReq {
|
||||
s.writeConnFail(c.Conn)
|
||||
}
|
||||
c.Close()
|
||||
if target != nil {
|
||||
target.Close()
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func (s *httpServer) NewServer(port int, scheme string) *http.Server {
|
||||
|
||||
+20
-2
@@ -2,6 +2,7 @@ package proxy
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/bridge"
|
||||
"github.com/cnlh/nps/lib/cache"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
@@ -21,12 +22,17 @@ type HttpsServer struct {
|
||||
httpsListenerMap sync.Map
|
||||
}
|
||||
|
||||
func NewHttpsServer(l net.Listener, bridge *bridge.Bridge) *HttpsServer {
|
||||
func NewHttpsServer(l net.Listener, bridge *bridge.Bridge, useCache bool, cacheLen int) *HttpsServer {
|
||||
https := &HttpsServer{listener: l}
|
||||
https.bridge = bridge
|
||||
https.useCache = useCache
|
||||
if useCache {
|
||||
https.cache = cache.New(cacheLen)
|
||||
}
|
||||
return https
|
||||
}
|
||||
|
||||
//start https server
|
||||
func (https *HttpsServer) Start() error {
|
||||
if b, err := beego.AppConfig.Bool("https_just_proxy"); err == nil && b {
|
||||
conn.Accept(https.listener, func(c net.Conn) {
|
||||
@@ -81,16 +87,19 @@ func (https *HttpsServer) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// close
|
||||
func (https *HttpsServer) Close() error {
|
||||
return https.listener.Close()
|
||||
}
|
||||
|
||||
// new https server by cert and key file
|
||||
func (https *HttpsServer) NewHttps(l net.Listener, certFile string, keyFile string) {
|
||||
go func() {
|
||||
logs.Error(https.NewServer(0, "https").ServeTLS(l, certFile, keyFile))
|
||||
}()
|
||||
}
|
||||
|
||||
//handle the https which is just proxy to other client
|
||||
func (https *HttpsServer) handleHttps(c net.Conn) {
|
||||
hostName, rb := GetServerNameFromClientHello(c)
|
||||
var targetAddr string
|
||||
@@ -116,7 +125,7 @@ func (https *HttpsServer) handleHttps(c net.Conn) {
|
||||
logs.Warn(err.Error())
|
||||
}
|
||||
logs.Trace("new https connection,clientId %d,host %s,remote address %s", host.Client.Id, r.Host, c.RemoteAddr().String())
|
||||
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Flow)
|
||||
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Flow, host.Target.LocalProxy)
|
||||
}
|
||||
|
||||
type HttpsListener struct {
|
||||
@@ -124,10 +133,12 @@ type HttpsListener struct {
|
||||
parentListener net.Listener
|
||||
}
|
||||
|
||||
// https listener
|
||||
func NewHttpsListener(l net.Listener) *HttpsListener {
|
||||
return &HttpsListener{parentListener: l, acceptConn: make(chan *conn.Conn)}
|
||||
}
|
||||
|
||||
// accept
|
||||
func (httpsListener *HttpsListener) Accept() (net.Conn, error) {
|
||||
httpsConn := <-httpsListener.acceptConn
|
||||
if httpsConn == nil {
|
||||
@@ -136,14 +147,17 @@ func (httpsListener *HttpsListener) Accept() (net.Conn, error) {
|
||||
return httpsConn, nil
|
||||
}
|
||||
|
||||
// close
|
||||
func (httpsListener *HttpsListener) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// addr
|
||||
func (httpsListener *HttpsListener) Addr() net.Addr {
|
||||
return httpsListener.parentListener.Addr()
|
||||
}
|
||||
|
||||
// get server name from connection by read client hello bytes
|
||||
func GetServerNameFromClientHello(c net.Conn) (string, []byte) {
|
||||
buf := make([]byte, 4096)
|
||||
data := make([]byte, 4096)
|
||||
@@ -151,12 +165,16 @@ func GetServerNameFromClientHello(c net.Conn) (string, []byte) {
|
||||
if err != nil {
|
||||
return "", nil
|
||||
}
|
||||
if n < 42 {
|
||||
return "", nil
|
||||
}
|
||||
copy(data, buf[:n])
|
||||
clientHello := new(crypt.ClientHelloMsg)
|
||||
clientHello.Unmarshal(data[5:n])
|
||||
return clientHello.GetServerName(), buf[:n]
|
||||
}
|
||||
|
||||
// build https request
|
||||
func buildHttpsRequest(hostName string) *http.Request {
|
||||
r := new(http.Request)
|
||||
r.RequestURI = "/"
|
||||
|
||||
+32
-21
@@ -1,8 +1,10 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
@@ -15,10 +17,12 @@ type P2PServer struct {
|
||||
}
|
||||
|
||||
type p2p struct {
|
||||
provider *conn.Conn
|
||||
visitor *conn.Conn
|
||||
visitorAddr string
|
||||
providerAddr string
|
||||
provider *conn.Conn
|
||||
visitor *conn.Conn
|
||||
visitorAddr string
|
||||
providerAddr string
|
||||
providerNatType int32
|
||||
visitorNatType int32
|
||||
}
|
||||
|
||||
func NewP2PServer(p2pPort int) *P2PServer {
|
||||
@@ -35,49 +39,56 @@ func (s *P2PServer) Start() error {
|
||||
}
|
||||
|
||||
func (s *P2PServer) p2pProcess(c *conn.Conn) {
|
||||
//获取密钥
|
||||
var (
|
||||
f string
|
||||
b []byte
|
||||
err error
|
||||
v *p2p
|
||||
ok bool
|
||||
f string
|
||||
b []byte
|
||||
err error
|
||||
v *p2p
|
||||
ok bool
|
||||
natType int32
|
||||
)
|
||||
if b, err = c.GetShortContent(32); err != nil {
|
||||
return
|
||||
}
|
||||
//获取角色
|
||||
//get role
|
||||
if f, err = c.ReadFlag(); err != nil {
|
||||
return
|
||||
}
|
||||
//get nat type
|
||||
if err := binary.Read(c, binary.LittleEndian, &natType); err != nil {
|
||||
return
|
||||
}
|
||||
if v, ok = s.p2p[string(b)]; !ok {
|
||||
v = new(p2p)
|
||||
s.p2p[string(b)] = v
|
||||
}
|
||||
logs.Trace("new p2p connection ,role %s , password %s, nat type %s ,local address %s", f, string(b), strconv.Itoa(int(natType)), c.RemoteAddr().String())
|
||||
//存储
|
||||
if f == common.WORK_P2P_VISITOR {
|
||||
v.visitorAddr = c.Conn.RemoteAddr().String()
|
||||
v.visitorNatType = natType
|
||||
v.visitor = c
|
||||
for {
|
||||
time.Sleep(time.Second)
|
||||
for i := 20; i > 0; i-- {
|
||||
if v.provider != nil {
|
||||
v.provider.WriteLenContent([]byte(v.visitorAddr))
|
||||
binary.Write(v.provider, binary.LittleEndian, v.visitorNatType)
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
if _, err := v.provider.ReadFlag(); err == nil {
|
||||
v.visitor.WriteLenContent([]byte(v.providerAddr))
|
||||
delete(s.p2p, string(b))
|
||||
} else {
|
||||
}
|
||||
v.provider = nil
|
||||
} else {
|
||||
v.providerAddr = c.Conn.RemoteAddr().String()
|
||||
v.providerNatType = natType
|
||||
v.provider = c
|
||||
for {
|
||||
time.Sleep(time.Second)
|
||||
for i := 20; i > 0; i-- {
|
||||
if v.visitor != nil {
|
||||
v.provider.WriteLenContent([]byte(v.visitorAddr))
|
||||
v.visitor.WriteLenContent([]byte(v.providerAddr))
|
||||
binary.Write(v.visitor, binary.LittleEndian, v.providerNatType)
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
v.visitor = nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,7 +142,7 @@ func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) {
|
||||
}
|
||||
s.DealClient(conn.NewConn(c), s.task.Client, addr, nil, ltype, func() {
|
||||
s.sendReply(c, succeeded)
|
||||
}, s.task.Flow)
|
||||
}, s.task.Flow, s.task.Target.LocalProxy)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -94,7 +94,7 @@ func ProcessTunnel(c *conn.Conn, s *TunnelModeServer) error {
|
||||
logs.Warn("tcp port %d ,client id %d,task id %d connect error %s", s.task.Port, s.task.Client.Id, s.task.Id, err.Error())
|
||||
return err
|
||||
}
|
||||
return s.DealClient(c, s.task.Client, targetAddr, nil, common.CONN_TCP, nil, s.task.Flow)
|
||||
return s.DealClient(c, s.task.Client, targetAddr, nil, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy)
|
||||
}
|
||||
|
||||
//http proxy
|
||||
@@ -112,5 +112,5 @@ func ProcessHttp(c *conn.Conn, s *TunnelModeServer) error {
|
||||
if err := s.auth(r, c, s.task.Client.Cnf.U, s.task.Client.Cnf.P); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.DealClient(c, s.task.Client, addr, rb, common.CONN_TCP, nil, s.task.Flow)
|
||||
return s.DealClient(c, s.task.Client, addr, rb, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy)
|
||||
}
|
||||
|
||||
+2
-2
@@ -54,8 +54,8 @@ func (s *UdpModeServer) process(addr *net.UDPAddr, data []byte) {
|
||||
return
|
||||
}
|
||||
defer s.task.Client.AddConn()
|
||||
link := conn.NewLink(common.CONN_UDP, s.task.Target.TargetStr, s.task.Client.Cnf.Crypt, s.task.Client.Cnf.Compress, addr.String())
|
||||
if target, err := s.bridge.SendLinkInfo(s.task.Client.Id, link, addr.String(), s.task); err != nil {
|
||||
link := conn.NewLink(common.CONN_UDP, s.task.Target.TargetStr, s.task.Client.Cnf.Crypt, s.task.Client.Cnf.Compress, addr.String(), s.task.Target.LocalProxy)
|
||||
if target, err := s.bridge.SendLinkInfo(s.task.Client.Id, link, s.task); err != nil {
|
||||
return
|
||||
} else {
|
||||
s.task.Flow.Add(int64(len(data)), 0)
|
||||
|
||||
+8
-7
@@ -66,11 +66,8 @@ func DealBridgeTask() {
|
||||
case s := <-Bridge.SecretChan:
|
||||
logs.Trace("New secret connection, addr", s.Conn.Conn.RemoteAddr())
|
||||
if t := file.GetDb().GetTaskByMd5Password(s.Password); t != nil {
|
||||
if !t.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.Client, t.Target.TargetStr, nil, common.CONN_TCP, nil, t.Flow)
|
||||
if t.Status {
|
||||
go proxy.NewBaseServer(Bridge, t).DealClient(s.Conn, t.Client, t.Target.TargetStr, nil, common.CONN_TCP, nil, t.Flow, t.Target.LocalProxy)
|
||||
} else {
|
||||
s.Conn.Close()
|
||||
logs.Trace("This key %s cannot be processed,status is close", s.Password)
|
||||
@@ -140,7 +137,11 @@ func NewMode(Bridge *bridge.Bridge, c *file.Tunnel) proxy.Service {
|
||||
AddTask(t)
|
||||
service = proxy.NewWebServer(Bridge)
|
||||
case "httpHostServer":
|
||||
service = proxy.NewHttp(Bridge, c)
|
||||
httpPort, _ := beego.AppConfig.Int("http_proxy_port")
|
||||
httpsPort, _ := beego.AppConfig.Int("https_proxy_port")
|
||||
useCache, _ := beego.AppConfig.Bool("http_cache")
|
||||
cacheLen, _ := beego.AppConfig.Int("http_cache_length")
|
||||
service = proxy.NewHttp(Bridge, c, httpPort, httpsPort, useCache, cacheLen)
|
||||
}
|
||||
return service
|
||||
}
|
||||
@@ -241,7 +242,7 @@ func GetTunnel(start, length int, typeVal string, clientId int, search string) (
|
||||
v.Client.IsConnect = false
|
||||
}
|
||||
if start--; start < 0 {
|
||||
if length--; length > 0 {
|
||||
if length--; length >= 0 {
|
||||
if _, ok := RunList[v.Id]; ok {
|
||||
v.RunStatus = true
|
||||
} else {
|
||||
|
||||
+2
-2
@@ -51,10 +51,10 @@ func TestServerConfig() {
|
||||
if port, err := strconv.Atoi(p); err != nil {
|
||||
log.Fatalln("get https port error", err)
|
||||
} else {
|
||||
if !common.FileExists(filepath.Join(beego.AppPath, beego.AppConfig.String("pemPath"))) {
|
||||
if !common.FileExists(filepath.Join(common.GetRunPath(), beego.AppConfig.String("pemPath"))) {
|
||||
log.Fatalf("ssl certFile %s is not exist", beego.AppConfig.String("pemPath"))
|
||||
}
|
||||
if !common.FileExists(filepath.Join(beego.AppPath, beego.AppConfig.String("ketPath"))) {
|
||||
if !common.FileExists(filepath.Join(common.GetRunPath(), beego.AppConfig.String("ketPath"))) {
|
||||
log.Fatalf("ssl keyFile %s is not exist", beego.AppConfig.String("pemPath"))
|
||||
}
|
||||
isInArr(&postTcpArr, port, "http port", "tcp")
|
||||
|
||||
@@ -17,9 +17,11 @@ var (
|
||||
ServerStatus []map[string]interface{}
|
||||
)
|
||||
|
||||
func init() {
|
||||
ServerStatus = make([]map[string]interface{}, 0, 1500)
|
||||
go getSeverStatus()
|
||||
func StartSystemInfo() {
|
||||
if b, err := beego.AppConfig.Bool("system_info_display"); err == nil && b {
|
||||
ServerStatus = make([]map[string]interface{}, 0, 1500)
|
||||
go getSeverStatus()
|
||||
}
|
||||
}
|
||||
|
||||
func InitAllowPort() {
|
||||
@@ -86,5 +88,3 @@ func getSeverStatus() {
|
||||
ServerStatus = append(ServerStatus, m)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
# Temporary files for running example
|
||||
go-stun
|
||||
|
||||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
Executable
+191
@@ -0,0 +1,191 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, and
|
||||
distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright
|
||||
owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all other entities
|
||||
that control, are controlled by, or are under common control with that entity.
|
||||
For the purposes of this definition, "control" means (i) the power, direct or
|
||||
indirect, to cause the direction or management of such entity, whether by
|
||||
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity exercising
|
||||
permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications, including
|
||||
but not limited to software source code, documentation source, and configuration
|
||||
files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical transformation or
|
||||
translation of a Source form, including but not limited to compiled object code,
|
||||
generated documentation, and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or Object form, made
|
||||
available under the License, as indicated by a copyright notice that is included
|
||||
in or attached to the work (an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object form, that
|
||||
is based on (or derived from) the Work and for which the editorial revisions,
|
||||
annotations, elaborations, or other modifications represent, as a whole, an
|
||||
original work of authorship. For the purposes of this License, Derivative Works
|
||||
shall not include works that remain separable from, or merely link (or bind by
|
||||
name) to the interfaces of, the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including the original version
|
||||
of the Work and any modifications or additions to that Work or Derivative Works
|
||||
thereof, that is intentionally submitted to Licensor for inclusion in the Work
|
||||
by the copyright owner or by an individual or Legal Entity authorized to submit
|
||||
on behalf of the copyright owner. For the purposes of this definition,
|
||||
"submitted" means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems, and
|
||||
issue tracking systems that are managed by, or on behalf of, the Licensor for
|
||||
the purpose of discussing and improving the Work, but excluding communication
|
||||
that is conspicuously marked or otherwise designated in writing by the copyright
|
||||
owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
|
||||
of whom a Contribution has been received by Licensor and subsequently
|
||||
incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License.
|
||||
|
||||
Subject to the terms and conditions of this License, each Contributor hereby
|
||||
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
||||
irrevocable copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the Work and such
|
||||
Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License.
|
||||
|
||||
Subject to the terms and conditions of this License, each Contributor hereby
|
||||
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
||||
irrevocable (except as stated in this section) patent license to make, have
|
||||
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
|
||||
such license applies only to those patent claims licensable by such Contributor
|
||||
that are necessarily infringed by their Contribution(s) alone or by combination
|
||||
of their Contribution(s) with the Work to which such Contribution(s) was
|
||||
submitted. If You institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
|
||||
Contribution incorporated within the Work constitutes direct or contributory
|
||||
patent infringement, then any patent licenses granted to You under this License
|
||||
for that Work shall terminate as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution.
|
||||
|
||||
You may reproduce and distribute copies of the Work or Derivative Works thereof
|
||||
in any medium, with or without modifications, and in Source or Object form,
|
||||
provided that You meet the following conditions:
|
||||
|
||||
You must give any other recipients of the Work or Derivative Works a copy of
|
||||
this License; and
|
||||
You must cause any modified files to carry prominent notices stating that You
|
||||
changed the files; and
|
||||
You must retain, in the Source form of any Derivative Works that You distribute,
|
||||
all copyright, patent, trademark, and attribution notices from the Source form
|
||||
of the Work, excluding those notices that do not pertain to any part of the
|
||||
Derivative Works; and
|
||||
If the Work includes a "NOTICE" text file as part of its distribution, then any
|
||||
Derivative Works that You distribute must include a readable copy of the
|
||||
attribution notices contained within such NOTICE file, excluding those notices
|
||||
that do not pertain to any part of the Derivative Works, in at least one of the
|
||||
following places: within a NOTICE text file distributed as part of the
|
||||
Derivative Works; within the Source form or documentation, if provided along
|
||||
with the Derivative Works; or, within a display generated by the Derivative
|
||||
Works, if and wherever such third-party notices normally appear. The contents of
|
||||
the NOTICE file are for informational purposes only and do not modify the
|
||||
License. You may add Your own attribution notices within Derivative Works that
|
||||
You distribute, alongside or as an addendum to the NOTICE text from the Work,
|
||||
provided that such additional attribution notices cannot be construed as
|
||||
modifying the License.
|
||||
You may add Your own copyright statement to Your modifications and may provide
|
||||
additional or different license terms and conditions for use, reproduction, or
|
||||
distribution of Your modifications, or for any such Derivative Works as a whole,
|
||||
provided Your use, reproduction, and distribution of the Work otherwise complies
|
||||
with the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions.
|
||||
|
||||
Unless You explicitly state otherwise, any Contribution intentionally submitted
|
||||
for inclusion in the Work by You to the Licensor shall be under the terms and
|
||||
conditions of this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify the terms of
|
||||
any separate license agreement you may have executed with Licensor regarding
|
||||
such Contributions.
|
||||
|
||||
6. Trademarks.
|
||||
|
||||
This License does not grant permission to use the trade names, trademarks,
|
||||
service marks, or product names of the Licensor, except as required for
|
||||
reasonable and customary use in describing the origin of the Work and
|
||||
reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty.
|
||||
|
||||
Unless required by applicable law or agreed to in writing, Licensor provides the
|
||||
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
|
||||
including, without limitation, any warranties or conditions of TITLE,
|
||||
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
|
||||
solely responsible for determining the appropriateness of using or
|
||||
redistributing the Work and assume any risks associated with Your exercise of
|
||||
permissions under this License.
|
||||
|
||||
8. Limitation of Liability.
|
||||
|
||||
In no event and under no legal theory, whether in tort (including negligence),
|
||||
contract, or otherwise, unless required by applicable law (such as deliberate
|
||||
and grossly negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special, incidental,
|
||||
or consequential damages of any character arising as a result of this License or
|
||||
out of the use or inability to use the Work (including but not limited to
|
||||
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
|
||||
any and all other commercial damages or losses), even if such Contributor has
|
||||
been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability.
|
||||
|
||||
While redistributing the Work or Derivative Works thereof, You may choose to
|
||||
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
|
||||
other liability obligations and/or rights consistent with this License. However,
|
||||
in accepting such obligations, You may act only on Your own behalf and on Your
|
||||
sole responsibility, not on behalf of any other Contributor, and only if You
|
||||
agree to indemnify, defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason of your
|
||||
accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work
|
||||
|
||||
To apply the Apache License to your work, attach the following boilerplate
|
||||
notice, with the fields enclosed by brackets "[]" replaced with your own
|
||||
identifying information. (Don't include the brackets!) The text should be
|
||||
enclosed in the appropriate comment syntax for the file format. We also
|
||||
recommend that a file or class name and description of purpose be included on
|
||||
the same "printed page" as the copyright notice for easier identification within
|
||||
third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"Vendor": true,
|
||||
"DisableAll": true,
|
||||
"Enable": [
|
||||
"vet",
|
||||
"safesql",
|
||||
"errcheck",
|
||||
"goconst",
|
||||
"goimports",
|
||||
"varcheck",
|
||||
"gas",
|
||||
"staticcheck",
|
||||
"gosimple",
|
||||
"lll",
|
||||
"unconvert",
|
||||
"misspell",
|
||||
"unconvert"
|
||||
],
|
||||
"Aggregate": true,
|
||||
"WarnUnmatchedNolint": true,
|
||||
"LineLength": 240,
|
||||
"Exclude": [
|
||||
"stun/const.go"
|
||||
],
|
||||
"Deadline": "300s",
|
||||
"Skip": []
|
||||
}
|
||||
Executable
+56
@@ -0,0 +1,56 @@
|
||||
// Copyright 2013, Cong Ding. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// author: Cong Ding <dinggnu@gmail.com>
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
|
||||
"github.com/ccding/go-stun/stun"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var serverAddr = flag.String("s", stun.DefaultServerAddr, "STUN server address")
|
||||
var v = flag.Bool("v", false, "verbose mode")
|
||||
var vv = flag.Bool("vv", false, "double verbose mode (includes -v)")
|
||||
var vvv = flag.Bool("vvv", false, "triple verbose mode (includes -v and -vv)")
|
||||
flag.Parse()
|
||||
|
||||
// Creates a STUN client. NewClientWithConnection can also be used if
|
||||
// you want to handle the UDP listener by yourself.
|
||||
client := stun.NewClient()
|
||||
// The default addr (stun.DefaultServerAddr) will be used unless we
|
||||
// call SetServerAddr.
|
||||
client.SetServerAddr(*serverAddr)
|
||||
// Non verbose mode will be used by default unless we call
|
||||
// SetVerbose(true) or SetVVerbose(true).
|
||||
client.SetVerbose(*v || *vv || *vvv)
|
||||
client.SetVVerbose(*vv || *vvv)
|
||||
// Discover the NAT and return the result.
|
||||
nat, host, err := client.Discover()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("NAT Type:", nat)
|
||||
if host != nil {
|
||||
fmt.Println("External IP Family:", host.Family())
|
||||
fmt.Println("External IP:", host.IP())
|
||||
fmt.Println("External Port:", host.Port())
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
// Copyright 2013, Cong Ding. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Author: Cong Ding <dinggnu@gmail.com>
|
||||
|
||||
package stun
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"hash/crc32"
|
||||
"net"
|
||||
)
|
||||
|
||||
type attribute struct {
|
||||
types uint16
|
||||
length uint16
|
||||
value []byte
|
||||
}
|
||||
|
||||
func newAttribute(types uint16, value []byte) *attribute {
|
||||
att := new(attribute)
|
||||
att.types = types
|
||||
att.value = padding(value)
|
||||
att.length = uint16(len(att.value))
|
||||
return att
|
||||
}
|
||||
|
||||
func newFingerprintAttribute(packet *packet) *attribute {
|
||||
crc := crc32.ChecksumIEEE(packet.bytes()) ^ fingerprint
|
||||
buf := make([]byte, 4)
|
||||
binary.BigEndian.PutUint32(buf, crc)
|
||||
return newAttribute(attributeFingerprint, buf)
|
||||
}
|
||||
|
||||
func newSoftwareAttribute(name string) *attribute {
|
||||
return newAttribute(attributeSoftware, []byte(name))
|
||||
}
|
||||
|
||||
func newChangeReqAttribute(changeIP bool, changePort bool) *attribute {
|
||||
value := make([]byte, 4)
|
||||
if changeIP {
|
||||
value[3] |= 0x04
|
||||
}
|
||||
if changePort {
|
||||
value[3] |= 0x02
|
||||
}
|
||||
return newAttribute(attributeChangeRequest, value)
|
||||
}
|
||||
|
||||
// 0 1 2 3
|
||||
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
|
||||
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
// |x x x x x x x x| Family | X-Port |
|
||||
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
// | X-Address (Variable)
|
||||
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
//
|
||||
// Figure 6: Format of XOR-MAPPED-ADDRESS Attribute
|
||||
func (v *attribute) xorAddr(transID []byte) *Host {
|
||||
xorIP := make([]byte, 16)
|
||||
for i := 0; i < len(v.value)-4; i++ {
|
||||
xorIP[i] = v.value[i+4] ^ transID[i]
|
||||
}
|
||||
family := uint16(v.value[1])
|
||||
port := binary.BigEndian.Uint16(v.value[2:4])
|
||||
// Truncate if IPv4, otherwise net.IP sometimes renders it as an IPv6 address.
|
||||
if family == attributeFamilyIPv4 {
|
||||
xorIP = xorIP[:4]
|
||||
}
|
||||
x := binary.BigEndian.Uint16(transID[:2])
|
||||
return &Host{family, net.IP(xorIP).String(), port ^ x}
|
||||
}
|
||||
|
||||
// 0 1 2 3
|
||||
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
|
||||
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
// |0 0 0 0 0 0 0 0| Family | Port |
|
||||
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
// | |
|
||||
// | Address (32 bits or 128 bits) |
|
||||
// | |
|
||||
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
//
|
||||
// Figure 5: Format of MAPPED-ADDRESS Attribute
|
||||
func (v *attribute) rawAddr() *Host {
|
||||
host := new(Host)
|
||||
host.family = uint16(v.value[1])
|
||||
host.port = binary.BigEndian.Uint16(v.value[2:4])
|
||||
// Truncate if IPv4, otherwise net.IP sometimes renders it as an IPv6 address.
|
||||
if host.family == attributeFamilyIPv4 {
|
||||
v.value = v.value[:8]
|
||||
}
|
||||
host.ip = net.IP(v.value[4:]).String()
|
||||
return host
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
// Copyright 2013, Cong Ding. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Author: Cong Ding <dinggnu@gmail.com>
|
||||
|
||||
package stun
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Client is a STUN client, which can be set STUN server address and is used
|
||||
// to discover NAT type.
|
||||
type Client struct {
|
||||
serverAddr string
|
||||
softwareName string
|
||||
conn net.PacketConn
|
||||
logger *Logger
|
||||
}
|
||||
|
||||
// NewClient returns a client without network connection. The network
|
||||
// connection will be build when calling Discover function.
|
||||
func NewClient() *Client {
|
||||
c := new(Client)
|
||||
c.SetSoftwareName(DefaultSoftwareName)
|
||||
c.logger = NewLogger()
|
||||
return c
|
||||
}
|
||||
|
||||
// NewClientWithConnection returns a client which uses the given connection.
|
||||
// Please note the connection should be acquired via net.Listen* method.
|
||||
func NewClientWithConnection(conn net.PacketConn) *Client {
|
||||
c := new(Client)
|
||||
c.conn = conn
|
||||
c.SetSoftwareName(DefaultSoftwareName)
|
||||
c.logger = NewLogger()
|
||||
return c
|
||||
}
|
||||
|
||||
// SetVerbose sets the client to be in the verbose mode, which prints
|
||||
// information in the discover process.
|
||||
func (c *Client) SetVerbose(v bool) {
|
||||
c.logger.SetDebug(v)
|
||||
}
|
||||
|
||||
// SetVVerbose sets the client to be in the double verbose mode, which prints
|
||||
// information and packet in the discover process.
|
||||
func (c *Client) SetVVerbose(v bool) {
|
||||
c.logger.SetInfo(v)
|
||||
}
|
||||
|
||||
// SetServerHost allows user to set the STUN hostname and port.
|
||||
func (c *Client) SetServerHost(host string, port int) {
|
||||
c.serverAddr = net.JoinHostPort(host, strconv.Itoa(port))
|
||||
}
|
||||
|
||||
// SetServerAddr allows user to set the transport layer STUN server address.
|
||||
func (c *Client) SetServerAddr(address string) {
|
||||
c.serverAddr = address
|
||||
}
|
||||
|
||||
// SetSoftwareName allows user to set the name of the software, which is used
|
||||
// for logging purpose (NOT used in the current implementation).
|
||||
func (c *Client) SetSoftwareName(name string) {
|
||||
c.softwareName = name
|
||||
}
|
||||
|
||||
// Discover contacts the STUN server and gets the response of NAT type, host
|
||||
// for UDP punching.
|
||||
func (c *Client) Discover() (NATType, *Host, error) {
|
||||
if c.serverAddr == "" {
|
||||
c.SetServerAddr(DefaultServerAddr)
|
||||
}
|
||||
serverUDPAddr, err := net.ResolveUDPAddr("udp", c.serverAddr)
|
||||
if err != nil {
|
||||
return NATError, nil, err
|
||||
}
|
||||
// Use the connection passed to the client if it is not nil, otherwise
|
||||
// create a connection and close it at the end.
|
||||
conn := c.conn
|
||||
if conn == nil {
|
||||
conn, err = net.ListenUDP("udp", nil)
|
||||
if err != nil {
|
||||
return NATError, nil, err
|
||||
}
|
||||
defer conn.Close()
|
||||
}
|
||||
return c.discover(conn, serverUDPAddr)
|
||||
}
|
||||
|
||||
// Keepalive sends and receives a bind request, which ensures the mapping stays open
|
||||
// Only applicable when client was created with a connection.
|
||||
func (c *Client) Keepalive() (*Host, error) {
|
||||
if c.conn == nil {
|
||||
return nil, errors.New("no connection available")
|
||||
}
|
||||
if c.serverAddr == "" {
|
||||
c.SetServerAddr(DefaultServerAddr)
|
||||
}
|
||||
serverUDPAddr, err := net.ResolveUDPAddr("udp", c.serverAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := c.test1(c.conn, serverUDPAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp == nil || resp.packet == nil {
|
||||
return nil, errors.New("failed to contact")
|
||||
}
|
||||
return resp.mappedAddr, nil
|
||||
}
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
// Copyright 2013, Cong Ding. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Author: Cong Ding <dinggnu@gmail.com>
|
||||
|
||||
package stun
|
||||
|
||||
// Default server address and client name.
|
||||
const (
|
||||
DefaultServerAddr = "stun.voiparound.com:3478"
|
||||
DefaultSoftwareName = "StunClient"
|
||||
)
|
||||
|
||||
const (
|
||||
magicCookie = 0x2112A442
|
||||
fingerprint = 0x5354554e
|
||||
)
|
||||
|
||||
// NATType is the type of NAT described by int.
|
||||
type NATType int
|
||||
|
||||
// NAT types.
|
||||
const (
|
||||
NATError NATType = iota
|
||||
NATUnknown
|
||||
NATNone
|
||||
NATBlocked
|
||||
NATFull
|
||||
NATSymmetric
|
||||
NATRestricted
|
||||
NATPortRestricted
|
||||
NATSymmetricUDPFirewall
|
||||
|
||||
// Deprecated spellings of these constants
|
||||
NATSymetric = NATSymmetric
|
||||
NATSymetricUDPFirewall = NATSymmetricUDPFirewall
|
||||
)
|
||||
|
||||
var natStr map[NATType]string
|
||||
|
||||
func init() {
|
||||
natStr = map[NATType]string{
|
||||
NATError: "Test failed",
|
||||
NATUnknown: "Unexpected response from the STUN server",
|
||||
NATBlocked: "UDP is blocked",
|
||||
NATFull: "Full cone NAT",
|
||||
NATSymmetric: "Symmetric NAT",
|
||||
NATRestricted: "Restricted NAT",
|
||||
NATPortRestricted: "Port restricted NAT",
|
||||
NATNone: "Not behind a NAT",
|
||||
NATSymmetricUDPFirewall: "Symmetric UDP firewall",
|
||||
}
|
||||
}
|
||||
|
||||
func (nat NATType) String() string {
|
||||
if s, ok := natStr[nat]; ok {
|
||||
return s
|
||||
}
|
||||
return "Unknown"
|
||||
}
|
||||
|
||||
const (
|
||||
errorTryAlternate = 300
|
||||
errorBadRequest = 400
|
||||
errorUnauthorized = 401
|
||||
errorUnassigned402 = 402
|
||||
errorForbidden = 403
|
||||
errorUnknownAttribute = 420
|
||||
errorAllocationMismatch = 437
|
||||
errorStaleNonce = 438
|
||||
errorUnassigned439 = 439
|
||||
errorAddressFamilyNotSupported = 440
|
||||
errorWrongCredentials = 441
|
||||
errorUnsupportedTransportProtocol = 442
|
||||
errorPeerAddressFamilyMismatch = 443
|
||||
errorConnectionAlreadyExists = 446
|
||||
errorConnectionTimeoutOrFailure = 447
|
||||
errorAllocationQuotaReached = 486
|
||||
errorRoleConflict = 487
|
||||
errorServerError = 500
|
||||
errorInsufficientCapacity = 508
|
||||
)
|
||||
const (
|
||||
attributeFamilyIPv4 = 0x01
|
||||
attributeFamilyIPV6 = 0x02
|
||||
)
|
||||
|
||||
const (
|
||||
attributeMappedAddress = 0x0001
|
||||
attributeResponseAddress = 0x0002
|
||||
attributeChangeRequest = 0x0003
|
||||
attributeSourceAddress = 0x0004
|
||||
attributeChangedAddress = 0x0005
|
||||
attributeUsername = 0x0006
|
||||
attributePassword = 0x0007
|
||||
attributeMessageIntegrity = 0x0008
|
||||
attributeErrorCode = 0x0009
|
||||
attributeUnknownAttributes = 0x000a
|
||||
attributeReflectedFrom = 0x000b
|
||||
attributeChannelNumber = 0x000c
|
||||
attributeLifetime = 0x000d
|
||||
attributeBandwidth = 0x0010
|
||||
attributeXorPeerAddress = 0x0012
|
||||
attributeData = 0x0013
|
||||
attributeRealm = 0x0014
|
||||
attributeNonce = 0x0015
|
||||
attributeXorRelayedAddress = 0x0016
|
||||
attributeRequestedAddressFamily = 0x0017
|
||||
attributeEvenPort = 0x0018
|
||||
attributeRequestedTransport = 0x0019
|
||||
attributeDontFragment = 0x001a
|
||||
attributeXorMappedAddress = 0x0020
|
||||
attributeTimerVal = 0x0021
|
||||
attributeReservationToken = 0x0022
|
||||
attributePriority = 0x0024
|
||||
attributeUseCandidate = 0x0025
|
||||
attributePadding = 0x0026
|
||||
attributeResponsePort = 0x0027
|
||||
attributeConnectionID = 0x002a
|
||||
attributeXorMappedAddressExp = 0x8020
|
||||
attributeSoftware = 0x8022
|
||||
attributeAlternateServer = 0x8023
|
||||
attributeCacheTimeout = 0x8027
|
||||
attributeFingerprint = 0x8028
|
||||
attributeIceControlled = 0x8029
|
||||
attributeIceControlling = 0x802a
|
||||
attributeResponseOrigin = 0x802b
|
||||
attributeOtherAddress = 0x802c
|
||||
attributeEcnCheckStun = 0x802d
|
||||
attributeCiscoFlowdata = 0xc000
|
||||
)
|
||||
|
||||
const (
|
||||
typeBindingRequest = 0x0001
|
||||
typeBindingResponse = 0x0101
|
||||
typeBindingErrorResponse = 0x0111
|
||||
typeSharedSecretRequest = 0x0002
|
||||
typeSharedSecretResponse = 0x0102
|
||||
typeSharedErrorResponse = 0x0112
|
||||
typeAllocate = 0x0003
|
||||
typeAllocateResponse = 0x0103
|
||||
typeAllocateErrorResponse = 0x0113
|
||||
typeRefresh = 0x0004
|
||||
typeRefreshResponse = 0x0104
|
||||
typeRefreshErrorResponse = 0x0114
|
||||
typeSend = 0x0006
|
||||
typeSendResponse = 0x0106
|
||||
typeSendErrorResponse = 0x0116
|
||||
typeData = 0x0007
|
||||
typeDataResponse = 0x0107
|
||||
typeDataErrorResponse = 0x0117
|
||||
typeCreatePermisiion = 0x0008
|
||||
typeCreatePermisiionResponse = 0x0108
|
||||
typeCreatePermisiionErrorResponse = 0x0118
|
||||
typeChannelBinding = 0x0009
|
||||
typeChannelBindingResponse = 0x0109
|
||||
typeChannelBindingErrorResponse = 0x0119
|
||||
typeConnect = 0x000a
|
||||
typeConnectResponse = 0x010a
|
||||
typeConnectErrorResponse = 0x011a
|
||||
typeConnectionBind = 0x000b
|
||||
typeConnectionBindResponse = 0x010b
|
||||
typeConnectionBindErrorResponse = 0x011b
|
||||
typeConnectionAttempt = 0x000c
|
||||
typeConnectionAttemptResponse = 0x010c
|
||||
typeConnectionAttemptErrorResponse = 0x011c
|
||||
)
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
// Copyright 2013, Cong Ding. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Author: Cong Ding <dinggnu@gmail.com>
|
||||
|
||||
package stun
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
)
|
||||
|
||||
// Follow RFC 3489 and RFC 5389.
|
||||
// Figure 2: Flow for type discovery process (from RFC 3489).
|
||||
// +--------+
|
||||
// | Test |
|
||||
// | I |
|
||||
// +--------+
|
||||
// |
|
||||
// |
|
||||
// V
|
||||
// /\ /\
|
||||
// N / \ Y / \ Y +--------+
|
||||
// UDP <-------/Resp\--------->/ IP \------------->| Test |
|
||||
// Blocked \ ? / \Same/ | II |
|
||||
// \ / \? / +--------+
|
||||
// \/ \/ |
|
||||
// | N |
|
||||
// | V
|
||||
// V /\
|
||||
// +--------+ Sym. N / \
|
||||
// | Test | UDP <---/Resp\
|
||||
// | II | Firewall \ ? /
|
||||
// +--------+ \ /
|
||||
// | \/
|
||||
// V |Y
|
||||
// /\ /\ |
|
||||
// Symmetric N / \ +--------+ N / \ V
|
||||
// NAT <--- / IP \<-----| Test |<--- /Resp\ Open
|
||||
// \Same/ | I | \ ? / Internet
|
||||
// \? / +--------+ \ /
|
||||
// \/ \/
|
||||
// |Y |Y
|
||||
// | |
|
||||
// | V
|
||||
// | Full
|
||||
// | Cone
|
||||
// V /\
|
||||
// +--------+ / \ Y
|
||||
// | Test |------>/Resp\---->Restricted
|
||||
// | III | \ ? /
|
||||
// +--------+ \ /
|
||||
// \/
|
||||
// |N
|
||||
// | Port
|
||||
// +------>Restricted
|
||||
func (c *Client) discover(conn net.PacketConn, addr *net.UDPAddr) (NATType, *Host, error) {
|
||||
// Perform test1 to check if it is under NAT.
|
||||
c.logger.Debugln("Do Test1")
|
||||
c.logger.Debugln("Send To:", addr)
|
||||
resp, err := c.test1(conn, addr)
|
||||
if err != nil {
|
||||
return NATError, nil, err
|
||||
}
|
||||
c.logger.Debugln("Received:", resp)
|
||||
if resp == nil {
|
||||
return NATBlocked, nil, nil
|
||||
}
|
||||
// identical used to check if it is open Internet or not.
|
||||
identical := resp.identical
|
||||
// changedAddr is used to perform second time test1 and test3.
|
||||
changedAddr := resp.changedAddr
|
||||
// mappedAddr is used as the return value, its IP is used for tests
|
||||
mappedAddr := resp.mappedAddr
|
||||
// Make sure IP and port are not changed.
|
||||
if resp.serverAddr.IP() != addr.IP.String() ||
|
||||
resp.serverAddr.Port() != uint16(addr.Port) {
|
||||
return NATError, mappedAddr, errors.New("Server error: response IP/port")
|
||||
}
|
||||
// if changedAddr is not available, use otherAddr as changedAddr,
|
||||
// which is updated in RFC 5780
|
||||
if changedAddr == nil {
|
||||
changedAddr = resp.otherAddr
|
||||
}
|
||||
// changedAddr shall not be nil
|
||||
if changedAddr == nil {
|
||||
return NATError, mappedAddr, errors.New("Server error: no changed address.")
|
||||
}
|
||||
// Perform test2 to see if the client can receive packet sent from
|
||||
// another IP and port.
|
||||
c.logger.Debugln("Do Test2")
|
||||
c.logger.Debugln("Send To:", addr)
|
||||
resp, err = c.test2(conn, addr)
|
||||
if err != nil {
|
||||
return NATError, mappedAddr, err
|
||||
}
|
||||
c.logger.Debugln("Received:", resp)
|
||||
// Make sure IP and port are changed.
|
||||
if resp != nil &&
|
||||
(resp.serverAddr.IP() == addr.IP.String() ||
|
||||
resp.serverAddr.Port() == uint16(addr.Port)) {
|
||||
return NATError, mappedAddr, errors.New("Server error: response IP/port")
|
||||
}
|
||||
if identical {
|
||||
if resp == nil {
|
||||
return NATSymmetricUDPFirewall, mappedAddr, nil
|
||||
}
|
||||
return NATNone, mappedAddr, nil
|
||||
}
|
||||
if resp != nil {
|
||||
return NATFull, mappedAddr, nil
|
||||
}
|
||||
// Perform test1 to another IP and port to see if the NAT use the same
|
||||
// external IP.
|
||||
c.logger.Debugln("Do Test1")
|
||||
c.logger.Debugln("Send To:", changedAddr)
|
||||
caddr, err := net.ResolveUDPAddr("udp", changedAddr.String())
|
||||
if err != nil {
|
||||
c.logger.Debugf("ResolveUDPAddr error: %v", err)
|
||||
}
|
||||
resp, err = c.test1(conn, caddr)
|
||||
if err != nil {
|
||||
return NATError, mappedAddr, err
|
||||
}
|
||||
c.logger.Debugln("Received:", resp)
|
||||
if resp == nil {
|
||||
// It should be NAT_BLOCKED, but will be detected in the first
|
||||
// step. So this will never happen.
|
||||
return NATUnknown, mappedAddr, nil
|
||||
}
|
||||
// Make sure IP/port is not changed.
|
||||
if resp.serverAddr.IP() != caddr.IP.String() ||
|
||||
resp.serverAddr.Port() != uint16(caddr.Port) {
|
||||
return NATError, mappedAddr, errors.New("Server error: response IP/port")
|
||||
}
|
||||
if mappedAddr.IP() == resp.mappedAddr.IP() && mappedAddr.Port() == resp.mappedAddr.Port() {
|
||||
// Perform test3 to see if the client can receive packet sent
|
||||
// from another port.
|
||||
c.logger.Debugln("Do Test3")
|
||||
c.logger.Debugln("Send To:", caddr)
|
||||
resp, err = c.test3(conn, caddr)
|
||||
if err != nil {
|
||||
return NATError, mappedAddr, err
|
||||
}
|
||||
c.logger.Debugln("Received:", resp)
|
||||
if resp == nil {
|
||||
return NATPortRestricted, mappedAddr, nil
|
||||
}
|
||||
// Make sure IP is not changed, and port is changed.
|
||||
if resp.serverAddr.IP() != caddr.IP.String() ||
|
||||
resp.serverAddr.Port() == uint16(caddr.Port) {
|
||||
return NATError, mappedAddr, errors.New("Server error: response IP/port")
|
||||
}
|
||||
return NATRestricted, mappedAddr, nil
|
||||
}
|
||||
return NATSymmetric, mappedAddr, nil
|
||||
}
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
// Copyright 2013, Cong Ding. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Author: Cong Ding <dinggnu@gmail.com>
|
||||
|
||||
// Package stun is a STUN (RFC 3489 and RFC 5389) client implementation in
|
||||
// golang.
|
||||
//
|
||||
// It is extremely easy to use -- just one line of code.
|
||||
//
|
||||
// nat, host, err := stun.NewClient().Discover()
|
||||
//
|
||||
// More details please go to `main.go`.
|
||||
package stun
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
// Copyright 2013, Cong Ding. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Author: Cong Ding <dinggnu@gmail.com>
|
||||
|
||||
package stun
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Host defines the network address including address family, IP address and port.
|
||||
type Host struct {
|
||||
family uint16
|
||||
ip string
|
||||
port uint16
|
||||
}
|
||||
|
||||
func newHostFromStr(s string) *Host {
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", s)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
host := new(Host)
|
||||
if udpAddr.IP.To4() != nil {
|
||||
host.family = attributeFamilyIPv4
|
||||
} else {
|
||||
host.family = attributeFamilyIPV6
|
||||
}
|
||||
host.ip = udpAddr.IP.String()
|
||||
host.port = uint16(udpAddr.Port)
|
||||
return host
|
||||
}
|
||||
|
||||
// Family returns the family type of a host (IPv4 or IPv6).
|
||||
func (h *Host) Family() uint16 {
|
||||
return h.family
|
||||
}
|
||||
|
||||
// IP returns the internet protocol address of the host.
|
||||
func (h *Host) IP() string {
|
||||
return h.ip
|
||||
}
|
||||
|
||||
// Port returns the port number of the host.
|
||||
func (h *Host) Port() uint16 {
|
||||
return h.port
|
||||
}
|
||||
|
||||
// TransportAddr returns the transport layer address of the host.
|
||||
func (h *Host) TransportAddr() string {
|
||||
return net.JoinHostPort(h.ip, strconv.Itoa(int(h.port)))
|
||||
}
|
||||
|
||||
// String returns the string representation of the host address.
|
||||
func (h *Host) String() string {
|
||||
return h.TransportAddr()
|
||||
}
|
||||
Executable
+87
@@ -0,0 +1,87 @@
|
||||
// Copyright 2016, Cong Ding. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Author: Cong Ding <dinggnu@gmail.com>
|
||||
|
||||
package stun
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
// Logger is a simple logger specified for this STUN client.
|
||||
type Logger struct {
|
||||
log.Logger
|
||||
debug bool
|
||||
info bool
|
||||
}
|
||||
|
||||
// NewLogger creates a default logger.
|
||||
func NewLogger() *Logger {
|
||||
logger := &Logger{*log.New(os.Stdout, "", log.LstdFlags), false, false}
|
||||
return logger
|
||||
}
|
||||
|
||||
// SetDebug sets the logger running in debug mode or not.
|
||||
func (l *Logger) SetDebug(v bool) {
|
||||
l.debug = v
|
||||
}
|
||||
|
||||
// SetInfo sets the logger running in info mode or not.
|
||||
func (l *Logger) SetInfo(v bool) {
|
||||
l.info = v
|
||||
}
|
||||
|
||||
// Debug outputs the log in the format of log.Print.
|
||||
func (l *Logger) Debug(v ...interface{}) {
|
||||
if l.debug {
|
||||
l.Print(v...)
|
||||
}
|
||||
}
|
||||
|
||||
// Debugf outputs the log in the format of log.Printf.
|
||||
func (l *Logger) Debugf(format string, v ...interface{}) {
|
||||
if l.debug {
|
||||
l.Printf(format, v...)
|
||||
}
|
||||
}
|
||||
|
||||
// Debugln outputs the log in the format of log.Println.
|
||||
func (l *Logger) Debugln(v ...interface{}) {
|
||||
if l.debug {
|
||||
l.Println(v...)
|
||||
}
|
||||
}
|
||||
|
||||
// Info outputs the log in the format of log.Print.
|
||||
func (l *Logger) Info(v ...interface{}) {
|
||||
if l.info {
|
||||
l.Print(v...)
|
||||
}
|
||||
}
|
||||
|
||||
// Infof outputs the log in the format of log.Printf.
|
||||
func (l *Logger) Infof(format string, v ...interface{}) {
|
||||
if l.info {
|
||||
l.Printf(format, v...)
|
||||
}
|
||||
}
|
||||
|
||||
// Infoln outputs the log in the format of log.Println.
|
||||
func (l *Logger) Infoln(v ...interface{}) {
|
||||
if l.info {
|
||||
l.Println(v...)
|
||||
}
|
||||
}
|
||||
Executable
+106
@@ -0,0 +1,106 @@
|
||||
// Copyright 2016, Cong Ding. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Author: Cong Ding <dinggnu@gmail.com>
|
||||
|
||||
package stun
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
numRetransmit = 9
|
||||
defaultTimeout = 100
|
||||
maxTimeout = 1600
|
||||
maxPacketSize = 1024
|
||||
)
|
||||
|
||||
func (c *Client) sendBindingReq(conn net.PacketConn, addr net.Addr, changeIP bool, changePort bool) (*response, error) {
|
||||
// Construct packet.
|
||||
pkt, err := newPacket()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pkt.types = typeBindingRequest
|
||||
attribute := newSoftwareAttribute(c.softwareName)
|
||||
pkt.addAttribute(*attribute)
|
||||
if changeIP || changePort {
|
||||
attribute = newChangeReqAttribute(changeIP, changePort)
|
||||
pkt.addAttribute(*attribute)
|
||||
}
|
||||
// length of fingerprint attribute must be included into crc,
|
||||
// so we add it before calculating crc, then subtract it after calculating crc.
|
||||
pkt.length += 8
|
||||
attribute = newFingerprintAttribute(pkt)
|
||||
pkt.length -= 8
|
||||
pkt.addAttribute(*attribute)
|
||||
// Send packet.
|
||||
return c.send(pkt, conn, addr)
|
||||
}
|
||||
|
||||
// RFC 3489: Clients SHOULD retransmit the request starting with an interval
|
||||
// of 100ms, doubling every retransmit until the interval reaches 1.6s.
|
||||
// Retransmissions continue with intervals of 1.6s until a response is
|
||||
// received, or a total of 9 requests have been sent.
|
||||
func (c *Client) send(pkt *packet, conn net.PacketConn, addr net.Addr) (*response, error) {
|
||||
c.logger.Info("\n" + hex.Dump(pkt.bytes()))
|
||||
timeout := defaultTimeout
|
||||
packetBytes := make([]byte, maxPacketSize)
|
||||
for i := 0; i < numRetransmit; i++ {
|
||||
// Send packet to the server.
|
||||
length, err := conn.WriteTo(pkt.bytes(), addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if length != len(pkt.bytes()) {
|
||||
return nil, errors.New("Error in sending data.")
|
||||
}
|
||||
err = conn.SetReadDeadline(time.Now().Add(time.Duration(timeout) * time.Millisecond))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if timeout < maxTimeout {
|
||||
timeout *= 2
|
||||
}
|
||||
for {
|
||||
// Read from the port.
|
||||
length, raddr, err := conn.ReadFrom(packetBytes)
|
||||
if err != nil {
|
||||
if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
|
||||
break
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
p, err := newPacketFromBytes(packetBytes[0:length])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// If transId mismatches, keep reading until get a
|
||||
// matched packet or timeout.
|
||||
if !bytes.Equal(pkt.transID, p.transID) {
|
||||
continue
|
||||
}
|
||||
c.logger.Info("\n" + hex.Dump(packetBytes[0:length]))
|
||||
resp := newResponse(p, conn)
|
||||
resp.serverAddr = newHostFromStr(raddr.String())
|
||||
return resp, err
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
// Copyright 2013, Cong Ding. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Author: Cong Ding <dinggnu@gmail.com>
|
||||
|
||||
package stun
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
)
|
||||
|
||||
type packet struct {
|
||||
types uint16
|
||||
length uint16
|
||||
transID []byte // 4 bytes magic cookie + 12 bytes transaction id
|
||||
attributes []attribute
|
||||
}
|
||||
|
||||
func newPacket() (*packet, error) {
|
||||
v := new(packet)
|
||||
v.transID = make([]byte, 16)
|
||||
binary.BigEndian.PutUint32(v.transID[:4], magicCookie)
|
||||
_, err := rand.Read(v.transID[4:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v.attributes = make([]attribute, 0, 10)
|
||||
v.length = 0
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func newPacketFromBytes(packetBytes []byte) (*packet, error) {
|
||||
if len(packetBytes) < 24 {
|
||||
return nil, errors.New("Received data length too short.")
|
||||
}
|
||||
pkt := new(packet)
|
||||
pkt.types = binary.BigEndian.Uint16(packetBytes[0:2])
|
||||
pkt.length = binary.BigEndian.Uint16(packetBytes[2:4])
|
||||
pkt.transID = packetBytes[4:20]
|
||||
pkt.attributes = make([]attribute, 0, 10)
|
||||
for pos := uint16(20); pos < uint16(len(packetBytes)); {
|
||||
types := binary.BigEndian.Uint16(packetBytes[pos : pos+2])
|
||||
length := binary.BigEndian.Uint16(packetBytes[pos+2 : pos+4])
|
||||
if pos+4+length > uint16(len(packetBytes)) {
|
||||
return nil, errors.New("Received data format mismatch.")
|
||||
}
|
||||
value := packetBytes[pos+4 : pos+4+length]
|
||||
attribute := newAttribute(types, value)
|
||||
pkt.addAttribute(*attribute)
|
||||
pos += align(length) + 4
|
||||
}
|
||||
return pkt, nil
|
||||
}
|
||||
|
||||
func (v *packet) addAttribute(a attribute) {
|
||||
v.attributes = append(v.attributes, a)
|
||||
v.length += align(a.length) + 4
|
||||
}
|
||||
|
||||
func (v *packet) bytes() []byte {
|
||||
packetBytes := make([]byte, 4)
|
||||
binary.BigEndian.PutUint16(packetBytes[0:2], v.types)
|
||||
binary.BigEndian.PutUint16(packetBytes[2:4], v.length)
|
||||
packetBytes = append(packetBytes, v.transID...)
|
||||
for _, a := range v.attributes {
|
||||
buf := make([]byte, 2)
|
||||
binary.BigEndian.PutUint16(buf, a.types)
|
||||
packetBytes = append(packetBytes, buf...)
|
||||
binary.BigEndian.PutUint16(buf, a.length)
|
||||
packetBytes = append(packetBytes, buf...)
|
||||
packetBytes = append(packetBytes, a.value...)
|
||||
}
|
||||
return packetBytes
|
||||
}
|
||||
|
||||
func (v *packet) getSourceAddr() *Host {
|
||||
return v.getRawAddr(attributeSourceAddress)
|
||||
}
|
||||
|
||||
func (v *packet) getMappedAddr() *Host {
|
||||
return v.getRawAddr(attributeMappedAddress)
|
||||
}
|
||||
|
||||
func (v *packet) getChangedAddr() *Host {
|
||||
return v.getRawAddr(attributeChangedAddress)
|
||||
}
|
||||
|
||||
func (v *packet) getOtherAddr() *Host {
|
||||
return v.getRawAddr(attributeOtherAddress)
|
||||
}
|
||||
|
||||
func (v *packet) getRawAddr(attribute uint16) *Host {
|
||||
for _, a := range v.attributes {
|
||||
if a.types == attribute {
|
||||
return a.rawAddr()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *packet) getXorMappedAddr() *Host {
|
||||
addr := v.getXorAddr(attributeXorMappedAddress)
|
||||
if addr == nil {
|
||||
addr = v.getXorAddr(attributeXorMappedAddressExp)
|
||||
}
|
||||
return addr
|
||||
}
|
||||
|
||||
func (v *packet) getXorAddr(attribute uint16) *Host {
|
||||
for _, a := range v.attributes {
|
||||
if a.types == attribute {
|
||||
return a.xorAddr(v.transID)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
// Copyright 2016, Cong Ding. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Author: Cong Ding <dinggnu@gmail.com>
|
||||
|
||||
package stun
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewPacketFromBytes(t *testing.T) {
|
||||
b := make([]byte, 23)
|
||||
_, err := newPacketFromBytes(b)
|
||||
if err == nil {
|
||||
t.Errorf("newPacketFromBytes error")
|
||||
}
|
||||
b = make([]byte, 24)
|
||||
_, err = newPacketFromBytes(b)
|
||||
if err != nil {
|
||||
t.Errorf("newPacketFromBytes error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewPacket(t *testing.T) {
|
||||
_, err := newPacket()
|
||||
if err != nil {
|
||||
t.Errorf("newPacket error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPacketAll(t *testing.T) {
|
||||
p, err := newPacket()
|
||||
if err != nil {
|
||||
t.Errorf("newPacket error")
|
||||
}
|
||||
p.addAttribute(*newChangeReqAttribute(true, true))
|
||||
p.addAttribute(*newSoftwareAttribute("aaa"))
|
||||
p.addAttribute(*newFingerprintAttribute(p))
|
||||
pkt, err := newPacketFromBytes(p.bytes())
|
||||
if err != nil {
|
||||
t.Errorf("newPacketFromBytes error")
|
||||
}
|
||||
if pkt.types != 0 {
|
||||
t.Errorf("newPacketFromBytes error")
|
||||
}
|
||||
if pkt.length < 24 {
|
||||
t.Errorf("newPacketFromBytes error")
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
// Copyright 2016, Cong Ding. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Author: Cong Ding <dinggnu@gmail.com>
|
||||
|
||||
package stun
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
)
|
||||
|
||||
type response struct {
|
||||
packet *packet // the original packet from the server
|
||||
serverAddr *Host // the address received packet
|
||||
changedAddr *Host // parsed from packet
|
||||
mappedAddr *Host // parsed from packet, external addr of client NAT
|
||||
otherAddr *Host // parsed from packet, to replace changedAddr in RFC 5780
|
||||
identical bool // if mappedAddr is in local addr list
|
||||
}
|
||||
|
||||
func newResponse(pkt *packet, conn net.PacketConn) *response {
|
||||
resp := &response{pkt, nil, nil, nil, nil, false}
|
||||
if pkt == nil {
|
||||
return resp
|
||||
}
|
||||
// RFC 3489 doesn't require the server return XOR mapped address.
|
||||
mappedAddr := pkt.getXorMappedAddr()
|
||||
if mappedAddr == nil {
|
||||
mappedAddr = pkt.getMappedAddr()
|
||||
}
|
||||
resp.mappedAddr = mappedAddr
|
||||
// compute identical
|
||||
localAddrStr := conn.LocalAddr().String()
|
||||
if mappedAddr != nil {
|
||||
mappedAddrStr := mappedAddr.String()
|
||||
resp.identical = isLocalAddress(localAddrStr, mappedAddrStr)
|
||||
}
|
||||
// compute changedAddr
|
||||
changedAddr := pkt.getChangedAddr()
|
||||
if changedAddr != nil {
|
||||
changedAddrHost := newHostFromStr(changedAddr.String())
|
||||
resp.changedAddr = changedAddrHost
|
||||
}
|
||||
// compute otherAddr
|
||||
otherAddr := pkt.getOtherAddr()
|
||||
if otherAddr != nil {
|
||||
otherAddrHost := newHostFromStr(otherAddr.String())
|
||||
resp.otherAddr = otherAddrHost
|
||||
}
|
||||
|
||||
return resp
|
||||
}
|
||||
|
||||
// String is only used for verbose mode output.
|
||||
func (r *response) String() string {
|
||||
if r == nil {
|
||||
return "Nil"
|
||||
}
|
||||
return fmt.Sprintf("{packet nil: %v, local: %v, remote: %v, changed: %v, other: %v, identical: %v}",
|
||||
r.packet == nil,
|
||||
r.mappedAddr,
|
||||
r.serverAddr,
|
||||
r.changedAddr,
|
||||
r.otherAddr,
|
||||
r.identical)
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
// Copyright 2016, Cong Ding. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Author: Cong Ding <dinggnu@gmail.com>
|
||||
|
||||
package stun
|
||||
|
||||
import (
|
||||
"net"
|
||||
)
|
||||
|
||||
func (c *Client) test1(conn net.PacketConn, addr net.Addr) (*response, error) {
|
||||
return c.sendBindingReq(conn, addr, false, false)
|
||||
}
|
||||
|
||||
func (c *Client) test2(conn net.PacketConn, addr net.Addr) (*response, error) {
|
||||
return c.sendBindingReq(conn, addr, true, true)
|
||||
}
|
||||
|
||||
func (c *Client) test3(conn net.PacketConn, addr net.Addr) (*response, error) {
|
||||
return c.sendBindingReq(conn, addr, false, true)
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
// Copyright 2016, Cong Ding. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Author: Cong Ding <dinggnu@gmail.com>
|
||||
|
||||
package stun
|
||||
|
||||
import (
|
||||
"net"
|
||||
)
|
||||
|
||||
// Padding the length of the byte slice to multiple of 4.
|
||||
func padding(bytes []byte) []byte {
|
||||
length := uint16(len(bytes))
|
||||
return append(bytes, make([]byte, align(length)-length)...)
|
||||
}
|
||||
|
||||
// Align the uint16 number to the smallest multiple of 4, which is larger than
|
||||
// or equal to the uint16 number.
|
||||
func align(n uint16) uint16 {
|
||||
return (n + 3) & 0xfffc
|
||||
}
|
||||
|
||||
// isLocalAddress check if localRemote is a local address.
|
||||
func isLocalAddress(local, localRemote string) bool {
|
||||
// Resolve the IP returned by the STUN server first.
|
||||
localRemoteAddr, err := net.ResolveUDPAddr("udp", localRemote)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
// Try comparing with the local address on the socket first, but only if
|
||||
// it's actually specified.
|
||||
addr, err := net.ResolveUDPAddr("udp", local)
|
||||
if err == nil && addr.IP != nil && !addr.IP.IsUnspecified() {
|
||||
return addr.IP.Equal(localRemoteAddr.IP)
|
||||
}
|
||||
// Fallback to checking IPs of all interfaces
|
||||
addrs, err := net.InterfaceAddrs()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, addr := range addrs {
|
||||
ip, _, err := net.ParseCIDR(addr.String())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if ip.Equal(localRemoteAddr.IP) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
// Copyright 2015, Cong Ding. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Author: Cong Ding <dinggnu@gmail.com>
|
||||
|
||||
package stun
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPadding(t *testing.T) {
|
||||
b := []byte{1, 2}
|
||||
expected := []byte{1, 2, 0, 0}
|
||||
result := padding(b)
|
||||
if len(result) != len(expected) {
|
||||
t.Errorf("Padding error: result size wrong.\n")
|
||||
}
|
||||
for i := range expected {
|
||||
if expected[i] != result[i] {
|
||||
t.Errorf("Padding error: data wrong in bit %d.\n", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlign(t *testing.T) {
|
||||
d := make(map[uint16]uint16)
|
||||
d[1] = 4
|
||||
d[4] = 4
|
||||
d[5] = 8
|
||||
d[6] = 8
|
||||
d[7] = 8
|
||||
d[8] = 8
|
||||
d[65528] = 65528
|
||||
d[65529] = 65532
|
||||
d[65531] = 65532
|
||||
d[65532] = 65532
|
||||
for k, v := range d {
|
||||
if align(k) != v {
|
||||
t.Errorf("Align error: expected %d, get %d", align(k), v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsLocalAddress(t *testing.T) {
|
||||
if !isLocalAddress(":1234", "127.0.0.1:8888") {
|
||||
t.Errorf("isLocal error")
|
||||
}
|
||||
if !isLocalAddress("192.168.0.1:1234", "192.168.0.1:8888") {
|
||||
t.Errorf("isLocal error")
|
||||
}
|
||||
if !isLocalAddress("8.8.8.8:1234", "8.8.8.8:8888") {
|
||||
t.Errorf("isLocal error")
|
||||
}
|
||||
if isLocalAddress(":1234", "8.8.8.8:8888") {
|
||||
t.Errorf("isLocal error")
|
||||
}
|
||||
}
|
||||
+16
-1
@@ -6,6 +6,7 @@ import (
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/server"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
"html"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -26,7 +27,7 @@ func (s *BaseController) Prepare() {
|
||||
// web api verify
|
||||
// param 1 is md5(authKey+Current timestamp)
|
||||
// param 2 is timestamp (It's limited to 20 seconds.)
|
||||
md5Key := s.GetString("auth_key")
|
||||
md5Key := s.getEscapeString("auth_key")
|
||||
timestamp := s.GetIntNoErr("timestamp")
|
||||
configKey := beego.AppConfig.String("auth_key")
|
||||
timeNowUnix := time.Now().Unix()
|
||||
@@ -39,12 +40,21 @@ func (s *BaseController) Prepare() {
|
||||
s.Ctx.Input.SetData("client_id", s.GetSession("clientId").(int))
|
||||
s.Ctx.Input.SetParam("client_id", strconv.Itoa(s.GetSession("clientId").(int)))
|
||||
s.Data["isAdmin"] = false
|
||||
s.Data["username"] = s.GetSession("username")
|
||||
s.CheckUserAuth()
|
||||
} else {
|
||||
s.Data["isAdmin"] = true
|
||||
}
|
||||
s.Data["https_just_proxy"], _ = beego.AppConfig.Bool("https_just_proxy")
|
||||
s.Data["allow_user_login"], _ = beego.AppConfig.Bool("allow_user_login")
|
||||
s.Data["allow_flow_limit"], _ = beego.AppConfig.Bool("allow_flow_limit")
|
||||
s.Data["allow_rate_limit"], _ = beego.AppConfig.Bool("allow_rate_limit")
|
||||
s.Data["allow_connection_num_limit"], _ = beego.AppConfig.Bool("allow_connection_num_limit")
|
||||
s.Data["allow_multi_ip"], _ = beego.AppConfig.Bool("allow_multi_ip")
|
||||
s.Data["system_info_display"], _ = beego.AppConfig.Bool("system_info_display")
|
||||
s.Data["allow_tunnel_num_limit"], _ = beego.AppConfig.Bool("allow_tunnel_num_limit")
|
||||
s.Data["allow_local_proxy"], _ = beego.AppConfig.Bool("allow_local_proxy")
|
||||
s.Data["allow_user_change_username"], _ = beego.AppConfig.Bool("allow_user_change_username")
|
||||
}
|
||||
|
||||
//加载模板
|
||||
@@ -76,6 +86,11 @@ func (s *BaseController) error() {
|
||||
s.TplName = "public/error.html"
|
||||
}
|
||||
|
||||
//getEscapeString
|
||||
func (s *BaseController) getEscapeString(key string) string {
|
||||
return html.EscapeString(s.GetString(key))
|
||||
}
|
||||
|
||||
//去掉没有err返回值的int
|
||||
func (s *BaseController) GetIntNoErr(key string, def ...int) int {
|
||||
strv := s.Ctx.Input.Query(key)
|
||||
|
||||
+23
-18
@@ -27,7 +27,7 @@ func (s *ClientController) List() {
|
||||
} else {
|
||||
clientId = clientIdSession.(int)
|
||||
}
|
||||
list, cnt := server.GetClientList(start, length, s.GetString("search"), s.GetString("sort"), s.GetString("order"), clientId)
|
||||
list, cnt := server.GetClientList(start, length, s.getEscapeString("search"), s.getEscapeString("sort"), s.getEscapeString("order"), clientId)
|
||||
s.AjaxTable(list, cnt, cnt)
|
||||
}
|
||||
|
||||
@@ -39,21 +39,22 @@ func (s *ClientController) Add() {
|
||||
s.display()
|
||||
} else {
|
||||
t := &file.Client{
|
||||
VerifyKey: s.GetString("vkey"),
|
||||
VerifyKey: s.getEscapeString("vkey"),
|
||||
Id: int(file.GetDb().JsonDb.GetClientId()),
|
||||
Status: true,
|
||||
Remark: s.GetString("remark"),
|
||||
Remark: s.getEscapeString("remark"),
|
||||
Cnf: &file.Config{
|
||||
U: s.GetString("u"),
|
||||
P: s.GetString("p"),
|
||||
Compress: common.GetBoolByStr(s.GetString("compress")),
|
||||
U: s.getEscapeString("u"),
|
||||
P: s.getEscapeString("p"),
|
||||
Compress: common.GetBoolByStr(s.getEscapeString("compress")),
|
||||
Crypt: s.GetBoolNoErr("crypt"),
|
||||
},
|
||||
ConfigConnAllow: s.GetBoolNoErr("config_conn_allow"),
|
||||
RateLimit: s.GetIntNoErr("rate_limit"),
|
||||
MaxConn: s.GetIntNoErr("max_conn"),
|
||||
WebUserName: s.GetString("web_username"),
|
||||
WebPassword: s.GetString("web_password"),
|
||||
WebUserName: s.getEscapeString("web_username"),
|
||||
WebPassword: s.getEscapeString("web_password"),
|
||||
MaxTunnelNum: s.GetIntNoErr("max_tunnel"),
|
||||
Flow: &file.Flow{
|
||||
ExportFlow: 0,
|
||||
InletFlow: 0,
|
||||
@@ -101,29 +102,33 @@ func (s *ClientController) Edit() {
|
||||
if c, err := file.GetDb().GetClient(id); err != nil {
|
||||
s.error()
|
||||
} else {
|
||||
if s.GetString("web_username") != "" {
|
||||
if s.GetString("web_username") == beego.AppConfig.String("web_username") || !file.GetDb().VerifyUserName(s.GetString("web_username"), c.Id) {
|
||||
if s.getEscapeString("web_username") != "" {
|
||||
if s.getEscapeString("web_username") == beego.AppConfig.String("web_username") || !file.GetDb().VerifyUserName(s.getEscapeString("web_username"), c.Id) {
|
||||
s.AjaxErr("web login username duplicate, please reset")
|
||||
return
|
||||
}
|
||||
}
|
||||
if s.GetSession("isAdmin").(bool) {
|
||||
if !file.GetDb().VerifyVkey(s.GetString("vkey"), c.Id) {
|
||||
if !file.GetDb().VerifyVkey(s.getEscapeString("vkey"), c.Id) {
|
||||
s.AjaxErr("Vkey duplicate, please reset")
|
||||
return
|
||||
}
|
||||
c.VerifyKey = s.GetString("vkey")
|
||||
c.VerifyKey = s.getEscapeString("vkey")
|
||||
c.Flow.FlowLimit = int64(s.GetIntNoErr("flow_limit"))
|
||||
c.RateLimit = s.GetIntNoErr("rate_limit")
|
||||
c.MaxConn = s.GetIntNoErr("max_conn")
|
||||
c.MaxTunnelNum = s.GetIntNoErr("max_tunnel")
|
||||
}
|
||||
c.Remark = s.GetString("remark")
|
||||
c.Cnf.U = s.GetString("u")
|
||||
c.Cnf.P = s.GetString("p")
|
||||
c.Cnf.Compress = common.GetBoolByStr(s.GetString("compress"))
|
||||
c.Remark = s.getEscapeString("remark")
|
||||
c.Cnf.U = s.getEscapeString("u")
|
||||
c.Cnf.P = s.getEscapeString("p")
|
||||
c.Cnf.Compress = common.GetBoolByStr(s.getEscapeString("compress"))
|
||||
c.Cnf.Crypt = s.GetBoolNoErr("crypt")
|
||||
c.WebUserName = s.GetString("web_username")
|
||||
c.WebPassword = s.GetString("web_password")
|
||||
b, err := beego.AppConfig.Bool("allow_user_change_username")
|
||||
if s.GetSession("isAdmin").(bool) || (err == nil && b) {
|
||||
c.WebUserName = s.getEscapeString("web_username")
|
||||
}
|
||||
c.WebPassword = s.getEscapeString("web_password")
|
||||
c.ConfigConnAllow = s.GetBoolNoErr("config_conn_allow")
|
||||
if c.Rate != nil {
|
||||
c.Rate.Stop()
|
||||
|
||||
+49
-44
@@ -68,7 +68,7 @@ func (s *IndexController) Host() {
|
||||
|
||||
func (s *IndexController) All() {
|
||||
s.Data["menu"] = "client"
|
||||
clientId := s.GetString("client_id")
|
||||
clientId := s.getEscapeString("client_id")
|
||||
s.Data["client_id"] = clientId
|
||||
s.SetInfo("client id:" + clientId)
|
||||
s.display("index/list")
|
||||
@@ -76,30 +76,30 @@ func (s *IndexController) All() {
|
||||
|
||||
func (s *IndexController) GetTunnel() {
|
||||
start, length := s.GetAjaxParams()
|
||||
taskType := s.GetString("type")
|
||||
taskType := s.getEscapeString("type")
|
||||
clientId := s.GetIntNoErr("client_id")
|
||||
list, cnt := server.GetTunnel(start, length, taskType, clientId, s.GetString("search"))
|
||||
list, cnt := server.GetTunnel(start, length, taskType, clientId, s.getEscapeString("search"))
|
||||
s.AjaxTable(list, cnt, cnt)
|
||||
}
|
||||
|
||||
func (s *IndexController) Add() {
|
||||
if s.Ctx.Request.Method == "GET" {
|
||||
s.Data["type"] = s.GetString("type")
|
||||
s.Data["client_id"] = s.GetString("client_id")
|
||||
s.Data["type"] = s.getEscapeString("type")
|
||||
s.Data["client_id"] = s.getEscapeString("client_id")
|
||||
s.SetInfo("add tunnel")
|
||||
s.display()
|
||||
} else {
|
||||
t := &file.Tunnel{
|
||||
Port: s.GetIntNoErr("port"),
|
||||
ServerIp: s.GetString("server_ip"),
|
||||
Mode: s.GetString("type"),
|
||||
Target: &file.Target{TargetStr: s.GetString("target")},
|
||||
ServerIp: s.getEscapeString("server_ip"),
|
||||
Mode: s.getEscapeString("type"),
|
||||
Target: &file.Target{TargetStr: s.getEscapeString("target"), LocalProxy: s.GetBoolNoErr("local_proxy")},
|
||||
Id: int(file.GetDb().JsonDb.GetTaskId()),
|
||||
Status: true,
|
||||
Remark: s.GetString("remark"),
|
||||
Password: s.GetString("password"),
|
||||
LocalPath: s.GetString("local_path"),
|
||||
StripPre: s.GetString("strip_pre"),
|
||||
Remark: s.getEscapeString("remark"),
|
||||
Password: s.getEscapeString("password"),
|
||||
LocalPath: s.getEscapeString("local_path"),
|
||||
StripPre: s.getEscapeString("strip_pre"),
|
||||
Flow: &file.Flow{},
|
||||
}
|
||||
if !tool.TestServerPort(t.Port, t.Mode) {
|
||||
@@ -109,6 +109,9 @@ func (s *IndexController) Add() {
|
||||
if t.Client, err = file.GetDb().GetClient(s.GetIntNoErr("client_id")); err != nil {
|
||||
s.AjaxErr(err.Error())
|
||||
}
|
||||
if t.Client.MaxTunnelNum != 0 && t.Client.GetTunnelNum() >= t.Client.MaxTunnelNum {
|
||||
s.AjaxErr("The number of tunnels exceeds the limit")
|
||||
}
|
||||
if err := file.GetDb().NewTask(t); err != nil {
|
||||
s.AjaxErr(err.Error())
|
||||
}
|
||||
@@ -158,14 +161,15 @@ func (s *IndexController) Edit() {
|
||||
}
|
||||
t.Port = s.GetIntNoErr("port")
|
||||
}
|
||||
t.ServerIp = s.GetString("server_ip")
|
||||
t.Mode = s.GetString("type")
|
||||
t.Target = &file.Target{TargetStr: s.GetString("target")}
|
||||
t.Password = s.GetString("password")
|
||||
t.ServerIp = s.getEscapeString("server_ip")
|
||||
t.Mode = s.getEscapeString("type")
|
||||
t.Target = &file.Target{TargetStr: s.getEscapeString("target")}
|
||||
t.Password = s.getEscapeString("password")
|
||||
t.Id = id
|
||||
t.LocalPath = s.GetString("local_path")
|
||||
t.StripPre = s.GetString("strip_pre")
|
||||
t.Remark = s.GetString("remark")
|
||||
t.LocalPath = s.getEscapeString("local_path")
|
||||
t.StripPre = s.getEscapeString("strip_pre")
|
||||
t.Remark = s.getEscapeString("remark")
|
||||
t.Target.LocalProxy = s.GetBoolNoErr("local_proxy")
|
||||
file.GetDb().UpdateTask(t)
|
||||
server.StopServer(t.Id)
|
||||
server.StartTask(t.Id)
|
||||
@@ -200,14 +204,14 @@ func (s *IndexController) Start() {
|
||||
|
||||
func (s *IndexController) HostList() {
|
||||
if s.Ctx.Request.Method == "GET" {
|
||||
s.Data["client_id"] = s.GetString("client_id")
|
||||
s.Data["client_id"] = s.getEscapeString("client_id")
|
||||
s.Data["menu"] = "host"
|
||||
s.SetInfo("host list")
|
||||
s.display("index/hlist")
|
||||
} else {
|
||||
start, length := s.GetAjaxParams()
|
||||
clientId := s.GetIntNoErr("client_id")
|
||||
list, cnt := file.GetDb().GetHost(start, length, clientId, s.GetString("search"))
|
||||
list, cnt := file.GetDb().GetHost(start, length, clientId, s.getEscapeString("search"))
|
||||
s.AjaxTable(list, cnt, cnt)
|
||||
}
|
||||
}
|
||||
@@ -236,23 +240,23 @@ func (s *IndexController) DelHost() {
|
||||
|
||||
func (s *IndexController) AddHost() {
|
||||
if s.Ctx.Request.Method == "GET" {
|
||||
s.Data["client_id"] = s.GetString("client_id")
|
||||
s.Data["client_id"] = s.getEscapeString("client_id")
|
||||
s.Data["menu"] = "host"
|
||||
s.SetInfo("add host")
|
||||
s.display("index/hadd")
|
||||
} else {
|
||||
h := &file.Host{
|
||||
Id: int(file.GetDb().JsonDb.GetHostId()),
|
||||
Host: s.GetString("host"),
|
||||
Target: &file.Target{TargetStr: s.GetString("target")},
|
||||
HeaderChange: s.GetString("header"),
|
||||
HostChange: s.GetString("hostchange"),
|
||||
Remark: s.GetString("remark"),
|
||||
Location: s.GetString("location"),
|
||||
Host: s.getEscapeString("host"),
|
||||
Target: &file.Target{TargetStr: s.getEscapeString("target"), LocalProxy: s.GetBoolNoErr("local_proxy")},
|
||||
HeaderChange: s.getEscapeString("header"),
|
||||
HostChange: s.getEscapeString("hostchange"),
|
||||
Remark: s.getEscapeString("remark"),
|
||||
Location: s.getEscapeString("location"),
|
||||
Flow: &file.Flow{},
|
||||
Scheme: s.GetString("scheme"),
|
||||
KeyFilePath: s.GetString("key_file_path"),
|
||||
CertFilePath: s.GetString("cert_file_path"),
|
||||
Scheme: s.getEscapeString("scheme"),
|
||||
KeyFilePath: s.getEscapeString("key_file_path"),
|
||||
CertFilePath: s.getEscapeString("cert_file_path"),
|
||||
}
|
||||
var err error
|
||||
if h.Client, err = file.GetDb().GetClient(s.GetIntNoErr("client_id")); err != nil {
|
||||
@@ -280,11 +284,11 @@ func (s *IndexController) EditHost() {
|
||||
if h, err := file.GetDb().GetHostById(id); err != nil {
|
||||
s.error()
|
||||
} else {
|
||||
if h.Host != s.GetString("host") {
|
||||
if h.Host != s.getEscapeString("host") {
|
||||
tmpHost := new(file.Host)
|
||||
tmpHost.Host = s.GetString("host")
|
||||
tmpHost.Location = s.GetString("location")
|
||||
tmpHost.Scheme = s.GetString("scheme")
|
||||
tmpHost.Host = s.getEscapeString("host")
|
||||
tmpHost.Location = s.getEscapeString("location")
|
||||
tmpHost.Scheme = s.getEscapeString("scheme")
|
||||
if file.GetDb().IsHostExist(tmpHost) {
|
||||
s.AjaxErr("host has exist")
|
||||
return
|
||||
@@ -295,15 +299,16 @@ func (s *IndexController) EditHost() {
|
||||
} else {
|
||||
h.Client = client
|
||||
}
|
||||
h.Host = s.GetString("host")
|
||||
h.Target = &file.Target{TargetStr: s.GetString("target")}
|
||||
h.HeaderChange = s.GetString("header")
|
||||
h.HostChange = s.GetString("hostchange")
|
||||
h.Remark = s.GetString("remark")
|
||||
h.Location = s.GetString("location")
|
||||
h.Scheme = s.GetString("scheme")
|
||||
h.KeyFilePath = s.GetString("key_file_path")
|
||||
h.CertFilePath = s.GetString("cert_file_path")
|
||||
h.Host = s.getEscapeString("host")
|
||||
h.Target = &file.Target{TargetStr: s.getEscapeString("target")}
|
||||
h.HeaderChange = s.getEscapeString("header")
|
||||
h.HostChange = s.getEscapeString("hostchange")
|
||||
h.Remark = s.getEscapeString("remark")
|
||||
h.Location = s.getEscapeString("location")
|
||||
h.Scheme = s.getEscapeString("scheme")
|
||||
h.KeyFilePath = s.getEscapeString("key_file_path")
|
||||
h.CertFilePath = s.getEscapeString("cert_file_path")
|
||||
h.Target.LocalProxy = s.GetBoolNoErr("local_proxy")
|
||||
file.GetDb().JsonDb.StoreHostToJsonFile()
|
||||
}
|
||||
s.AjaxOk("modified success")
|
||||
|
||||
@@ -13,6 +13,7 @@ type LoginController struct {
|
||||
}
|
||||
|
||||
func (self *LoginController) Index() {
|
||||
self.Data["register_allow"], _ = beego.AppConfig.Bool("allow_user_register")
|
||||
self.TplName = "login/index.html"
|
||||
}
|
||||
func (self *LoginController) Verify() {
|
||||
@@ -42,6 +43,7 @@ func (self *LoginController) Verify() {
|
||||
if auth {
|
||||
self.SetSession("isAdmin", false)
|
||||
self.SetSession("clientId", v.Id)
|
||||
self.SetSession("username", v.WebUserName)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
@@ -55,6 +57,37 @@ func (self *LoginController) Verify() {
|
||||
}
|
||||
self.ServeJSON()
|
||||
}
|
||||
func (self *LoginController) Register() {
|
||||
if self.Ctx.Request.Method == "GET" {
|
||||
self.TplName = "login/register.html"
|
||||
} else {
|
||||
if b, err := beego.AppConfig.Bool("allow_user_register"); err != nil || !b {
|
||||
self.Data["json"] = map[string]interface{}{"status": 0, "msg": "register is not allow"}
|
||||
self.ServeJSON()
|
||||
return
|
||||
}
|
||||
if self.GetString("username") == "" || self.GetString("password") == "" || self.GetString("username") == beego.AppConfig.String("web_username") {
|
||||
self.Data["json"] = map[string]interface{}{"status": 0, "msg": "please check your input"}
|
||||
self.ServeJSON()
|
||||
return
|
||||
}
|
||||
t := &file.Client{
|
||||
Id: int(file.GetDb().JsonDb.GetClientId()),
|
||||
Status: true,
|
||||
Cnf: &file.Config{},
|
||||
WebUserName: self.GetString("username"),
|
||||
WebPassword: self.GetString("password"),
|
||||
Flow: &file.Flow{},
|
||||
}
|
||||
if err := file.GetDb().NewClient(t); err != nil {
|
||||
self.Data["json"] = map[string]interface{}{"status": 0, "msg": err.Error()}
|
||||
} else {
|
||||
self.Data["json"] = map[string]interface{}{"status": 1, "msg": "register success"}
|
||||
}
|
||||
self.ServeJSON()
|
||||
}
|
||||
}
|
||||
|
||||
func (self *LoginController) Out() {
|
||||
self.SetSession("auth", false)
|
||||
self.Redirect("/login/index", 302)
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
placeholder="remark">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{{if eq true .allow_flow_limit}}
|
||||
<div class="form-group" id="flow_limit">
|
||||
<label class="col-sm-2 control-label" langtag="info-flow-limit">流量限制</label>
|
||||
<div class="col-sm-10">
|
||||
@@ -20,7 +20,8 @@
|
||||
<span class="help-block m-b-none" langtag="info-flow-limit-unit">unit: M</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{{end}}
|
||||
{{if eq true .allow_rate_limit}}
|
||||
<div class="form-group" id="rate_limit">
|
||||
<label class="control-label col-sm-2" langtag="info-bandwidth">带宽限制</label>
|
||||
<div class="col-sm-10">
|
||||
@@ -29,6 +30,8 @@
|
||||
<span class="help-block m-b-none" langtag="info-bandwidth-unit">unit: KB/S</span>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if eq true .allow_connection_num_limit}}
|
||||
<div class="form-group" id="max_conn">
|
||||
<label class="control-label col-sm-2" langtag="info-max-conn-num">客户端最大连接数量</label>
|
||||
<div class="col-sm-10">
|
||||
@@ -36,6 +39,16 @@
|
||||
placeholder="empty means to be unrestricted">
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if eq true .allow_tunnel_num_limit}}
|
||||
<div class="form-group" id="max_tunnel">
|
||||
<label class="control-label col-sm-2" langtag="info-max-tunnel-num">客户端最大隧道数量</label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" type="text" name="max_tunnel"
|
||||
placeholder="empty means to be unrestricted">
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
<div class="form-group" id="u">
|
||||
<label class="control-label col-sm-2" langtag="info-web-auth-username">basic权限认证用户名</label>
|
||||
<div class="col-sm-10">
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
</div>
|
||||
</div>
|
||||
{{if eq true .isAdmin}}
|
||||
{{if eq true .allow_flow_limit}}
|
||||
<div class="form-group" id="flow_limit">
|
||||
<label class="col-sm-2 control-label" langtag="info-flow-limit">流量限制</label>
|
||||
<div class="col-sm-10">
|
||||
@@ -21,6 +22,8 @@
|
||||
<span class="help-block m-b-none">unit: M</span>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if eq true .allow_rate_limit}}
|
||||
|
||||
<div class="form-group" id="rate_limit">
|
||||
<label class="control-label col-sm-2" langtag="info-bandwidth">带宽限制</label>
|
||||
@@ -30,6 +33,9 @@
|
||||
<span class="help-block m-b-none">unit: KB/S</span>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if eq true .allow_connection_num_limit}}
|
||||
|
||||
<div class="form-group" id="max_conn">
|
||||
<label class="control-label col-sm-2" langtag="info-max-conn-num">客户端最大连接数</label>
|
||||
<div class="col-sm-10">
|
||||
@@ -37,6 +43,16 @@
|
||||
placeholder="empty means to be unrestricted">
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if eq true .allow_tunnel_num_limit}}
|
||||
<div class="form-group" id="max_tunnel">
|
||||
<label class="control-label col-sm-2" langtag="info-max-tunnel-num">客户端最大隧道数量</label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control" value="{{.c.MaxTunnelNum}}" type="text" name="max_tunnel"
|
||||
placeholder="empty means to be unrestricted">
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{end}}
|
||||
<div class="form-group" id="u">
|
||||
<label class="control-label col-sm-2" langtag="info-web-auth-username">basic权限认证用户名</label>
|
||||
@@ -65,6 +81,7 @@
|
||||
</div>
|
||||
{{end}}
|
||||
{{if eq true .allow_user_login}}
|
||||
{{if or (eq true .allow_user_change_username) (eq true .isAdmin)}}
|
||||
<div class="form-group" id="web_username">
|
||||
<label class="control-label col-sm-2" langtag="info-client-web-username">web登陆用户名</label>
|
||||
<div class="col-sm-10">
|
||||
@@ -72,6 +89,7 @@
|
||||
placeholder="empty means to be unrestricted">
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
<div class="form-group" id="web_password">
|
||||
<label class="control-label col-sm-2" langtag="info-client-web-password">web登陆密码</label>
|
||||
<div class="col-sm-10">
|
||||
|
||||
@@ -127,6 +127,7 @@
|
||||
+ '<b langtag="info-now-conn-num">当前连接数</b>:' + row.NowConn + `       `
|
||||
+ '<b langtag="info-flow-limit">流量限制</b>:' + row.Flow.FlowLimit + `m       `
|
||||
+ '<b langtag="info-rate-limit">带宽限制</b>:' + row.RateLimit + `kb/s       `
|
||||
+ '<b langtag="info-max-tunnel-num">隧道数限制</b>:' + row.MaxTunnelNum + `       `
|
||||
+ '<b langtag="info-client-web-username">web登陆用户名</b>:' + row.WebUserName + `       `
|
||||
+ '<b langtag="info-client-web-password">web登陆密码</b>:' + row.WebPassword + `       `
|
||||
+ `       ` + "<br/><br>"
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
placeholder="empty means to be unrestricted">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{{if eq true .allow_multi_ip}}
|
||||
<div class="form-group" id="server_ip">
|
||||
<label class="col-sm-2 control-label" langtag="info-server-ip">服务端ip</label>
|
||||
<div class="col-sm-10">
|
||||
@@ -35,7 +35,7 @@
|
||||
placeholder="such as 0.0.0.0">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{{end}}
|
||||
<div class="form-group" id="port">
|
||||
<label class="col-sm-2 control-label" langtag="info-server-port">服务端端口</label>
|
||||
<div class="col-sm-10">
|
||||
@@ -43,8 +43,20 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{{if eq true .allow_local_proxy}}
|
||||
<div class="form-group" id="local_proxy">
|
||||
<label class="control-label col-sm-2" langtag="info-local-proxy">是否代理为服务端本地</label>
|
||||
<div class="col-sm-10">
|
||||
<select class="form-control" name="local_proxy">
|
||||
<option value="0">no</option>
|
||||
<option value="1">yes</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
<div class="form-group" id="target">
|
||||
<label class="col-sm-2 control-label" langtag="info-target">内网目标(ip:端口)</label>
|
||||
<label class="col-sm-2 control-label" langtag="info-target">目标(ip:端口)</label>
|
||||
<div class="col-sm-10">
|
||||
<textarea class="form-control" name="target" rows="4" placeholder="10.1.50.203:22
|
||||
10.1.50.202:22"></textarea>
|
||||
@@ -103,13 +115,13 @@
|
||||
</div>
|
||||
<script>
|
||||
var arr = []
|
||||
arr["all"] = ["type", "port", "compress", "u", "p", "target", "password", "strip_pre", "local_path"]
|
||||
arr["tcp"] = ["type", "port", "target", "compress", "u", "p", "tcp隧道模式,提供一条tcp隧道,适用于ssh、远程桌面等,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,访问公网服务器的设定端口,则相当于访问内网目标地址的目标端口"]
|
||||
arr["udp"] = ["type", "port", "target", "compress", "udp隧道模式,提供一条udp隧道,适用于dns、内网dns访问等,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,访问公网服务器的设定端口,则相当于访问内网目标地址的udp目标端口"]
|
||||
arr["all"] = ["type", "port", "compress", "u", "p", "target", "password", "strip_pre", "local_path", "local_proxy"]
|
||||
arr["tcp"] = ["type", "port", "target", "compress", "u", "p", "local_proxy", "tcp隧道模式,提供一条tcp隧道,适用于ssh、远程桌面等,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,访问公网服务器的设定端口,则相当于访问内网目标地址的目标端口"]
|
||||
arr["udp"] = ["type", "port", "target", "compress", "local_proxy", "udp隧道模式,提供一条udp隧道,适用于dns、内网dns访问等,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,访问公网服务器的设定端口,则相当于访问内网目标地址的udp目标端口"]
|
||||
arr["socks5"] = ["type", "port", "compress", "u", "p", "socks5代理模式,内网socks5代理,配合proxifer,可如同使用vpn一样访问内网设备或资源,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,在外网环境下本机配置socks5代理,即访问内网设备或者资源 "]
|
||||
arr["httpProxy"] = ["type", "port", "compress", "u", "p", " http代理模式,内网http代理,可访问内网网站,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,在外网环境下本机配置http代理,即访问内网站点"]
|
||||
arr["secret"] = ["type", "target", "compress", "password", "u", "p", " http代理模式,内网http代理,可访问内网网站,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,在外网环境下本机配置http代理,即访问内网站点"]
|
||||
arr["p2p"] = ["type", "compress", "password", "u", "p", " http代理模式,内网http代理,可访问内网网站,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,在外网环境下本机配置http代理,即访问内网站点"]
|
||||
arr["p2p"] = ["type", "target", "compress", "password", "u", "p", " http代理模式,内网http代理,可访问内网网站,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,在外网环境下本机配置http代理,即访问内网站点"]
|
||||
arr["file"] = ["type", "strip_pre", "local_path", "port", " http代理模式,内网http代理,可访问内网网站,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,在外网环境下本机配置http代理,即访问内网站点"]
|
||||
arrClientHide = ["compress", "u", "p", "crypt", "mux"]
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
placeholder="empty means to be unrestricted">
|
||||
</div>
|
||||
</div>
|
||||
{{if eq true .allow_multi_ip}}
|
||||
<div class="form-group" id="server_ip">
|
||||
<label class="col-sm-2 control-label" langtag="info-server-ip">服务端ip</label>
|
||||
<div class="col-sm-10">
|
||||
@@ -35,6 +36,7 @@
|
||||
placeholder="such as 0.0.0.0">
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
<div class="form-group" id="port">
|
||||
<label class="col-sm-2 control-label" langtag="info-server-port">服务端端口</label>
|
||||
<div class="col-sm-10">
|
||||
@@ -42,6 +44,17 @@
|
||||
placeholder="such as 8024">
|
||||
</div>
|
||||
</div>
|
||||
{{if eq true .allow_local_proxy}}
|
||||
<div class="form-group" id="local_proxy">
|
||||
<label class="control-label col-sm-2" langtag="info-local-proxy">是否代理为服务端本地</label>
|
||||
<div class="col-sm-10">
|
||||
<select class="form-control" name="local_proxy">
|
||||
<option {{if eq false .t.Target.LocalProxy}}selected{{end}} value="0">no</option>
|
||||
<option {{if eq true .t.Target.LocalProxy}}selected{{end}} value="1">yes</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
<div class="form-group" id="target">
|
||||
<label class="col-sm-2 control-label" langtag="info-target">内网目标(ip:端口)</label>
|
||||
<div class="col-sm-10">
|
||||
@@ -101,13 +114,13 @@
|
||||
</div>
|
||||
<script>
|
||||
var arr = []
|
||||
arr["all"] = ["type", "port", "compress", "u", "p", "target", "password", "local_path", "strip_pre"]
|
||||
arr["tcp"] = ["type", "port", "target", "u", "p", "compress"]
|
||||
arr["udp"] = ["type", "port", "target", "compress"]
|
||||
arr["all"] = ["type", "port", "compress", "u", "p", "target", "password", "local_path", "strip_pre", "local_proxy"]
|
||||
arr["tcp"] = ["type", "port", "target", "u", "p", "compress", "local_proxy"]
|
||||
arr["udp"] = ["type", "port", "target", "compress", "local_proxy"]
|
||||
arr["socks5"] = ["type", "port", "compress", "u", "p"]
|
||||
arr["httpProxy"] = ["type", "port", "compress", "u", "p"]
|
||||
arr["secret"] = ["type", "target", "compress", "u", "p", "password"]
|
||||
arr["p2p"] = ["type", "password"]
|
||||
arr["p2p"] = ["type", "target", "password"]
|
||||
arr["file"] = ["type", "port", "local_path", "strip_pre"]
|
||||
arrClientHide = ["compress", "u", "p", "crypt", "mux"]
|
||||
|
||||
|
||||
@@ -56,6 +56,17 @@
|
||||
placeholder="client id">
|
||||
</div>
|
||||
</div>
|
||||
{{if eq true .allow_local_proxy}}
|
||||
<div class="form-group" id="local_proxy">
|
||||
<label class="control-label col-sm-2" langtag="info-local-proxy">是否代理为服务端本地</label>
|
||||
<div class="col-sm-10">
|
||||
<select class="form-control" name="local_proxy">
|
||||
<option value="0">no</option>
|
||||
<option value="1">yes</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" langtag="info-target">内网目标(ip:端口)</label>
|
||||
<div class="col-sm-10">
|
||||
|
||||
@@ -59,6 +59,17 @@
|
||||
placeholder="client id">
|
||||
</div>
|
||||
</div>
|
||||
{{if eq true .allow_local_proxy}}
|
||||
<div class="form-group" id="local_proxy">
|
||||
<label class="control-label col-sm-2" langtag="info-local-proxy">是否代理为服务端本地</label>
|
||||
<div class="col-sm-10">
|
||||
<select class="form-control" name="local_proxy">
|
||||
<option {{if eq false .h.Target.LocalProxy}}selected{{end}} value="0">no</option>
|
||||
<option {{if eq true .h.Target.LocalProxy}}selected{{end}} value="1">yes</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" langtag="info-target">内网目标(ip:端口)</label>
|
||||
<div class="col-sm-10">
|
||||
|
||||
@@ -242,7 +242,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{{if eq true .system_info_display}}
|
||||
<div class="row">
|
||||
<div class="col-lg-6">
|
||||
<div class="ibox float-e-margins">
|
||||
@@ -340,6 +340,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
<div class="row">
|
||||
<div class="col-lg-6">
|
||||
|
||||
@@ -63,12 +63,19 @@
|
||||
detailView: true,
|
||||
smartDisplay: true, // 智能显示 pagination 和 cardview 等
|
||||
detailFormatter: function (index, row, element) {
|
||||
return '<b langtag="info-export-flow">出口流量</b>:' + change(row.Flow.ExportFlow) + `       `
|
||||
+ '<b langtag="info-inlet-flow">入口流量</b>:' + change(row.Flow.InletFlow) + `       ` + "<br/><br>"
|
||||
tmp = '<b langtag="info-export-flow">出口流量</b>:' + change(row.Flow.ExportFlow) + `       `
|
||||
+ '<b langtag="info-inlet-flow">入口流量</b>:' + change(row.Flow.InletFlow) + `       `
|
||||
+ '<b langtag="info-crypt">加密</b>:' + row.Client.Cnf.Crypt + `       `
|
||||
+ '<b langtag="info-compress">压缩</b>:' + row.Client.Cnf.Compress + `       `
|
||||
+ '<b langtag="info-web-auth-username">basic权限认证用户名</b>:' + row.Client.Cnf.U + `       `
|
||||
+ '<b langtag="info-web-auth-password">basic权限认证密码</b>:' + row.Client.Cnf.P + `       `
|
||||
if (row.Mode == "p2p") {
|
||||
return tmp + "<br/><br>" + '<b langtag="info-command">访问端命令</b>:' + "<code>./npc{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.Client.VerifyKey + " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -target=" + row.Target.TargetStr + "</code>"
|
||||
}
|
||||
if (row.Mode = "secret") {
|
||||
return tmp + "<br/><br>" + '<b langtag="info-command">访问端命令</b>:' + "<code>./npc{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.Client.VerifyKey + " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -local_type=secret" + "</code>"
|
||||
}
|
||||
return tmp
|
||||
},
|
||||
//表格的列
|
||||
columns: [
|
||||
@@ -112,13 +119,13 @@
|
||||
field: 'Password',//域值
|
||||
title: 'secret',//标题
|
||||
visible: true,//false表示不显示
|
||||
|
||||
|
||||
},
|
||||
{
|
||||
field: 'Status',//域值
|
||||
title: 'setting',//内容
|
||||
visible: true,//false表示不显示
|
||||
|
||||
|
||||
formatter: function (value, row, index) {
|
||||
if (value) {
|
||||
return '<span class="badge badge-primary">open</span>'
|
||||
@@ -131,7 +138,7 @@
|
||||
field: 'RunStatus',//域值
|
||||
title: 'run',//内容
|
||||
visible: true,//false表示不显示
|
||||
|
||||
|
||||
formatter: function (value, row, index) {
|
||||
if (value) {
|
||||
return '<span class="badge badge-primary">open</span>'
|
||||
@@ -144,7 +151,7 @@
|
||||
field: '',//域值
|
||||
title: 'client',//内容
|
||||
visible: true,//false表示不显示
|
||||
|
||||
|
||||
formatter: function (value, row, index) {
|
||||
if (row.Client.IsConnect) {
|
||||
return '<span class="badge badge-primary">online</span>'
|
||||
@@ -157,7 +164,7 @@
|
||||
field: 'option',//域值
|
||||
title: 'option',//内容
|
||||
visible: true,//false表示不显示
|
||||
|
||||
|
||||
formatter: function (value, row, index) {
|
||||
btn_group = '<div class="btn-group">'
|
||||
btn = `<button onclick="del(` + row.Id + `)" class="btn-danger"><i class="fa fa-trash"></i></button><button onclick="edit(` + row.Id + `)" class="btn-primary"><i class="fa fa-edit"></i></button></div>`
|
||||
|
||||
@@ -48,6 +48,9 @@
|
||||
<input name="password" type="password" class="form-control" placeholder="password" required="">
|
||||
</div>
|
||||
<button onclick="login()" class="btn btn-primary block full-width m-b">login</button>
|
||||
{{if eq true .register_allow}}
|
||||
<a class="btn btn-sm btn-white btn-block" href="/login/register">register</a>
|
||||
{{end}}
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<title>nps register</title>
|
||||
|
||||
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="/static/font-awesome/css/font-awesome.css" rel="stylesheet">
|
||||
|
||||
<link href="/static/css/style.css" rel="stylesheet">
|
||||
|
||||
</head>
|
||||
|
||||
<body class="gray-bg">
|
||||
|
||||
<div class="middle-box text-center loginscreen animated fadeInDown">
|
||||
<div>
|
||||
<div>
|
||||
|
||||
<h1 class="logo-name">NPS</h1>
|
||||
|
||||
</div>
|
||||
<h3>register NPS</h3>
|
||||
<form class="m-t" role="form" onsubmit="return false">
|
||||
<div class="form-group">
|
||||
<input type="text" class="form-control" placeholder="username" name="username" required="">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<input type="password" class="form-control" placeholder="password" name="password" required="">
|
||||
</div>
|
||||
<button onclick="register()" type="submit" class="btn btn-primary block full-width m-b">register</button>
|
||||
|
||||
<a class="btn btn-sm btn-white btn-block" href="/login/index">login</a>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/static/js/jquery-2.1.1.js"></script>
|
||||
<script>
|
||||
function register() {
|
||||
$.ajax({
|
||||
type: "POST",
|
||||
url: "/login/register",
|
||||
data: $("form").serializeArray(),
|
||||
success: function (res) {
|
||||
alert(res.msg)
|
||||
if (res.status) {
|
||||
window.location.href = "/login/index"
|
||||
}
|
||||
}
|
||||
})
|
||||
return false
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -42,7 +42,7 @@
|
||||
{{if eq true .isAdmin}}
|
||||
admin
|
||||
{{else}}
|
||||
user
|
||||
{{.username}}
|
||||
{{end}}
|
||||
</strong>
|
||||
</span> <span class="text-muted text-xs block">system </span> </span>
|
||||
|
||||
Reference in New Issue
Block a user