Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ef519331e2 | ||
|
|
19fee9b51b | ||
|
|
16a7f6a4c4 | ||
|
|
1aca99b2d7 | ||
|
|
2733d99cf7 |
@@ -31,7 +31,32 @@
|
||||
|
||||
|
||||
# 更新日志
|
||||
- 2026-05-23 v0.26.33
|
||||
- 2026-06-04 v0.26.34
|
||||
- 新增:
|
||||
- `nps -server` 管理脚本欢迎语显示当前版本号,更新版本时比对版本,已是最新则直接退出,避免无谓覆盖 [#328](https://github.com/yisier/nps/issues/328)
|
||||
- `npc` 管理脚本欢迎语显示当前版本号,新增 `[5] 更新客户端` 选项,更新并替换 npc 二进制
|
||||
- 客户端新增到期时间字段,创建/修改客户端时可选填写,到期后自动暂停客户端 [#322](https://github.com/yisier/nps/issues/322)
|
||||
- 修复:
|
||||
- Dashboard IO 速率采集阻塞请求 500ms,改为后台采集缓存,消除 Sleep 等待
|
||||
- ServerStatus 切片并发读写不安全,添加 RWMutex 保护
|
||||
- flowSession goroutine 泄漏,改为仅在 StartNewServer 启动一次
|
||||
- GetTunnel 双重遍历 sync.Map 性能问题,合并为单次 Range
|
||||
- Bridge Client 字段并发读写不安全,添加 Mutex 保护
|
||||
- TLS ClientHello recordLen 无上限,添加 16KB 限制防止内存耗尽
|
||||
- SOCKS5 地址解析未检查 Read 返回值,改用 io.ReadFull
|
||||
- 文件存储 panic 改为错误日志,defer 清理临时文件防止泄漏
|
||||
- GenerateServerPort 可能无限循环,限制 1000 次重试
|
||||
- P2P UDP 无超时永久阻塞,添加 30s ReadDeadline
|
||||
- P2P goroutine 退出控制改用 context,修复潜在泄漏
|
||||
- 客户端 UDP ReadFrom 错误后未退出,修复无效数据继续处理
|
||||
- [#324](https://github.com/yisier/nps/issues/324) 隧道/域名解析/UDP 流量始终为 0
|
||||
- muxPackager buffer pool 泄漏:UnPack() 错误路径未归还 windowBuff 导致内存持续增长
|
||||
- bridge 客户端重连时旧 WORK_CHAN/WORK_FILE mux 未关闭,底层连接和 goroutine 永不释放
|
||||
- pmux 连接超时泄漏:process() channel 发送超时后连接未关闭,且 ACCEPT_TIME_OUT 单位错误(10ns 应为 10s)
|
||||
- pmux 关闭流程 panic:加 done channel + WaitGroup 保证 Close() 等所有 process() 退出后再 close conn channel;process() 入口设 ReadDeadline 防止阻塞读导致 wg.Wait() 死锁;PortListener 加 done channel 唤醒 Accept()
|
||||
- 优化:ioutil.WriteFile → os.WriteFile、rand.Seed → rand.New 本地随机源
|
||||
|
||||
- 2026-05-23 v0.26.33
|
||||
- 新增:
|
||||
- 配置文件自动生成:启动时若 conf 目录或 nps.conf 不存在,自动创建并写入默认配置,方便 Docker 部署
|
||||
- 首次启动默认 web_username/admin、web_password、auth_key、auth_crypt_key 均改为随机生成,并打印到终端,提升安全性
|
||||
|
||||
+59
-18
@@ -12,6 +12,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"ehang.io/nps/lib/common"
|
||||
@@ -28,11 +29,12 @@ import (
|
||||
var ServerTlsEnable bool = false
|
||||
|
||||
type Client struct {
|
||||
mu sync.Mutex // 保护 signal/tunnel/Version 等字段的并发读写
|
||||
tunnel *nps_mux.Mux
|
||||
signal *conn.Conn
|
||||
file *nps_mux.Mux
|
||||
Version string
|
||||
retryTime int // it will be add 1 when ping not ok until to 3 will close the client
|
||||
retryTime atomic.Int32 // it will be add 1 when ping not ok until to 3 will close the client
|
||||
}
|
||||
|
||||
func NewClient(t, f *nps_mux.Mux, s *conn.Conn, vs string) *Client {
|
||||
@@ -237,8 +239,13 @@ func (s *Bridge) cliProcess(c *conn.Conn) {
|
||||
|
||||
func (s *Bridge) DelClient(id int) {
|
||||
if v, ok := s.Client.Load(id); ok {
|
||||
if v.(*Client).signal != nil {
|
||||
v.(*Client).signal.Close()
|
||||
cl := v.(*Client)
|
||||
cl.mu.Lock()
|
||||
signalToClose := cl.signal
|
||||
cl.signal = nil
|
||||
cl.mu.Unlock()
|
||||
if signalToClose != nil {
|
||||
signalToClose.Close()
|
||||
}
|
||||
s.Client.Delete(id)
|
||||
if file.GetDb().IsPubClient(id) {
|
||||
@@ -267,18 +274,30 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int, vs string) {
|
||||
}
|
||||
//the vKey connect by another ,close the client of before
|
||||
if v, ok := s.Client.LoadOrStore(id, NewClient(nil, nil, c, vs)); ok {
|
||||
if v.(*Client).signal != nil {
|
||||
v.(*Client).signal.WriteClose()
|
||||
cl := v.(*Client)
|
||||
cl.mu.Lock()
|
||||
oldSignal := cl.signal
|
||||
cl.signal = c
|
||||
cl.Version = vs
|
||||
cl.mu.Unlock()
|
||||
cl.retryTime.Store(0)
|
||||
if oldSignal != nil {
|
||||
oldSignal.WriteClose()
|
||||
}
|
||||
v.(*Client).signal = c
|
||||
v.(*Client).Version = vs
|
||||
}
|
||||
go s.GetHealthFromClient(id, c)
|
||||
logs.Info("clientId %d connection succeeded, address:%s ", id, c.Conn.RemoteAddr())
|
||||
case common.WORK_CHAN:
|
||||
muxConn := nps_mux.NewMux(c.Conn, s.tunnelType, s.disconnectTime)
|
||||
if v, ok := s.Client.LoadOrStore(id, NewClient(muxConn, nil, nil, vs)); ok {
|
||||
v.(*Client).tunnel = muxConn
|
||||
cl := v.(*Client)
|
||||
cl.mu.Lock()
|
||||
oldTunnel := cl.tunnel
|
||||
cl.tunnel = muxConn
|
||||
cl.mu.Unlock()
|
||||
if oldTunnel != nil {
|
||||
oldTunnel.Close()
|
||||
}
|
||||
}
|
||||
case common.WORK_CONFIG:
|
||||
client, err := file.GetDb().GetClient(id)
|
||||
@@ -299,7 +318,14 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int, vs string) {
|
||||
case common.WORK_FILE:
|
||||
muxConn := nps_mux.NewMux(c.Conn, s.tunnelType, s.disconnectTime)
|
||||
if v, ok := s.Client.LoadOrStore(id, NewClient(nil, muxConn, nil, vs)); ok {
|
||||
v.(*Client).file = muxConn
|
||||
cl := v.(*Client)
|
||||
cl.mu.Lock()
|
||||
oldFile := cl.file
|
||||
cl.file = muxConn
|
||||
cl.mu.Unlock()
|
||||
if oldFile != nil {
|
||||
oldFile.Close()
|
||||
}
|
||||
}
|
||||
case common.WORK_P2P:
|
||||
//read md5 secret
|
||||
@@ -311,15 +337,22 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int, vs string) {
|
||||
if v, ok := s.Client.Load(t.Client.Id); !ok {
|
||||
return
|
||||
} else {
|
||||
cl := v.(*Client)
|
||||
cl.mu.Lock()
|
||||
sig := cl.signal
|
||||
cl.mu.Unlock()
|
||||
if sig == nil {
|
||||
return
|
||||
}
|
||||
//向密钥对应的客户端发送与服务端udp建立连接信息,地址,密钥
|
||||
v.(*Client).signal.Write([]byte(common.NEW_UDP_CONN))
|
||||
sig.Write([]byte(common.NEW_UDP_CONN))
|
||||
svrAddr := beego.AppConfig.String("p2p_ip") + ":" + beego.AppConfig.String("p2p_port")
|
||||
if err != nil {
|
||||
logs.Warn("get local udp addr error")
|
||||
return
|
||||
}
|
||||
v.(*Client).signal.WriteLenContent([]byte(svrAddr))
|
||||
v.(*Client).signal.WriteLenContent(b)
|
||||
sig.WriteLenContent([]byte(svrAddr))
|
||||
sig.WriteLenContent(b)
|
||||
//向该请求者发送建立连接请求,服务器地址
|
||||
c.WriteLenContent([]byte(svrAddr))
|
||||
}
|
||||
@@ -356,11 +389,14 @@ func (s *Bridge) SendLinkInfo(clientId int, link *conn.Link, t *file.Tunnel) (ta
|
||||
}
|
||||
}
|
||||
var tunnel *nps_mux.Mux
|
||||
cl := v.(*Client)
|
||||
cl.mu.Lock()
|
||||
if t != nil && t.Mode == "file" {
|
||||
tunnel = v.(*Client).file
|
||||
tunnel = cl.file
|
||||
} else {
|
||||
tunnel = v.(*Client).tunnel
|
||||
tunnel = cl.tunnel
|
||||
}
|
||||
cl.mu.Unlock()
|
||||
if tunnel == nil {
|
||||
err = errors.New("the client connect error")
|
||||
return
|
||||
@@ -393,14 +429,19 @@ func (s *Bridge) ping() {
|
||||
arr := make([]int, 0)
|
||||
s.Client.Range(func(key, value interface{}) bool {
|
||||
v := value.(*Client)
|
||||
if v.tunnel == nil || v.signal == nil {
|
||||
v.retryTime += 1
|
||||
if v.retryTime >= 3 {
|
||||
v.mu.Lock()
|
||||
tunnel := v.tunnel
|
||||
signal := v.signal
|
||||
if tunnel == nil || signal == nil {
|
||||
v.mu.Unlock()
|
||||
if v.retryTime.Add(1) >= 3 {
|
||||
arr = append(arr, key.(int))
|
||||
}
|
||||
return true
|
||||
}
|
||||
if v.tunnel.IsClose {
|
||||
isClose := tunnel.IsClose()
|
||||
v.mu.Unlock()
|
||||
if isClose {
|
||||
arr = append(arr, key.(int))
|
||||
}
|
||||
return true
|
||||
|
||||
+7
-5
@@ -307,7 +307,7 @@ func (s *TRPClient) handleChan(src net.Conn) {
|
||||
}
|
||||
}
|
||||
|
||||
conn.CopyWaitGroup(src, targetConn, lk.Crypt, lk.Compress, nil, nil, false, nil, nil)
|
||||
conn.CopyWaitGroup(src, targetConn, lk.Crypt, lk.Compress, nil, nil, false, nil, nil, nil)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -324,20 +324,22 @@ func (s *TRPClient) handleUdp(serverConn net.Conn) {
|
||||
defer serverConn.Close()
|
||||
b := common.BufPoolUdp.Get().([]byte)
|
||||
defer common.BufPoolUdp.Put(b)
|
||||
var buf bytes.Buffer
|
||||
for {
|
||||
n, raddr, err := local.ReadFrom(b)
|
||||
if err != nil {
|
||||
s.logError("read data from remote server error %s", err.Error())
|
||||
return
|
||||
}
|
||||
buf := bytes.Buffer{}
|
||||
buf.Reset()
|
||||
dgram := common.NewUDPDatagram(common.NewUDPHeader(0, 0, common.ToSocksAddr(raddr)), b[:n])
|
||||
dgram.Write(&buf)
|
||||
b, err := conn.GetLenBytes(buf.Bytes())
|
||||
data, err := conn.GetLenBytes(buf.Bytes())
|
||||
if err != nil {
|
||||
s.logWarn("get len bytes error %s", err.Error())
|
||||
continue
|
||||
}
|
||||
if _, err := serverConn.Write(b); err != nil {
|
||||
if _, err := serverConn.Write(data); err != nil {
|
||||
s.logError("write data to remote error %s", err.Error())
|
||||
return
|
||||
}
|
||||
@@ -377,7 +379,7 @@ loop:
|
||||
for {
|
||||
select {
|
||||
case <-s.ticker.C:
|
||||
if s.tunnel != nil && s.tunnel.IsClose {
|
||||
if s.tunnel != nil && s.tunnel.IsClose() {
|
||||
s.Close()
|
||||
break loop
|
||||
}
|
||||
|
||||
+33
-30
@@ -2,12 +2,12 @@ package client
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"math"
|
||||
"math/rand"
|
||||
@@ -147,7 +147,7 @@ re:
|
||||
}
|
||||
vkey = string(b)
|
||||
}
|
||||
ioutil.WriteFile(filepath.Join(common.GetTmpPath(), "npc_vkey.txt"), []byte(vkey), 0600)
|
||||
os.WriteFile(filepath.Join(common.GetTmpPath(), "npc_vkey.txt"), []byte(vkey), 0600)
|
||||
|
||||
//send hosts to server
|
||||
for _, v := range cnf.Hosts {
|
||||
@@ -343,6 +343,7 @@ func handleP2PUdp(localAddr, rAddr, md5Password, role string) (remoteAddress str
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer localConn.Close()
|
||||
err = getRemoteAddressFromServer(rAddr, localConn, md5Password, role, 0)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
@@ -359,27 +360,32 @@ func handleP2PUdp(localAddr, rAddr, md5Password, role string) (remoteAddress str
|
||||
return
|
||||
}
|
||||
var remoteAddr1, remoteAddr2, remoteAddr3 string
|
||||
// 修复:添加超时,避免无限等待远端响应
|
||||
localConn.SetReadDeadline(time.Now().Add(30 * time.Second))
|
||||
buf := make([]byte, 1024)
|
||||
for {
|
||||
buf := make([]byte, 1024)
|
||||
if n, addr, er := localConn.ReadFromUDP(buf); er != nil {
|
||||
err = er
|
||||
var n int
|
||||
var addr *net.UDPAddr
|
||||
n, addr, err = localConn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
localConn.SetReadDeadline(time.Time{})
|
||||
return
|
||||
} else {
|
||||
rAddr2, _ := getNextAddr(rAddr, 1)
|
||||
rAddr3, _ := getNextAddr(rAddr, 2)
|
||||
switch addr.String() {
|
||||
case rAddr:
|
||||
remoteAddr1 = string(buf[:n])
|
||||
case rAddr2:
|
||||
remoteAddr2 = string(buf[:n])
|
||||
case rAddr3:
|
||||
remoteAddr3 = string(buf[:n])
|
||||
}
|
||||
}
|
||||
rAddr2, _ := getNextAddr(rAddr, 1)
|
||||
rAddr3, _ := getNextAddr(rAddr, 2)
|
||||
switch addr.String() {
|
||||
case rAddr:
|
||||
remoteAddr1 = string(buf[:n])
|
||||
case rAddr2:
|
||||
remoteAddr2 = string(buf[:n])
|
||||
case rAddr3:
|
||||
remoteAddr3 = string(buf[:n])
|
||||
}
|
||||
if remoteAddr1 != "" && remoteAddr2 != "" && remoteAddr3 != "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
localConn.SetReadDeadline(time.Time{})
|
||||
if remoteAddress, err = sendP2PTestMsg(localConn, remoteAddr1, remoteAddr2, remoteAddr3); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -389,9 +395,8 @@ func handleP2PUdp(localAddr, rAddr, md5Password, role string) (remoteAddress str
|
||||
|
||||
func sendP2PTestMsg(localConn *net.UDPConn, remoteAddr1, remoteAddr2, remoteAddr3 string) (string, error) {
|
||||
logs.Trace(remoteAddr3, remoteAddr2, remoteAddr1)
|
||||
defer localConn.Close()
|
||||
isClose := false
|
||||
defer func() { isClose = true }()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
interval, err := getAddrInterval(remoteAddr1, remoteAddr2, remoteAddr3)
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -410,10 +415,9 @@ func sendP2PTestMsg(localConn *net.UDPConn, remoteAddr1, remoteAddr2, remoteAddr
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if isClose {
|
||||
return
|
||||
}
|
||||
if _, err := localConn.WriteTo([]byte(common.WORK_P2P_CONNECT), remoteUdpAddr); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -436,10 +440,9 @@ func sendP2PTestMsg(localConn *net.UDPConn, remoteAddr1, remoteAddr2, remoteAddr
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if isClose {
|
||||
return
|
||||
}
|
||||
if _, err := localConn.WriteTo([]byte(common.WORK_P2P_CONNECT), remoteUdpAddr); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -552,13 +555,13 @@ func getRandomPortArr(min, max int) []int {
|
||||
for i := min; i <= max; i++ {
|
||||
addrAddr[max-i] = i
|
||||
}
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
var r, temp int
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
var ri, temp int
|
||||
for i := max - min; i > 0; i-- {
|
||||
r = rand.Int() % i
|
||||
ri = r.Int() % i
|
||||
temp = addrAddr[i]
|
||||
addrAddr[i] = addrAddr[r]
|
||||
addrAddr[r] = temp
|
||||
addrAddr[i] = addrAddr[ri]
|
||||
addrAddr[ri] = temp
|
||||
}
|
||||
return addrAddr
|
||||
}
|
||||
|
||||
+2
-2
@@ -161,7 +161,7 @@ func handleSecret(localTcpConn net.Conn, config *config.CommonConfig, l *config.
|
||||
logs.Error("Local connection server failed ", err.Error())
|
||||
return
|
||||
}
|
||||
conn.CopyWaitGroup(remoteConn.Conn, localTcpConn, false, false, nil, nil, false, nil, nil)
|
||||
conn.CopyWaitGroup(remoteConn.Conn, localTcpConn, false, false, nil, nil, false, nil, nil, nil)
|
||||
}
|
||||
|
||||
func handleP2PVisitor(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
|
||||
@@ -178,7 +178,7 @@ func handleP2PVisitor(localTcpConn net.Conn, config *config.CommonConfig, l *con
|
||||
udpConnStatus = false
|
||||
return
|
||||
} else {
|
||||
conn.CopyWaitGroup(target, localTcpConn, false, config.Client.Cnf.Compress, nil, nil, false, nil, nil)
|
||||
conn.CopyWaitGroup(target, localTcpConn, false, config.Client.Cnf.Compress, nil, nil, false, nil, nil, nil)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+10
-3
@@ -292,8 +292,10 @@ func printSlogan() {
|
||||
fmt.Printf("\u001B[32m输入[3]\u001B[0m - 启动系统服务\n")
|
||||
fmt.Printf("\u001B[32m输入[4]\u001B[0m - 停止系统服务\n")
|
||||
fmt.Printf("---------------------\n")
|
||||
fmt.Printf("\u001B[32m输入[5]\u001B[0m - 更新客户端\n")
|
||||
fmt.Printf("\u001B[32m输入[0]\u001B[0m - 退出\n")
|
||||
fmt.Printf("---------------------\n")
|
||||
fmt.Printf("\u001B[32m当前版本:%s\u001B[0m\n", version.VERSION)
|
||||
fmt.Printf("直接输入[快捷启动命令]则是启动隧道,多个[快捷启动命令]用英文逗号拼接\n")
|
||||
fmt.Printf("\n")
|
||||
}
|
||||
@@ -314,8 +316,8 @@ func inputCmd() {
|
||||
|
||||
flag := strings.Replace(flag, " ", "", -1)
|
||||
|
||||
// 如果输入不等于 1,2,3,4,则启动隧道
|
||||
if flag != "1" && flag != "2" && flag != "3" && flag != "4" {
|
||||
// 如果输入不等于 1,2,3,4,5,则启动隧道
|
||||
if flag != "1" && flag != "2" && flag != "3" && flag != "4" && flag != "5" {
|
||||
|
||||
vkeys := strings.Split(flag, `,`)
|
||||
var cmdArray []string
|
||||
@@ -336,7 +338,12 @@ func inputCmd() {
|
||||
}
|
||||
|
||||
} else {
|
||||
systemService(flag)
|
||||
if flag == "5" {
|
||||
install.UpdateNpcNew()
|
||||
inputCmd()
|
||||
} else {
|
||||
systemService(flag)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -215,7 +215,7 @@ func printSlogan() {
|
||||
|
||||
fmt.Printf("%s", green(""))
|
||||
|
||||
fmt.Printf("\033[32;0m欢迎使用 NPS 管理脚本 \n")
|
||||
fmt.Printf("\033[32;0m欢迎使用 NPS 管理脚本,当前版本:v%s\n", version.VERSION)
|
||||
fmt.Printf("\033[0m") // 重置颜色
|
||||
|
||||
fmt.Printf("\n")
|
||||
@@ -332,7 +332,7 @@ func inputCmd() {
|
||||
break
|
||||
case "3":
|
||||
install.UpdateNpsNew()
|
||||
return
|
||||
break
|
||||
case "4":
|
||||
// 查看状态
|
||||
var statusMsg = ""
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
{"Cnf":{"U":"","P":"","Compress":false,"Crypt":false},"Id":2,"VerifyKey":"aceecc399e","Addr":"127.0.0.1","Remark":"","Status":true,"IsConnect":true,"RateLimit":0,"Flow":{"ExportFlow":7888065,"InletFlow":7888065,"FlowLimit":0},"Rate":{"NowRate":17179869184},"NoStore":false,"NoDisplay":false,"MaxConn":0,"NowConn":0,"WebUserName":"","WebPassword":"","ConfigConnAllow":true,"MaxTunnelNum":0,"Version":"0.26.19","BlackIpList":[],"CreateTime":"2026-05-14 16:37:55","LastOnlineTime":"2026-05-14 17:30:13","IpWhite":false,"IpWhitePass":"","IpWhiteList":[]}
|
||||
*#*
|
||||
@@ -1,2 +0,0 @@
|
||||
{"Id":1,"Port":33833,"ServerIp":"0.0.0.0","Mode":"tcp","Status":true,"RunStatus":true,"Client":{"Cnf":{"U":"","P":"","Compress":false,"Crypt":false},"Id":2,"VerifyKey":"aceecc399e","Addr":"127.0.0.1","Remark":"","Status":true,"IsConnect":true,"RateLimit":0,"Flow":{"ExportFlow":7888065,"InletFlow":7888065,"FlowLimit":0},"Rate":{"NowRate":0},"NoStore":false,"NoDisplay":false,"MaxConn":0,"NowConn":0,"WebUserName":"","WebPassword":"","ConfigConnAllow":true,"MaxTunnelNum":0,"Version":"0.26.19","BlackIpList":[],"CreateTime":"2026-05-14 16:37:55","LastOnlineTime":"2026-05-14 17:30:13","IpWhite":false,"IpWhitePass":"","IpWhiteList":[]},"Ports":"","Flow":{"ExportFlow":0,"InletFlow":0,"FlowLimit":0},"Password":"","Remark":"","TargetAddr":"","NoStore":false,"LocalPath":"","StripPre":"","ProtoVersion":"","Target":{"TargetStr":"192.168.225.103:8081","TargetArr":["192.168.225.103:8081"],"LocalProxy":false},"MultiAccount":null,"HealthCheckTimeout":0,"HealthMaxFail":0,"HealthCheckInterval":0,"HealthNextTime":"0001-01-01T00:00:00Z","HealthMap":null,"HttpHealthUrl":"","HealthRemoveArr":null,"HealthCheckType":"","HealthCheckTarget":""}
|
||||
*#*
|
||||
@@ -45,6 +45,7 @@ POST /client/add/
|
||||
| flow\_limit | 流量限制 单位M 空则为不限制 |
|
||||
| max\_conn | 客户端最大连接数量 空则为不限制 |
|
||||
| max\_tunnel | 客户端最大隧道数量 空则为不限制 |
|
||||
| expire\_time | 到期时间,留空表示永不过期,到期后自动暂停。支持格式:`2006-01-02 15:04:05`、`2006-01-02 15:04`、`2006-01-02T15:04:05`、`2006-01-02T15:04`、`2006-01-02` |
|
||||
|
||||
***
|
||||
修改客户端
|
||||
@@ -67,6 +68,7 @@ POST /client/edit/
|
||||
| flow\_limit | 流量限制 单位M 空则为不限制 |
|
||||
| max\_conn | 客户端最大连接数量 空则为不限制 |
|
||||
| max\_tunnel | 客户端最大隧道数量 空则为不限制 |
|
||||
| expire\_time | 到期时间,留空表示永不过期,到期后自动暂停。格式同新增接口 |
|
||||
| id | 要修改的客户端id |
|
||||
|
||||
***
|
||||
|
||||
+2
-2
@@ -376,7 +376,7 @@ func SetUdpSession(sess *kcp.UDPSession) {
|
||||
|
||||
//conn1 mux conn
|
||||
func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Rate,
|
||||
flow *file.Flow, isServer bool, rb []byte, task *file.Tunnel) {
|
||||
flow *file.Flow, isServer bool, rb []byte, task *file.Tunnel, host *file.Host) {
|
||||
//var in, out int64
|
||||
//var wg sync.WaitGroup
|
||||
connHandle := GetConn(conn1, crypt, snappy, rate, isServer)
|
||||
@@ -399,7 +399,7 @@ func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Ra
|
||||
//}
|
||||
wg := new(sync.WaitGroup)
|
||||
wg.Add(1)
|
||||
err := goroutine.CopyConnsPool.Invoke(goroutine.NewConns(connHandle, conn2, flow, wg, task))
|
||||
err := goroutine.CopyConnsPool.Invoke(goroutine.NewConns(connHandle, conn2, flow, wg, task, host))
|
||||
wg.Wait()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
|
||||
+28
-11
@@ -187,8 +187,14 @@ func storeSyncMapToFile(m sync.Map, filePath string) {
|
||||
file, err := os.Create(filePath + ".tmp")
|
||||
// first create a temporary file to store
|
||||
if err != nil {
|
||||
panic(err)
|
||||
logs.Error("store to file: create tmp file error: %v", err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
file.Close()
|
||||
os.Remove(filePath + ".tmp")
|
||||
}()
|
||||
var writeErr bool
|
||||
m.Range(func(key, value interface{}) bool {
|
||||
var b []byte
|
||||
var err error
|
||||
@@ -211,9 +217,6 @@ func storeSyncMapToFile(m sync.Map, filePath string) {
|
||||
return true
|
||||
}
|
||||
b, err = json.Marshal(obj)
|
||||
//case *Glob:
|
||||
// obj := value.(*Glob)
|
||||
// b, err = json.Marshal(obj)
|
||||
default:
|
||||
return true
|
||||
}
|
||||
@@ -222,40 +225,54 @@ func storeSyncMapToFile(m sync.Map, filePath string) {
|
||||
}
|
||||
_, err = file.Write(b)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
logs.Error("store to file: write error: %v", err)
|
||||
writeErr = true
|
||||
return false
|
||||
}
|
||||
_, err = file.Write([]byte("\n" + common.CONN_DATA_SEQ))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
logs.Error("store to file: write separator error: %v", err)
|
||||
writeErr = true
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
if writeErr {
|
||||
return
|
||||
}
|
||||
_ = file.Sync()
|
||||
_ = file.Close()
|
||||
// must close file first, then rename it
|
||||
err = os.Rename(filePath+".tmp", filePath)
|
||||
if err != nil {
|
||||
logs.Error(err, "store to file err, data will lost")
|
||||
}
|
||||
// replace the file, maybe provides atomic operation
|
||||
}
|
||||
|
||||
func storeGlobalToFile(m *Glob, filePath string) {
|
||||
file, err := os.Create(filePath + ".tmp")
|
||||
// first create a temporary file to store
|
||||
if err != nil {
|
||||
panic(err)
|
||||
logs.Error("store global to file: create tmp file error: %v", err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
file.Close()
|
||||
os.Remove(filePath + ".tmp")
|
||||
}()
|
||||
|
||||
var b []byte
|
||||
b, err = json.Marshal(m)
|
||||
if err != nil {
|
||||
logs.Error("store global to file: marshal error: %v", err)
|
||||
return
|
||||
}
|
||||
_, err = file.Write(b)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
logs.Error("store global to file: write error: %v", err)
|
||||
return
|
||||
}
|
||||
_ = file.Sync()
|
||||
_ = file.Close()
|
||||
// must close file first, then rename it
|
||||
err = os.Rename(filePath+".tmp", filePath)
|
||||
if err != nil {
|
||||
logs.Error(err, "store to file err, data will lost")
|
||||
|
||||
@@ -57,6 +57,7 @@ type Client struct {
|
||||
IpWhite bool // 是否启用ip白名单
|
||||
IpWhitePass string // ip授权密码
|
||||
IpWhiteList []string // ip白名单
|
||||
ExpireTime string // 到期时间,留空表示永不过期,格式 2006-01-02 15:04:05
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
|
||||
+16
-7
@@ -22,6 +22,7 @@ type connGroup struct {
|
||||
n *int64
|
||||
flow *file.Flow
|
||||
task *file.Tunnel
|
||||
host *file.Host
|
||||
remote string
|
||||
}
|
||||
|
||||
@@ -34,7 +35,7 @@ type connGroup struct {
|
||||
// }
|
||||
//}
|
||||
|
||||
func newConnGroup(dst, src io.ReadWriteCloser, wg *sync.WaitGroup, n *int64, flow *file.Flow, task *file.Tunnel, remote string) connGroup {
|
||||
func newConnGroup(dst, src io.ReadWriteCloser, wg *sync.WaitGroup, n *int64, flow *file.Flow, task *file.Tunnel, host *file.Host, remote string) connGroup {
|
||||
return connGroup{
|
||||
src: src,
|
||||
dst: dst,
|
||||
@@ -42,11 +43,12 @@ func newConnGroup(dst, src io.ReadWriteCloser, wg *sync.WaitGroup, n *int64, flo
|
||||
n: n,
|
||||
flow: flow,
|
||||
task: task,
|
||||
host: host,
|
||||
remote: remote,
|
||||
}
|
||||
}
|
||||
|
||||
func CopyBuffer(dst io.Writer, src io.Reader, flow *file.Flow, task *file.Tunnel, remote string) (err error) {
|
||||
func CopyBuffer(dst io.Writer, src io.Reader, flow *file.Flow, task *file.Tunnel, host *file.Host, remote string) (err error) {
|
||||
buf := common.CopyBuff.Get()
|
||||
defer common.CopyBuff.Put(buf)
|
||||
for {
|
||||
@@ -129,7 +131,12 @@ func CopyBuffer(dst io.Writer, src io.Reader, flow *file.Flow, task *file.Tunnel
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if task != nil && task.Flow != nil && task.Flow != flow {
|
||||
task.Flow.Add(int64(nw), int64(nw))
|
||||
}
|
||||
if host != nil && host.Flow != nil && host.Flow != flow {
|
||||
host.Flow.Add(int64(nw), int64(nw))
|
||||
}
|
||||
}
|
||||
if ew != nil {
|
||||
err = ew
|
||||
@@ -156,7 +163,7 @@ func copyConnGroup(group interface{}) {
|
||||
}
|
||||
|
||||
var err error
|
||||
err = CopyBuffer(cg.dst, cg.src, cg.flow, cg.task, cg.remote)
|
||||
err = CopyBuffer(cg.dst, cg.src, cg.flow, cg.task, cg.host, cg.remote)
|
||||
if err != nil {
|
||||
cg.src.Close()
|
||||
cg.dst.Close()
|
||||
@@ -175,15 +182,17 @@ type Conns struct {
|
||||
flow *file.Flow
|
||||
wg *sync.WaitGroup
|
||||
task *file.Tunnel
|
||||
host *file.Host
|
||||
}
|
||||
|
||||
func NewConns(c1 io.ReadWriteCloser, c2 net.Conn, flow *file.Flow, wg *sync.WaitGroup, task *file.Tunnel) Conns {
|
||||
func NewConns(c1 io.ReadWriteCloser, c2 net.Conn, flow *file.Flow, wg *sync.WaitGroup, task *file.Tunnel, host *file.Host) Conns {
|
||||
return Conns{
|
||||
conn1: c1,
|
||||
conn2: c2,
|
||||
flow: flow,
|
||||
wg: wg,
|
||||
task: task,
|
||||
host: host,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,9 +203,9 @@ func copyConns(group interface{}) {
|
||||
wg.Add(2)
|
||||
var in, out int64
|
||||
remoteAddr := conns.conn2.RemoteAddr().String()
|
||||
_ = connCopyPool.Invoke(newConnGroup(conns.conn1, conns.conn2, wg, &in, conns.flow, conns.task, remoteAddr))
|
||||
_ = connCopyPool.Invoke(newConnGroup(conns.conn1, conns.conn2, wg, &in, conns.flow, conns.task, conns.host, remoteAddr))
|
||||
// outside to mux : incoming
|
||||
_ = connCopyPool.Invoke(newConnGroup(conns.conn2, conns.conn1, wg, &out, conns.flow, conns.task, remoteAddr))
|
||||
_ = connCopyPool.Invoke(newConnGroup(conns.conn2, conns.conn1, wg, &out, conns.flow, conns.task, conns.host, remoteAddr))
|
||||
// mux to outside : outgoing
|
||||
wg.Wait()
|
||||
//if conns.flow != nil {
|
||||
|
||||
@@ -2,6 +2,7 @@ package install
|
||||
|
||||
import (
|
||||
"ehang.io/nps/lib/common"
|
||||
"ehang.io/nps/lib/version"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -13,6 +14,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -142,12 +144,52 @@ func UpdateNps() {
|
||||
}
|
||||
|
||||
func UpdateNpsNew() {
|
||||
latest, err := fetchLatestVersion()
|
||||
if err != nil {
|
||||
log.Println("获取最新版本失败:", err)
|
||||
return
|
||||
} else {
|
||||
fmt.Println("最新版本为:", latest)
|
||||
if compareVersion(version.VERSION, latest) >= 0 {
|
||||
fmt.Println("当前已是最新版本,无需更新")
|
||||
return
|
||||
}
|
||||
}
|
||||
destPath := downloadLatest2("server", filepath.Join(common.GetAppPath(), "temp"))
|
||||
//复制文件到对应目录
|
||||
copyStaticFileReplaceNps(destPath, common.GetAppPath())
|
||||
fmt.Println("更新成功,请重启服务")
|
||||
}
|
||||
|
||||
func fetchLatestVersion() (string, error) {
|
||||
resp, err := http.Get("https://api.github.com/repos/yisier/nps/releases/latest")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
rl := new(release)
|
||||
if err := json.Unmarshal(b, rl); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return rl.TagName, nil
|
||||
}
|
||||
|
||||
func compareVersion(a, b string) int {
|
||||
ai, _ := strconv.Atoi(strings.ReplaceAll(strings.TrimPrefix(a, "v"), ".", ""))
|
||||
bi, _ := strconv.Atoi(strings.ReplaceAll(strings.TrimPrefix(b, "v"), ".", ""))
|
||||
if ai < bi {
|
||||
return -1
|
||||
}
|
||||
if ai > bi {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func UpdateNpc() {
|
||||
destPath := downloadLatest("client")
|
||||
//复制文件到对应目录
|
||||
@@ -155,6 +197,23 @@ func UpdateNpc() {
|
||||
fmt.Println("Update completed, please restart")
|
||||
}
|
||||
|
||||
func UpdateNpcNew() {
|
||||
latest, err := fetchLatestVersion()
|
||||
if err != nil {
|
||||
log.Println("获取最新版本失败:", err)
|
||||
return
|
||||
} else {
|
||||
fmt.Println("最新版本为:", latest)
|
||||
if compareVersion(version.VERSION, latest) >= 0 {
|
||||
fmt.Println("当前已是最新版本,无需更新")
|
||||
return
|
||||
}
|
||||
}
|
||||
destPath := downloadLatest2("client", filepath.Join(common.GetAppPath(), "temp"))
|
||||
copyStaticFileReplaceNpc(destPath, common.GetAppPath())
|
||||
fmt.Println("更新成功,请重启客户端")
|
||||
}
|
||||
|
||||
type release struct {
|
||||
TagName string `json:"tag_name"`
|
||||
}
|
||||
@@ -286,6 +345,18 @@ func copyStaticFileReplaceNps(srcPath, descPath string) string {
|
||||
return binPath
|
||||
}
|
||||
|
||||
func copyStaticFileReplaceNpc(srcPath, descPath string) string {
|
||||
binPath, _ := filepath.Abs(os.Args[0])
|
||||
if !common.IsWindows() {
|
||||
os.Rename(filepath.Join(srcPath, "npc"), filepath.Join(descPath, "npc"))
|
||||
} else {
|
||||
os.Rename(filepath.Join(srcPath, "npc.exe"), filepath.Join(descPath, "npc.exe"))
|
||||
}
|
||||
chMod(binPath, 0755)
|
||||
os.RemoveAll(srcPath)
|
||||
return binPath
|
||||
}
|
||||
|
||||
func InstallNpc() {
|
||||
path := common.GetInstallPath()
|
||||
if !common.FileExists(path) {
|
||||
|
||||
+1
-1
@@ -72,7 +72,7 @@ func (s *conn) Close() (err error) {
|
||||
func (s *conn) closeProcess() {
|
||||
s.isClose = true
|
||||
s.receiveWindow.mux.connMap.Delete(s.connId)
|
||||
if !s.receiveWindow.mux.IsClose {
|
||||
if !s.receiveWindow.mux.IsClose() {
|
||||
// if server or user close the conn while reading, will Get a io.EOF
|
||||
// and this Close method will be invoke, send this signal to close other side
|
||||
s.receiveWindow.mux.sendInfo(muxConnClose, s.connId, nil)
|
||||
|
||||
+18
-16
@@ -35,7 +35,7 @@ type Mux struct {
|
||||
newConnCh chan *conn
|
||||
id int32
|
||||
closeChan chan struct{}
|
||||
IsClose bool
|
||||
isClose atomic.Bool
|
||||
counter *latencyCounter
|
||||
bw *bandwidth
|
||||
pingCh chan []byte
|
||||
@@ -70,7 +70,6 @@ func NewMux(c net.Conn, connType string, pingCheckThreshold int) *Mux {
|
||||
closeChan: make(chan struct{}, 1),
|
||||
newConnCh: make(chan *conn),
|
||||
bw: NewBandwidth(fd),
|
||||
IsClose: false,
|
||||
connType: connType,
|
||||
pingCh: make(chan []byte),
|
||||
pingCheckThreshold: checkThreshold,
|
||||
@@ -86,8 +85,11 @@ func NewMux(c net.Conn, connType string, pingCheckThreshold int) *Mux {
|
||||
return m
|
||||
}
|
||||
|
||||
// IsClose returns whether the mux connection has been closed.
|
||||
func (s *Mux) IsClose() bool { return s.isClose.Load() }
|
||||
|
||||
func (s *Mux) NewConn() (*conn, error) {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
return nil, errors.New("the mux has closed")
|
||||
}
|
||||
conn := NewConn(s.getId(), s)
|
||||
@@ -106,7 +108,7 @@ func (s *Mux) NewConn() (*conn, error) {
|
||||
}
|
||||
|
||||
func (s *Mux) Accept() (net.Conn, error) {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
return nil, errors.New("accpet error,the mux has closed")
|
||||
}
|
||||
conn := <-s.newConnCh
|
||||
@@ -121,7 +123,7 @@ func (s *Mux) Addr() net.Addr {
|
||||
}
|
||||
|
||||
func (s *Mux) sendInfo(flag uint8, id int32, data interface{}) {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
return
|
||||
}
|
||||
var err error
|
||||
@@ -140,11 +142,11 @@ func (s *Mux) sendInfo(flag uint8, id int32, data interface{}) {
|
||||
func (s *Mux) writeSession() {
|
||||
go func() {
|
||||
for {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
break
|
||||
}
|
||||
pack := s.writeQueue.Pop()
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
break
|
||||
}
|
||||
//if pack.flag == muxNewMsg || pack.flag == muxNewMsgPart {
|
||||
@@ -173,7 +175,7 @@ func (s *Mux) ping() {
|
||||
ticker := time.NewTicker(time.Second * 5)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
break
|
||||
}
|
||||
select {
|
||||
@@ -197,7 +199,7 @@ func (s *Mux) ping() {
|
||||
var now time.Time
|
||||
var data []byte
|
||||
for {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
break
|
||||
}
|
||||
select {
|
||||
@@ -213,7 +215,7 @@ func (s *Mux) ping() {
|
||||
// convert float64 to bits, store it atomic
|
||||
//log.Println("ping", math.Float64frombits(atomic.LoadUint64(&s.latency)))
|
||||
}
|
||||
if cap(data) > 0 && !s.IsClose {
|
||||
if cap(data) > 0 && !s.isClose.Load() {
|
||||
windowBuff.Put(data)
|
||||
}
|
||||
}
|
||||
@@ -224,11 +226,11 @@ func (s *Mux) readSession() {
|
||||
go func() {
|
||||
var connection *conn
|
||||
for {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
break
|
||||
}
|
||||
connection = s.newConnQueue.Pop()
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
break // make sure that is closed
|
||||
}
|
||||
s.connMap.Set(connection.connId, connection) //it has been Set before send ok
|
||||
@@ -241,7 +243,7 @@ func (s *Mux) readSession() {
|
||||
var l uint16
|
||||
var err error
|
||||
for {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
return
|
||||
}
|
||||
pack = muxPack.Get()
|
||||
@@ -322,10 +324,10 @@ func (s *Mux) newMsg(connection *conn, pack *muxPackager) (err error) {
|
||||
}
|
||||
|
||||
func (s *Mux) Close() (err error) {
|
||||
if s.IsClose {
|
||||
if s.isClose.Load() {
|
||||
return errors.New("the mux has closed")
|
||||
}
|
||||
s.IsClose = true
|
||||
s.isClose.Store(true)
|
||||
log.Println("close mux")
|
||||
s.connMap.Close()
|
||||
//s.connMap = nil
|
||||
@@ -361,7 +363,7 @@ func (s *Mux) release() {
|
||||
s.newConnQueue.Stop()
|
||||
}
|
||||
|
||||
//Get New connId as unique flag
|
||||
// Get New connId as unique flag
|
||||
func (s *Mux) getId() (id int32) {
|
||||
//Avoid going beyond the scope
|
||||
if (math.MaxInt32 - s.id) < 10000 {
|
||||
|
||||
@@ -135,6 +135,7 @@ func (Self *muxPackager) UnPack(reader io.Reader) (n uint16, err error) {
|
||||
Self.buf = Self.buf[0:13]
|
||||
l, err := io.ReadFull(reader, Self.buf[:5])
|
||||
if err != nil {
|
||||
windowBuff.Put(Self.buf) // 归还 buf,避免 pool 泄漏
|
||||
return
|
||||
}
|
||||
n += uint16(l)
|
||||
@@ -145,6 +146,11 @@ func (Self *muxPackager) UnPack(reader io.Reader) (n uint16, err error) {
|
||||
var m uint16
|
||||
Self.content = windowBuff.Get() // need Get a window buf from pool
|
||||
m, err = Self.basePackager.UnPack(reader)
|
||||
if err != nil {
|
||||
windowBuff.Put(Self.content) // 归还 content buf,避免 pool 泄漏
|
||||
windowBuff.Put(Self.buf)
|
||||
return
|
||||
}
|
||||
n += m
|
||||
case muxMsgSendOk:
|
||||
l, err = io.ReadFull(reader, Self.buf[5:13])
|
||||
|
||||
+11
-5
@@ -10,12 +10,14 @@ type PortListener struct {
|
||||
connCh chan *PortConn
|
||||
addr net.Addr
|
||||
isClose bool
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func NewPortListener(connCh chan *PortConn, addr net.Addr) *PortListener {
|
||||
return &PortListener{
|
||||
connCh: connCh,
|
||||
addr: addr,
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,19 +25,23 @@ func (pListener *PortListener) Accept() (net.Conn, error) {
|
||||
if pListener.isClose {
|
||||
return nil, errors.New("the listener has closed")
|
||||
}
|
||||
conn := <-pListener.connCh
|
||||
if conn != nil {
|
||||
return conn, nil
|
||||
select {
|
||||
case <-pListener.done:
|
||||
return nil, errors.New("the listener has closed")
|
||||
case conn := <-pListener.connCh:
|
||||
if conn != nil {
|
||||
return conn, nil
|
||||
}
|
||||
return nil, errors.New("the listener has closed")
|
||||
}
|
||||
return nil, errors.New("the listener has closed")
|
||||
}
|
||||
|
||||
func (pListener *PortListener) Close() error {
|
||||
//close
|
||||
if pListener.isClose {
|
||||
return errors.New("the listener has closed")
|
||||
}
|
||||
pListener.isClose = true
|
||||
close(pListener.done)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
+29
-5
@@ -10,6 +10,7 @@ import (
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"ehang.io/nps/lib/common"
|
||||
@@ -34,6 +35,8 @@ type PortMux struct {
|
||||
net.Listener
|
||||
port int
|
||||
isClose bool
|
||||
done chan struct{} // 关闭时触发 process() 退出,避免 send on closed channel
|
||||
wg sync.WaitGroup // 跟踪 in-flight process(),保证 Close() 关闭 conn channel 前全部退出
|
||||
managerHost string
|
||||
clientConn chan *PortConn
|
||||
httpConn chan *PortConn
|
||||
@@ -45,6 +48,7 @@ func NewPortMux(port int, managerHost string) *PortMux {
|
||||
pMux := &PortMux{
|
||||
managerHost: managerHost,
|
||||
port: port,
|
||||
done: make(chan struct{}),
|
||||
clientConn: make(chan *PortConn),
|
||||
httpConn: make(chan *PortConn),
|
||||
httpsConn: make(chan *PortConn),
|
||||
@@ -65,25 +69,35 @@ func (pMux *PortMux) Start() error {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
pMux.wg.Add(1)
|
||||
go func() {
|
||||
defer pMux.wg.Done()
|
||||
for {
|
||||
conn, err := pMux.Listener.Accept()
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
//close
|
||||
pMux.Close()
|
||||
return
|
||||
}
|
||||
go pMux.process(conn)
|
||||
pMux.wg.Add(1)
|
||||
go func(c net.Conn) {
|
||||
defer pMux.wg.Done()
|
||||
pMux.process(c)
|
||||
}(conn)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pMux *PortMux) process(conn net.Conn) {
|
||||
// 设置读超时,防止客户端不发数据导致 goroutine 永久阻塞,造成 wg.Wait() 死锁
|
||||
readTimeout := ACCEPT_TIME_OUT * time.Second
|
||||
conn.SetReadDeadline(time.Now().Add(readTimeout))
|
||||
|
||||
// Recognition according to different signs
|
||||
// read 3 byte
|
||||
buf := make([]byte, 3)
|
||||
if n, err := io.ReadFull(conn, buf); err != nil || n != 3 {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
var ch chan *PortConn
|
||||
@@ -92,6 +106,7 @@ func (pMux *PortMux) process(conn net.Conn) {
|
||||
var readMore = false
|
||||
switch common.BytesToNum(buf) {
|
||||
case HTTP_CONNECT, HTTP_DELETE, HTTP_GET, HTTP_HEAD, HTTP_OPTIONS, HTTP_POST, HTTP_PUT, HTTP_TRACE: //http and manager
|
||||
conn.SetReadDeadline(time.Now().Add(readTimeout)) // 刷新超时,给 HTTP 头读取完整时间窗口
|
||||
buffer.Reset()
|
||||
r := bufio.NewReader(conn)
|
||||
buffer.Write(buf)
|
||||
@@ -127,12 +142,18 @@ func (pMux *PortMux) process(conn net.Conn) {
|
||||
readMore = true
|
||||
ch = pMux.httpsConn
|
||||
}
|
||||
// 清除读超时,后续由 PortConn 的消费者自行管理超时
|
||||
conn.SetReadDeadline(time.Time{})
|
||||
if len(rs) == 0 {
|
||||
rs = buf
|
||||
}
|
||||
timer := time.NewTimer(ACCEPT_TIME_OUT)
|
||||
timer := time.NewTimer(readTimeout)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-pMux.done:
|
||||
conn.Close()
|
||||
case <-timer.C:
|
||||
conn.Close()
|
||||
case ch <- newPortConn(conn, rs, readMore):
|
||||
}
|
||||
}
|
||||
@@ -142,11 +163,14 @@ func (pMux *PortMux) Close() error {
|
||||
return errors.New("the port pmux has closed")
|
||||
}
|
||||
pMux.isClose = true
|
||||
_ = pMux.Listener.Close() // 停止接收新连接,触发 accept 协程退出
|
||||
close(pMux.done) // 唤醒 in-flight process()
|
||||
pMux.wg.Wait() // 等待所有 process() 退出后再 close conn channel
|
||||
close(pMux.clientConn)
|
||||
close(pMux.httpsConn)
|
||||
close(pMux.httpConn)
|
||||
close(pMux.managerConn)
|
||||
return pMux.Listener.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pMux *PortMux) GetClientListener() net.Listener {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package version
|
||||
|
||||
const VERSION = "0.26.33"
|
||||
const VERSION = "0.26.34"
|
||||
|
||||
// Compulsory minimum version, Minimum downward compatibility to this version
|
||||
func GetVersion() string {
|
||||
|
||||
@@ -96,7 +96,7 @@ func in(target string, str_array []string) bool {
|
||||
|
||||
// create a new connection and start bytes copying
|
||||
func (s *BaseServer) DealClient(c *conn.Conn, client *file.Client, addr string,
|
||||
rb []byte, tp string, f func(), flow *file.Flow, localProxy bool, task *file.Tunnel) error {
|
||||
rb []byte, tp string, f func(), flow *file.Flow, localProxy bool, task *file.Tunnel, host *file.Host) error {
|
||||
|
||||
// 判断访问地址是否在全局黑名单内
|
||||
if IsGlobalBlackIp(c.RemoteAddr().String()) {
|
||||
@@ -124,7 +124,7 @@ func (s *BaseServer) DealClient(c *conn.Conn, client *file.Client, addr string,
|
||||
if f != nil {
|
||||
f()
|
||||
}
|
||||
conn.CopyWaitGroup(target, c.Conn, link.Crypt, link.Compress, client.Rate, flow, true, rb, task)
|
||||
conn.CopyWaitGroup(target, c.Conn, link.Crypt, link.Compress, client.Rate, flow, true, rb, task, host)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -262,7 +262,7 @@ reset:
|
||||
}
|
||||
}()
|
||||
|
||||
err1 := goroutine.CopyBuffer(c, connClient, host.Client.Flow, nil, "")
|
||||
err1 := goroutine.CopyBuffer(c, connClient, host.Client.Flow, nil, host, "")
|
||||
if err1 != nil {
|
||||
return
|
||||
}
|
||||
@@ -292,6 +292,7 @@ reset:
|
||||
}
|
||||
logs.Trace("%s request, method %s, host %s, url %s, remote address %s, return cache", r.URL.Scheme, r.Method, r.Host, r.URL.Path, c.RemoteAddr().String())
|
||||
host.Client.Flow.Add(int64(n), int64(n))
|
||||
host.Flow.Add(int64(n), int64(n))
|
||||
//if return cache and does not create a new conn with client and Connection is not set or close, close the connection.
|
||||
if strings.ToLower(r.Header.Get("Connection")) == "close" || strings.ToLower(r.Header.Get("Connection")) == "" {
|
||||
break
|
||||
@@ -313,6 +314,7 @@ reset:
|
||||
break
|
||||
}
|
||||
host.Client.Flow.Add(int64(lenConn.Len), int64(lenConn.Len))
|
||||
host.Flow.Add(int64(lenConn.Len), int64(lenConn.Len))
|
||||
|
||||
readReq:
|
||||
//read req from connection
|
||||
|
||||
@@ -259,7 +259,7 @@ func (https *HttpsServer) handleHttps2(c net.Conn, hostName string, rb []byte, r
|
||||
logs.Warn(err.Error())
|
||||
}
|
||||
logs.Info("new https connection,clientId %d,host %s,remote address %s", host.Client.Id, r.Host, c.RemoteAddr().String())
|
||||
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Client.Flow, host.Target.LocalProxy, nil)
|
||||
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Client.Flow, host.Target.LocalProxy, nil, host)
|
||||
}
|
||||
|
||||
// close
|
||||
@@ -302,7 +302,7 @@ func (https *HttpsServer) handleHttps(c net.Conn) {
|
||||
logs.Warn(err.Error())
|
||||
}
|
||||
logs.Trace("new https connection,clientId %d,host %s,remote address %s", host.Client.Id, r.Host, c.RemoteAddr().String())
|
||||
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Client.Flow, host.Target.LocalProxy, nil)
|
||||
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Client.Flow, host.Target.LocalProxy, nil, host)
|
||||
}
|
||||
|
||||
type HttpsListener struct {
|
||||
@@ -345,7 +345,7 @@ func GetServerNameFromClientHello(c net.Conn) (string, []byte) {
|
||||
return "", header
|
||||
}
|
||||
recordLen := int(header[3])<<8 | int(header[4])
|
||||
if recordLen <= 0 {
|
||||
if recordLen <= 0 || recordLen > 16384 {
|
||||
return "", header
|
||||
}
|
||||
|
||||
|
||||
+68
-14
@@ -108,22 +108,47 @@ func (s *Sock5ModeServer) sendReply(c net.Conn, rep uint8) {
|
||||
// do conn
|
||||
func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) {
|
||||
addrType := make([]byte, 1)
|
||||
c.Read(addrType)
|
||||
if _, err := io.ReadFull(c, addrType); err != nil {
|
||||
logs.Warn("read addr type error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
var host string
|
||||
switch addrType[0] {
|
||||
case ipV4:
|
||||
ipv4 := make(net.IP, net.IPv4len)
|
||||
c.Read(ipv4)
|
||||
if _, err := io.ReadFull(c, ipv4); err != nil {
|
||||
logs.Warn("read ipv4 error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
host = ipv4.String()
|
||||
case ipV6:
|
||||
ipv6 := make(net.IP, net.IPv6len)
|
||||
c.Read(ipv6)
|
||||
if _, err := io.ReadFull(c, ipv6); err != nil {
|
||||
logs.Warn("read ipv6 error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
host = ipv6.String()
|
||||
case domainName:
|
||||
var domainLen uint8
|
||||
binary.Read(c, binary.BigEndian, &domainLen)
|
||||
if err := binary.Read(c, binary.BigEndian, &domainLen); err != nil {
|
||||
logs.Warn("read domain len error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
domain := make([]byte, domainLen)
|
||||
c.Read(domain)
|
||||
if _, err := io.ReadFull(c, domain); err != nil {
|
||||
logs.Warn("read domain error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
host = string(domain)
|
||||
default:
|
||||
s.sendReply(c, addrTypeNotSupported)
|
||||
@@ -131,7 +156,12 @@ func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) {
|
||||
}
|
||||
|
||||
var port uint16
|
||||
binary.Read(c, binary.BigEndian, &port)
|
||||
if err := binary.Read(c, binary.BigEndian, &port); err != nil {
|
||||
logs.Warn("read port error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
// connect to host
|
||||
addr := net.JoinHostPort(host, strconv.Itoa(int(port)))
|
||||
var ltype string
|
||||
@@ -142,7 +172,7 @@ func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) {
|
||||
}
|
||||
s.DealClient(conn.NewConn(c), s.task.Client, addr, nil, ltype, func() {
|
||||
s.sendReply(c, succeeded)
|
||||
}, s.task.Flow, s.task.Target.LocalProxy, nil)
|
||||
}, s.task.Flow, s.task.Target.LocalProxy, nil, nil)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -176,22 +206,42 @@ func (s *Sock5ModeServer) sendUdpReply(writeConn net.Conn, c net.Conn, rep uint8
|
||||
func (s *Sock5ModeServer) handleUDP(c net.Conn) {
|
||||
defer c.Close()
|
||||
addrType := make([]byte, 1)
|
||||
c.Read(addrType)
|
||||
if _, err := io.ReadFull(c, addrType); err != nil {
|
||||
logs.Warn("read addr type error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
return
|
||||
}
|
||||
var host string
|
||||
switch addrType[0] {
|
||||
case ipV4:
|
||||
ipv4 := make(net.IP, net.IPv4len)
|
||||
c.Read(ipv4)
|
||||
if _, err := io.ReadFull(c, ipv4); err != nil {
|
||||
logs.Warn("read ipv4 error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
return
|
||||
}
|
||||
host = ipv4.String()
|
||||
case ipV6:
|
||||
ipv6 := make(net.IP, net.IPv6len)
|
||||
c.Read(ipv6)
|
||||
if _, err := io.ReadFull(c, ipv6); err != nil {
|
||||
logs.Warn("read ipv6 error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
return
|
||||
}
|
||||
host = ipv6.String()
|
||||
case domainName:
|
||||
var domainLen uint8
|
||||
binary.Read(c, binary.BigEndian, &domainLen)
|
||||
if err := binary.Read(c, binary.BigEndian, &domainLen); err != nil {
|
||||
logs.Warn("read domain len error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
return
|
||||
}
|
||||
domain := make([]byte, domainLen)
|
||||
c.Read(domain)
|
||||
if _, err := io.ReadFull(c, domain); err != nil {
|
||||
logs.Warn("read domain error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
return
|
||||
}
|
||||
host = string(domain)
|
||||
default:
|
||||
s.sendReply(c, addrTypeNotSupported)
|
||||
@@ -199,8 +249,12 @@ func (s *Sock5ModeServer) handleUDP(c net.Conn) {
|
||||
}
|
||||
//读取端口
|
||||
var port uint16
|
||||
binary.Read(c, binary.BigEndian, &port)
|
||||
logs.Warn(host, string(port))
|
||||
if err := binary.Read(c, binary.BigEndian, &port); err != nil {
|
||||
logs.Warn("read port error", err)
|
||||
s.sendReply(c, serverFailure)
|
||||
return
|
||||
}
|
||||
logs.Warn(host, strconv.Itoa(int(port)))
|
||||
replyAddr, err := net.ResolveUDPAddr("udp", s.task.ServerIp+":0")
|
||||
if err != nil {
|
||||
logs.Error("build local reply addr error", err)
|
||||
|
||||
+2
-2
@@ -106,7 +106,7 @@ func ProcessTunnel(c *conn.Conn, s *TunnelModeServer) error {
|
||||
logs.Warn("tcp port %d ,client id %d,task id %d connect error %s", s.task.Port, s.task.Client.Id, s.task.Id, err.Error())
|
||||
return err
|
||||
}
|
||||
return s.DealClient(c, s.task.Client, targetAddr, nil, common.CONN_TCP, nil, s.task.Client.Flow, s.task.Target.LocalProxy, s.task)
|
||||
return s.DealClient(c, s.task.Client, targetAddr, nil, common.CONN_TCP, nil, s.task.Client.Flow, s.task.Target.LocalProxy, s.task, nil)
|
||||
}
|
||||
|
||||
// http proxy
|
||||
@@ -125,6 +125,6 @@ func ProcessHttp(c *conn.Conn, s *TunnelModeServer) error {
|
||||
if err := s.auth(r, c, s.task.Client.Cnf.U, s.task.Client.Cnf.P); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.DealClient(c, s.task.Client, addr, rb, common.CONN_TCP, nil, s.task.Client.Flow, s.task.Target.LocalProxy, nil)
|
||||
return s.DealClient(c, s.task.Client, addr, rb, common.CONN_TCP, nil, s.task.Client.Flow, s.task.Target.LocalProxy, nil, nil)
|
||||
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ func HandleTrans(c *conn.Conn, s *TunnelModeServer) error {
|
||||
if addr, err := getAddress(c.Conn); err != nil {
|
||||
return err
|
||||
} else {
|
||||
return s.DealClient(c, s.task.Client, addr, nil, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy, nil)
|
||||
return s.DealClient(c, s.task.Client, addr, nil, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy, nil, nil)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -144,6 +144,7 @@ func (s *UdpModeServer) dispatch(key string, sess *udpSession, data []byte, n in
|
||||
}
|
||||
sess.touch()
|
||||
s.task.Client.Flow.Add(int64(n), int64(n))
|
||||
s.task.Flow.Add(int64(n), int64(n))
|
||||
}
|
||||
|
||||
// runSession 由占位赢家执行:建立到 npc 的 stream、发送首包、运行下行读循环。
|
||||
@@ -191,6 +192,7 @@ func (s *UdpModeServer) runSession(addr *net.UDPAddr, key string, sess *udpSessi
|
||||
}
|
||||
common.BufPoolUdp.Put(buf)
|
||||
s.task.Client.Flow.Add(int64(n), int64(n))
|
||||
s.task.Flow.Add(int64(n), int64(n))
|
||||
|
||||
// 下行读循环
|
||||
rbuf := common.BufPoolUdp.Get().([]byte)
|
||||
@@ -211,6 +213,7 @@ func (s *UdpModeServer) runSession(addr *net.UDPAddr, key string, sess *udpSessi
|
||||
return
|
||||
}
|
||||
s.task.Client.Flow.Add(int64(rn), int64(rn))
|
||||
s.task.Flow.Add(int64(rn), int64(rn))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -257,7 +257,7 @@ func Join(c1 io.ReadWriteCloser, c2 io.ReadWriteCloser, host *file.Host) (inCoun
|
||||
defer to.Close()
|
||||
defer from.Close()
|
||||
defer wait.Done()
|
||||
goroutine.CopyBuffer(to, from, host.Client.Flow, nil, "")
|
||||
goroutine.CopyBuffer(to, from, host.Client.Flow, nil, host, "")
|
||||
//*count, _ = io.Copy(to, from)
|
||||
}
|
||||
|
||||
|
||||
+88
-47
@@ -71,7 +71,7 @@ func DealBridgeTask() {
|
||||
logs.Trace("New secret connection, addr", s.Conn.Conn.RemoteAddr())
|
||||
if t := file.GetDb().GetTaskByMd5Password(s.Password); t != nil {
|
||||
if t.Status {
|
||||
go proxy.NewBaseServer(Bridge, t).DealClient(s.Conn, t.Client, t.Target.TargetStr, nil, common.CONN_TCP, nil, t.Flow, t.Target.LocalProxy, nil)
|
||||
go proxy.NewBaseServer(Bridge, t).DealClient(s.Conn, t.Client, t.Target.TargetStr, nil, common.CONN_TCP, nil, t.Flow, t.Target.LocalProxy, nil, nil)
|
||||
} else {
|
||||
s.Conn.Close()
|
||||
logs.Trace("This key %s cannot be processed,status is close", s.Password)
|
||||
@@ -87,6 +87,12 @@ func DealBridgeTask() {
|
||||
// start a new server
|
||||
func StartNewServer(bridgePort int, cnf *file.Tunnel, bridgeType string, bridgeDisconnect int) {
|
||||
Bridge = bridge.NewTunnel(bridgePort, bridgeType, common.GetBoolByStr(beego.AppConfig.String("ip_limit")), RunList, bridgeDisconnect)
|
||||
// 启动流量持久化(只启动一次,避免每次 AddTask 创建泄漏的 goroutine)
|
||||
if minute, err := beego.AppConfig.Int("flow_store_interval"); err == nil && minute > 0 {
|
||||
go flowSession(time.Minute * time.Duration(minute))
|
||||
}
|
||||
// 启动后台 IO 速率采集,Dashboard 直接读缓存,无需 Sleep
|
||||
tool.StartIORateCollector()
|
||||
go func() {
|
||||
if err := Bridge.StartTunnel(); err != nil {
|
||||
logs.Error("start server bridge error", err)
|
||||
@@ -100,6 +106,7 @@ func StartNewServer(bridgePort int, cnf *file.Tunnel, bridgeType string, bridgeD
|
||||
}
|
||||
go DealBridgeTask()
|
||||
go dealClientFlow()
|
||||
go dealClientExpire()
|
||||
if svr := NewMode(Bridge, cnf); svr != nil {
|
||||
if err := svr.Start(); err != nil {
|
||||
logs.Error(err)
|
||||
@@ -122,6 +129,50 @@ func dealClientFlow() {
|
||||
}
|
||||
}
|
||||
|
||||
// dealClientExpire 周期性扫描客户端到期时间,过期则自动暂停
|
||||
func dealClientExpire() {
|
||||
// 启动时立即检查一次,避免重启后到期客户端最多 1 分钟内才被暂停
|
||||
checkClientExpire()
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
checkClientExpire()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkClientExpire 遍历所有客户端,若 ExpireTime 已过则将 Status 置为 false 并断开连接
|
||||
func checkClientExpire() {
|
||||
now := time.Now()
|
||||
changed := false
|
||||
file.GetDb().JsonDb.Clients.Range(func(key, value interface{}) bool {
|
||||
v, ok := value.(*file.Client)
|
||||
if !ok || v == nil {
|
||||
return true
|
||||
}
|
||||
if v.ExpireTime == "" || !v.Status {
|
||||
return true
|
||||
}
|
||||
t, err := time.ParseInLocation("2006-01-02 15:04:05", v.ExpireTime, time.Local)
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
if now.Before(t) {
|
||||
return true
|
||||
}
|
||||
v.Status = false
|
||||
changed = true
|
||||
logs.Info("client id %d (remark: %s) expired at %s, auto paused", v.Id, v.Remark, v.ExpireTime)
|
||||
DelClientConnect(v.Id)
|
||||
return true
|
||||
})
|
||||
if changed {
|
||||
file.GetDb().JsonDb.StoreClientsToJsonFile()
|
||||
}
|
||||
}
|
||||
|
||||
// new a server by mode name
|
||||
func NewMode(Bridge *bridge.Bridge, c *file.Tunnel) proxy.Service {
|
||||
var service proxy.Service
|
||||
@@ -189,9 +240,6 @@ func AddTask(t *file.Tunnel) error {
|
||||
logs.Error("taskId %d start error port %d open failed", t.Id, t.Port)
|
||||
return errors.New("the port open error")
|
||||
}
|
||||
if minute, err := beego.AppConfig.Int("flow_store_interval"); err == nil && minute > 0 {
|
||||
go flowSession(time.Minute * time.Duration(minute))
|
||||
}
|
||||
if svr := NewMode(Bridge, t); svr != nil {
|
||||
logs.Info("tunnel task %s start mode:%s port %d", t.Remark, t.Mode, t.Port)
|
||||
//RunList[t.Id] = svr
|
||||
@@ -238,18 +286,16 @@ func GetTunnel(start, length int, typeVal string, clientId int, search string, s
|
||||
all_list := make([]*file.Tunnel, 0) //store all Tunnel
|
||||
list := make([]*file.Tunnel, 0)
|
||||
var cnt int
|
||||
keys := file.GetMapKeys(file.GetDb().JsonDb.Tasks, false, "", "")
|
||||
|
||||
//get all Tunnel and sort
|
||||
for _, key := range keys {
|
||||
if value, ok := file.GetDb().JsonDb.Tasks.Load(key); ok {
|
||||
v := value.(*file.Tunnel)
|
||||
if (typeVal != "" && v.Mode != typeVal || (clientId != 0 && v.Client.Id != clientId)) || (typeVal == "" && clientId != v.Client.Id) {
|
||||
continue
|
||||
}
|
||||
all_list = append(all_list, v)
|
||||
// 单次遍历收集所有符合条件的 Tunnel(修复原代码双重遍历 sync.Map 的性能问题)
|
||||
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
v := value.(*file.Tunnel)
|
||||
if (typeVal != "" && v.Mode != typeVal || (clientId != 0 && v.Client.Id != clientId)) || (typeVal == "" && clientId != v.Client.Id) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
all_list = append(all_list, v)
|
||||
return true
|
||||
})
|
||||
//sort by Id, Remark, TargetStr, Port, asc or desc
|
||||
if sortField == "Id" {
|
||||
if order == "asc" {
|
||||
@@ -283,31 +329,25 @@ func GetTunnel(start, length int, typeVal string, clientId int, search string, s
|
||||
}
|
||||
}
|
||||
|
||||
//search
|
||||
for _, key := range all_list {
|
||||
if value, ok := file.GetDb().JsonDb.Tasks.Load(key.Id); ok {
|
||||
v := value.(*file.Tunnel)
|
||||
if (typeVal != "" && v.Mode != typeVal || (clientId != 0 && v.Client.Id != clientId)) || (typeVal == "" && clientId != v.Client.Id) {
|
||||
continue
|
||||
}
|
||||
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || v.Port == common.GetIntNoErrByStr(search) || strings.Contains(v.Password, search) || strings.Contains(v.Remark, search) || strings.Contains(v.Target.TargetStr, search)) {
|
||||
continue
|
||||
}
|
||||
cnt++
|
||||
if _, ok := Bridge.Client.Load(v.Client.Id); ok {
|
||||
v.Client.IsConnect = true
|
||||
} else {
|
||||
v.Client.IsConnect = false
|
||||
}
|
||||
if start--; start < 0 {
|
||||
if length--; length >= 0 {
|
||||
if _, ok := RunList.Load(v.Id); ok {
|
||||
v.RunStatus = true
|
||||
} else {
|
||||
v.RunStatus = false
|
||||
}
|
||||
list = append(list, v)
|
||||
//search and paginate(直接在已排序的列表上操作,避免二次 Load)
|
||||
for _, v := range all_list {
|
||||
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || v.Port == common.GetIntNoErrByStr(search) || strings.Contains(v.Password, search) || strings.Contains(v.Remark, search) || strings.Contains(v.Target.TargetStr, search)) {
|
||||
continue
|
||||
}
|
||||
cnt++
|
||||
if _, ok := Bridge.Client.Load(v.Client.Id); ok {
|
||||
v.Client.IsConnect = true
|
||||
} else {
|
||||
v.Client.IsConnect = false
|
||||
}
|
||||
if start--; start < 0 {
|
||||
if length--; length >= 0 {
|
||||
if _, ok := RunList.Load(v.Id); ok {
|
||||
v.RunStatus = true
|
||||
} else {
|
||||
v.RunStatus = false
|
||||
}
|
||||
list = append(list, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -450,25 +490,26 @@ func GetDashboardData() map[string]interface{} {
|
||||
data["swap_mem"] = math.Round(swap.UsedPercent)
|
||||
vir, _ := mem.VirtualMemory()
|
||||
data["virtual_mem"] = math.Round(vir.UsedPercent)
|
||||
conn, _ := net.ProtoCounters(nil)
|
||||
io1, _ := net.IOCounters(false)
|
||||
time.Sleep(time.Millisecond * 500)
|
||||
io2, _ := net.IOCounters(false)
|
||||
if len(io2) > 0 && len(io1) > 0 {
|
||||
data["io_send"] = (io2[0].BytesSent - io1[0].BytesSent) * 2
|
||||
data["io_recv"] = (io2[0].BytesRecv - io1[0].BytesRecv) * 2
|
||||
// IO 速率从后台缓存读取,无需 Sleep 500ms
|
||||
if cached, ok := tool.IORateCache.Load().(map[string]uint64); ok {
|
||||
data["io_send"] = cached["io_send"]
|
||||
data["io_recv"] = cached["io_recv"]
|
||||
}
|
||||
conn, _ := net.ProtoCounters(nil)
|
||||
for _, v := range conn {
|
||||
data[v.Protocol] = v.Stats["CurrEstab"]
|
||||
}
|
||||
//chart
|
||||
var fg int
|
||||
if len(tool.ServerStatus) >= 10 {
|
||||
fg = len(tool.ServerStatus) / 10
|
||||
tool.ServerStatusMu.RLock()
|
||||
statusLen := len(tool.ServerStatus)
|
||||
if statusLen >= 10 {
|
||||
fg = statusLen / 10
|
||||
for i := 0; i <= 9; i++ {
|
||||
data["sys"+strconv.Itoa(i+1)] = tool.ServerStatus[i*fg]
|
||||
}
|
||||
}
|
||||
tool.ServerStatusMu.RUnlock()
|
||||
return data
|
||||
}
|
||||
|
||||
|
||||
+59
-9
@@ -4,6 +4,8 @@ import (
|
||||
"math"
|
||||
"math/rand"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"ehang.io/nps/lib/common"
|
||||
@@ -15,8 +17,10 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ports []int
|
||||
ServerStatus []map[string]interface{}
|
||||
ports []int
|
||||
ServerStatus []map[string]interface{}
|
||||
ServerStatusMu sync.RWMutex
|
||||
IORateCache atomic.Value
|
||||
)
|
||||
|
||||
func StartSystemInfo() {
|
||||
@@ -52,7 +56,7 @@ func TestServerPort(p int, m string) (b bool) {
|
||||
}
|
||||
|
||||
func GenerateServerPort(m string) int {
|
||||
for {
|
||||
for i := 0; i < 1000; i++ {
|
||||
//生成随机数 1024 - 65535
|
||||
serverPort := rand.Intn(65535)
|
||||
if serverPort < 1024 {
|
||||
@@ -63,6 +67,7 @@ func GenerateServerPort(m string) int {
|
||||
return serverPort
|
||||
}
|
||||
}
|
||||
return 0 // 超过最大重试次数,返回0表示无法分配端口
|
||||
}
|
||||
|
||||
func getSeverStatus() {
|
||||
@@ -88,12 +93,9 @@ func getSeverStatus() {
|
||||
vir, _ := mem.VirtualMemory()
|
||||
m["virtual_mem"] = math.Round(vir.UsedPercent)
|
||||
conn, _ := net.ProtoCounters(nil)
|
||||
io1, _ := net.IOCounters(false)
|
||||
time.Sleep(time.Millisecond * 500)
|
||||
io2, _ := net.IOCounters(false)
|
||||
if len(io2) > 0 && len(io1) > 0 {
|
||||
m["io_send"] = (io2[0].BytesSent - io1[0].BytesSent) * 2
|
||||
m["io_recv"] = (io2[0].BytesRecv - io1[0].BytesRecv) * 2
|
||||
if cached, ok := IORateCache.Load().(map[string]uint64); ok {
|
||||
m["io_send"] = cached["io_send"]
|
||||
m["io_recv"] = cached["io_recv"]
|
||||
}
|
||||
t := time.Now()
|
||||
m["time"] = strconv.Itoa(t.Hour()) + ":" + strconv.Itoa(t.Minute()) + ":" + strconv.Itoa(t.Second())
|
||||
@@ -102,8 +104,56 @@ func getSeverStatus() {
|
||||
m[v.Protocol] = v.Stats["CurrEstab"]
|
||||
}
|
||||
if len(ServerStatus) >= 1440 {
|
||||
ServerStatusMu.Lock()
|
||||
ServerStatus = ServerStatus[1:]
|
||||
ServerStatusMu.Unlock()
|
||||
}
|
||||
ServerStatusMu.Lock()
|
||||
ServerStatus = append(ServerStatus, m)
|
||||
ServerStatusMu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// StartIORateCollector 启动后台 IO 速率采集,每 2s 刷新一次 IORateCache
|
||||
func StartIORateCollector() {
|
||||
go collectIORate()
|
||||
}
|
||||
|
||||
func collectIORate() {
|
||||
var lastSent, lastRecv uint64
|
||||
// 修复:无论首次 IOCounters 是否成功,都把 lastTime 设为 now,
|
||||
// 否则首次有效采样的 elapsed 会是几十年,导致 sendRate/recvRate 直接为 0
|
||||
lastTime := time.Now()
|
||||
if io, err := net.IOCounters(false); err == nil && len(io) > 0 {
|
||||
lastSent = io[0].BytesSent
|
||||
lastRecv = io[0].BytesRecv
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(2 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
now := time.Now()
|
||||
io, err := net.IOCounters(false)
|
||||
if err != nil || len(io) == 0 {
|
||||
continue
|
||||
}
|
||||
elapsed := now.Sub(lastTime).Seconds()
|
||||
if elapsed <= 0 {
|
||||
continue
|
||||
}
|
||||
var sendRate, recvRate uint64
|
||||
if io[0].BytesSent >= lastSent {
|
||||
sendRate = uint64(float64(io[0].BytesSent-lastSent) / elapsed)
|
||||
}
|
||||
if io[0].BytesRecv >= lastRecv {
|
||||
recvRate = uint64(float64(io[0].BytesRecv-lastRecv) / elapsed)
|
||||
}
|
||||
lastSent = io[0].BytesSent
|
||||
lastRecv = io[0].BytesRecv
|
||||
lastTime = now
|
||||
IORateCache.Store(map[string]uint64{
|
||||
"io_send": sendRate,
|
||||
"io_recv": recvRate,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,6 +73,7 @@ func (s *ClientController) Add() {
|
||||
IpWhite: s.GetBoolNoErr("ipwhite"),
|
||||
IpWhitePass: s.getEscapeString("ipwhitepass"),
|
||||
IpWhiteList: RemoveRepeatedElement(strings.Split(s.getEscapeString("ipwhitelist"), "\r\n")),
|
||||
ExpireTime: normalizeExpireTime(s.getEscapeString("expire_time")),
|
||||
CreateTime: time.Now().Format("2006-01-02 15:04:05"),
|
||||
}
|
||||
if err := file.GetDb().NewClient(t); err != nil {
|
||||
@@ -159,6 +160,7 @@ func (s *ClientController) Edit() {
|
||||
}
|
||||
|
||||
c.BlackIpList = RemoveRepeatedElement(strings.Split(s.getEscapeString("blackiplist"), "\r\n"))
|
||||
c.ExpireTime = normalizeExpireTime(s.getEscapeString("expire_time"))
|
||||
file.GetDb().JsonDb.StoreClientsToJsonFile()
|
||||
}
|
||||
s.AjaxOk("save success")
|
||||
@@ -186,6 +188,39 @@ func RemoveRepeatedElement(arr []string) (newArr []string) {
|
||||
return
|
||||
}
|
||||
|
||||
// expireTimeFormats 支持的到期时间输入格式
|
||||
var expireTimeFormats = []string{
|
||||
"2006-01-02 15:04:05",
|
||||
"2006-01-02 15:04",
|
||||
"2006-01-02T15:04:05",
|
||||
"2006-01-02T15:04",
|
||||
"2006-01-02",
|
||||
}
|
||||
|
||||
// ParseExpireTime 将多种格式的到期时间字符串解析为 time.Time
|
||||
// 留空或无法解析返回 ok=false
|
||||
func ParseExpireTime(s string) (time.Time, bool) {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return time.Time{}, false
|
||||
}
|
||||
for _, f := range expireTimeFormats {
|
||||
if t, err := time.ParseInLocation(f, s, time.Local); err == nil {
|
||||
return t, true
|
||||
}
|
||||
}
|
||||
return time.Time{}, false
|
||||
}
|
||||
|
||||
// normalizeExpireTime 将用户提交的到期时间统一为 "2006-01-02 15:04:05"
|
||||
// 无法解析则返回空串表示不限制
|
||||
func normalizeExpireTime(s string) string {
|
||||
if t, ok := ParseExpireTime(s); ok {
|
||||
return t.Format("2006-01-02 15:04:05")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// 更改状态
|
||||
func (s *ClientController) ChangeStatus() {
|
||||
id := s.GetIntNoErr("id")
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
(function (global, factory) {
|
||||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
|
||||
typeof define === 'function' && define.amd ? define(['exports'], factory) :
|
||||
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.zh = {}));
|
||||
}(this, (function (exports) { 'use strict';
|
||||
|
||||
var fp = typeof window !== "undefined" && window.flatpickr !== undefined
|
||||
? window.flatpickr
|
||||
: {
|
||||
l10ns: {},
|
||||
};
|
||||
var Mandarin = {
|
||||
weekdays: {
|
||||
shorthand: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
|
||||
longhand: [
|
||||
"星期日",
|
||||
"星期一",
|
||||
"星期二",
|
||||
"星期三",
|
||||
"星期四",
|
||||
"星期五",
|
||||
"星期六",
|
||||
],
|
||||
},
|
||||
months: {
|
||||
shorthand: [
|
||||
"一月",
|
||||
"二月",
|
||||
"三月",
|
||||
"四月",
|
||||
"五月",
|
||||
"六月",
|
||||
"七月",
|
||||
"八月",
|
||||
"九月",
|
||||
"十月",
|
||||
"十一月",
|
||||
"十二月",
|
||||
],
|
||||
longhand: [
|
||||
"一月",
|
||||
"二月",
|
||||
"三月",
|
||||
"四月",
|
||||
"五月",
|
||||
"六月",
|
||||
"七月",
|
||||
"八月",
|
||||
"九月",
|
||||
"十月",
|
||||
"十一月",
|
||||
"十二月",
|
||||
],
|
||||
},
|
||||
rangeSeparator: " 至 ",
|
||||
weekAbbreviation: "周",
|
||||
scrollTitle: "滚动切换",
|
||||
toggleTitle: "点击切换 12/24 小时时制",
|
||||
};
|
||||
fp.l10ns.zh = Mandarin;
|
||||
var zh = fp.l10ns;
|
||||
|
||||
exports.Mandarin = Mandarin;
|
||||
exports.default = zh;
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
})));
|
||||
Vendored
+2
File diff suppressed because one or more lines are too long
@@ -792,6 +792,16 @@
|
||||
<en-US>Last Online Time</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="word-expiretime">
|
||||
<zh-CN>到期时间</zh-CN>
|
||||
<en-US>Expire Time</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="info-expiretime">
|
||||
<zh-CN>留空表示永不过期,到期后将自动暂停客户端</zh-CN>
|
||||
<en-US>Leave blank for no expiration. The client will be paused automatically when expired.</en-US>
|
||||
</lang>
|
||||
|
||||
<lang id="word-ipwhite">
|
||||
<zh-CN>启用IP白名单</zh-CN>
|
||||
<en-US> Enable IP White </en-US>
|
||||
|
||||
@@ -142,6 +142,14 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="expire_time">
|
||||
<label class="control-label font-bold" langtag="word-expiretime"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control flatpickr-expire" type="text" name="expire_time" placeholder="2026-12-31 23:59:59" autocomplete="off">
|
||||
<span class="help-block m-b-none" langtag="info-expiretime"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="hr-line-dashed"></div>
|
||||
<div class="form-group">
|
||||
<div class="col-sm-4 col-sm-offset-2">
|
||||
@@ -170,5 +178,18 @@ $(document).ready(function() {
|
||||
$('#black_ip_list').show();
|
||||
}
|
||||
});
|
||||
|
||||
// 到期时间选择器
|
||||
if (typeof flatpickr !== 'undefined') {
|
||||
flatpickr('.flatpickr-expire', {
|
||||
enableTime: true,
|
||||
enableSeconds: true,
|
||||
time_24hr: true,
|
||||
dateFormat: 'Y-m-d H:i:S',
|
||||
minDate: 'today',
|
||||
allowInput: true,
|
||||
locale: (flatpickr.l10ns && flatpickr.l10ns.zh) ? 'zh' : 'default'
|
||||
});
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -166,6 +166,15 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="expire_time">
|
||||
<label class="control-label font-bold" langtag="word-expiretime"></label>
|
||||
<div class="col-sm-10">
|
||||
<input class="form-control flatpickr-expire" value="{{.c.ExpireTime}}" type="text" name="expire_time"
|
||||
placeholder="2026-12-31 23:59:59" autocomplete="off">
|
||||
<span class="help-block m-b-none" langtag="info-expiretime"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="hr-line-dashed"></div>
|
||||
<div class="form-group">
|
||||
<div class="col-sm-4 col-sm-offset-2">
|
||||
@@ -199,5 +208,17 @@
|
||||
$(document).ready(function () {
|
||||
// 页面加载时初始化显示状态
|
||||
changeIpWhite();
|
||||
|
||||
// 到期时间选择器
|
||||
if (typeof flatpickr !== 'undefined') {
|
||||
flatpickr('.flatpickr-expire', {
|
||||
enableTime: true,
|
||||
enableSeconds: true,
|
||||
time_24hr: true,
|
||||
dateFormat: 'Y-m-d H:i:S',
|
||||
allowInput: true,
|
||||
locale: (flatpickr.l10ns && flatpickr.l10ns.zh) ? 'zh' : 'default'
|
||||
});
|
||||
}
|
||||
});
|
||||
</script>
|
||||
@@ -73,7 +73,8 @@
|
||||
+ '<b langtag="word-ipwhitelist"></b>: ' + row.IpWhiteList + ' <br/>'
|
||||
+ '<b langtag="word-blackip"></b>: ' + row.BlackIpList + ' <br/><br/>'
|
||||
+ '<b langtag="word-createtime"></b>: ' + row.CreateTime + ' <br/>'
|
||||
+ '<b langtag="word-lastonlinetime"></b>: ' + row.LastOnlineTime + ' <br/><br/>'
|
||||
+ '<b langtag="word-lastonlinetime"></b>: ' + row.LastOnlineTime + ' <br/>'
|
||||
+ '<b langtag="word-expiretime"></b>: ' + (row.ExpireTime || '<span langtag="info-unrestricted"></span>') + ' <br/><br/>'
|
||||
+ '<b langtag="word-quicklycommand"></b>: <span>' + encodeToBase64(row.Remark +'|'+'{{.ip}}:{{.p}}|' + row.VerifyKey + '|false') + '</span> <button class="copy btn btn-info btn-xs" onclick="copyCommand(this)" data-clipboard-text="">复制</button><br/>'
|
||||
+ '<b langtag="word-tlsquicklycommand"></b>: <span>' + encodeToBase64(row.Remark +'|'+'{{.ip}}:{{.tls_p}}|' + row.VerifyKey + '|true') + '</span> <button class="copy btn btn-info btn-xs" onclick="copyCommand(this)" data-clipboard-text="">复制</button><br/>'
|
||||
+ '<b langtag="word-commandclient"></b>: ' + "<code>{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.VerifyKey + " -type=" +{{.bridgeType}} +"</code><button class=\"copy btn btn-info btn-xs\" onclick=\"copyCommand(this)\" data-clipboard-text=\"\">复制</button><br/>"
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
<link href="{{.web_base_url}}/static/css/bootstrap.min.css?v={{.version}}" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/bootstrap-table.min.css?v={{.version}}" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/style.css?v={{.version}}" rel="stylesheet">
|
||||
<link href="{{.web_base_url}}/static/css/flatpickr.min.css?v={{.version}}" rel="stylesheet">
|
||||
|
||||
<!-- Latest compiled and minified JavaScript -->
|
||||
<script src="{{.web_base_url}}/static/js/jquery-3.4.1.min.js?v={{.version}}"></script>
|
||||
@@ -28,6 +29,8 @@
|
||||
<script src="{{.web_base_url}}/static/js/bootstrap-table-locale-all.min.js?v={{.version}}"></script>
|
||||
<script src="{{.web_base_url}}/static/js/echarts.min.js?v={{.version}}"></script>
|
||||
<script src="{{.web_base_url}}/static/js/inspinia.js?v={{.version}}"></script>
|
||||
<script src="{{.web_base_url}}/static/js/flatpickr.min.js?v={{.version}}"></script>
|
||||
<script src="{{.web_base_url}}/static/js/flatpickr-l10n-zh.js?v={{.version}}"></script>
|
||||
<!-- Latest compiled and minified Locales -->
|
||||
<script src="{{.web_base_url}}/static/js/language.js?v={{.version}}" type="text/javascript"></script>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user