Compare commits

..
8 Commits
Author SHA1 Message Date
刘河 69e60a3337 Readme 2019-03-26 15:55:50 +08:00
刘河 5beee738df hot reload 2019-03-26 15:54:20 +08:00
刘河 8fa3e8f785 Version 2019-03-26 15:31:21 +08:00
刘河 65e0822b63 nps some config hot reload 2019-03-26 15:23:39 +08:00
刘河 7edc65cfde http proxy bug 2019-03-26 14:28:43 +08:00
刘河 ff030b9c1c target hot reload bug 2019-03-26 13:38:49 +08:00
刘河 7637cd448e Flow display and user login and rate limit bug 2019-03-26 11:13:07 +08:00
刘河 2a5a45a700 https crypt bug 2019-03-25 20:40:22 +08:00
26 changed files with 245 additions and 38 deletions
+18
View File
@@ -40,6 +40,7 @@ nps是一款轻量级、高性能、功能强大的**内网穿透**代理服务
* [服务端测试](#服务端测试)
* [服务端启动](#服务端启动)
* [web管理](#web管理)
* [服务端配置文件重载](#服务端配置文件重载)
* [服务端停止或重启](#服务端停止或重启)
* [配置文件说明](#服务端配置文件)
@@ -51,6 +52,7 @@ nps是一款轻量级、高性能、功能强大的**内网穿透**代理服务
* [自定义客户端连接密钥](#自定义客户端连接密钥)
* [关闭公钥访问](#关闭公钥访问)
* [关闭web管理](#关闭web管理)
* [服务端多用户登陆](#服务端多用户登陆)
* [客户端](#客户端)
* [客户端启动](#客户端启动)
* [无配置文件模式](#无配置文件模式)
@@ -96,6 +98,7 @@ nps是一款轻量级、高性能、功能强大的**内网穿透**代理服务
* [相关说明](#相关说明)
* [流量统计](#流量统计)
* [当前客户端带宽](#当前客户端带宽)
* [热更新支持](#热更新支持)
* [获取用户真实ip](#获取用户真实ip)
* [客户端地址显示](#客户端地址显示)
@@ -285,6 +288,14 @@ port=2001
进入web管理界面,有详细的说明
#### 服务端配置文件重载
如果是daemon启动
```shell
./nps reload
```
**说明:** 仅支持部分配置重载,例如`allow_user_login` `auth_crypt_key` `auth_key` `web_username` `web_password` 等,未来将支持更多
#### 服务端停止或重启
如果是daemon启动
```shell
@@ -394,6 +405,10 @@ web上可以自定义客户端连接的密钥,但是必须具有唯一性
### 关闭web管理
可以将`nps.conf`中的`web_port`设置为空或者删除
### 服务端多用户登陆
如果将`nps.conf`中的`allow_user_login`设置为true,服务端web将支持多用户登陆,登陆用户名为user,密码为每个客户端的验证密钥,默认该功能是关闭的。
## 客户端
### 客户端启动
@@ -838,6 +853,9 @@ health_http_url | 健康检查url,仅http模式适用
### 流量统计
可统计显示每个代理使用的流量,由于压缩和加密等原因,会和实际环境中的略有差异
### 当前客户端带宽
可统计每个客户端当前的带宽,可能和实际有一定差异,仅供参考。
### 客户端与服务端版本对比
为了程序正常运行,客户端与服务端的版本必须一致,否则将导致客户端无法成功连接致服务端。
+1 -1
View File
@@ -208,7 +208,7 @@ func (s *TRPClient) srcProcess(src net.Conn) {
src.Close()
} else {
logs.Trace("new %s connection with the goal of %s, remote address:%s", lk.ConnType, lk.Host, lk.RemoteAddr)
conn.CopyWaitGroup(src, targetConn, lk.Crypt, lk.Compress, nil, nil, false)
conn.CopyWaitGroup(src, targetConn, lk.Crypt, lk.Compress, nil, nil, false, nil)
}
}
+4 -2
View File
@@ -189,8 +189,10 @@ func NewConn(tp string, vkey string, server string, connType string, proxyUrl st
}
} else {
sess, err = kcp.DialWithOptions(server, nil, 10, 3)
conn.SetUdpSession(sess)
connection = sess
if err == nil {
conn.SetUdpSession(sess)
connection = sess
}
}
if err != nil {
return nil, err
+2
View File
@@ -79,6 +79,7 @@ func check(t *file.Health) {
err = errors.New("status code is not match")
}
}
t.Lock()
if err != nil {
t.HealthMap[v] += 1
} else if t.HealthMap[v] >= t.HealthMaxFail {
@@ -91,5 +92,6 @@ func check(t *file.Health) {
//send fail remove
serverConn.SendHealthInfo(v, "0")
}
t.Unlock()
}
}
+3 -3
View File
@@ -70,7 +70,7 @@ func processSecret(localTcpConn net.Conn, config *config.CommonConfig, l *config
logs.Error("Local connection server failed ", err.Error())
return
}
conn.CopyWaitGroup(remoteConn.Conn, localTcpConn, false, false, nil, nil, false)
conn.CopyWaitGroup(remoteConn.Conn, localTcpConn, false, false, nil, nil, false, nil)
}
func processP2P(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
@@ -91,7 +91,7 @@ func processP2P(localTcpConn net.Conn, config *config.CommonConfig, l *config.Lo
logs.Error(err)
return
}
conn.CopyWaitGroup(nowConn, localTcpConn, config.Cnf.Crypt, config.Cnf.Compress, nil, nil, false)
conn.CopyWaitGroup(nowConn, localTcpConn, config.Cnf.Crypt, config.Cnf.Compress, nil, nil, false, nil)
}
func newUdpConn(config *config.CommonConfig, l *config.LocalServer) {
@@ -124,11 +124,11 @@ func newUdpConn(config *config.CommonConfig, l *config.LocalServer) {
return
}
localKcpConn, err := kcp.NewConn(string(rAddr), nil, 150, 3, localConn)
conn.SetUdpSession(localKcpConn)
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)
+1 -1
View File
@@ -34,7 +34,7 @@ func main() {
test.TestServerConfig()
log.Println("test ok, no error")
return
case "start", "restart", "stop", "status":
case "start", "restart", "stop", "status", "reload":
daemon.InitDaemon("nps", common.GetRunPath(), common.GetTmpPath())
case "install":
install.InstallNps()
+2 -4
View File
@@ -1,4 +1,2 @@
8,sl6ytyj7lv5224zr,,true,,,0,false,0,0,0,0
2,sqk6hfw7qirdmuep,,true,,,1,false,0,0,0,0
11,1hh13x99zrw90lg7,,true,,,0,false,0,0,0,1
5,phmgbeyns2yvtl6m,,true,,,0,false,0,0,0,1
12,ao0yd0jx6ty0ht69,,true,,,0,false,0,0,0,1
11,mxg22qa06dc137of,,true,,,0,false,0,0,0,1
1 8 12 sl6ytyj7lv5224zr ao0yd0jx6ty0ht69 true 0 false 0 0 0 0 1
2 2 11 sqk6hfw7qirdmuep mxg22qa06dc137of true 1 0 false 0 0 0 0 1
11 1hh13x99zrw90lg7 true 0 false 0 0 0 1
5 phmgbeyns2yvtl6m true 0 false 0 0 0 1
+1 -3
View File
@@ -1,3 +1 @@
a.o.com,127.0.0.1:8080,2,,,,/,1,0,60307,all
c.o.com,127.0.0.1:8082,2,,,,/,2,0,0,http
c.o.com,127.0.0.1:8082,2,,,,/,3,0,0,https
a.o.com,123.206.77.88:8080,11,,,,/,1,0,0,all
1 a.o.com 127.0.0.1:8080 123.206.77.88:8080 2 11 / 1 0 60307 0 all
c.o.com 127.0.0.1:8082 2 / 2 0 0 http
c.o.com 127.0.0.1:8082 2 / 3 0 0 https
+3
View File
@@ -46,3 +46,6 @@ auth_key=test
auth_crypt_key =1234567812345678
#allow_ports=9001-9009,10001,11000-12000
#Web management multi-user login
#allow_user_login=true
+1 -3
View File
@@ -1,3 +1 @@
0,p2p,,1,25,5,,0,0,p2ptest
0,p2p,,1,1,2,,0,0,c
0,secret,123.206.77.88:22,1,11,2,sec,0,0,sec
9988,tcp,127.0.0.1:8080,1,3,11,,0,504,
1 9988 p2p tcp 127.0.0.1:8080 1 25 3 5 11 0 0 0 504 p2ptest
p2p 1 1 2 0 0 0 c
secret 1 11 2 123.206.77.88:22 0 0 0 sec sec
+5 -5
View File
@@ -440,16 +440,16 @@ func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Ra
}
//get crypt or snappy conn
func GetConn(conn net.Conn, cpt, snappy bool, rate *rate.Rate, isServer bool) (io.ReadWriteCloser) {
func GetConn(conn net.Conn, cpt, snappy bool, rt *rate.Rate, isServer bool) (io.ReadWriteCloser) {
if cpt {
if isServer {
return crypt.NewTlsServerConn(conn)
return rate.NewRateConn(crypt.NewTlsServerConn(conn), rt)
}
return crypt.NewTlsClientConn(conn)
return rate.NewRateConn(crypt.NewTlsClientConn(conn), rt)
} else if snappy {
return NewSnappyConn(conn, cpt, rate)
return NewSnappyConn(conn, cpt, rt)
}
return conn
return rate.NewRateConn(conn, rt)
}
//read length or id (content length=4)
+23 -4
View File
@@ -24,21 +24,40 @@ func InitDaemon(f string, runPath string, pidPath string) {
switch os.Args[1] {
case "start":
start(args, f, pidPath, runPath)
os.Exit(0)
case "stop":
stop(f, args[0], pidPath)
os.Exit(0)
case "restart":
stop(f, args[0], pidPath)
start(args, f, pidPath, runPath)
os.Exit(0)
case "status":
if status(f, pidPath) {
log.Printf("%s is running", f)
} else {
log.Printf("%s is not running", f)
}
os.Exit(0)
case "reload":
reload(f, pidPath)
}
os.Exit(0)
}
func reload(f string, pidPath string) {
if f == "nps" && !common.IsWindows() && !status(f, pidPath) {
log.Println("reload fail")
return
}
var c *exec.Cmd
var err error
b, err := ioutil.ReadFile(filepath.Join(pidPath, f+".pid"))
if err == nil {
c = exec.Command("/bin/bash", "-c", `kill -30 `+string(b))
} else {
log.Fatalln("reload error,pid file does not exist")
}
if c.Run() == nil {
log.Println("reload success")
} else {
log.Println("reload fail")
}
}
+23
View File
@@ -0,0 +1,23 @@
// +build !windows
package daemon
import (
"github.com/cnlh/nps/lib/common"
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
"os"
"os/signal"
"path/filepath"
"syscall"
)
func init() {
s := make(chan os.Signal, 1)
signal.Notify(s, syscall.SIGUSR1)
go func() {
for {
<-s
beego.LoadAppConfig("ini", filepath.Join(common.GetRunPath(), "conf", "nps.conf"))
}
}()
}
+11
View File
@@ -256,6 +256,9 @@ func (s *Csv) LoadClientFromCsv() {
if post.RateLimit > 0 {
post.Rate = rate.NewRate(int64(post.RateLimit * 1024))
post.Rate.Start()
} else {
post.Rate = rate.NewRate(int64(2 << 23))
post.Rate.Start()
}
post.Flow = new(Flow)
post.Flow.FlowLimit = int64(common.GetIntNoErrByStr(item[9]))
@@ -382,6 +385,10 @@ reset:
isNotSet = true
c.VerifyKey = crypt.GetRandomString(16)
}
if c.RateLimit == 0 {
c.Rate = rate.NewRate(int64(2 << 23))
c.Rate.Start()
}
if !s.VerifyVkey(c.VerifyKey, c.id) {
if isNotSet {
goto reset
@@ -426,6 +433,10 @@ func (s *Csv) GetHostId() int32 {
func (s *Csv) UpdateClient(t *Client) error {
s.Clients.Store(t.Id, t)
if t.RateLimit == 0 {
t.Rate = rate.NewRate(int64(2 << 23))
t.Rate.Start()
}
return nil
}
+1
View File
@@ -142,6 +142,7 @@ type Health struct {
HealthRemoveArr []string
HealthCheckType string
HealthCheckTarget string
sync.RWMutex
}
func (s *Tunnel) GetRandomTarget() (string, error) {
+38
View File
@@ -0,0 +1,38 @@
package rate
import (
"io"
"net"
)
type rateConn struct {
conn net.Conn
rate *Rate
}
func NewRateConn(conn net.Conn, rate *Rate) io.ReadWriteCloser {
return &rateConn{
conn: conn,
rate: rate,
}
}
func (s *rateConn) Read(b []byte) (n int, err error) {
n, err = s.conn.Read(b)
if s.rate != nil {
s.rate.Get(int64(n))
}
return
}
func (s *rateConn) Write(b []byte) (n int, err error) {
n, err = s.conn.Write(b)
if s.rate != nil {
s.rate.Get(int64(n))
}
return
}
func (s *rateConn) Close() error {
return s.conn.Close()
}
+8 -1
View File
@@ -10,6 +10,7 @@ type Rate struct {
bucketSurplusSize int64 //当前桶中体积
bucketAddSize int64 //每次加水大小
stopChan chan bool //停止
NowRate int64
}
func NewRate(addSize int64) *Rate {
@@ -26,7 +27,8 @@ func (s *Rate) Start() {
}
func (s *Rate) add(size int64) {
if (s.bucketSize - s.bucketSurplusSize) < s.bucketAddSize {
if res := s.bucketSize - s.bucketSurplusSize; res < s.bucketAddSize {
atomic.AddInt64(&s.bucketSurplusSize, res)
return
}
atomic.AddInt64(&s.bucketSurplusSize, size)
@@ -65,6 +67,11 @@ func (s *Rate) session() {
for {
select {
case <-ticker.C:
if rs := s.bucketAddSize - s.bucketSurplusSize; rs > 0 {
s.NowRate = rs
} else {
s.NowRate = s.bucketSize - s.bucketSurplusSize
}
s.add(s.bucketAddSize)
case <-s.stopChan:
ticker.Stop()
+1 -1
View File
@@ -1,6 +1,6 @@
package version
const VERSION = "0.19.2"
const VERSION = "0.20.0"
// Compulsory minimum version, Minimum downward compatibility to this version
func GetVersion() string {
+1 -1
View File
@@ -105,7 +105,7 @@ func ProcessHttp(c *conn.Conn, s *TunnelModeServer) error {
return err
}
if r.Method == "CONNECT" {
c.Write([]byte("HTTP/1.1 200 Connection Established\r\n"))
c.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
rb = nil
}
if err := s.auth(r, c, s.task.Client.Cnf.U, s.task.Client.Cnf.P); err != nil {
+1 -1
View File
@@ -227,7 +227,7 @@ func GetTunnel(start, length int, typeVal string, clientId int, search string) (
for _, key := range keys {
if value, ok := file.GetCsvDb().Tasks.Load(key); ok {
v := value.(*file.Tunnel)
if (typeVal != "" && v.Mode != typeVal) || (typeVal == "" && clientId != v.Client.Id) {
if (typeVal != "" && v.Mode != typeVal || (clientId != 0 && v.Client.Id != clientId)) || (typeVal == "" && clientId != v.Client.Id) {
continue
}
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || v.Port == common.GetIntNoErrByStr(search) || strings.Contains(v.Password, search) || strings.Contains(v.Remark, search)) {
+36
View File
@@ -3,6 +3,7 @@ package controllers
import (
"github.com/cnlh/nps/lib/common"
"github.com/cnlh/nps/lib/crypt"
"github.com/cnlh/nps/lib/file"
"github.com/cnlh/nps/server"
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
"strconv"
@@ -33,6 +34,14 @@ func (s *BaseController) Prepare() {
s.Redirect("/login/index", 302)
}
}
if s.GetSession("isAdmin") != nil && !s.GetSession("isAdmin").(bool) {
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.CheckUserAuth()
} else {
s.Data["isAdmin"] = true
}
}
//加载模板
@@ -128,3 +137,30 @@ func (s *BaseController) SetInfo(name string) {
func (s *BaseController) SetType(name string) {
s.Data["type"] = name
}
func (s *BaseController) CheckUserAuth() {
if s.controllerName == "client" {
s.StopRun()
}
if s.controllerName == "index" {
if id := s.GetIntNoErr("id"); id != 0 {
belong := false
if strings.Contains(s.actionName, "h") {
if v, ok := file.GetCsvDb().Hosts.Load(id); ok {
if v.(*file.Host).Client.Id == s.GetSession("clientId").(int) {
belong = true
}
}
} else {
if v, ok := file.GetCsvDb().Tasks.Load(id); ok {
if v.(*file.Tunnel).Client.Id == s.GetSession("clientId").(int) {
belong = true
}
}
}
if !belong {
s.StopRun()
}
}
}
}
+2 -1
View File
@@ -111,7 +111,8 @@ func (s *ClientController) Edit() {
c.Rate = rate.NewRate(int64(c.RateLimit * 1024))
c.Rate.Start()
} else {
c.Rate = nil
c.Rate = rate.NewRate(int64(2 << 23))
c.Rate.Start()
}
file.GetCsvDb().StoreClientsToCsv()
}
+5
View File
@@ -152,12 +152,16 @@ func (s *IndexController) Edit() {
t.LocalPath = s.GetString("local_path")
t.StripPre = s.GetString("strip_pre")
t.Remark = s.GetString("remark")
if !tool.TestServerPort(t.Port, t.Mode) {
s.AjaxErr("The port cannot be opened because it may has been occupied or is no longer allowed.")
}
if t.Client, err = file.GetCsvDb().GetClient(s.GetIntNoErr("client_id")); err != nil {
s.AjaxErr("modified error")
}
file.GetCsvDb().UpdateTask(t)
server.StopServer(t.Id)
server.StartTask(t.Id)
t.TargetArr = nil
}
s.AjaxOk("modified success")
}
@@ -280,6 +284,7 @@ func (s *IndexController) EditHost() {
if h.Client, err = file.GetCsvDb().GetClient(s.GetIntNoErr("client_id")); err != nil {
s.AjaxErr("modified error")
}
h.TargetArr = nil
}
s.AjaxOk("modified success")
}
+21 -3
View File
@@ -2,6 +2,7 @@ package controllers
import (
"github.com/cnlh/nps/lib/common"
"github.com/cnlh/nps/lib/file"
"github.com/cnlh/nps/server"
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
"time"
@@ -15,15 +16,32 @@ func (self *LoginController) Index() {
self.TplName = "login/index.html"
}
func (self *LoginController) Verify() {
var auth bool
if self.GetString("password") == beego.AppConfig.String("web_password") && self.GetString("username") == beego.AppConfig.String("web_username") {
self.SetSession("isAdmin", true)
auth = true
server.Bridge.Register.Store(common.GetIpByAddr(self.Ctx.Request.RemoteAddr), time.Now().Add(time.Hour*time.Duration(2)))
}
b, err := beego.AppConfig.Bool("allow_user_login")
if err == nil && b && self.GetString("username") == "user" && !auth {
file.GetCsvDb().Clients.Range(func(key, value interface{}) bool {
v := value.(*file.Client)
if v.VerifyKey == self.GetString("password") && v.Status {
self.SetSession("isAdmin", false)
self.SetSession("clientId", v.Id)
auth = true
return false
}
return true
})
}
if auth {
self.SetSession("auth", true)
self.Data["json"] = map[string]interface{}{"status": 1, "msg": "login success"}
server.Bridge.Register.Store(common.GetIpByAddr(self.Ctx.Request.RemoteAddr), time.Now().Add(time.Hour*time.Duration(2)))
self.ServeJSON()
} else {
self.Data["json"] = map[string]interface{}{"status": 0, "msg": "username or password incorrect"}
self.ServeJSON()
}
self.ServeJSON()
}
func (self *LoginController) Out() {
self.SetSession("auth", false)
+28 -2
View File
@@ -124,8 +124,7 @@
+ '<b langtag="info-now-conn-num">当前连接数</b>:' + row.NowConn + `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
+ '<b langtag="info-flow-limit">流量限制</b>:' + row.Flow.FlowLimit + `m&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
+ '<b langtag="info-rate-limit">带宽限制</b>:' + row.RateLimit + `kb/s&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
+ '<b langtag="info-export-flow">出口流量</b>:' + change(row.Flow.ExportFlow) + `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
+ '<b langtag="info-inlet-flow">入口流量</b>:' + change(row.Flow.InletFlow) + `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp` + "<br/><br>"
+ `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp` + "<br/><br>"
+ '<b langtag="info-crypt">加密</b>:' + row.Cnf.Crypt + `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
+ '<b langtag="info-compress">压缩</b>:' + row.Cnf.Compress + `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
+ '<b langtag="info-config-conn-allow">是否允许配置文件模式连接</b>:' + row.ConfigConnAllow + `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
@@ -166,6 +165,33 @@
visible: true,//false表示不显示
sortable: true,//启用排序
},
{
field: 'Addr',//域值
title: 'in flow',//标题
visible: true,//false表示不显示
sortable: true,//启用排序
formatter: function (value, row, index) {
return change(row.Flow.InletFlow)
}
},
{
field: 'Addr',//域值
title: 'out flow',//标题
visible: true,//false表示不显示
sortable: true,//启用排序
formatter: function (value, row, index) {
return change(row.Flow.ExportFlow)
}
},
{
field: 'IsConnect',//域值
title: 'speed',//内容
visible: true,//false表示不显示
sortable: true,//启用排序
formatter: function (value, row, index) {
return change(row.Rate.NowRate) + "/S"
}
},
{
field: 'Status',//域值
title: 'setting status',//内容
+5 -2
View File
@@ -43,16 +43,19 @@
</a>
</div>
<div class="logo-element">
IN+
NPS
</div>
</li>
{{if eq true .isAdmin}}
<li class="{{if eq "index" .menu}}active{{end}}">
<a href="/"><i class="fa fa-dashboard"></i> <span langtag="menu-dashboard" class="nav-label">仪表盘</span></a>
<a href="/"><i class="fa fa-dashboard"></i> <span langtag="menu-dashboard"
class="nav-label">仪表盘</span></a>
</li>
<li class="{{if eq "client" .menu}}active{{end}}">
<a href="/client/list"><i class="fa fa-clipboard"></i> <span langtag="menu-client"
class="nav-label">客户端</span></a>
</li>
{{end}}
<li class="{{if eq "host" .menu}}active{{end}}">
<a href="/index/hostlist"><i class="fa fa-paperclip"></i> <span langtag="menu-host"
class="nav-label">域名解析</span></a>