Compare commits

..
15 Commits
39 changed files with 1375 additions and 475 deletions
+35 -35
View File
@@ -17,41 +17,41 @@ deploy:
token: ${GH_TOKEN}
cleanup: false
file:
- freebsd_386_client.tar.gz
- freebsd_386_server.tar.gz
- freebsd_amd64_client.tar.gz
- freebsd_amd64_server.tar.gz
- freebsd_arm_client.tar.gz
- freebsd_arm_server.tar.gz
- linux_386_client.tar.gz
- linux_386_server.tar.gz
- linux_amd64_client.tar.gz
- linux_amd64_server.tar.gz
- linux_arm64_client.tar.gz
- linux_arm64_server.tar.gz
- linux_arm_v5_client.tar.gz
- linux_arm_v6_client.tar.gz
- linux_arm_v7_client.tar.gz
- linux_arm_v5_server.tar.gz
- linux_arm_v6_server.tar.gz
- linux_arm_v7_server.tar.gz
- linux_mips64le_client.tar.gz
- linux_mips64le_server.tar.gz
- linux_mips64_client.tar.gz
- linux_mips64_server.tar.gz
- linux_mipsle_client.tar.gz
- linux_mipsle_server.tar.gz
- linux_mips_client.tar.gz
- linux_mips_server.tar.gz
- darwin_amd64_client.tar.gz
- darwin_amd64_server.tar.gz
- windows_386_client.tar.gz
- windows_386_server.tar.gz
- windows_amd64_client.tar.gz
- windows_amd64_server.tar.gz
- npc_syno.spk
- npc_sdk.tar.gz
- android_client.apk
- freebsd_386_client.tar.gz
- freebsd_386_server.tar.gz
- freebsd_amd64_client.tar.gz
- freebsd_amd64_server.tar.gz
- freebsd_arm_client.tar.gz
- freebsd_arm_server.tar.gz
- linux_386_client.tar.gz
- linux_386_server.tar.gz
- linux_amd64_client.tar.gz
- linux_amd64_server.tar.gz
- linux_arm64_client.tar.gz
- linux_arm64_server.tar.gz
- linux_arm_v5_client.tar.gz
- linux_arm_v6_client.tar.gz
- linux_arm_v7_client.tar.gz
- linux_arm_v5_server.tar.gz
- linux_arm_v6_server.tar.gz
- linux_arm_v7_server.tar.gz
- linux_mips64le_client.tar.gz
- linux_mips64le_server.tar.gz
- linux_mips64_client.tar.gz
- linux_mips64_server.tar.gz
- linux_mipsle_client.tar.gz
- linux_mipsle_server.tar.gz
- linux_mips_client.tar.gz
- linux_mips_server.tar.gz
- darwin_amd64_client.tar.gz
- darwin_amd64_server.tar.gz
- windows_386_client.tar.gz
- windows_386_server.tar.gz
- windows_amd64_client.tar.gz
- windows_amd64_server.tar.gz
- npc_syno.spk
- npc_sdk.tar.gz
- android_client.apk
on:
tags: true
all_branches: true
+1 -1
View File
@@ -1,6 +1,6 @@
# NPS
![Version](https://img.shields.io/badge/version-v0.26.35-blue)
![Version](https://img.shields.io/badge/version-v0.26.37-blue)
![License](https://img.shields.io/badge/license-GPL--3.0-green)
![Go](https://img.shields.io/badge/Go-%3E%3D1.22-00ADD8?logo=go)
+46 -6
View File
@@ -117,6 +117,37 @@ func (s *Bridge) StartTunnel() error {
return nil
}
// requestClientLocalAddr asks the client for private/LAN IPs on the main signal conn.
// New clients reply with WriteLenContent; old clients ignore the flag and we time out.
func (s *Bridge) requestClientLocalAddr(id int, c *conn.Conn) {
if c == nil || c.Conn == nil {
return
}
if _, err := c.Write([]byte(common.REPORT_LOCAL_IP)); err != nil {
return
}
_ = c.Conn.SetReadDeadline(time.Now().Add(2 * time.Second))
defer func() {
// clear deadline so health / later reads are not affected
_ = c.Conn.SetReadDeadline(time.Time{})
}()
b, err := c.GetShortLenContent()
if err != nil {
logs.Trace("clientId %d did not report local addr (old client or timeout): %v", id, err)
return
}
localAddr := strings.TrimSpace(string(b))
if localAddr == "" {
return
}
if client, err := file.GetDb().GetClient(id); err == nil {
client.Lock()
client.LocalAddr = localAddr
client.Unlock()
logs.Info("clientId %d local addr: %s", id, localAddr)
}
}
// get health information form client
func (s *Bridge) GetHealthFromClient(id int, c *conn.Conn) {
for {
@@ -185,6 +216,7 @@ func (s *Bridge) GetHealthFromClient(id int, c *conn.Conn) {
// 验证失败,返回错误验证flag,并且关闭连接
func (s *Bridge) verifyError(c *conn.Conn) {
c.Write([]byte(common.VERIFY_EER))
c.Close()
}
func (s *Bridge) verifySuccess(c *conn.Conn) {
@@ -192,16 +224,19 @@ func (s *Bridge) verifySuccess(c *conn.Conn) {
}
func (s *Bridge) cliProcess(c *conn.Conn) {
// 握手 10s 超时:扫描/半开连接不会一直占着 goroutine;成功后清掉
_ = c.SetReadDeadline(time.Now().Add(10 * time.Second))
//read test flag
if _, err := c.GetShortContent(3); err != nil {
logs.Info("The client %s connect error", c.Conn.RemoteAddr(), err.Error())
c.Close()
return
}
//version check
if b, err := c.GetShortLenContent(); err != nil || string(b) != version.GetVersion() {
//logs.Info("The client %s version does not match", c.Conn.RemoteAddr())
//c.Close()
//return
//version check(版本不匹配仍兼容放行;读失败则断开)
if _, err := c.GetShortLenContent(); err != nil {
c.Close()
return
}
//version get
var vs []byte
@@ -213,7 +248,7 @@ func (s *Bridge) cliProcess(c *conn.Conn) {
}
//write server version to client
c.Write([]byte(crypt.Md5(version.GetVersion())))
c.SetReadDeadlineBySecond(5)
_ = c.SetReadDeadline(time.Now().Add(10 * time.Second))
var buf []byte
//get vKey from client
if buf, err = c.GetShortContent(32); err != nil {
@@ -230,9 +265,12 @@ func (s *Bridge) cliProcess(c *conn.Conn) {
s.verifySuccess(c)
}
if flag, err := c.ReadFlag(); err == nil {
// 握手完成,交给 typeDeal 做长连接
_ = c.SetReadDeadline(time.Time{})
s.typeDeal(flag, c, id, string(vs))
} else {
logs.Warn(err, flag)
c.Close()
}
return
}
@@ -285,6 +323,8 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int, vs string) {
oldSignal.WriteClose()
}
}
// Request private/LAN IPs from client. Old clients ignore the flag; short timeout keeps compatibility.
s.requestClientLocalAddr(id, c)
go s.GetHealthFromClient(id, c)
logs.Info("clientId %d connection succeeded, address:%s ", id, c.Conn.RemoteAddr())
case common.WORK_CHAN:
+17 -17
View File
@@ -8,79 +8,79 @@ tar -czvf npc_sdk.tar.gz npc_sdk.dll npc_sdk.so npc_sdk.h
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_amd64_client.tar.gz npc
tar -czvf linux_amd64_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_386_client.tar.gz npc
tar -czvf linux_386_client.tar.gz npc
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_386_client.tar.gz npc
tar -czvf freebsd_386_client.tar.gz npc
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_amd64_client.tar.gz npc
tar -czvf freebsd_amd64_client.tar.gz npc
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_arm_client.tar.gz npc
tar -czvf freebsd_arm_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v7_client.tar.gz npc
tar -czvf linux_arm_v7_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v6_client.tar.gz npc
tar -czvf linux_arm_v6_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v5_client.tar.gz npc
tar -czvf linux_arm_v5_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm64_client.tar.gz npc
tar -czvf linux_arm64_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 GOMIPS64=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips64_client.tar.gz npc
tar -czvf linux_mips64_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le GOMIPS64=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips64le_client.tar.gz npc
tar -czvf linux_mips64le_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle GOMIPS=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mipsle_client.tar.gz npc
tar -czvf linux_mipsle_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mips GOMIPS=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips_client.tar.gz npc
tar -czvf linux_mips_client.tar.gz npc
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf windows_386_client.tar.gz npc.exe
tar -czvf windows_386_client.tar.gz npc.exe
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf windows_amd64_client.tar.gz npc.exe
tar -czvf windows_amd64_client.tar.gz npc.exe
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf darwin_amd64_client.tar.gz npc
tar -czvf darwin_amd64_client.tar.gz npc
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf darwin_arm64_client.tar.gz npc
tar -czvf darwin_arm64_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
+18 -18
View File
@@ -1,5 +1,5 @@
#/bash/sh
export VERSION=0.26.33
export VERSION=0.26.37
export GOPROXY=direct
sudo apt-get update
@@ -13,71 +13,71 @@ tar -xvf upx-3.95-amd64_linux.tar.xz
cp upx-3.95-amd64_linux/upx ./
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_amd64_client.tar.gz npc
tar -czvf linux_amd64_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_386_client.tar.gz npc
tar -czvf linux_386_client.tar.gz npc
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_386_client.tar.gz npc
tar -czvf freebsd_386_client.tar.gz npc
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_amd64_client.tar.gz npc
tar -czvf freebsd_amd64_client.tar.gz npc
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_arm_client.tar.gz npc
tar -czvf freebsd_arm_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v7_client.tar.gz npc
tar -czvf linux_arm_v7_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v6_client.tar.gz npc
tar -czvf linux_arm_v6_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v5_client.tar.gz npc
tar -czvf linux_arm_v5_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm64_client.tar.gz npc
tar -czvf linux_arm64_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 GOMIPS64=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips64_client.tar.gz npc
tar -czvf linux_mips64_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le GOMIPS64=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips64le_client.tar.gz npc
tar -czvf linux_mips64le_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle GOMIPS=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mipsle_client.tar.gz npc
tar -czvf linux_mipsle_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=mips GOMIPS=softfloat go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips_client.tar.gz npc
tar -czvf linux_mips_client.tar.gz npc
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf windows_386_client.tar.gz npc.exe
tar -czvf windows_386_client.tar.gz npc.exe
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf windows_amd64_client.tar.gz npc.exe
tar -czvf windows_amd64_client.tar.gz npc.exe
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf darwin_amd64_client.tar.gz npc
tar -czvf darwin_amd64_client.tar.gz npc
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf darwin_arm64_client.tar.gz npc
tar -czvf darwin_arm64_client.tar.gz npc
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
+29 -8
View File
@@ -34,6 +34,7 @@ type TRPClient struct {
cnf *config.Config
disconnectTime int
once sync.Once
closeCh chan struct{} // closed when client is shutting down; stops ping
logger *logs.BeeLogger // 每个客户端独立的 logger
}
@@ -48,6 +49,7 @@ func NewRPClient(svraddr string, vKey string, bridgeConnType string, proxyUrl st
cnf: cnf,
disconnectTime: disconnectTime,
once: sync.Once{},
closeCh: make(chan struct{}),
logger: nil, // 默认使用全局 logger,可通过 SetLogger 设置
}
}
@@ -134,6 +136,7 @@ retry:
// handle main connection
func (s *TRPClient) handleMain() {
mainLoop:
for {
flags, err := s.signal.ReadFlag()
if err != nil {
@@ -141,11 +144,19 @@ func (s *TRPClient) handleMain() {
break
}
switch flags {
case common.REPORT_LOCAL_IP:
// server requests private/LAN IPs (new nps); ignore failures so main loop continues
localIPs := common.GetLocalIPs(s.signal.Conn)
if err := s.signal.WriteLenContent([]byte(localIPs)); err != nil {
s.logWarn("report local ip failed: %s", err.Error())
} else {
s.logInfo("reported local addr: %s", localIPs)
}
case common.NEW_UDP_CONN:
//read server udp addr and password
if lAddr, err := s.signal.GetShortLenContent(); err != nil {
s.logWarn(err.Error())
return
break mainLoop
} else if pwd, err := s.signal.GetShortLenContent(); err == nil {
var localAddr string
//The local port remains unchanged for a certain period of time
@@ -153,7 +164,7 @@ func (s *TRPClient) handleMain() {
tmpConn, err := common.GetLocalUdpAddr()
if err != nil {
s.logError(err.Error())
return
break mainLoop
}
localAddr = tmpConn.LocalAddr().String()
} else {
@@ -203,7 +214,10 @@ func (s *TRPClient) newUdpConn(localAddr, rAddr string, md5Password string) {
func (s *TRPClient) newChan() {
tunnel, err := NewConn(s.bridgeConnType, s.vKey, s.svrAddr, common.WORK_CHAN, s.proxyUrl)
if err != nil {
s.logError("connect to %s error: %v", s.svrAddr, err)
// WORK_MAIN may already be up; without Close the client stays half-connected
// (handleMain blocks, outer reconnect loop never runs). See #115.
s.logError("connect to %s error: %v, client will reconnect", s.svrAddr, err)
s.Close()
return
}
s.tunnel = nps_mux.NewMux(tunnel.Conn, s.bridgeConnType, s.disconnectTime)
@@ -376,14 +390,18 @@ func (s *TRPClient) handleUdp(serverConn net.Conn) {
// Whether the monitor channel is closed
func (s *TRPClient) ping() {
s.ticker = time.NewTicker(time.Second * 5)
loop:
defer s.ticker.Stop()
for {
select {
case <-s.ticker.C:
// tunnel still nil: newChan failed or still connecting; if Close already ran, closeCh fires.
// tunnel established then closed: tear down so outer loop can reconnect.
if s.tunnel != nil && s.tunnel.IsClose() {
s.Close()
break loop
return
}
case <-s.closeCh:
return
}
}
}
@@ -395,13 +413,16 @@ func (s *TRPClient) Close() {
func (s *TRPClient) closing() {
CloseClient = true
NowStatus = 0
// unblock ping; safe: closing runs only once via once.Do
select {
case <-s.closeCh:
default:
close(s.closeCh)
}
if s.tunnel != nil {
_ = s.tunnel.Close()
}
if s.signal != nil {
_ = s.signal.Close()
}
if s.ticker != nil {
s.ticker.Stop()
}
}
+1 -1
View File
@@ -14,7 +14,7 @@
},
"info": {
"productName": "NPS Client",
"productVersion": "0.26.33",
"productVersion": "0.26.37",
"companyName": "NPS",
"copyright": "Copyright © 2026 NPS"
},
+2
View File
@@ -213,6 +213,8 @@ func run() {
common.InitPProfFromArg(*pprofAddr)
//p2p or secret command
if *password != "" {
client.SetTlsEnable(*tlsEnable)
logs.Info("the version of client is %s, the core version of client is %s,tls enable is %t", version.VERSION, version.GetVersion(), client.GetTlsEnable())
commonConfig := new(config.CommonConfig)
commonConfig.Server = *serverAddr
commonConfig.VKey = *verifyKey
+20 -4
View File
@@ -26,7 +26,6 @@ import (
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/crypt"
"ehang.io/nps/web"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
@@ -52,6 +51,7 @@ func main() {
return
}
if *serverCmd {
_ = logs.SetLogger(logs.AdapterConsole, `{"level":7,"color":true}`)
printSlogan()
inputCmd()
return
@@ -270,7 +270,15 @@ func inputCmd() {
_ = service.Control(s, "uninstall")
binPath := install.InstallNpsToCurrentDir()
beego.LoadAppConfig("ini", filepath.Join(common.GetAppPath(), "conf", "nps.conf"))
// Ensure conf exists (same as normal startup), then load it for display.
// Previously LoadAppConfig error was ignored and web_port could be empty,
// printing "127.0.0.1:" with no port. See #317.
confDir := filepath.Join(common.GetAppPath(), "conf")
initConfig(confDir)
if err := beego.LoadAppConfig("ini", filepath.Join(confDir, "nps.conf")); err != nil {
fmt.Println("加载配置文件失败:", err)
break
}
logPath := filepath.Join(common.GetAppPath(), "nps.log")
if common.IsWindows() {
@@ -303,7 +311,16 @@ func inputCmd() {
if err != nil {
fmt.Println("启动NPS服务失败", err)
} else {
fmt.Println("NPS服务已启动,管理面板访问地址:127.0.0.1:" + beego.AppConfig.String("web_port"))
webPort := beego.AppConfig.String("web_port")
if webPort == "" {
fmt.Println("NPS服务已启动(未配置 web_port,管理面板已关闭)")
} else {
scheme := "http"
if beego.AppConfig.DefaultBool("web_open_ssl", false) {
scheme = "https"
}
fmt.Println("NPS服务已启动,管理面板访问地址:" + scheme + "://127.0.0.1:" + webPort)
}
}
break
@@ -472,7 +489,6 @@ func initConfig(confDir string) {
logs.Info("auth_key:", authKey)
logs.Info("auth_crypt_key:", authCryptKey)
}
web.ExtractWebFiles(common.GetRunPath())
}
const defaultNpsConf = `http_proxy_ip=0.0.0.0
+24
View File
@@ -1,4 +1,28 @@
# 更新日志
- 2026-08-08 v0.26.37
- 修复:
- NPC 安装到系统服务失败 BUG [#338](https://github.com/yisier/nps/issues/338)
- 隧道实际未运行但面板提示「启动成功」、运行状态始终为关闭的问题 [#339](https://github.com/yisier/nps/issues/339)
- 配置 `allow_ports` 后随机生成端口问题 [#339](https://github.com/yisier/nps/issues/339)
- Web 面板`languages.xml`使用 NPS 版本号作为缓存标识 [#342](https://github.com/yisier/nps/issues/342)
- 新增:
- 客户端、隧道、域名解析修改接口支持修改流量数据 [#341](https://github.com/yisier/nps/issues/341)
- 2026-07-12 v0.26.36
- 新增:
- 新增客户端内网地址上报功能,客户端列表展示 npc 内网地址 [#333](https://github.com/yisier/nps/issues/333)
- Web 管理端客户端/隧道/域名列表业务字段支持服务端排序(备注、状态、在线等)[#254](https://github.com/yisier/nps/issues/254)
- 优化:
- 不再依赖外部 `web` 目录的静态文件
- 修复:
- 客户端/服务端在线更新失败 BUG
- `nps -server` 安装成功后 `web_port` 未正常显示BUG [#317](https://github.com/yisier/nps/issues/317)
- Bridge 握手增加 10s 读超时,校验失败/读失败立即关闭连接,减轻端口扫描导致的连接与 goroutine 堆积 [#281](https://github.com/yisier/nps/issues/281)
- 解决私密代理和P2P连接的TLS启用问题 [#143](https://github.com/yisier/nps/issues/143)
- HTTP 正向代理 Basic 认证 BUG[#133](https://github.com/yisier/nps/issues/133)
- SOCKS5 用户名密码认证 BUG [#133](https://github.com/yisier/nps/issues/133)
- 客户端建连失败后半连接假死、需手动重启 npc BUG [#115](https://github.com/yisier/nps/issues/115)
- 2026-07-04 v0.26.35
- 新增:
- 客户端列表、隧道列表、域名解析列表支持多选批量删除 [#287](https://github.com/yisier/nps/issues/287)
+6 -4
View File
@@ -103,6 +103,8 @@ POST /client/edit/
| ipwhitepass | IP 白名单授权密码 |
| ipwhitelist | 白名单 IP 列表,`\r\n` 分隔 |
| expire_time | 到期时间,格式同新增接口 |
| flow_inlet | 入口流量,单位字节,传入则覆盖原值(留空不修改) |
| flow_export | 出口流量,单位字节,传入则覆盖原值(留空不修改) |
---
@@ -219,6 +221,8 @@ POST /index/edit/
| local_path | 本地文件路径 |
| strip_pre | URL 前缀去除 |
| proto_version | 协议版本 |
| flow_inlet | 入口流量,单位字节,传入则覆盖原值(留空不修改) |
| flow_export | 出口流量,单位字节,传入则覆盖原值(留空不修改) |
---
@@ -331,10 +335,8 @@ POST /index/edithost/
| key_file_path | HTTPS 证书私钥文本或路径 |
| cert_file_path | HTTPS 证书文件文本或路径 |
| AutoHttps | 是否自动 HTTPS |
---
### 停止域名解析
| flow_inlet | 入口流量,单位字节,传入则覆盖原值(留空不修改) |
| flow_export | 出口流量,单位字节,传入则覆盖原值(留空不修改) |
```
POST /index/hoststop/
+10
View File
@@ -21,6 +21,9 @@ const (
RES_MSG = "msg0"
RES_CLOSE = "clse"
NEW_UDP_CONN = "udpc" //p2p udp conn
// REPORT_LOCAL_IP: server requests client local/private IPs on WORK_MAIN.
// New clients reply with WriteLenContent; old clients ignore the flag (server times out).
REPORT_LOCAL_IP = "rlip"
NEW_TASK = "task"
NEW_CONF = "conf"
NEW_HOST = "host"
@@ -32,6 +35,13 @@ Content-Type: text/plain; charset=utf-8
WWW-Authenticate: Basic realm="easyProxy"
401 Unauthorized`
// ProxyAuthRequiredBytes is the challenge for HTTP forward proxy Basic auth (RFC 7235).
// Clients expect 407 + Proxy-Authenticate, not 401 + WWW-Authenticate.
ProxyAuthRequiredBytes = "HTTP/1.1 407 Proxy Authentication Required\r\n" +
"Content-Type: text/plain; charset=utf-8\r\n" +
"Proxy-Authenticate: Basic realm=\"nps\"\r\n" +
"\r\n" +
"407 Proxy Authentication Required"
ConnectionFailBytes = `HTTP/1.1 404 Not Found
`
+93
View File
@@ -482,6 +482,99 @@ func GetIntranetIp() (error, string) {
return errors.New("get intranet ip error"), ""
}
// isUsefulPrivateIPv4 reports whether ip is a usable LAN IPv4 for display:
// RFC1918 private only — excludes loopback, link-local (169.254.0.0/16), public, etc.
func isUsefulPrivateIPv4(ip net.IP) bool {
if ip == nil {
return false
}
v4 := ip.To4()
if v4 == nil {
return false
}
if v4.IsLoopback() || v4.IsLinkLocalUnicast() || v4.IsLinkLocalMulticast() || v4.IsUnspecified() || v4.IsMulticast() {
return false
}
// RFC1918 only (not 169.254, not public)
return v4.IsPrivate()
}
func ipFromAddr(addr net.Addr) net.IP {
if addr == nil {
return nil
}
switch a := addr.(type) {
case *net.TCPAddr:
return a.IP
case *net.UDPAddr:
return a.IP
default:
return net.ParseIP(GetIpByAddr(addr.String()))
}
}
// GetLocalIPs returns private (RFC1918) IPv4 addresses useful for identifying the npc host.
// Prefers the local IP of conn (path toward nps). Falls back to interface scan.
// Link-local 169.254.0.0/16, loopback and public addresses are excluded.
func GetLocalIPs(conn net.Conn) string {
seen := make(map[string]struct{})
ips := make([]string, 0, 4)
add := func(ip net.IP) {
if !isUsefulPrivateIPv4(ip) {
return
}
s := ip.To4().String()
if _, ok := seen[s]; ok {
return
}
seen[s] = struct{}{}
ips = append(ips, s)
}
// 1) Local endpoint of the bridge connection — usually the real LAN IP used to reach nps.
if conn != nil {
add(ipFromAddr(conn.LocalAddr()))
// One correct path IP is enough for most hosts (avoids docker/vm junk alongside).
if len(ips) > 0 {
return ips[0]
}
}
// 2) Outbound interface toward the internet (same idea as GetLocalUdpAddr).
if tmp, err := net.Dial("udp", "114.114.114.114:53"); err == nil {
add(ipFromAddr(tmp.LocalAddr()))
_ = tmp.Close()
if len(ips) > 0 {
return ips[0]
}
}
// 3) Fallback: all up interfaces with private IPv4.
ifaces, err := net.Interfaces()
if err == nil {
for _, iface := range ifaces {
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
continue
}
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok {
add(ipnet.IP)
}
}
}
}
if len(ips) > 1 {
sort.Strings(ips)
}
return strings.Join(ips, ",")
}
func IsPublicIP(IP net.IP) bool {
if IP.IsLoopback() || IP.IsLinkLocalMulticast() || IP.IsLinkLocalUnicast() {
return false
+66 -50
View File
@@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"net/http"
"sort"
"strings"
"sync"
@@ -36,43 +35,42 @@ func GetDb() *DbUtils {
return Db
}
func GetMapKeys(m sync.Map, isSort bool, sortKey, order string) (keys []int) {
if sortKey != "" && isSort {
return sortClientByKey(m, sortKey, order)
}
m.Range(func(key, value interface{}) bool {
keys = append(keys, key.(int))
func (s *DbUtils) GetClientList(start, length int, search, sortField, order string, clientId int) ([]*Client, int) {
all := make([]*Client, 0)
s.JsonDb.Clients.Range(func(key, value interface{}) bool {
v := value.(*Client)
if v.NoDisplay {
return true
}
if clientId != 0 && clientId != v.Id {
return true
}
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.VerifyKey, search) || strings.Contains(v.Remark, search) || strings.Contains(v.Addr, search) || strings.Contains(v.LocalAddr, search)) {
return true
}
all = append(all, v)
return true
})
sort.Ints(keys)
return
SortClients(all, sortField, order)
return paginateClients(all, start, length)
}
func (s *DbUtils) GetClientList(start, length int, search, sort, order string, clientId int) ([]*Client, int) {
list := make([]*Client, 0)
var cnt int
keys := GetMapKeys(s.JsonDb.Clients, true, sort, order)
for _, key := range keys {
if value, ok := s.JsonDb.Clients.Load(key); ok {
v := value.(*Client)
if v.NoDisplay {
continue
}
if clientId != 0 && clientId != v.Id {
continue
}
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.VerifyKey, search) || strings.Contains(v.Remark, search)) {
continue
}
cnt++
if start--; start < 0 {
if length--; length >= 0 {
list = append(list, v)
}
}
}
func paginateClients(all []*Client, start, length int) ([]*Client, int) {
cnt := len(all)
if start < 0 {
start = 0
}
return list, cnt
if length <= 0 {
return []*Client{}, cnt
}
if start >= cnt {
return []*Client{}, cnt
}
end := start + length
if end > cnt {
end = cnt
}
return all[start:end], cnt
}
func (s *DbUtils) GetIdByVerifyKey(vKey string, addr string) (id int, err error) {
@@ -182,27 +180,45 @@ func (s *DbUtils) NewHost(t *Host) error {
return nil
}
func (s *DbUtils) GetHost(start, length int, id int, search string) ([]*Host, int) {
list := make([]*Host, 0)
var cnt int
keys := GetMapKeys(s.JsonDb.Hosts, false, "", "")
for _, key := range keys {
if value, ok := s.JsonDb.Hosts.Load(key); ok {
v := value.(*Host)
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.Host, search) || strings.Contains(v.Remark, search) || strings.Contains(v.Client.VerifyKey, search)) {
continue
func (s *DbUtils) GetHost(start, length int, id int, search, sortField, order string) ([]*Host, int) {
all := make([]*Host, 0)
s.JsonDb.Hosts.Range(func(key, value interface{}) bool {
v := value.(*Host)
if search != "" {
vkey := ""
if v.Client != nil {
vkey = v.Client.VerifyKey
}
if id == 0 || v.Client.Id == id {
cnt++
if start--; start < 0 {
if length--; length >= 0 {
list = append(list, v)
}
}
if !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.Host, search) || strings.Contains(v.Remark, search) || strings.Contains(vkey, search)) {
return true
}
}
if id != 0 && (v.Client == nil || v.Client.Id != id) {
return true
}
all = append(all, v)
return true
})
SortHosts(all, sortField, order)
return paginateHosts(all, start, length)
}
func paginateHosts(all []*Host, start, length int) ([]*Host, int) {
cnt := len(all)
if start < 0 {
start = 0
}
return list, cnt
if length <= 0 {
return []*Host{}, cnt
}
if start >= cnt {
return []*Host{}, cnt
}
end := start + length
if end > cnt {
end = cnt
}
return all[start:end], cnt
}
func (s *DbUtils) DelClient(id int) error {
+3 -1
View File
@@ -35,7 +35,8 @@ type Client struct {
Cnf *Config
Id int //id
VerifyKey string //verify key
Addr string //the ip of client
Addr string // client egress address as seen by server (RemoteAddr)
LocalAddr string // client private/LAN addresses reported by npc
Remark string //remark
Status bool //is allow connect
IsConnect bool //is the client connect
@@ -67,6 +68,7 @@ func NewClient(vKey string, noStore bool, noDisplay bool) *Client {
Id: 0,
VerifyKey: vKey,
Addr: "",
LocalAddr: "",
Remark: "",
Status: true,
IsConnect: false,
+221 -29
View File
@@ -1,41 +1,233 @@
package file
import (
"reflect"
"sort"
"sync"
"strings"
)
// A data structure to hold a key/value pair.
type Pair struct {
key string //sort key
cId int
order string
clientFlow *Flow
}
// A slice of Pairs that implements sort.Interface to sort by Value.
type PairList []*Pair
func (p PairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p PairList) Len() int { return len(p) }
func (p PairList) Less(i, j int) bool {
if p[i].order == "desc" {
return reflect.ValueOf(*p[i].clientFlow).FieldByName(p[i].key).Int() < reflect.ValueOf(*p[j].clientFlow).FieldByName(p[j].key).Int()
func lessBool(a, b bool, asc bool) bool {
if a == b {
return false
}
return reflect.ValueOf(*p[i].clientFlow).FieldByName(p[i].key).Int() > reflect.ValueOf(*p[j].clientFlow).FieldByName(p[j].key).Int()
if asc {
return !a && b // false first
}
return a && !b // true first
}
// A function to turn a map into a PairList, then sort and return it.
func sortClientByKey(m sync.Map, sortKey, order string) (res []int) {
p := make(PairList, 0)
m.Range(func(key, value interface{}) bool {
p = append(p, &Pair{sortKey, value.(*Client).Id, order, value.(*Client).Flow})
return true
func lessInt(a, b int, asc bool) bool {
if asc {
return a < b
}
return a > b
}
func lessInt64(a, b int64, asc bool) bool {
if asc {
return a < b
}
return a > b
}
func lessString(a, b string, asc bool) bool {
if asc {
return strings.ToLower(a) < strings.ToLower(b)
}
return strings.ToLower(a) > strings.ToLower(b)
}
// SortClients sorts clients in-place by the given field (bootstrap-table sort name).
func SortClients(list []*Client, sortField, order string) {
if sortField == "" || len(list) < 2 {
if sortField == "" && len(list) > 1 {
sort.SliceStable(list, func(i, j int) bool { return list[i].Id < list[j].Id })
}
return
}
asc := order != "desc"
sort.SliceStable(list, func(i, j int) bool {
a, b := list[i], list[j]
switch sortField {
case "Id":
return lessInt(a.Id, b.Id, asc)
case "Remark":
return lessString(a.Remark, b.Remark, asc)
case "Version":
return lessString(a.Version, b.Version, asc)
case "VerifyKey":
return lessString(a.VerifyKey, b.VerifyKey, asc)
case "Addr":
return lessString(a.Addr, b.Addr, asc)
case "LocalAddr":
return lessString(a.LocalAddr, b.LocalAddr, asc)
case "InletFlow":
return lessInt64(flowInlet(a), flowInlet(b), asc)
case "ExportFlow":
return lessInt64(flowExport(a), flowExport(b), asc)
case "NowRate":
return lessInt64(nowRate(a), nowRate(b), asc)
case "Status":
return lessBool(a.Status, b.Status, asc)
case "IsConnect":
return lessBool(a.IsConnect, b.IsConnect, asc)
default:
return lessInt(a.Id, b.Id, true)
}
})
sort.Sort(p)
for _, v := range p {
res = append(res, v.cId)
}
func flowInlet(c *Client) int64 {
if c == nil || c.Flow == nil {
return 0
}
return
return c.Flow.InletFlow
}
func flowExport(c *Client) int64 {
if c == nil || c.Flow == nil {
return 0
}
return c.Flow.ExportFlow
}
func nowRate(c *Client) int64 {
if c == nil || c.Rate == nil {
return 0
}
return c.Rate.NowRate
}
// SortTunnels sorts tunnels in-place by the given field.
func SortTunnels(list []*Tunnel, sortField, order string) {
if sortField == "" || len(list) < 2 {
if sortField == "" && len(list) > 1 {
sort.SliceStable(list, func(i, j int) bool { return list[i].Id < list[j].Id })
}
return
}
asc := order != "desc"
sort.SliceStable(list, func(i, j int) bool {
a, b := list[i], list[j]
switch sortField {
case "Id":
return lessInt(a.Id, b.Id, asc)
case "ClientId":
return lessInt(clientIdOfTunnel(a), clientIdOfTunnel(b), asc)
case "Remark":
return lessString(a.Remark, b.Remark, asc)
case "Client.VerifyKey", "VerifyKey":
return lessString(clientVkeyOfTunnel(a), clientVkeyOfTunnel(b), asc)
case "Mode":
return lessString(a.Mode, b.Mode, asc)
case "Port":
return lessInt(a.Port, b.Port, asc)
case "Target":
return lessString(targetStrOfTunnel(a), targetStrOfTunnel(b), asc)
case "Password":
return lessString(a.Password, b.Password, asc)
case "Status":
return lessBool(a.Status, b.Status, asc)
case "RunStatus":
return lessBool(a.RunStatus, b.RunStatus, asc)
case "IsConnect", "Client.IsConnect":
return lessBool(clientConnectOfTunnel(a), clientConnectOfTunnel(b), asc)
default:
return lessInt(a.Id, b.Id, true)
}
})
}
func clientIdOfTunnel(t *Tunnel) int {
if t == nil || t.Client == nil {
return 0
}
return t.Client.Id
}
func clientVkeyOfTunnel(t *Tunnel) string {
if t == nil || t.Client == nil {
return ""
}
return t.Client.VerifyKey
}
func clientConnectOfTunnel(t *Tunnel) bool {
if t == nil || t.Client == nil {
return false
}
return t.Client.IsConnect
}
func targetStrOfTunnel(t *Tunnel) string {
if t == nil || t.Target == nil {
return ""
}
return t.Target.TargetStr
}
// SortHosts sorts hosts in-place by the given field.
func SortHosts(list []*Host, sortField, order string) {
if sortField == "" || len(list) < 2 {
if sortField == "" && len(list) > 1 {
sort.SliceStable(list, func(i, j int) bool { return list[i].Id < list[j].Id })
}
return
}
asc := order != "desc"
sort.SliceStable(list, func(i, j int) bool {
a, b := list[i], list[j]
switch sortField {
case "Id":
return lessInt(a.Id, b.Id, asc)
case "ClientId":
return lessInt(clientIdOfHost(a), clientIdOfHost(b), asc)
case "Remark":
return lessString(a.Remark, b.Remark, asc)
case "Client.VerifyKey", "VerifyKey":
return lessString(clientVkeyOfHost(a), clientVkeyOfHost(b), asc)
case "Host":
return lessString(a.Host, b.Host, asc)
case "Scheme":
return lessString(a.Scheme, b.Scheme, asc)
case "Target":
return lessString(targetStrOfHost(a), targetStrOfHost(b), asc)
case "Location":
return lessString(a.Location, b.Location, asc)
case "IsClose", "Status":
// IsClose: false=open, true=closed — sort by open status for "Status" display
return lessBool(a.IsClose, b.IsClose, asc)
case "IsConnect", "Client.IsConnect":
return lessBool(clientConnectOfHost(a), clientConnectOfHost(b), asc)
default:
return lessInt(a.Id, b.Id, true)
}
})
}
func clientIdOfHost(h *Host) int {
if h == nil || h.Client == nil {
return 0
}
return h.Client.Id
}
func clientVkeyOfHost(h *Host) string {
if h == nil || h.Client == nil {
return ""
}
return h.Client.VerifyKey
}
func clientConnectOfHost(h *Host) bool {
if h == nil || h.Client == nil {
return false
}
return h.Client.IsConnect
}
func targetStrOfHost(h *Host) string {
if h == nil || h.Target == nil {
return ""
}
return h.Target.TargetStr
}
+2 -2
View File
@@ -5,12 +5,12 @@ import (
"fmt"
"io"
"net"
"path/filepath"
"strings"
"sync"
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/file"
"ehang.io/nps/web"
"github.com/astaxie/beego/logs"
"github.com/panjf2000/ants/v2"
)
@@ -64,7 +64,7 @@ func CopyBuffer(dst io.Writer, src io.Reader, flow *file.Flow, task *file.Tunnel
ip := common.GetIpByAddr(remote)
var jsonBytes []byte
errorContent, _ := common.ReadAllFromFile(filepath.Join(common.GetRunPath(), "web", "static", "page", "auth.html"))
errorContent, _ := web.ReadStaticFile("page/auth.html")
authHtml := string(errorContent)
authHtml = strings.ReplaceAll(authHtml, "${ip}", ip)
+215 -126
View File
@@ -137,9 +137,16 @@ WantedBy=multi-user.target
`
func UpdateNps() {
destPath := downloadLatest("server")
destPath, err := downloadLatest("server")
if err != nil {
log.Println("下载更新失败:", err)
return
}
//复制文件到对应目录
copyStaticFile(destPath, "nps")
if _, err := copyStaticFile(destPath, "nps"); err != nil {
log.Println("替换服务端文件失败:", err)
return
}
fmt.Println("Update completed, please restart")
}
@@ -148,16 +155,23 @@ func UpdateNpsNew() {
if err != nil {
log.Println("获取最新版本失败:", err)
return
} else {
fmt.Println("最新版本为:", latest)
if compareVersion(version.VERSION, latest) >= 0 {
fmt.Println("当前已是最新版本,无需更新")
return
}
}
destPath := downloadLatest2("server", filepath.Join(common.GetAppPath(), "temp"))
fmt.Println("最新版本为:", latest)
if compareVersion(version.VERSION, latest) >= 0 {
fmt.Println("当前已是最新版本,无需更新")
return
}
tempDir := filepath.Join(common.GetAppPath(), "temp")
destPath, err := downloadLatest2("server", tempDir)
if err != nil {
log.Println("下载更新失败:", err)
return
}
//复制文件到对应目录
copyStaticFileReplaceNps(destPath, common.GetAppPath())
if err := copyStaticFileReplaceNps(destPath, common.GetAppPath()); err != nil {
log.Println("替换服务端文件失败:", err)
return
}
fmt.Println("更新成功,请重启服务")
}
@@ -167,6 +181,9 @@ func fetchLatestVersion() (string, error) {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("HTTP %d", resp.StatusCode)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
@@ -175,6 +192,9 @@ func fetchLatestVersion() (string, error) {
if err := json.Unmarshal(b, rl); err != nil {
return "", err
}
if rl.TagName == "" {
return "", errors.New("无法解析最新版本号")
}
return rl.TagName, nil
}
@@ -191,9 +211,16 @@ func compareVersion(a, b string) int {
}
func UpdateNpc() {
destPath := downloadLatest("client")
destPath, err := downloadLatest("client")
if err != nil {
log.Println("下载更新失败:", err)
return
}
//复制文件到对应目录
copyStaticFile(destPath, "npc")
if _, err := copyStaticFile(destPath, "npc"); err != nil {
log.Println("替换客户端文件失败:", err)
return
}
fmt.Println("Update completed, please restart")
}
@@ -202,15 +229,22 @@ func UpdateNpcNew() {
if err != nil {
log.Println("获取最新版本失败:", err)
return
} else {
fmt.Println("最新版本为:", latest)
if compareVersion(version.VERSION, latest) >= 0 {
fmt.Println("当前已是最新版本,无需更新")
return
}
}
destPath := downloadLatest2("client", filepath.Join(common.GetAppPath(), "temp"))
copyStaticFileReplaceNpc(destPath, common.GetAppPath())
fmt.Println("最新版本为:", latest)
if compareVersion(version.VERSION, latest) >= 0 {
fmt.Println("当前已是最新版本,无需更新")
return
}
tempDir := filepath.Join(common.GetAppPath(), "temp")
destPath, err := downloadLatest2("client", tempDir)
if err != nil {
log.Println("下载更新失败:", err)
return
}
if err := copyStaticFileReplaceNpc(destPath, common.GetAppPath()); err != nil {
log.Println("替换客户端文件失败:", err)
return
}
fmt.Println("更新成功,请重启客户端")
}
@@ -218,69 +252,52 @@ type release struct {
TagName string `json:"tag_name"`
}
func downloadLatest(bin string) string {
// get version
data, err := http.Get("https://api.github.com/repos/yisier/nps/releases/latest")
if err != nil {
log.Fatal(err.Error())
}
b, err := ioutil.ReadAll(data.Body)
if err != nil {
log.Fatal(err)
}
rl := new(release)
json.Unmarshal(b, &rl)
version := rl.TagName
fmt.Println("the latest version is", version)
filename := runtime.GOOS + "_" + runtime.GOARCH + "_" + bin + ".tar.gz"
// download latest package
downloadUrl := fmt.Sprintf("https://github.com/yisier/nps/releases/download/%s/%s", version, filename)
fmt.Println("download package from ", downloadUrl)
resp, err := http.Get(downloadUrl)
if err != nil {
log.Fatal(err.Error())
}
destPath, err := unpackit.Unpack(resp.Body, "")
if err != nil {
log.Fatal(err)
}
if bin == "server" {
destPath = strings.Replace(destPath, "/web", "", -1)
destPath = strings.Replace(destPath, `\web`, "", -1)
destPath = strings.Replace(destPath, "/views", "", -1)
destPath = strings.Replace(destPath, `\views`, "", -1)
} else {
destPath = strings.Replace(destPath, `\conf`, "", -1)
destPath = strings.Replace(destPath, "/conf", "", -1)
}
return destPath
func downloadLatest(bin string) (string, error) {
return downloadAndUnpack(bin, "")
}
func downloadLatest2(bin string, path string) string {
// get version
func downloadLatest2(bin string, path string) (string, error) {
return downloadAndUnpack(bin, path)
}
// downloadAndUnpack fetches the latest release package for the current OS/arch.
// Releases ship as .tar.gz (see build.assets.sh / release.yml).
func downloadAndUnpack(bin, unpackPath string) (string, error) {
data, err := http.Get("https://api.github.com/repos/yisier/nps/releases/latest")
if err != nil {
log.Fatal(err.Error())
return "", err
}
defer data.Body.Close()
if data.StatusCode != http.StatusOK {
return "", fmt.Errorf("获取版本信息失败: HTTP %d", data.StatusCode)
}
b, err := ioutil.ReadAll(data.Body)
if err != nil {
log.Fatal(err)
return "", err
}
rl := new(release)
json.Unmarshal(b, &rl)
version := rl.TagName
fmt.Println("the latest version is", version)
if err := json.Unmarshal(b, rl); err != nil {
return "", err
}
if rl.TagName == "" {
return "", errors.New("无法解析最新版本号")
}
ver := rl.TagName
fmt.Println("the latest version is", ver)
filename := runtime.GOOS + "_" + runtime.GOARCH + "_" + bin + ".tar.gz"
// download latest package
downloadUrl := fmt.Sprintf("https://github.com/yisier/nps/releases/download/%s/%s", version, filename)
downloadUrl := fmt.Sprintf("https://github.com/yisier/nps/releases/download/%s/%s", ver, filename)
fmt.Println("download package from ", downloadUrl)
resp, err := http.Get(downloadUrl)
if err != nil {
log.Fatal(err.Error())
return "", err
}
destPath, err := unpackit.Unpack(resp.Body, path)
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("下载失败: HTTP %d %s", resp.StatusCode, downloadUrl)
}
destPath, err := unpackit.Unpack(resp.Body, unpackPath)
if err != nil {
log.Fatal(err)
return "", err
}
if bin == "server" {
destPath = strings.Replace(destPath, "/web", "", -1)
@@ -291,70 +308,139 @@ func downloadLatest2(bin string, path string) string {
destPath = strings.Replace(destPath, `\conf`, "", -1)
destPath = strings.Replace(destPath, "/conf", "", -1)
}
return destPath
return destPath, nil
}
func copyStaticFile(srcPath, bin string) string {
path := common.GetInstallPath()
if bin == "nps" {
//复制文件到对应目录
if err := CopyDir(filepath.Join(srcPath, "web", "views"), filepath.Join(path, "web", "views")); err != nil {
log.Fatalln(err)
}
chMod(filepath.Join(path, "web", "views"), 0766)
if err := CopyDir(filepath.Join(srcPath, "web", "static"), filepath.Join(path, "web", "static")); err != nil {
log.Fatalln(err)
}
chMod(filepath.Join(path, "web", "static"), 0766)
}
func copyStaticFile(srcPath, bin string) (string, error) {
// nps web UI is embedded in the binary; no web/ files to copy.
binPath, _ := filepath.Abs(os.Args[0])
srcBin := filepath.Join(srcPath, bin)
if common.IsWindows() {
srcBin += ".exe"
}
if _, err := os.Stat(srcBin); err != nil {
return "", fmt.Errorf("更新包中未找到可执行文件 %s: %w", srcBin, err)
}
if !common.IsWindows() {
if _, err := copyFile(filepath.Join(srcPath, bin), "/usr/bin/"+bin); err != nil {
if _, err := copyFile(filepath.Join(srcPath, bin), "/usr/local/bin/"+bin); err != nil {
log.Fatalln(err)
} else {
copyFile(filepath.Join(srcPath, bin), "/usr/local/bin/"+bin+"-update")
chMod("/usr/local/bin/"+bin+"-update", 0755)
binPath = "/usr/local/bin/" + bin
if _, err := copyFile(srcBin, "/usr/bin/"+bin); err != nil {
if _, err := copyFile(srcBin, "/usr/local/bin/"+bin); err != nil {
return "", err
}
binPath = "/usr/local/bin/" + bin
} else {
copyFile(filepath.Join(srcPath, bin), "/usr/bin/"+bin+"-update")
chMod("/usr/bin/"+bin+"-update", 0755)
binPath = "/usr/bin/" + bin
}
} else {
copyFile(filepath.Join(srcPath, bin+".exe"), filepath.Join(common.GetAppPath(), bin+"-update.exe"))
copyFile(filepath.Join(srcPath, bin+".exe"), filepath.Join(common.GetAppPath(), bin+".exe"))
destBin := filepath.Join(common.GetAppPath(), bin+".exe")
if err := replaceExecutable(srcBin, destBin); err != nil {
return "", err
}
binPath = destBin
}
chMod(binPath, 0755)
return binPath
return binPath, nil
}
func copyStaticFileReplaceNps(srcPath, descPath string) string {
//复制文件到对应目录
os.Rename(filepath.Join(srcPath, "web"), filepath.Join(descPath, "web"))
chMod(filepath.Join(descPath, "web"), 0766)
binPath, _ := filepath.Abs(os.Args[0])
if !common.IsWindows() {
os.Rename(filepath.Join(srcPath, "nps"), filepath.Join(descPath, "nps"))
} else {
os.Rename(filepath.Join(srcPath, "nps.exe"), filepath.Join(descPath, "nps.exe"))
}
chMod(binPath, 0755)
os.RemoveAll(srcPath)
return binPath
func copyStaticFileReplaceNps(srcPath, descPath string) error {
// Web UI is embedded in the binary; only replace the executable.
return replaceBinFromPackage(srcPath, descPath, "nps")
}
func copyStaticFileReplaceNpc(srcPath, descPath string) string {
binPath, _ := filepath.Abs(os.Args[0])
if !common.IsWindows() {
os.Rename(filepath.Join(srcPath, "npc"), filepath.Join(descPath, "npc"))
} else {
os.Rename(filepath.Join(srcPath, "npc.exe"), filepath.Join(descPath, "npc.exe"))
func copyStaticFileReplaceNpc(srcPath, descPath string) error {
return replaceBinFromPackage(srcPath, descPath, "npc")
}
func replaceBinFromPackage(srcPath, descPath, bin string) error {
srcBin := filepath.Join(srcPath, bin)
destBin := filepath.Join(descPath, bin)
if common.IsWindows() {
srcBin += ".exe"
destBin += ".exe"
}
chMod(binPath, 0755)
os.RemoveAll(srcPath)
return binPath
// Prefer replacing the actually running binary when its basename matches.
if exe, err := os.Executable(); err == nil {
if filepath.Base(exe) == filepath.Base(destBin) {
destBin = exe
}
}
if _, err := os.Stat(srcBin); err != nil {
// unpackit may return a nested root dir; search one level if needed
if found, findErr := findBinInDir(srcPath, filepath.Base(srcBin)); findErr == nil {
srcBin = found
} else {
return fmt.Errorf("更新包中未找到可执行文件 %s: %w", srcBin, err)
}
}
if err := replaceExecutable(srcBin, destBin); err != nil {
return err
}
chMod(destBin, 0755)
// Clean temp package; keep parent temp dir if still in use
_ = os.RemoveAll(srcPath)
return nil
}
func findBinInDir(root, name string) (string, error) {
var found string
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil || info == nil || info.IsDir() {
return err
}
if info.Name() == name {
found = path
return errors.New("found")
}
return nil
})
if found != "" {
return found, nil
}
if err != nil {
return "", err
}
return "", os.ErrNotExist
}
// replaceExecutable places srcBin at destBin. On Windows a running executable
// cannot be overwritten, but it can be renamed aside first.
func replaceExecutable(srcBin, destBin string) error {
if _, err := os.Stat(srcBin); err != nil {
return fmt.Errorf("源文件不存在: %s: %w", srcBin, err)
}
if dstFi, err := os.Stat(destBin); err == nil {
if srcFi, err := os.Stat(srcBin); err == nil {
if os.SameFile(srcFi, dstFi) {
return nil
}
}
}
if err := os.MkdirAll(filepath.Dir(destBin), 0755); err != nil {
return err
}
// Move the current binary out of the way when present (required on Windows
// while the process is still running).
if _, err := os.Stat(destBin); err == nil {
bak := destBin + ".old"
_ = os.Remove(bak)
if err := os.Rename(destBin, bak); err != nil {
return fmt.Errorf("无法备份当前程序 %s: %w", destBin, err)
}
}
// Same filesystem: rename is atomic. Fall back to copy across volumes.
if err := os.Rename(srcBin, destBin); err != nil {
if _, copyErr := copyFile(srcBin, destBin); copyErr != nil {
// Best-effort restore of previous binary
bak := destBin + ".old"
if _, statErr := os.Stat(bak); statErr == nil {
_ = os.Rename(bak, destBin)
}
return fmt.Errorf("替换可执行文件失败: %w", copyErr)
}
_ = os.Remove(srcBin)
}
return nil
}
func InstallNpc() {
@@ -365,33 +451,36 @@ func InstallNpc() {
log.Fatal(err)
}
}
copyStaticFile(common.GetAppPath(), "npc")
if _, err := copyStaticFile(common.GetAppPath(), "npc"); err != nil {
log.Fatalln(err)
}
}
func InstallNps() string {
path := common.GetInstallPath()
log.Println("install path:" + path)
if common.FileExists(path) {
MkidrDirAll(path, "web/static", "web/views")
} else {
MkidrDirAll(path, "conf", "web/static", "web/views")
if !common.FileExists(path) {
MkidrDirAll(path, "conf")
// not copy config if the config file is exist
if err := CopyDir(filepath.Join(common.GetAppPath(), "conf"), filepath.Join(path, "conf")); err != nil {
log.Fatalln(err)
}
chMod(filepath.Join(path, "conf"), 0766)
}
binPath := copyStaticFile(common.GetAppPath(), "nps")
binPath, err := copyStaticFile(common.GetAppPath(), "nps")
if err != nil {
log.Fatalln(err)
}
log.Println("install ok!")
log.Println("Static files and configuration files in the current directory will be useless")
log.Println("Web UI is embedded in the nps binary; no web/ directory is required")
log.Println("The new configuration file is located in", path, "you can edit them")
if !common.IsWindows() {
log.Println(`You can start with:
nps start|stop|restart|uninstall|update or nps-update update
nps start|stop|restart|uninstall|update
anywhere!`)
} else {
log.Println(`You can copy executable files to any directory and start working with:
nps.exe start|stop|restart|uninstall|update or nps-update.exe update
nps.exe start|stop|restart|uninstall|update
now!`)
}
chMod(common.GetLogPath(), 0777)
+1 -1
View File
@@ -1,6 +1,6 @@
package version
const VERSION = "0.26.35"
const VERSION = "0.26.37"
// Compulsory minimum version, Minimum downward compatibility to this version
func GetVersion() string {
+12 -3
View File
@@ -64,12 +64,21 @@ func (s *BaseServer) writeConnFail(c net.Conn) {
c.Write(s.errorContent)
}
// auth check
// auth check for reverse-proxy hosts (401 + WWW-Authenticate).
func (s *BaseServer) auth(r *http.Request, c *conn.Conn, u, p string) error {
return s.doAuth(r, c, u, p, common.UnauthorizedBytes, "401 Unauthorized")
}
// proxyAuth check for HTTP forward proxy (407 + Proxy-Authenticate).
func (s *BaseServer) proxyAuth(r *http.Request, c *conn.Conn, u, p string) error {
return s.doAuth(r, c, u, p, common.ProxyAuthRequiredBytes, "407 Proxy Authentication Required")
}
func (s *BaseServer) doAuth(r *http.Request, c *conn.Conn, u, p, failBytes, errMsg string) error {
if u != "" && p != "" && !common.CheckAuth(r, u, p) {
c.Write([]byte(common.UnauthorizedBytes))
c.Write([]byte(failBytes))
c.Close()
return errors.New("401 Unauthorized")
return errors.New(errMsg)
}
return nil
}
+3 -2
View File
@@ -10,6 +10,7 @@ import (
"ehang.io/nps/lib/file"
"ehang.io/nps/lib/goroutine"
"ehang.io/nps/server/connection"
"ehang.io/nps/web"
"encoding/json"
"fmt"
"github.com/astaxie/beego"
@@ -58,7 +59,7 @@ func NewHttp(bridge *bridge.Bridge, c *file.Tunnel, httpPort, httpsPort int, use
func (s *httpServer) Start() error {
var err error
if s.errorContent, err = common.ReadAllFromFile(filepath.Join(common.GetRunPath(), "web", "static", "page", "error.html")); err != nil {
if s.errorContent, err = web.ReadStaticFile("page/error.html"); err != nil {
s.errorContent = []byte("nps 404")
}
if s.httpPort > 0 {
@@ -231,7 +232,7 @@ reset:
return
}
errorContent, _ := common.ReadAllFromFile(filepath.Join(common.GetRunPath(), "web", "static", "page", "auth.html"))
errorContent, _ := web.ReadStaticFile("page/auth.html")
authHtml := string(errorContent)
authHtml = strings.ReplaceAll(authHtml, "${ip}", common.GetIpByAddr(c.RemoteAddr().String()))
s.errorContent, err = []byte(authHtml), err
+62 -36
View File
@@ -348,33 +348,62 @@ func (s *Sock5ModeServer) handleConn(c net.Conn) {
c.Close()
return
}
nMethods := buf[1]
nMethods := int(buf[1])
if nMethods == 0 {
logs.Warn("socks5 client offered no auth methods, remote %s", c.RemoteAddr())
c.Close()
return
}
methods := make([]byte, nMethods)
if len, err := c.Read(methods); len != int(nMethods) || err != nil {
if _, err := io.ReadFull(c, methods); err != nil {
logs.Warn("wrong method")
c.Close()
return
}
if (s.task.Client.Cnf.U != "" && s.task.Client.Cnf.P != "") || (s.task.MultiAccount != nil && len(s.task.MultiAccount.AccountMap) > 0) {
buf[1] = UserPassAuth
c.Write(buf)
needAuth := (s.task.Client.Cnf.U != "" && s.task.Client.Cnf.P != "") ||
(s.task.MultiAccount != nil && len(s.task.MultiAccount.AccountMap) > 0)
if needAuth {
if !methodOffered(methods, UserPassAuth) {
// Client cannot authenticate; reply no acceptable methods (RFC 1928).
_, _ = c.Write([]byte{5, 0xFF})
c.Close()
logs.Warn("socks5 client %s does not support username/password auth", c.RemoteAddr())
return
}
if _, err := c.Write([]byte{5, UserPassAuth}); err != nil {
c.Close()
return
}
if err := s.Auth(c); err != nil {
c.Close()
logs.Warn("Validation failed:", err)
logs.Warn("Validation failed: %v, remote %s", err, c.RemoteAddr())
return
}
} else {
buf[1] = 0
c.Write(buf)
if _, err := c.Write([]byte{5, 0}); err != nil {
c.Close()
return
}
}
s.handleRequest(c)
}
// socks5 auth
func methodOffered(methods []byte, method byte) bool {
for _, m := range methods {
if m == method {
return true
}
}
return false
}
// socks5 auth (RFC 1929 username/password)
func (s *Sock5ModeServer) Auth(c net.Conn) error {
header := []byte{0, 0}
if _, err := io.ReadAtLeast(c, header, 2); err != nil {
header := make([]byte, 2)
if _, err := io.ReadFull(c, header); err != nil {
return err
}
if header[0] != userAuthVersion {
@@ -382,46 +411,43 @@ func (s *Sock5ModeServer) Auth(c net.Conn) error {
}
userLen := int(header[1])
user := make([]byte, userLen)
if _, err := io.ReadAtLeast(c, user, userLen); err != nil {
return err
if userLen > 0 {
if _, err := io.ReadFull(c, user); err != nil {
return err
}
}
if _, err := c.Read(header[:1]); err != nil {
plen := make([]byte, 1)
if _, err := io.ReadFull(c, plen); err != nil {
return errors.New("密码长度获取错误")
}
passLen := int(header[0])
passLen := int(plen[0])
pass := make([]byte, passLen)
if _, err := io.ReadAtLeast(c, pass, passLen); err != nil {
return err
if passLen > 0 {
if _, err := io.ReadFull(c, pass); err != nil {
return err
}
}
var U, P string
if s.task.MultiAccount != nil {
// enable multi user auth
U = string(user)
if len(U) == 0 {
return errors.New("验证不通过")
}
var ok bool
P, ok = s.task.MultiAccount.AccountMap[U]
if !ok {
return errors.New("验证不通过")
ok := false
if s.task.MultiAccount != nil && len(s.task.MultiAccount.AccountMap) > 0 {
// multi-user auth
if expected, found := s.task.MultiAccount.AccountMap[string(user)]; found && string(pass) == expected {
ok = true
}
} else {
U = s.task.Client.Cnf.U
P = s.task.Client.Cnf.P
ok = string(user) == s.task.Client.Cnf.U && string(pass) == s.task.Client.Cnf.P
}
if string(user) == U && string(pass) == P {
if ok {
if _, err := c.Write([]byte{userAuthVersion, authSuccess}); err != nil {
return err
}
return nil
} else {
if _, err := c.Write([]byte{userAuthVersion, authFailure}); err != nil {
return err
}
return errors.New("验证不通过")
}
if _, err := c.Write([]byte{userAuthVersion, authFailure}); err != nil {
return err
}
return errors.New("验证不通过")
}
// start
+14 -10
View File
@@ -7,7 +7,6 @@ import (
"errors"
"net"
"net/http"
"path/filepath"
"strconv"
"ehang.io/nps/bridge"
@@ -15,6 +14,7 @@ import (
"ehang.io/nps/lib/conn"
"ehang.io/nps/lib/file"
"ehang.io/nps/server/connection"
"ehang.io/nps/web"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
)
@@ -66,8 +66,8 @@ func (s *WebServer) Start() error {
<-stop
}
beego.BConfig.WebConfig.Session.SessionOn = true
beego.SetStaticPath(beego.AppConfig.String("web_base_url")+"/static", filepath.Join(common.GetRunPath(), "web", "static"))
beego.SetViewsPath(filepath.Join(common.GetRunPath(), "web", "views"))
// Serve management UI from embedded assets only (no disk web/ directory).
web.InitBeegoAssets()
err := errors.New("Web management startup failure ")
var l net.Listener
if l, err = connection.GetWebManagerListener(); err == nil {
@@ -111,20 +111,24 @@ func ProcessTunnel(c *conn.Conn, s *TunnelModeServer) error {
// http proxy
func ProcessHttp(c *conn.Conn, s *TunnelModeServer) error {
_, addr, rb, err, r := c.GetHost()
if err != nil {
c.Close()
logs.Info(err)
return err
}
if r.Method == "CONNECT" {
c.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
rb = nil
}
if err := s.auth(r, c, s.task.Client.Cnf.U, s.task.Client.Cnf.P); err != nil {
// Authenticate before establishing CONNECT tunnel (fixes auth-after-200 bug).
if err := s.proxyAuth(r, c, s.task.Client.Cnf.U, s.task.Client.Cnf.P); err != nil {
logs.Warn("http proxy auth failed, client %d, remote %s: %v", s.task.Client.Id, c.Conn.RemoteAddr(), err)
return err
}
if r.Method == "CONNECT" {
if _, err := c.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n")); err != nil {
c.Close()
return err
}
rb = nil
}
logs.Info("http proxy request, method %s, host %s, client %d, remote %s", r.Method, addr, s.task.Client.Id, c.Conn.RemoteAddr())
return s.DealClient(c, s.task.Client, addr, rb, common.CONN_TCP, nil, s.task.Client.Flow, s.task.Target.LocalProxy, nil, nil)
}
+205
View File
@@ -1,11 +1,15 @@
package proxy
import (
"bufio"
"bytes"
"encoding/base64"
"io"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
@@ -92,3 +96,204 @@ func TestProcessTunnelForwardsBufferedBytesWhenAuthProbeFails(t *testing.T) {
t.Fatal("ProcessTunnel did not exit after connections closed")
}
}
func setupProxyTestConf(t *testing.T) {
t.Helper()
confPath := t.TempDir()
confDir := filepath.Join(confPath, "conf")
if err := os.MkdirAll(confDir, 0755); err != nil {
t.Fatal(err)
}
for _, name := range []string{"clients.json", "tasks.json", "hosts.json"} {
if err := os.WriteFile(filepath.Join(confDir, name), nil, 0644); err != nil {
t.Fatal(err)
}
}
oldConfPath := common.ConfPath
common.ConfPath = confPath
t.Cleanup(func() {
common.ConfPath = oldConfPath
})
}
func newHTTPProxyServer(t *testing.T, u, p string, target net.Conn) *TunnelModeServer {
t.Helper()
client := file.NewClient("test", true, true)
client.Id = 1
client.Cnf.U = u
client.Cnf.P = p
task := &file.Tunnel{
Id: 1,
Client: client,
Mode: "httpProxy",
Target: &file.Target{TargetStr: "127.0.0.1:80"},
}
return NewTunnelModeServer(ProcessHttp, &tunnelTestBridge{target: target}, task)
}
func TestProcessHttpConnectAuthBeforeTunnel(t *testing.T) {
setupProxyTestConf(t)
clientConn, serverConn := net.Pipe()
defer clientConn.Close()
defer serverConn.Close()
// target unused: auth must fail before DealClient
targetClient, targetServer := net.Pipe()
defer targetClient.Close()
defer targetServer.Close()
server := newHTTPProxyServer(t, "user", "pass", targetServer)
done := make(chan error, 1)
go func() {
done <- ProcessHttp(conn.NewConn(serverConn), server)
}()
// CONNECT without credentials
req := "CONNECT example.com:443 HTTP/1.1\r\nHost: example.com:443\r\n\r\n"
if _, err := clientConn.Write([]byte(req)); err != nil {
t.Fatal(err)
}
_ = clientConn.SetReadDeadline(time.Now().Add(time.Second))
br := bufio.NewReader(clientConn)
resp, err := http.ReadResponse(br, nil)
if err != nil {
t.Fatalf("read response: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusProxyAuthRequired {
t.Fatalf("expected 407 before CONNECT tunnel, got %d", resp.StatusCode)
}
if got := resp.Header.Get("Proxy-Authenticate"); !strings.Contains(got, "Basic") {
t.Fatalf("expected Proxy-Authenticate Basic challenge, got %q", got)
}
select {
case err := <-done:
if err == nil {
t.Fatal("expected auth error")
}
case <-time.After(time.Second):
t.Fatal("ProcessHttp did not exit after auth failure")
}
}
func TestProcessHttpConnectWithProxyAuth(t *testing.T) {
setupProxyTestConf(t)
clientConn, serverConn := net.Pipe()
defer clientConn.Close()
defer serverConn.Close()
targetClient, targetServer := net.Pipe()
defer targetClient.Close()
defer targetServer.Close()
server := newHTTPProxyServer(t, "user", "pass", targetServer)
done := make(chan error, 1)
go func() {
done <- ProcessHttp(conn.NewConn(serverConn), server)
}()
token := base64.StdEncoding.EncodeToString([]byte("user:pass"))
req := "CONNECT example.com:443 HTTP/1.1\r\n" +
"Host: example.com:443\r\n" +
"Proxy-Authorization: Basic " + token + "\r\n\r\n"
if _, err := clientConn.Write([]byte(req)); err != nil {
t.Fatal(err)
}
_ = clientConn.SetReadDeadline(time.Now().Add(time.Second))
br := bufio.NewReader(clientConn)
// First line of CONNECT success is not always a full http.Response parse-friendly body;
// read status line.
statusLine, err := br.ReadString('\n')
if err != nil {
t.Fatalf("read status: %v", err)
}
if !strings.Contains(statusLine, "200") {
t.Fatalf("expected 200 Connection established after auth, got %q", statusLine)
}
// consume remaining headers
for {
line, err := br.ReadString('\n')
if err != nil {
t.Fatal(err)
}
if line == "\r\n" || line == "\n" {
break
}
}
// After tunnel is up, write application data and ensure it reaches target.
payload := []byte("hello-tls")
if _, err := clientConn.Write(payload); err != nil {
t.Fatal(err)
}
_ = targetClient.SetReadDeadline(time.Now().Add(time.Second))
got := make([]byte, len(payload))
if _, err := io.ReadFull(targetClient, got); err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, payload) {
t.Fatalf("expected %q, got %q", payload, got)
}
clientConn.Close()
targetClient.Close()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("ProcessHttp did not exit")
}
}
func TestProcessHttpPlainGetWithProxyAuth(t *testing.T) {
setupProxyTestConf(t)
clientConn, serverConn := net.Pipe()
defer clientConn.Close()
defer serverConn.Close()
targetClient, targetServer := net.Pipe()
defer targetClient.Close()
defer targetServer.Close()
server := newHTTPProxyServer(t, "user", "pass", targetServer)
done := make(chan error, 1)
go func() {
done <- ProcessHttp(conn.NewConn(serverConn), server)
}()
token := base64.StdEncoding.EncodeToString([]byte("user:pass"))
req := "GET http://example.com/ HTTP/1.1\r\n" +
"Host: example.com\r\n" +
"Proxy-Authorization: Basic " + token + "\r\n\r\n"
if _, err := clientConn.Write([]byte(req)); err != nil {
t.Fatal(err)
}
// Absolute-form request is forwarded (buffered) to the tunnel target.
_ = targetClient.SetReadDeadline(time.Now().Add(time.Second))
buf := make([]byte, 512)
n, err := targetClient.Read(buf)
if err != nil {
t.Fatal(err)
}
if !bytes.Contains(buf[:n], []byte("GET ")) {
t.Fatalf("expected forwarded GET, got %q", buf[:n])
}
clientConn.Close()
targetClient.Close()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("ProcessHttp did not exit")
}
}
+53 -66
View File
@@ -5,7 +5,6 @@ import (
"errors"
"math"
"os"
"sort"
"strconv"
"strings"
"sync"
@@ -260,13 +259,15 @@ func AddTask(t *file.Tunnel) error {
// start task
func StartTask(id int) error {
if t, err := file.GetDb().GetTask(id); err != nil {
t, err := file.GetDb().GetTask(id)
if err != nil {
return err
} else {
AddTask(t)
t.Status = true
file.GetDb().UpdateTask(t)
}
if err := AddTask(t); err != nil {
return err
}
t.Status = true
file.GetDb().UpdateTask(t)
return nil
}
@@ -283,84 +284,70 @@ func DelTask(id int) error {
// get task list by page num
func GetTunnel(start, length int, typeVal string, clientId int, search string, sortField string, order string) ([]*file.Tunnel, int) {
all_list := make([]*file.Tunnel, 0) //store all Tunnel
list := make([]*file.Tunnel, 0)
var cnt int
all_list := make([]*file.Tunnel, 0)
// 单次遍历收集所有符合条件的 Tunnel(修复原代码双重遍历 sync.Map 的性能问题)
// collect + fill runtime fields before sort/paginate
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
v := value.(*file.Tunnel)
if (typeVal != "" && v.Mode != typeVal || (clientId != 0 && v.Client.Id != clientId)) || (typeVal == "" && clientId != v.Client.Id) {
return true
}
if search != "" {
targetStr := ""
if v.Target != nil {
targetStr = v.Target.TargetStr
}
if !(v.Id == common.GetIntNoErrByStr(search) || v.Port == common.GetIntNoErrByStr(search) || strings.Contains(v.Password, search) || strings.Contains(v.Remark, search) || strings.Contains(targetStr, search)) {
return true
}
}
if v.Client != nil {
if _, ok := Bridge.Client.Load(v.Client.Id); ok {
v.Client.IsConnect = true
} else {
v.Client.IsConnect = false
}
}
if _, ok := RunList.Load(v.Id); ok {
v.RunStatus = true
} else {
v.RunStatus = false
}
all_list = append(all_list, v)
return true
})
//sort by Id, Remark, TargetStr, Port, asc or desc
if sortField == "Id" {
if order == "asc" {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Id < all_list[j].Id })
} else {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Id > all_list[j].Id })
}
} else if sortField == "ClientId" {
if order == "asc" {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Client.Id < all_list[j].Client.Id })
} else {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Client.Id > all_list[j].Client.Id })
}
} else if sortField == "Remark" {
if order == "asc" {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Remark < all_list[j].Remark })
} else {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Remark > all_list[j].Remark })
}
} else if sortField == "Client.VerifyKey" {
if order == "asc" {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Client.VerifyKey < all_list[j].Client.VerifyKey })
} else {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Client.VerifyKey > all_list[j].Client.VerifyKey })
}
} else if sortField == "Target" {
if order == "asc" {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Target.TargetStr < all_list[j].Target.TargetStr })
} else {
sort.SliceStable(all_list, func(i, j int) bool { return all_list[i].Target.TargetStr > all_list[j].Target.TargetStr })
}
}
//search and paginate(直接在已排序的列表上操作,避免二次 Load)
for _, v := range all_list {
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || v.Port == common.GetIntNoErrByStr(search) || strings.Contains(v.Password, search) || strings.Contains(v.Remark, search) || strings.Contains(v.Target.TargetStr, search)) {
continue
}
cnt++
if _, ok := Bridge.Client.Load(v.Client.Id); ok {
v.Client.IsConnect = true
} else {
v.Client.IsConnect = false
}
if start--; start < 0 {
if length--; length >= 0 {
if _, ok := RunList.Load(v.Id); ok {
v.RunStatus = true
} else {
v.RunStatus = false
}
list = append(list, v)
}
}
file.SortTunnels(all_list, sortField, order)
cnt := len(all_list)
if start < 0 {
start = 0
}
return list, cnt
if length <= 0 || start >= cnt {
return []*file.Tunnel{}, cnt
}
end := start + length
if end > cnt {
end = cnt
}
return all_list[start:end], cnt
}
// get client list
func GetClientList(start, length int, search, sort, order string, clientId int) (list []*file.Client, cnt int) {
list, cnt = file.GetDb().GetClientList(start, length, search, sort, order, clientId)
func GetClientList(start, length int, search, sortField, order string, clientId int) (list []*file.Client, cnt int) {
// fill IsConnect / Version before sort so IsConnect ordering is correct
dealClientData()
list, cnt = file.GetDb().GetClientList(start, length, search, sortField, order, clientId)
return
}
// GetHostList returns hosts with client online status filled before sort/pagination.
func GetHostList(start, length int, clientId int, search, sortField, order string) ([]*file.Host, int) {
// ensure Client.IsConnect is current for sort and display
dealClientData()
return file.GetDb().GetHost(start, length, clientId, search, sortField, order)
}
func dealClientData() {
file.GetDb().JsonDb.Clients.Range(func(key, value interface{}) bool {
+14
View File
@@ -56,6 +56,20 @@ func TestServerPort(p int, m string) (b bool) {
}
func GenerateServerPort(m string) int {
// allow_ports 已配置:在允许范围内随机选取,打乱顺序后逐个尝试以避免重复命中已占用端口
if len(ports) != 0 {
shuffled := make([]int, len(ports))
copy(shuffled, ports)
rand.Shuffle(len(shuffled), func(i, j int) {
shuffled[i], shuffled[j] = shuffled[j], shuffled[i]
})
for _, p := range shuffled {
if TestServerPort(p, m) {
return p
}
}
return 0
}
for i := 0; i < 1000; i++ {
//生成随机数 1024 - 65535
serverPort := rand.Intn(65535)
+2
View File
@@ -109,8 +109,10 @@ func (s *BaseController) display(tpl ...string) {
if bridge.ServerTlsEnable {
tlsPort := strconv.Itoa(beego.AppConfig.DefaultInt("tls_bridge_port", 8025))
s.Data["tls_p"] = tlsPort
s.Data["tls_enable"] = true
s.Data["p1"] = strconv.Itoa(server.Bridge.TunnelPort) + " / " + tlsPort
} else {
s.Data["tls_enable"] = false
s.Data["p1"] = strconv.Itoa(server.Bridge.TunnelPort)
}
+6
View File
@@ -134,6 +134,12 @@ func (s *ClientController) Edit() {
c.MaxConn = s.GetIntNoErr("max_conn")
c.MaxTunnelNum = s.GetIntNoErr("max_tunnel")
}
if s.GetString("flow_inlet") != "" {
c.Flow.InletFlow = int64(s.GetIntNoErr("flow_inlet"))
}
if s.GetString("flow_export") != "" {
c.Flow.ExportFlow = int64(s.GetIntNoErr("flow_export"))
}
c.Remark = s.getEscapeString("remark")
c.Cnf.U = s.getEscapeString("u")
c.Cnf.P = s.getEscapeString("p")
+14 -2
View File
@@ -218,7 +218,7 @@ func (s *IndexController) Edit() {
t.Port = tool.GenerateServerPort(t.Mode)
}
if !tool.TestServerPort(s.GetIntNoErr("port"), t.Mode) {
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.")
return
}
@@ -233,6 +233,12 @@ func (s *IndexController) Edit() {
t.StripPre = s.getEscapeString("strip_pre")
t.Remark = s.getEscapeString("remark")
t.Target.LocalProxy = s.GetBoolNoErr("local_proxy")
if s.GetString("flow_inlet") != "" {
t.Flow.InletFlow = int64(s.GetIntNoErr("flow_inlet"))
}
if s.GetString("flow_export") != "" {
t.Flow.ExportFlow = int64(s.GetIntNoErr("flow_export"))
}
file.GetDb().UpdateTask(t)
server.StopServer(t.Id)
server.StartTask(t.Id)
@@ -274,7 +280,7 @@ func (s *IndexController) HostList() {
} else {
start, length := s.GetAjaxParams()
clientId := s.GetIntNoErr("client_id")
list, cnt := file.GetDb().GetHost(start, length, clientId, s.getEscapeString("search"))
list, cnt := server.GetHostList(start, length, clientId, s.getEscapeString("search"), s.getEscapeString("sort"), s.getEscapeString("order"))
s.AjaxTable(list, cnt, cnt, nil)
}
}
@@ -409,6 +415,12 @@ func (s *IndexController) EditHost() {
h.AutoHttps = false
}
if s.GetString("flow_inlet") != "" {
h.Flow.InletFlow = int64(s.GetIntNoErr("flow_inlet"))
}
if s.GetString("flow_export") != "" {
h.Flow.ExportFlow = int64(s.GetIntNoErr("flow_export"))
}
file.GetDb().JsonDb.StoreHostToJsonFile()
}
s.AjaxOk("modified success")
+3
View File
@@ -10,6 +10,7 @@ import (
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/file"
"ehang.io/nps/lib/version"
"ehang.io/nps/server"
"github.com/astaxie/beego"
)
@@ -41,6 +42,7 @@ func (self *LoginController) Index() {
self.Data["web_base_url"] = webBaseUrl
self.Data["register_allow"], _ = beego.AppConfig.Bool("allow_user_register")
self.Data["captcha_open"], _ = beego.AppConfig.Bool("open_captcha")
self.Data["version"] = version.VERSION
self.TplName = "login/index.html"
}
@@ -125,6 +127,7 @@ func (self *LoginController) doLogin(username, password string, explicit bool) b
func (self *LoginController) Register() {
if self.Ctx.Request.Method == "GET" {
self.Data["web_base_url"] = beego.AppConfig.String("web_base_url")
self.Data["version"] = version.VERSION
self.TplName = "login/register.html"
} else {
if b, err := beego.AppConfig.Bool("allow_user_register"); err != nil || !b {
+67 -34
View File
@@ -3,11 +3,11 @@ package web
import (
"embed"
"io/fs"
"os"
"path/filepath"
"net/http"
"path"
"strings"
"ehang.io/nps/lib/common"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego"
)
//go:embed static
@@ -16,37 +16,70 @@ var StaticFS embed.FS
//go:embed views
var ViewsFS embed.FS
func ExtractWebFiles(runPath string) {
webDir := filepath.Join(runPath, "web")
staticDir := filepath.Join(webDir, "static")
viewsDir := filepath.Join(webDir, "views")
if !common.FileExists(staticDir) {
extractFS(StaticFS, "static", webDir)
logs.Info("Extracted embedded web/static to", staticDir)
}
if !common.FileExists(viewsDir) {
extractFS(ViewsFS, "views", webDir)
logs.Info("Extracted embedded web/views to", viewsDir)
}
// slashFileSystem normalizes path separators so embed.FS works on Windows
// (beego uses filepath.Join which produces backslashes).
type slashFileSystem struct {
fs http.FileSystem
}
func extractFS(efs embed.FS, root string, destDir string) {
fs.WalkDir(efs, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
targetPath := filepath.Join(destDir, path)
if d.IsDir() {
os.MkdirAll(targetPath, 0755)
return nil
}
data, err := efs.ReadFile(path)
if err != nil {
return err
}
os.MkdirAll(filepath.Dir(targetPath), 0755)
os.WriteFile(targetPath, data, 0644)
return nil
func (s slashFileSystem) Open(name string) (http.File, error) {
name = strings.ReplaceAll(name, "\\", "/")
name = path.Clean("/" + strings.TrimPrefix(name, "/"))
if name == "/" {
name = "."
} else {
name = strings.TrimPrefix(name, "/")
}
return s.fs.Open(name)
}
// ViewsHTTPFS returns an http.FileSystem for embedded view templates.
// Paths are rooted at "views/..." to match beego SetViewsPath("views").
func ViewsHTTPFS() http.FileSystem {
return slashFileSystem{fs: http.FS(ViewsFS)}
}
// StaticHTTPFS returns an http.FileSystem rooted at the embedded static/ directory
// (so Open("css/style.css") maps to static/css/style.css).
func StaticHTTPFS() http.FileSystem {
sub, err := fs.Sub(StaticFS, "static")
if err != nil {
panic("web: embed static sub FS: " + err.Error())
}
return slashFileSystem{fs: http.FS(sub)}
}
// ReadStaticFile reads a file from the embedded static FS.
// name is relative to static/, e.g. "page/error.html".
func ReadStaticFile(name string) ([]byte, error) {
name = strings.ReplaceAll(name, "\\", "/")
name = path.Clean("/" + strings.TrimPrefix(name, "/"))
name = strings.TrimPrefix(name, "/")
return StaticFS.ReadFile(path.Join("static", name))
}
// InitBeegoAssets configures Beego to serve views and static files exclusively
// from the embedded filesystem. Disk web/ directories are never used.
func InitBeegoAssets() {
beego.SetTemplateFSFunc(func() http.FileSystem {
return ViewsHTTPFS()
})
beego.SetViewsPath("views")
// Drop default (and any prior) disk-based static mappings.
beego.DelStaticPath("/static")
base := strings.TrimSuffix(beego.AppConfig.String("web_base_url"), "/")
staticPrefix := base + "/static"
if !strings.HasPrefix(staticPrefix, "/") {
staticPrefix = "/" + staticPrefix
}
staticPrefix = path.Clean(staticPrefix)
if base != "" {
// Also clear a bare /static mapping when web_base_url is set.
beego.DelStaticPath(staticPrefix)
}
fileServer := http.StripPrefix(staticPrefix, http.FileServer(StaticHTTPFS()))
// options[0]=true registers as prefix match: staticPrefix/?:all(.*)
beego.Handler(staticPrefix, fileServer, true)
}
+1 -1
View File
@@ -59,7 +59,7 @@
$.fn.cloudLang = function () {
$.ajax({
type: 'GET',
url: window.nps.web_base_url + '/static/page/languages.xml?v=202512051',
url: window.nps.web_base_url + '/static/page/languages.xml?v=' + window.nps.version,
dataType: 'xml',
success: function (xml) {
languages['content'] = xml2json($(xml).children())['content'];
+22 -2
View File
@@ -122,8 +122,12 @@
</lang>
<lang id="word-address">
<zh-CN>客户端地址</zh-CN>
<en-US>Client address</en-US>
<zh-CN>客户端出口地址</zh-CN>
<en-US>Client egress address</en-US>
</lang>
<lang id="word-localaddr">
<zh-CN>内网地址</zh-CN>
<en-US>LAN address</en-US>
</lang>
<lang id="word-add">
<zh-CN>新增</zh-CN>
@@ -189,6 +193,22 @@
<zh-CN>访问端命令</zh-CN>
<en-US>Access command</en-US>
</lang>
<lang id="word-commandaccess-tls">
<zh-CN>访问端命令 (TLS)</zh-CN>
<en-US>Access command (TLS)</en-US>
</lang>
<lang id="word-commandaccessp2p-tls">
<zh-CN>访问端命令 (TCP / TLS)</zh-CN>
<en-US>Access command (TCP / TLS)</en-US>
</lang>
<lang id="word-commandaccessp2ps-tls">
<zh-CN>访问端命令 (SOCKS 5 / TLS)</zh-CN>
<en-US>Access command (SOCKS 5 / TLS)</en-US>
</lang>
<lang id="word-commandaccessp2pt-tls">
<zh-CN>访问端命令 (透明代理 / TLS)</zh-CN>
<en-US>Access command (Transparent proxy / TLS)</en-US>
</lang>
<lang id="word-protoversion">
<zh-CN>Proxy Protocol Version</zh-CN>
<en-US>Proxy Protocol Version</en-US>
+25 -1
View File
@@ -46,6 +46,15 @@
method: 'post', // 服务器数据的请求方式 get or post
url: "{{.web_base_url}}/client/list", // 服务器数据的加载地址
contentType: "application/x-www-form-urlencoded",
queryParams: function (params) {
return {
"offset": params.offset,
"limit": params.limit,
"search": params.search,
"sort": params.sort,
"order": params.order
}
},
striped: true, // 设置为true会有隔行变色效果
search: true,
showHeader: true,
@@ -93,24 +102,28 @@
field: 'Id',//域值
title: '<span langtag="word-id"></span>',//标题
halign: 'center',
sortable: true,
visible: true//false表示不显示
},
{
field: 'Remark',//域值
title: '<span langtag="word-remark"></span>',//标题
halign: 'center',
sortable: true,
visible: true//false表示不显示
},
{
field: 'Version',//域值
title: '<span langtag="word-version"></span>',//标题
halign: 'center',
sortable: true,
visible: true//false表示不显示
},
{
field: 'VerifyKey',//域值
title: '<span langtag="word-verifykey"></span>',//标题
halign: 'center',
sortable: true,
visible: true,//false表示不显示
formatter: function (value, row, index) {
if (!row.NoStore) {
@@ -124,6 +137,14 @@
field: 'Addr',//域值
title: '<span langtag="word-address"></span>',//标题
halign: 'center',
sortable: true,
visible: true//false表示不显示
},
{
field: 'LocalAddr',//域值
title: '<span langtag="word-localaddr"></span>',//标题
halign: 'center',
sortable: true,
visible: true//false表示不显示
},
{
@@ -147,10 +168,11 @@
}
},
{
field: 'IsConnect',//域值
field: 'NowRate',//域值
title: '<span langtag="word-speed"></span>',//内容
halign: 'center',
visible: true,//false表示不显示
sortable: true,
formatter: function (value, row, index) {
return changeunit(row.Rate.NowRate) + "/S"
}
@@ -161,6 +183,7 @@
align: 'center',
halign: 'center',
visible: true,//false表示不显示
sortable: true,
formatter: function (value, row, index) {
if (value) {
return '<span class="badge badge-primary" langtag="word-open"></span>'
@@ -175,6 +198,7 @@
align: 'center',
halign: 'center',
visible: true,//false表示不显示
sortable: true,
formatter: function (value, row, index) {
if (value) {
return '<span class="badge badge-primary" langtag="word-online"></span>'
+16 -3
View File
@@ -47,7 +47,10 @@
return {
"offset": params.offset,
"limit": params.limit,
"search": params.search
"search": params.search,
"sort": params.sort,
"order": params.order,
"client_id": {{if .client_id}}{{.client_id}}{{else}}0{{end}}
}
},
search: true,
@@ -87,12 +90,14 @@
field: 'Id',//域值
title: '<span langtag="word-id"></span>',//标题
halign: 'center',
sortable: true,
visible: true//false表示不显示
},
{
field: 'Id',//域值
field: 'ClientId',//域值
title: '<span langtag="word-clientid"></span>',//标题
halign: 'center',
sortable: true,
visible: true,//false表示不显示
formatter: function (value, row, index) {
return row.Client.Id + '-' + row.Client.Remark
@@ -102,18 +107,21 @@
field: 'Remark',//域值
title: '<span langtag="word-remark"></span>',//标题
halign: 'center',
sortable: true,
visible: true//false表示不显示
},
{
field: 'Client.VerifyKey',//域值
title: '<span langtag="word-verifykey"></span>',//标题
halign: 'center',
sortable: true,
visible: true//false表示不显示
},
{
field: 'Host',//域值
title: '<span langtag="word-host"></span>',//标题
halign: 'center',
sortable: true,
visible: true,//false表示不显示
formatter: function (value, row, index) {
return "<a href='http://" + row.Host + '{{.http_proxy_port}}' + "' target='_blank'>" + row.Host + '{{.http_proxy_port}}' + "</a>"
@@ -123,6 +131,7 @@
field: 'Scheme',//域值
title: '<span langtag="word-scheme"></span>',//标题
halign: 'center',
sortable: true,
visible: true,//false表示不显示
formatter: function (value, row, index) {
return '<span langtag="word-' +value+ '"></span>'
@@ -132,6 +141,7 @@
field: 'Target',//域值
title: '<span langtag="word-target"></span>',//标题
halign: 'center',
sortable: true,
visible: true,//false表示不显示
formatter: function (value, row, index) {
return row.Target.TargetStr
@@ -141,6 +151,7 @@
field: 'Location',//域值
title: '<span langtag="word-location"></span>',//标题
halign: 'center',
sortable: true,
visible: true//false表示不显示
},
{
@@ -148,6 +159,7 @@
title: '<span langtag="word-status"></span>',//内容
align: 'center',
halign: 'center',
sortable: true,
visible: true,//false表示不显示
formatter: function (value, row, index) {
if (!value) {
@@ -158,10 +170,11 @@
}
},
{
field: '',//域值
field: 'IsConnect',//域值
title: '<span langtag="word-clientstatus"></span>',//内容
align: 'center',
halign: 'center',
sortable: true,
visible: true,//false表示不显示
formatter: function (value, row, index) {
hosturl = ((row.Scheme == 'http' ) ? 'http://' : 'https://') + row.Host + row.Location
+43 -9
View File
@@ -79,19 +79,34 @@
+ '<b langtag="word-basicusername"></b>: ' + row.Client.Cnf.U + '&emsp;'
+ '<b langtag="word-basicpassword"></b>: ' + row.Client.Cnf.P + '&emsp;'
+ '<b langtag="word-protoversion"></b>: ' + row.ProtoVersion + '&emsp;'
var copyBtn = '<button class="copy btn btn-info btn-xs" onclick="copyCommand(this)" data-clipboard-text="">复制</button>'
if (row.Mode == "p2p") {
return tmp + "<br/><br>"
var p2pCmd = tmp + "<br/><br>"
+ '<b langtag="word-commandaccessp2p"></b>: ' + "<code>{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.Client.VerifyKey
+ " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -target=" + row.Target.TargetStr + "</code>" + "<br/><br>"
+ " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -target=" + row.Target.TargetStr + "</code>" + copyBtn + "<br/><br>"
+ '<b langtag="word-commandaccessp2ps"></b>: ' + "<code>{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.Client.VerifyKey
+ " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -local_type=p2ps" + "</code>" + "<br/><br>"
+ " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -local_type=p2ps" + "</code>" + copyBtn + "<br/><br>"
+ '<b langtag="word-commandaccessp2pt"></b>: ' + "<code>{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.Client.VerifyKey
+ " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -local_type=p2pt" + "</code>"
+ " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -local_type=p2pt" + "</code>" + copyBtn
{{if .tls_enable}}
p2pCmd += "<br/><br>"
+ '<b langtag="word-commandaccessp2p-tls"></b>: ' + "<code>{{.win}} -server={{.ip}}:{{.tls_p}} -vkey=" + row.Client.VerifyKey
+ " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -target=" + row.Target.TargetStr + " -tls_enable=true</code>" + copyBtn + "<br/><br>"
+ '<b langtag="word-commandaccessp2ps-tls"></b>: ' + "<code>{{.win}} -server={{.ip}}:{{.tls_p}} -vkey=" + row.Client.VerifyKey
+ " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -local_type=p2ps -tls_enable=true</code>" + copyBtn + "<br/><br>"
+ '<b langtag="word-commandaccessp2pt-tls"></b>: ' + "<code>{{.win}} -server={{.ip}}:{{.tls_p}} -vkey=" + row.Client.VerifyKey
+ " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -local_type=p2pt -tls_enable=true</code>" + copyBtn
{{end}}
return p2pCmd
}
if (row.Mode == "secret") {
return tmp + "<br/><br>" + '<b langtag="word-commandaccess"></b>: ' + "<code>{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.Client.VerifyKey
+ " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -local_type=secret" + "</code>"
var secretCmd = tmp + "<br/><br>" + '<b langtag="word-commandaccess"></b>: ' + "<code>{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.Client.VerifyKey
+ " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -local_type=secret" + "</code>" + copyBtn
{{if .tls_enable}}
secretCmd += "<br/><br>" + '<b langtag="word-commandaccess-tls"></b>: ' + "<code>{{.win}} -server={{.ip}}:{{.tls_p}} -vkey=" + row.Client.VerifyKey
+ " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -local_type=secret -tls_enable=true</code>" + copyBtn
{{end}}
return secretCmd
}
return tmp
},
@@ -123,6 +138,7 @@
field: 'Remark',//域值
title: '<span langtag="word-remark"></span>',//标题
halign: 'center',
sortable: true,
visible: true//false表示不显示
},
{
@@ -136,6 +152,7 @@
field: 'Mode',//域值
title: '<span langtag="word-scheme"></span>',//标题
halign: 'center',
sortable: true,
visible: true,//false表示不显示
formatter: function (value, row, index) {
return '<span langtag="scheme-' + value + '"></span>'
@@ -152,7 +169,7 @@
field: 'address',//域值
title: '<span langtag="word-accessaddress"></span>',//标题
halign: 'center',
sortable: false, //启用排序
sortable: false, //计算列,按 Port 排序即可
visible: true,//false表示不显示
formatter: function (value, row, index) {
var address = {{.ip}} + ":" + row.Port
@@ -173,6 +190,7 @@
field: 'Password',//域值
title: '<span langtag="word-identificationkey"></span>',//标题
halign: 'center',
sortable: true,
visible: true//false表示不显示
},
{
@@ -181,6 +199,7 @@
align: 'center',
halign: 'center',
visible: true,//false表示不显示
sortable: true,
formatter: function (value, row, index) {
if (value) {
return '<span class="badge badge-primary" langtag="word-open"></span>'
@@ -195,6 +214,7 @@
align: 'center',
halign: 'center',
visible: true,//false表示不显示
sortable: true,
formatter: function (value, row, index) {
if (value) {
return '<span class="badge badge-primary" langtag="word-open"></span>'
@@ -204,11 +224,12 @@
}
},
{
field: '',//域值
field: 'IsConnect',//域值
title: '<span langtag="word-clientstatus"></span>',//内容
align: 'center',
halign: 'center',
visible: true,//false表示不显示
sortable: true,
formatter: function (value, row, index) {
if (row.Client.IsConnect) {
return '<span class="badge badge-primary" langtag="word-online"></span>'
@@ -246,4 +267,17 @@
}
]
});
function copyCommand(data) {
data.setAttribute("data-clipboard-text", data.previousElementSibling.innerHTML)
}
var clipboard = new ClipboardJS('.copy');
clipboard.on('success', function (e) {
toastr.success('复制成功');
e.clearSelection();
});
clipboard.on('error', function (e) {
toastr.error('复制失败', '提示');
});
</script>
+1 -1
View File
@@ -97,7 +97,7 @@
<script type="text/javascript">
window.nps = {"web_base_url": {{.web_base_url}} }
window.nps = {"web_base_url": {{.web_base_url}}, "version": "{{.version}}" }
// Login Page Flipbox control
function login() {
+1 -1
View File
@@ -59,7 +59,7 @@
<div><strong langtag="word-copyright"></strong> <span langtag="application"></span> &copy; 2018-2019</div>
</div>
<script>
window.nps = { "web_base_url": {{.web_base_url}} }
window.nps = { "web_base_url": {{.web_base_url}}, "version": "{{.version}}" }
function register() {
$.ajax({
type: "POST",
+1 -1
View File
@@ -155,7 +155,7 @@
</html>
<script>
window.nps = { "web_base_url": {{.web_base_url}} }
window.nps = { "web_base_url": {{.web_base_url}}, "version": "{{.version}}" }
/* googleTranslateElementInit()
function googleTranslateElementInit() {