Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b7a1a249a4 | |||
| 5cee8daabc | |||
|
|
a9ca714b24 | ||
|
|
d6627a292d | ||
| e0d88e9ad7 | |||
|
|
ba9edd3c02 | ||
|
|
e40d079f7a | ||
|
|
8ce5b149f7 | ||
|
|
0a41e10793 | ||
|
|
3386b0fcb6 | ||
|
|
98a5525e6d | ||
|
|
5c8020d5fb |
@@ -84,6 +84,7 @@ func main() {
|
||||
registry := plugin.NewRegistry()
|
||||
server.SetPluginRegistry(registry)
|
||||
server.SetJSPluginStore(clientStore) // 设置 JS 插件存储,用于客户端重连时恢复插件
|
||||
server.SetTrafficStore(clientStore) // 设置流量存储,用于记录流量统计
|
||||
|
||||
// 启动 Web 控制台
|
||||
if cfg.Server.Web.Enabled {
|
||||
|
||||
7
go.mod
7
go.mod
@@ -27,6 +27,7 @@ require (
|
||||
github.com/dlclark/regexp2 v1.11.4 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||
github.com/gen2brain/shm v0.1.0 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/go-ole/go-ole v1.2.6 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.22.4 // indirect
|
||||
@@ -44,12 +45,16 @@ require (
|
||||
github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/goccy/go-yaml v1.19.1 // indirect
|
||||
github.com/godbus/dbus/v5 v5.1.0 // indirect
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e // indirect
|
||||
github.com/jezek/xgb v1.1.1 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/kbinani/screenshot v0.0.0-20250624051815-089614a94018 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
|
||||
github.com/lxn/win v0.0.0-20210218163916-a377121e959e // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
@@ -59,7 +64,7 @@ require (
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/quic-go/quic-go v0.58.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/shoenig/go-m1cpu v0.1.6 // indirect
|
||||
github.com/shoenig/go-m1cpu v0.1.7 // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.12 // indirect
|
||||
github.com/tklauser/numcpus v0.6.1 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
|
||||
19
go.sum
19
go.sum
@@ -22,6 +22,8 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/gen2brain/shm v0.1.0 h1:MwPeg+zJQXN0RM9o+HqaSFypNoNEcNpeoGp0BTSx2YY=
|
||||
github.com/gen2brain/shm v0.1.0/go.mod h1:UgIcVtvmOu+aCJpqJX7GOtiN7X2ct+TKLg4RTxwPIUA=
|
||||
github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4=
|
||||
github.com/gin-contrib/gzip v0.0.6/go.mod h1:QOJlmV2xmayAjkNS2Y8NQsMneuRShOU/kjovCXNuzzk=
|
||||
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||
@@ -71,6 +73,8 @@ github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/goccy/go-yaml v1.19.1 h1:3rG3+v8pkhRqoQ/88NYNMHYVGYztCOCIZ7UQhu7H+NE=
|
||||
github.com/goccy/go-yaml v1.19.1/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
|
||||
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
@@ -85,8 +89,12 @@ github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aN
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE=
|
||||
github.com/hashicorp/yamux v0.1.1/go.mod h1:CtWFDAQgb7dxtzFs4tWbplKIe2jSi3+5vKbgIO0SLnQ=
|
||||
github.com/jezek/xgb v1.1.1 h1:bE/r8ZZtSv7l9gk6nU0mYx51aXrvnyb44892TwSaqS4=
|
||||
github.com/jezek/xgb v1.1.1/go.mod h1:nrhwO0FX/enq75I7Y7G8iN1ubpSGZEiA3v9e9GyRFlk=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/kbinani/screenshot v0.0.0-20250624051815-089614a94018 h1:NQYgMY188uWrS+E/7xMVpydsI48PMHcc7SfR4OxkDF4=
|
||||
github.com/kbinani/screenshot v0.0.0-20250624051815-089614a94018/go.mod h1:Pmpz2BLf55auQZ67u3rvyI2vAQvNetkK/4zYUmpauZQ=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
@@ -97,6 +105,8 @@ github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4=
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=
|
||||
github.com/lxn/win v0.0.0-20210218163916-a377121e959e h1:H+t6A/QJMbhCSEH5rAuRxh+CtW96g0Or0Fxa9IKr4uc=
|
||||
github.com/lxn/win v0.0.0-20210218163916-a377121e959e/go.mod h1:KxxjdtRkfNoYDCUP5ryK7XJJNTnpC8atvtmTheChOtk=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
@@ -122,10 +132,10 @@ github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjR
|
||||
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
|
||||
github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/iZ9pI=
|
||||
github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk=
|
||||
github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM=
|
||||
github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ=
|
||||
github.com/shoenig/test v0.6.4 h1:kVTaSd7WLz5WZ2IaoM0RSzRsUD+m8wRR+5qvntpn4LU=
|
||||
github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k=
|
||||
github.com/shoenig/go-m1cpu v0.1.7 h1:C76Yd0ObKR82W4vhfjZiCp0HxcSZ8Nqd84v+HZ0qyI0=
|
||||
github.com/shoenig/go-m1cpu v0.1.7/go.mod h1:KkDOw6m3ZJQAPHbrzkZki4hnx+pDRR1Lo+ldA56wD5w=
|
||||
github.com/shoenig/test v1.7.0 h1:eWcHtTXa6QLnBvm0jgEabMRN/uJ4DMV3M8xUGgRkZmk=
|
||||
github.com/shoenig/test v1.7.0/go.mod h1:UxJ6u/x2v/TNs/LoLxBNJRV9DiwBBKYxXSyczsBHFoI=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
@@ -181,6 +191,7 @@ golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201018230417-eeed37f84f13/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package tunnel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
@@ -32,7 +34,6 @@ const (
|
||||
reconnectDelay = 5 * time.Second
|
||||
disconnectDelay = 3 * time.Second
|
||||
udpBufferSize = 65535
|
||||
idFileName = "id"
|
||||
)
|
||||
|
||||
// Client 隧道客户端
|
||||
@@ -40,6 +41,7 @@ type Client struct {
|
||||
ServerAddr string
|
||||
Token string
|
||||
ID string
|
||||
Name string // 客户端名称(主机名)
|
||||
TLSEnabled bool
|
||||
TLSConfig *tls.Config
|
||||
DataDir string // 数据目录
|
||||
@@ -55,29 +57,46 @@ type Client struct {
|
||||
|
||||
// NewClient 创建客户端
|
||||
func NewClient(serverAddr, token, id string) *Client {
|
||||
// 默认数据目录
|
||||
home, _ := os.UserHomeDir()
|
||||
dataDir := filepath.Join(home, ".gotunnel")
|
||||
// 默认数据目录:优先使用用户主目录,失败时回退到当前工作目录
|
||||
var dataDir string
|
||||
if home, err := os.UserHomeDir(); err == nil && home != "" {
|
||||
dataDir = filepath.Join(home, ".gotunnel")
|
||||
} else {
|
||||
// UserHomeDir 失败(如 Android adb shell 环境),使用当前工作目录
|
||||
if cwd, err := os.Getwd(); err == nil {
|
||||
dataDir = filepath.Join(cwd, ".gotunnel")
|
||||
log.Printf("[Client] UserHomeDir unavailable, using current directory: %s", dataDir)
|
||||
} else {
|
||||
// 最后回退到相对路径
|
||||
dataDir = ".gotunnel"
|
||||
log.Printf("[Client] Warning: using relative path for data directory")
|
||||
}
|
||||
}
|
||||
|
||||
// 确保数据目录存在
|
||||
if err := os.MkdirAll(dataDir, 0755); err != nil {
|
||||
log.Printf("[Client] Failed to create data dir: %v", err)
|
||||
log.Printf("Failed to create data dir: %v", err)
|
||||
}
|
||||
|
||||
// ID 优先级:命令行参数 > 机器ID
|
||||
if id == "" {
|
||||
id = loadClientID(dataDir)
|
||||
id = getMachineID()
|
||||
}
|
||||
|
||||
// 获取主机名作为客户端名称
|
||||
hostname, _ := os.Hostname()
|
||||
|
||||
// 初始化日志收集器
|
||||
logger, err := NewLogger(dataDir)
|
||||
if err != nil {
|
||||
log.Printf("[Client] Failed to initialize logger: %v", err)
|
||||
log.Printf("Failed to initialize logger: %v", err)
|
||||
}
|
||||
|
||||
return &Client{
|
||||
ServerAddr: serverAddr,
|
||||
Token: token,
|
||||
ID: id,
|
||||
Name: hostname,
|
||||
DataDir: dataDir,
|
||||
runningPlugins: make(map[string]plugin.ClientPlugin),
|
||||
logger: logger,
|
||||
@@ -94,27 +113,6 @@ func (c *Client) InitVersionStore() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// getIDFilePath 获取 ID 文件路径
|
||||
func getIDFilePath(dataDir string) string {
|
||||
return filepath.Join(dataDir, idFileName)
|
||||
}
|
||||
|
||||
// loadClientID 从本地文件加载客户端 ID
|
||||
func loadClientID(dataDir string) string {
|
||||
data, err := os.ReadFile(getIDFilePath(dataDir))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
// saveClientID 保存客户端 ID 到本地文件
|
||||
func saveClientID(dataDir, id string) {
|
||||
if err := os.WriteFile(getIDFilePath(dataDir), []byte(id), 0600); err != nil {
|
||||
log.Printf("[Client] Failed to save client ID: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// SetPluginRegistry 设置插件注册表
|
||||
func (c *Client) SetPluginRegistry(registry *plugin.Registry) {
|
||||
c.pluginRegistry = registry
|
||||
@@ -151,14 +149,14 @@ func (c *Client) logWarnf(format string, args ...interface{}) {
|
||||
func (c *Client) Run() error {
|
||||
for {
|
||||
if err := c.connect(); err != nil {
|
||||
c.logErrorf("[Client] Connect error: %v", err)
|
||||
c.logf("[Client] Reconnecting in %v...", reconnectDelay)
|
||||
c.logErrorf("Connect error: %v", err)
|
||||
c.logf("Reconnecting in %v...", reconnectDelay)
|
||||
time.Sleep(reconnectDelay)
|
||||
continue
|
||||
}
|
||||
|
||||
c.handleSession()
|
||||
c.logWarnf("[Client] Disconnected, reconnecting...")
|
||||
c.logWarnf("Disconnected, reconnecting...")
|
||||
time.Sleep(disconnectDelay)
|
||||
}
|
||||
}
|
||||
@@ -181,6 +179,7 @@ func (c *Client) connect() error {
|
||||
authReq := protocol.AuthRequest{
|
||||
ClientID: c.ID,
|
||||
Token: c.Token,
|
||||
Name: c.Name,
|
||||
OS: runtime.GOOS,
|
||||
Arch: runtime.GOARCH,
|
||||
Version: version.Version,
|
||||
@@ -207,14 +206,13 @@ func (c *Client) connect() error {
|
||||
return fmt.Errorf("auth failed: %s", authResp.Message)
|
||||
}
|
||||
|
||||
// 如果服务端分配了新 ID,则更新并保存
|
||||
// 如果服务端分配了新 ID,则更新
|
||||
if authResp.ClientID != "" && authResp.ClientID != c.ID {
|
||||
c.ID = authResp.ClientID
|
||||
saveClientID(c.DataDir, c.ID)
|
||||
c.logf("[Client] New ID assigned and saved: %s", c.ID)
|
||||
c.logf("ID updated to: %s", c.ID)
|
||||
}
|
||||
|
||||
c.logf("[Client] Authenticated as %s", c.ID)
|
||||
c.logf("Authenticated as %s", c.ID)
|
||||
|
||||
session, err := yamux.Client(conn, nil)
|
||||
if err != nil {
|
||||
@@ -252,8 +250,7 @@ func (c *Client) handleStream(stream net.Conn) {
|
||||
|
||||
switch msg.Type {
|
||||
case protocol.MsgTypeProxyConfig:
|
||||
defer stream.Close()
|
||||
c.handleProxyConfig(msg)
|
||||
c.handleProxyConfig(stream, msg)
|
||||
case protocol.MsgTypeNewProxy:
|
||||
defer stream.Close()
|
||||
c.handleNewProxy(stream, msg)
|
||||
@@ -291,14 +288,20 @@ func (c *Client) handleStream(stream net.Conn) {
|
||||
c.handlePluginAPIRequest(stream, msg)
|
||||
case protocol.MsgTypeSystemStatsRequest:
|
||||
c.handleSystemStatsRequest(stream, msg)
|
||||
case protocol.MsgTypeScreenshotRequest:
|
||||
c.handleScreenshotRequest(stream, msg)
|
||||
case protocol.MsgTypeShellExecuteRequest:
|
||||
c.handleShellExecuteRequest(stream, msg)
|
||||
}
|
||||
}
|
||||
|
||||
// handleProxyConfig 处理代理配置
|
||||
func (c *Client) handleProxyConfig(msg *protocol.Message) {
|
||||
func (c *Client) handleProxyConfig(stream net.Conn, msg *protocol.Message) {
|
||||
defer stream.Close()
|
||||
|
||||
var cfg protocol.ProxyConfig
|
||||
if err := msg.ParsePayload(&cfg); err != nil {
|
||||
c.logErrorf("[Client] Parse proxy config error: %v", err)
|
||||
c.logErrorf("Parse proxy config error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -306,17 +309,21 @@ func (c *Client) handleProxyConfig(msg *protocol.Message) {
|
||||
c.rules = cfg.Rules
|
||||
c.mu.Unlock()
|
||||
|
||||
c.logf("[Client] Received %d proxy rules", len(cfg.Rules))
|
||||
c.logf("Received %d proxy rules", len(cfg.Rules))
|
||||
for _, r := range cfg.Rules {
|
||||
c.logf("[Client] %s: %s:%d", r.Name, r.LocalIP, r.LocalPort)
|
||||
c.logf(" %s: %s:%d", r.Name, r.LocalIP, r.LocalPort)
|
||||
}
|
||||
|
||||
// 发送配置确认
|
||||
ack := &protocol.Message{Type: protocol.MsgTypeProxyReady}
|
||||
protocol.WriteMessage(stream, ack)
|
||||
}
|
||||
|
||||
// handleNewProxy 处理新代理请求
|
||||
func (c *Client) handleNewProxy(stream net.Conn, msg *protocol.Message) {
|
||||
var req protocol.NewProxyRequest
|
||||
if err := msg.ParsePayload(&req); err != nil {
|
||||
c.logErrorf("[Client] Parse new proxy request error: %v", err)
|
||||
c.logErrorf("Parse new proxy request error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -331,14 +338,14 @@ func (c *Client) handleNewProxy(stream net.Conn, msg *protocol.Message) {
|
||||
c.mu.RUnlock()
|
||||
|
||||
if rule == nil {
|
||||
c.logWarnf("[Client] Unknown port %d", req.RemotePort)
|
||||
c.logWarnf("Unknown port %d", req.RemotePort)
|
||||
return
|
||||
}
|
||||
|
||||
localAddr := fmt.Sprintf("%s:%d", rule.LocalIP, rule.LocalPort)
|
||||
localConn, err := net.DialTimeout("tcp", localAddr, localDialTimeout)
|
||||
if err != nil {
|
||||
c.logErrorf("[Client] Connect %s error: %v", localAddr, err)
|
||||
c.logErrorf("Connect %s error: %v", localAddr, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -448,24 +455,24 @@ func (c *Client) findRuleByPort(port int) *protocol.ProxyRule {
|
||||
func (c *Client) handlePluginConfig(msg *protocol.Message) {
|
||||
var cfg protocol.PluginConfigSync
|
||||
if err := msg.ParsePayload(&cfg); err != nil {
|
||||
c.logErrorf("[Client] Parse plugin config error: %v", err)
|
||||
c.logErrorf("Parse plugin config error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
c.logf("[Client] Received config for plugin: %s", cfg.PluginName)
|
||||
c.logf("Received config for plugin: %s", cfg.PluginName)
|
||||
|
||||
// 应用配置到插件
|
||||
if c.pluginRegistry != nil {
|
||||
handler, err := c.pluginRegistry.GetClient(cfg.PluginName)
|
||||
if err != nil {
|
||||
c.logWarnf("[Client] Plugin %s not found: %v", cfg.PluginName, err)
|
||||
c.logWarnf("Plugin %s not found: %v", cfg.PluginName, err)
|
||||
return
|
||||
}
|
||||
if err := handler.Init(cfg.Config); err != nil {
|
||||
c.logErrorf("[Client] Plugin %s init error: %v", cfg.PluginName, err)
|
||||
c.logErrorf("Plugin %s init error: %v", cfg.PluginName, err)
|
||||
return
|
||||
}
|
||||
c.logf("[Client] Plugin %s config applied", cfg.PluginName)
|
||||
c.logf("Plugin %s config applied", cfg.PluginName)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -479,7 +486,7 @@ func (c *Client) handleClientPluginStart(stream net.Conn, msg *protocol.Message)
|
||||
return
|
||||
}
|
||||
|
||||
c.logf("[Client] Starting plugin %s for rule %s", req.PluginName, req.RuleName)
|
||||
c.logf("Starting plugin %s for rule %s", req.PluginName, req.RuleName)
|
||||
|
||||
// 获取插件
|
||||
if c.pluginRegistry == nil {
|
||||
@@ -511,7 +518,7 @@ func (c *Client) handleClientPluginStart(stream net.Conn, msg *protocol.Message)
|
||||
c.runningPlugins[key] = handler
|
||||
c.pluginMu.Unlock()
|
||||
|
||||
c.logf("[Client] Plugin %s started at %s", req.PluginName, localAddr)
|
||||
c.logf("Plugin %s started at %s", req.PluginName, localAddr)
|
||||
c.sendPluginStatus(stream, req.PluginName, req.RuleName, true, localAddr, "")
|
||||
}
|
||||
|
||||
@@ -553,7 +560,7 @@ func (c *Client) handleClientPluginConn(stream net.Conn, msg *protocol.Message)
|
||||
c.pluginMu.RUnlock()
|
||||
|
||||
if !ok {
|
||||
c.logWarnf("[Client] Plugin %s (ID: %s) not running", req.PluginName, req.PluginID)
|
||||
c.logWarnf("Plugin %s (ID: %s) not running", req.PluginName, req.PluginID)
|
||||
stream.Close()
|
||||
return
|
||||
}
|
||||
@@ -572,7 +579,7 @@ func (c *Client) handleJSPluginInstall(stream net.Conn, msg *protocol.Message) {
|
||||
return
|
||||
}
|
||||
|
||||
c.logf("[Client] Installing JS plugin: %s (ID: %s)", req.PluginName, req.PluginID)
|
||||
c.logf("Installing JS plugin: %s (ID: %s)", req.PluginName, req.PluginID)
|
||||
|
||||
// 使用 PluginID 作为 key(如果有),否则回退到 pluginName:ruleName
|
||||
key := req.PluginID
|
||||
@@ -583,9 +590,9 @@ func (c *Client) handleJSPluginInstall(stream net.Conn, msg *protocol.Message) {
|
||||
// 如果插件已经在运行,先停止它
|
||||
c.pluginMu.Lock()
|
||||
if existingHandler, ok := c.runningPlugins[key]; ok {
|
||||
c.logf("[Client] Stopping existing plugin %s before reinstall", key)
|
||||
c.logf("Stopping existing plugin %s before reinstall", key)
|
||||
if err := existingHandler.Stop(); err != nil {
|
||||
c.logErrorf("[Client] Stop existing plugin error: %v", err)
|
||||
c.logErrorf("Stop existing plugin error: %v", err)
|
||||
}
|
||||
delete(c.runningPlugins, key)
|
||||
}
|
||||
@@ -593,11 +600,11 @@ func (c *Client) handleJSPluginInstall(stream net.Conn, msg *protocol.Message) {
|
||||
|
||||
// 验证官方签名
|
||||
if err := c.verifyJSPluginSignature(req.PluginName, req.Source, req.Signature); err != nil {
|
||||
c.logErrorf("[Client] JS plugin %s signature verification failed: %v", req.PluginName, err)
|
||||
c.logErrorf("JS plugin %s signature verification failed: %v", req.PluginName, err)
|
||||
c.sendJSPluginResult(stream, req.PluginName, false, "signature verification failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
c.logf("[Client] JS plugin %s signature verified", req.PluginName)
|
||||
c.logf("JS plugin %s signature verified", req.PluginName)
|
||||
|
||||
// 创建 JS 插件
|
||||
jsPlugin, err := script.NewJSPlugin(req.PluginName, req.Source)
|
||||
@@ -611,7 +618,7 @@ func (c *Client) handleJSPluginInstall(stream net.Conn, msg *protocol.Message) {
|
||||
c.pluginRegistry.RegisterClient(jsPlugin)
|
||||
}
|
||||
|
||||
c.logf("[Client] JS plugin %s installed", req.PluginName)
|
||||
c.logf("JS plugin %s installed", req.PluginName)
|
||||
|
||||
// 保存版本信息(防止降级攻击)
|
||||
if c.versionStore != nil {
|
||||
@@ -644,13 +651,13 @@ func (c *Client) sendJSPluginResult(stream net.Conn, name string, success bool,
|
||||
// startJSPlugin 启动 JS 插件
|
||||
func (c *Client) startJSPlugin(handler plugin.ClientPlugin, req protocol.JSPluginInstallRequest) {
|
||||
if err := handler.Init(req.Config); err != nil {
|
||||
c.logErrorf("[Client] JS plugin %s init error: %v", req.PluginName, err)
|
||||
c.logErrorf("JS plugin %s init error: %v", req.PluginName, err)
|
||||
return
|
||||
}
|
||||
|
||||
localAddr, err := handler.Start()
|
||||
if err != nil {
|
||||
c.logErrorf("[Client] JS plugin %s start error: %v", req.PluginName, err)
|
||||
c.logErrorf("JS plugin %s start error: %v", req.PluginName, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -663,7 +670,7 @@ func (c *Client) startJSPlugin(handler plugin.ClientPlugin, req protocol.JSPlugi
|
||||
c.runningPlugins[key] = handler
|
||||
c.pluginMu.Unlock()
|
||||
|
||||
c.logf("[Client] JS plugin %s (ID: %s) started at %s", req.PluginName, req.PluginID, localAddr)
|
||||
c.logf("JS plugin %s (ID: %s) started at %s", req.PluginName, req.PluginID, localAddr)
|
||||
}
|
||||
|
||||
// verifyJSPluginSignature 验证 JS 插件签名
|
||||
@@ -741,13 +748,13 @@ func (c *Client) handleClientPluginStop(stream net.Conn, msg *protocol.Message)
|
||||
|
||||
if ok {
|
||||
if err := handler.Stop(); err != nil {
|
||||
c.logErrorf("[Client] Plugin %s stop error: %v", key, err)
|
||||
c.logErrorf("Plugin %s stop error: %v", key, err)
|
||||
}
|
||||
delete(c.runningPlugins, key)
|
||||
}
|
||||
c.pluginMu.Unlock()
|
||||
|
||||
c.logf("[Client] Plugin %s stopped", key)
|
||||
c.logf("Plugin %s stopped", key)
|
||||
c.sendPluginStatus(stream, req.PluginName, req.RuleName, false, "", "")
|
||||
}
|
||||
|
||||
@@ -758,7 +765,7 @@ func (c *Client) handleClientRestart(stream net.Conn, msg *protocol.Message) {
|
||||
var req protocol.ClientRestartRequest
|
||||
msg.ParsePayload(&req)
|
||||
|
||||
c.logf("[Client] Restart requested: %s", req.Reason)
|
||||
c.logf("Restart requested: %s", req.Reason)
|
||||
|
||||
// 发送响应
|
||||
resp := protocol.ClientRestartResponse{
|
||||
@@ -771,7 +778,7 @@ func (c *Client) handleClientRestart(stream net.Conn, msg *protocol.Message) {
|
||||
// 停止所有运行中的插件
|
||||
c.pluginMu.Lock()
|
||||
for key, handler := range c.runningPlugins {
|
||||
c.logf("[Client] Stopping plugin %s for restart", key)
|
||||
c.logf("Stopping plugin %s for restart", key)
|
||||
handler.Stop()
|
||||
}
|
||||
c.runningPlugins = make(map[string]plugin.ClientPlugin)
|
||||
@@ -813,7 +820,7 @@ func (c *Client) handlePluginConfigUpdate(stream net.Conn, msg *protocol.Message
|
||||
}
|
||||
c.pluginMu.RUnlock()
|
||||
|
||||
c.logf("[Client] Config update for plugin %s", key)
|
||||
c.logf("Config update for plugin %s", key)
|
||||
|
||||
if !ok {
|
||||
c.sendPluginConfigUpdateResult(stream, req.PluginName, req.RuleName, false, "plugin not running")
|
||||
@@ -824,7 +831,7 @@ func (c *Client) handlePluginConfigUpdate(stream net.Conn, msg *protocol.Message
|
||||
// 停止并重启插件
|
||||
c.pluginMu.Lock()
|
||||
if err := handler.Stop(); err != nil {
|
||||
c.logErrorf("[Client] Plugin %s stop error: %v", key, err)
|
||||
c.logErrorf("Plugin %s stop error: %v", key, err)
|
||||
}
|
||||
delete(c.runningPlugins, key)
|
||||
c.pluginMu.Unlock()
|
||||
@@ -845,7 +852,7 @@ func (c *Client) handlePluginConfigUpdate(stream net.Conn, msg *protocol.Message
|
||||
c.runningPlugins[key] = handler
|
||||
c.pluginMu.Unlock()
|
||||
|
||||
c.logf("[Client] Plugin %s restarted at %s with new config", key, localAddr)
|
||||
c.logf("Plugin %s restarted at %s with new config", key, localAddr)
|
||||
}
|
||||
|
||||
c.sendPluginConfigUpdateResult(stream, req.PluginName, req.RuleName, true, "")
|
||||
@@ -869,17 +876,17 @@ func (c *Client) handleUpdateDownload(stream net.Conn, msg *protocol.Message) {
|
||||
|
||||
var req protocol.UpdateDownloadRequest
|
||||
if err := msg.ParsePayload(&req); err != nil {
|
||||
c.logErrorf("[Client] Parse update request error: %v", err)
|
||||
c.logErrorf("Parse update request error: %v", err)
|
||||
c.sendUpdateResult(stream, false, "invalid request")
|
||||
return
|
||||
}
|
||||
|
||||
c.logf("[Client] Update download requested: %s", req.DownloadURL)
|
||||
c.logf("Update download requested: %s", req.DownloadURL)
|
||||
|
||||
// 异步执行更新
|
||||
go func() {
|
||||
if err := c.performSelfUpdate(req.DownloadURL); err != nil {
|
||||
c.logErrorf("[Client] Update failed: %v", err)
|
||||
c.logErrorf("Update failed: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -898,57 +905,128 @@ func (c *Client) sendUpdateResult(stream net.Conn, success bool, message string)
|
||||
|
||||
// performSelfUpdate 执行自更新
|
||||
func (c *Client) performSelfUpdate(downloadURL string) error {
|
||||
c.logf("[Client] Starting self-update from: %s", downloadURL)
|
||||
|
||||
// 使用共享的下载和解压逻辑
|
||||
binaryPath, cleanup, err := update.DownloadAndExtract(downloadURL, "client")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer cleanup()
|
||||
c.logf("Starting self-update from: %s", downloadURL)
|
||||
|
||||
// 获取当前可执行文件路径
|
||||
currentPath, err := os.Executable()
|
||||
if err != nil {
|
||||
return fmt.Errorf("get executable: %w", err)
|
||||
c.logErrorf("Update failed: cannot get executable path: %v", err)
|
||||
return err
|
||||
}
|
||||
currentPath, _ = filepath.EvalSymlinks(currentPath)
|
||||
|
||||
// 预检查:验证是否有写权限(在下载前检查,避免浪费带宽)
|
||||
// Windows 跳过预检查,因为 Windows 更新通过 batch 脚本以提升权限执行
|
||||
// 非 Windows:原始路径 → DataDir → 临时目录,逐级回退
|
||||
fallbackDir := ""
|
||||
if runtime.GOOS != "windows" {
|
||||
if err := c.checkUpdatePermissions(currentPath); err != nil {
|
||||
// 尝试 DataDir
|
||||
fallbackDir = c.DataDir
|
||||
testFile := filepath.Join(fallbackDir, ".gotunnel_update_test")
|
||||
if f, err := os.Create(testFile); err != nil {
|
||||
// DataDir 也不可写,回退到临时目录
|
||||
fallbackDir = os.TempDir()
|
||||
c.logf("DataDir not writable, falling back to temp directory: %s", fallbackDir)
|
||||
} else {
|
||||
f.Close()
|
||||
os.Remove(testFile)
|
||||
c.logf("Original path not writable, falling back to data directory: %s", fallbackDir)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 使用共享的下载和解压逻辑
|
||||
c.logf("Downloading update package...")
|
||||
binaryPath, cleanup, err := update.DownloadAndExtract(downloadURL, "client")
|
||||
if err != nil {
|
||||
c.logErrorf("Update failed: download/extract error: %v", err)
|
||||
return err
|
||||
}
|
||||
defer cleanup()
|
||||
|
||||
// Windows 需要特殊处理
|
||||
if runtime.GOOS == "windows" {
|
||||
return performWindowsClientUpdate(binaryPath, currentPath, c.ServerAddr, c.Token, c.ID)
|
||||
}
|
||||
|
||||
// Linux/Mac: 直接替换
|
||||
backupPath := currentPath + ".bak"
|
||||
// 确定目标路径
|
||||
targetPath := currentPath
|
||||
if fallbackDir != "" {
|
||||
targetPath = filepath.Join(fallbackDir, filepath.Base(currentPath))
|
||||
c.logf("Will install to fallback path: %s", targetPath)
|
||||
}
|
||||
|
||||
// 停止所有插件
|
||||
c.stopAllPlugins()
|
||||
|
||||
// 备份当前文件
|
||||
if err := os.Rename(currentPath, backupPath); err != nil {
|
||||
return fmt.Errorf("backup current: %w", err)
|
||||
if fallbackDir == "" {
|
||||
// 原地替换:备份 → 复制 → 清理
|
||||
backupPath := currentPath + ".bak"
|
||||
|
||||
c.logf("Backing up current binary...")
|
||||
if err := os.Rename(currentPath, backupPath); err != nil {
|
||||
c.logErrorf("Update failed: cannot backup current binary: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
c.logf("Installing new binary...")
|
||||
if err := update.CopyFile(binaryPath, currentPath); err != nil {
|
||||
os.Rename(backupPath, currentPath)
|
||||
c.logErrorf("Update failed: cannot install new binary: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if err := os.Chmod(currentPath, 0755); err != nil {
|
||||
os.Rename(backupPath, currentPath)
|
||||
c.logErrorf("Update failed: cannot set execute permission: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
os.Remove(backupPath)
|
||||
} else {
|
||||
// 回退路径:直接复制到回退目录
|
||||
c.logf("Installing new binary to data directory...")
|
||||
if err := update.CopyFile(binaryPath, targetPath); err != nil {
|
||||
c.logErrorf("Update failed: cannot install new binary: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if err := os.Chmod(targetPath, 0755); err != nil {
|
||||
c.logErrorf("Update failed: cannot set execute permission: %v", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// 复制新文件(不能用 rename,可能跨文件系统)
|
||||
if err := update.CopyFile(binaryPath, currentPath); err != nil {
|
||||
os.Rename(backupPath, currentPath)
|
||||
return fmt.Errorf("replace binary: %w", err)
|
||||
c.logf("Update completed successfully, restarting...")
|
||||
|
||||
// 重启进程(从新路径启动)
|
||||
restartClientProcess(targetPath, c.ServerAddr, c.Token, c.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkUpdatePermissions 检查是否有更新权限
|
||||
func (c *Client) checkUpdatePermissions(execPath string) error {
|
||||
// 检查可执行文件所在目录是否可写
|
||||
dir := filepath.Dir(execPath)
|
||||
testFile := filepath.Join(dir, ".gotunnel_update_test")
|
||||
|
||||
f, err := os.Create(testFile)
|
||||
if err != nil {
|
||||
c.logErrorf("No write permission to directory: %s", dir)
|
||||
return err
|
||||
}
|
||||
f.Close()
|
||||
os.Remove(testFile)
|
||||
|
||||
// 设置执行权限
|
||||
if err := os.Chmod(currentPath, 0755); err != nil {
|
||||
os.Rename(backupPath, currentPath)
|
||||
return fmt.Errorf("chmod: %w", err)
|
||||
// 检查可执行文件本身是否可写
|
||||
f, err = os.OpenFile(execPath, os.O_WRONLY, 0)
|
||||
if err != nil {
|
||||
c.logErrorf("No write permission to executable: %s", execPath)
|
||||
return err
|
||||
}
|
||||
f.Close()
|
||||
|
||||
// 删除备份
|
||||
os.Remove(backupPath)
|
||||
|
||||
c.logf("[Client] Update completed, restarting...")
|
||||
|
||||
// 重启进程
|
||||
restartClientProcess(currentPath, c.ServerAddr, c.Token, c.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -956,7 +1034,7 @@ func (c *Client) performSelfUpdate(downloadURL string) error {
|
||||
func (c *Client) stopAllPlugins() {
|
||||
c.pluginMu.Lock()
|
||||
for key, handler := range c.runningPlugins {
|
||||
c.logf("[Client] Stopping plugin %s for update", key)
|
||||
c.logf("Stopping plugin %s for update", key)
|
||||
handler.Stop()
|
||||
}
|
||||
c.runningPlugins = make(map[string]plugin.ClientPlugin)
|
||||
@@ -972,6 +1050,12 @@ func performWindowsClientUpdate(newFile, currentPath, serverAddr, token, id stri
|
||||
}
|
||||
|
||||
batchScript := fmt.Sprintf(`@echo off
|
||||
:: Check for admin rights, request UAC elevation if needed
|
||||
net session >nul 2>&1
|
||||
if %%errorlevel%% neq 0 (
|
||||
powershell -Command "Start-Process cmd -ArgumentList '/C \\"\"%%~f0\"\"' -Verb RunAs"
|
||||
exit /b
|
||||
)
|
||||
ping 127.0.0.1 -n 2 > nul
|
||||
del "%s"
|
||||
move "%s" "%s"
|
||||
@@ -1122,7 +1206,7 @@ func (c *Client) handlePluginAPIRequest(stream net.Conn, msg *protocol.Message)
|
||||
return
|
||||
}
|
||||
|
||||
c.logf("[Client] Plugin API request: %s %s for plugin %s (ID: %s)", req.Method, req.Path, req.PluginName, req.PluginID)
|
||||
c.logf("Plugin API request: %s %s for plugin %s (ID: %s)", req.Method, req.Path, req.PluginName, req.PluginID)
|
||||
|
||||
// 查找运行中的插件
|
||||
c.pluginMu.RLock()
|
||||
@@ -1185,7 +1269,7 @@ func (c *Client) handleSystemStatsRequest(stream net.Conn, msg *protocol.Message
|
||||
|
||||
stats, err := utils.GetSystemStats()
|
||||
if err != nil {
|
||||
log.Printf("[Client] Failed to get system stats: %v", err)
|
||||
log.Printf("Failed to get system stats: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1202,3 +1286,104 @@ func (c *Client) handleSystemStatsRequest(stream net.Conn, msg *protocol.Message
|
||||
respMsg, _ := protocol.NewMessage(protocol.MsgTypeSystemStatsResponse, resp)
|
||||
protocol.WriteMessage(stream, respMsg)
|
||||
}
|
||||
|
||||
// handleScreenshotRequest 处理截图请求
|
||||
func (c *Client) handleScreenshotRequest(stream net.Conn, msg *protocol.Message) {
|
||||
defer stream.Close()
|
||||
|
||||
var req protocol.ScreenshotRequest
|
||||
msg.ParsePayload(&req)
|
||||
|
||||
// 捕获截图
|
||||
data, width, height, err := utils.CaptureScreenshot(req.Quality)
|
||||
if err != nil {
|
||||
c.logErrorf("Screenshot capture failed: %v", err)
|
||||
resp := protocol.ScreenshotResponse{Error: err.Error()}
|
||||
respMsg, _ := protocol.NewMessage(protocol.MsgTypeScreenshotResponse, resp)
|
||||
protocol.WriteMessage(stream, respMsg)
|
||||
return
|
||||
}
|
||||
|
||||
// 编码为 Base64
|
||||
base64Data := base64.StdEncoding.EncodeToString(data)
|
||||
|
||||
resp := protocol.ScreenshotResponse{
|
||||
Data: base64Data,
|
||||
Width: width,
|
||||
Height: height,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
}
|
||||
|
||||
respMsg, _ := protocol.NewMessage(protocol.MsgTypeScreenshotResponse, resp)
|
||||
protocol.WriteMessage(stream, respMsg)
|
||||
}
|
||||
|
||||
// handleShellExecuteRequest 处理 Shell 执行请求
|
||||
func (c *Client) handleShellExecuteRequest(stream net.Conn, msg *protocol.Message) {
|
||||
defer stream.Close()
|
||||
|
||||
var req protocol.ShellExecuteRequest
|
||||
if err := msg.ParsePayload(&req); err != nil {
|
||||
resp := protocol.ShellExecuteResponse{Error: err.Error(), ExitCode: -1}
|
||||
respMsg, _ := protocol.NewMessage(protocol.MsgTypeShellExecuteResponse, resp)
|
||||
protocol.WriteMessage(stream, respMsg)
|
||||
return
|
||||
}
|
||||
|
||||
// 设置默认超时
|
||||
timeout := req.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = 30
|
||||
}
|
||||
|
||||
c.logf("Executing shell command: %s", req.Command)
|
||||
|
||||
// 根据操作系统选择 shell
|
||||
var cmd *exec.Cmd
|
||||
if runtime.GOOS == "windows" {
|
||||
cmd = exec.Command("cmd", "/C", req.Command)
|
||||
} else {
|
||||
cmd = exec.Command("sh", "-c", req.Command)
|
||||
}
|
||||
|
||||
// 设置超时上下文
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
|
||||
defer cancel()
|
||||
cmd = exec.CommandContext(ctx, cmd.Path, cmd.Args[1:]...)
|
||||
|
||||
// 执行命令并获取输出
|
||||
output, err := cmd.CombinedOutput()
|
||||
|
||||
exitCode := 0
|
||||
if err != nil {
|
||||
if exitErr, ok := err.(*exec.ExitError); ok {
|
||||
exitCode = exitErr.ExitCode()
|
||||
} else if ctx.Err() == context.DeadlineExceeded {
|
||||
resp := protocol.ShellExecuteResponse{
|
||||
Output: string(output),
|
||||
ExitCode: -1,
|
||||
Error: "command timeout",
|
||||
}
|
||||
respMsg, _ := protocol.NewMessage(protocol.MsgTypeShellExecuteResponse, resp)
|
||||
protocol.WriteMessage(stream, respMsg)
|
||||
return
|
||||
} else {
|
||||
resp := protocol.ShellExecuteResponse{
|
||||
Output: string(output),
|
||||
ExitCode: -1,
|
||||
Error: err.Error(),
|
||||
}
|
||||
respMsg, _ := protocol.NewMessage(protocol.MsgTypeShellExecuteResponse, resp)
|
||||
protocol.WriteMessage(stream, respMsg)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
resp := protocol.ShellExecuteResponse{
|
||||
Output: string(output),
|
||||
ExitCode: exitCode,
|
||||
}
|
||||
|
||||
respMsg, _ := protocol.NewMessage(protocol.MsgTypeShellExecuteResponse, resp)
|
||||
protocol.WriteMessage(stream, respMsg)
|
||||
}
|
||||
|
||||
133
internal/client/tunnel/machine_id.go
Normal file
133
internal/client/tunnel/machine_id.go
Normal file
@@ -0,0 +1,133 @@
|
||||
package tunnel
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// getMachineID 获取机器唯一标识
|
||||
// 优先级:系统机器ID > MAC地址哈希
|
||||
func getMachineID() string {
|
||||
// 尝试获取系统机器 ID
|
||||
if id := getSystemMachineID(); id != "" {
|
||||
return hashID(id)
|
||||
}
|
||||
|
||||
// 备选:使用主网卡 MAC 地址
|
||||
if id := getMACAddress(); id != "" {
|
||||
return hashID(id)
|
||||
}
|
||||
|
||||
// 都失败则返回空,让服务端生成
|
||||
return ""
|
||||
}
|
||||
|
||||
// getSystemMachineID 获取系统机器 ID
|
||||
func getSystemMachineID() string {
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
return getLinuxMachineID()
|
||||
case "darwin":
|
||||
return getDarwinMachineID()
|
||||
case "windows":
|
||||
return getWindowsMachineID()
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// getLinuxMachineID 获取 Linux 机器 ID
|
||||
func getLinuxMachineID() string {
|
||||
// 优先读取 /etc/machine-id
|
||||
if data, err := os.ReadFile("/etc/machine-id"); err == nil {
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
// 备选 /var/lib/dbus/machine-id
|
||||
if data, err := os.ReadFile("/var/lib/dbus/machine-id"); err == nil {
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// getDarwinMachineID 获取 macOS 机器 ID (IOPlatformUUID)
|
||||
func getDarwinMachineID() string {
|
||||
cmd := exec.Command("ioreg", "-rd1", "-c", "IOPlatformExpertDevice")
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
// 解析 IOPlatformUUID
|
||||
lines := strings.Split(string(output), "\n")
|
||||
for _, line := range lines {
|
||||
if strings.Contains(line, "IOPlatformUUID") {
|
||||
parts := strings.Split(line, "=")
|
||||
if len(parts) == 2 {
|
||||
uuid := strings.TrimSpace(parts[1])
|
||||
uuid = strings.Trim(uuid, "\"")
|
||||
return uuid
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// getWindowsMachineID 获取 Windows 机器 ID
|
||||
func getWindowsMachineID() string {
|
||||
cmd := exec.Command("reg", "query",
|
||||
`HKLM\SOFTWARE\Microsoft\Cryptography`,
|
||||
"/v", "MachineGuid")
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
// 解析注册表输出
|
||||
lines := strings.Split(string(output), "\n")
|
||||
for _, line := range lines {
|
||||
if strings.Contains(line, "MachineGuid") {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) >= 3 {
|
||||
return fields[len(fields)-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// getMACAddress 获取主网卡 MAC 地址
|
||||
func getMACAddress() string {
|
||||
interfaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
for _, iface := range interfaces {
|
||||
// 跳过回环和无效接口
|
||||
if iface.Flags&net.FlagLoopback != 0 {
|
||||
continue
|
||||
}
|
||||
if iface.Flags&net.FlagUp == 0 {
|
||||
continue
|
||||
}
|
||||
if len(iface.HardwareAddr) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// 返回第一个有效的 MAC 地址
|
||||
return iface.HardwareAddr.String()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// hashID 对 ID 进行哈希处理,生成固定长度的客户端 ID
|
||||
func hashID(id string) string {
|
||||
hash := sha256.Sum256([]byte(id))
|
||||
// 取前 16 个字符作为客户端 ID
|
||||
return hex.EncodeToString(hash[:])[:16]
|
||||
}
|
||||
@@ -397,12 +397,17 @@ func (s *SQLiteStore) Get24HourTraffic() (inbound, outbound int64, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// GetHourlyTraffic 获取每小时流量记录
|
||||
// GetHourlyTraffic 获取每小时流量记录(始终返回完整的 hours 小时数据)
|
||||
func (s *SQLiteStore) GetHourlyTraffic(hours int) ([]TrafficRecord, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
cutoff := time.Now().Add(-time.Duration(hours) * time.Hour).Unix()
|
||||
// 计算当前小时的起始时间戳
|
||||
now := time.Now()
|
||||
currentHour := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, now.Location())
|
||||
|
||||
// 查询数据库中的记录
|
||||
cutoff := currentHour.Add(-time.Duration(hours-1) * time.Hour).Unix()
|
||||
rows, err := s.db.Query(`
|
||||
SELECT hour_ts, inbound, outbound FROM traffic_stats
|
||||
WHERE hour_ts >= ? ORDER BY hour_ts ASC
|
||||
@@ -412,13 +417,26 @@ func (s *SQLiteStore) GetHourlyTraffic(hours int) ([]TrafficRecord, error) {
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var records []TrafficRecord
|
||||
// 将数据库记录放入 map 以便快速查找
|
||||
dbRecords := make(map[int64]TrafficRecord)
|
||||
for rows.Next() {
|
||||
var r TrafficRecord
|
||||
if err := rows.Scan(&r.Timestamp, &r.Inbound, &r.Outbound); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
records = append(records, r)
|
||||
dbRecords[r.Timestamp] = r
|
||||
}
|
||||
|
||||
// 生成完整的 hours 小时数据
|
||||
records := make([]TrafficRecord, hours)
|
||||
for i := 0; i < hours; i++ {
|
||||
ts := currentHour.Add(-time.Duration(hours-1-i) * time.Hour).Unix()
|
||||
if r, ok := dbRecords[ts]; ok {
|
||||
records[i] = r
|
||||
} else {
|
||||
records[i] = TrafficRecord{Timestamp: ts, Inbound: 0, Outbound: 0}
|
||||
}
|
||||
}
|
||||
|
||||
return records, nil
|
||||
}
|
||||
|
||||
@@ -115,7 +115,7 @@ func (h *ClientHandler) Get(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
online, lastPing, remoteAddr, clientOS, clientArch, clientVersion := h.app.GetServer().GetClientStatus(clientID)
|
||||
online, lastPing, remoteAddr, clientName, clientOS, clientArch, clientVersion := h.app.GetServer().GetClientStatus(clientID)
|
||||
|
||||
// 复制插件列表
|
||||
plugins := make([]db.ClientPlugin, len(client.Plugins))
|
||||
@@ -145,9 +145,15 @@ func (h *ClientHandler) Get(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// 如果客户端在线且有名称,优先使用在线名称
|
||||
nickname := client.Nickname
|
||||
if online && clientName != "" && nickname == "" {
|
||||
nickname = clientName
|
||||
}
|
||||
|
||||
resp := dto.ClientResponse{
|
||||
ID: client.ID,
|
||||
Nickname: client.Nickname,
|
||||
Nickname: nickname,
|
||||
Rules: client.Rules,
|
||||
Plugins: plugins,
|
||||
Online: online,
|
||||
@@ -242,8 +248,7 @@ func (h *ClientHandler) Delete(c *gin.Context) {
|
||||
func (h *ClientHandler) PushConfig(c *gin.Context) {
|
||||
clientID := c.Param("id")
|
||||
|
||||
online, _, _, _, _, _ := h.app.GetServer().GetClientStatus(clientID)
|
||||
if !online {
|
||||
if !h.app.GetServer().IsClientOnline(clientID) {
|
||||
ClientNotOnline(c)
|
||||
return
|
||||
}
|
||||
@@ -311,8 +316,7 @@ func (h *ClientHandler) Restart(c *gin.Context) {
|
||||
func (h *ClientHandler) InstallPlugins(c *gin.Context) {
|
||||
clientID := c.Param("id")
|
||||
|
||||
online, _, _, _, _, _ := h.app.GetServer().GetClientStatus(clientID)
|
||||
if !online {
|
||||
if !h.app.GetServer().IsClientOnline(clientID) {
|
||||
ClientNotOnline(c)
|
||||
return
|
||||
}
|
||||
@@ -462,6 +466,47 @@ func (h *ClientHandler) GetSystemStats(c *gin.Context) {
|
||||
Success(c, stats)
|
||||
}
|
||||
|
||||
// GetScreenshot 获取客户端截图
|
||||
func (h *ClientHandler) GetScreenshot(c *gin.Context) {
|
||||
clientID := c.Param("id")
|
||||
quality := 0
|
||||
if q, ok := c.GetQuery("quality"); ok {
|
||||
fmt.Sscanf(q, "%d", &quality)
|
||||
}
|
||||
|
||||
screenshot, err := h.app.GetServer().GetClientScreenshot(clientID, quality)
|
||||
if err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
Success(c, screenshot)
|
||||
}
|
||||
|
||||
// ExecuteShellRequest Shell 执行请求体
|
||||
type ExecuteShellRequest struct {
|
||||
Command string `json:"command" binding:"required"`
|
||||
Timeout int `json:"timeout"`
|
||||
}
|
||||
|
||||
// ExecuteShell 执行 Shell 命令
|
||||
func (h *ClientHandler) ExecuteShell(c *gin.Context) {
|
||||
clientID := c.Param("id")
|
||||
var req ExecuteShellRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
BadRequest(c, "Invalid request: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.app.GetServer().ExecuteClientShell(clientID, req.Command, req.Timeout)
|
||||
if err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
Success(c, result)
|
||||
}
|
||||
|
||||
// validateClientID 验证客户端 ID 格式
|
||||
func validateClientID(id string) bool {
|
||||
if len(id) < 1 || len(id) > 64 {
|
||||
|
||||
@@ -165,6 +165,12 @@ func performSelfUpdate(downloadURL string, restart bool) error {
|
||||
// performWindowsUpdate Windows 平台更新
|
||||
func performWindowsUpdate(newFile, currentPath string, restart bool) error {
|
||||
batchScript := fmt.Sprintf(`@echo off
|
||||
:: Check for admin rights, request UAC elevation if needed
|
||||
net session >nul 2>&1
|
||||
if %%errorlevel%% neq 0 (
|
||||
powershell -Command "Start-Process cmd -ArgumentList '/C \\"\"%%~f0\"\"' -Verb RunAs"
|
||||
exit /b
|
||||
)
|
||||
ping 127.0.0.1 -n 2 > nul
|
||||
del "%s"
|
||||
move "%s" "%s"
|
||||
|
||||
@@ -19,11 +19,13 @@ type AppInterface interface {
|
||||
|
||||
// ServerInterface 服务端接口
|
||||
type ServerInterface interface {
|
||||
GetClientStatus(clientID string) (online bool, lastPing, remoteAddr, clientOS, clientArch, clientVersion string)
|
||||
IsClientOnline(clientID string) bool
|
||||
GetClientStatus(clientID string) (online bool, lastPing, remoteAddr, clientName, clientOS, clientArch, clientVersion string)
|
||||
GetAllClientStatus() map[string]struct {
|
||||
Online bool
|
||||
LastPing string
|
||||
RemoteAddr string
|
||||
Name string
|
||||
OS string
|
||||
Arch string
|
||||
Version string
|
||||
@@ -59,7 +61,12 @@ type ServerInterface interface {
|
||||
// 插件 API 代理
|
||||
ProxyPluginAPIRequest(clientID string, req protocol.PluginAPIRequest) (*protocol.PluginAPIResponse, error)
|
||||
// 系统状态
|
||||
// 系统状态
|
||||
GetClientSystemStats(clientID string) (*protocol.SystemStatsResponse, error)
|
||||
// 截图
|
||||
GetClientScreenshot(clientID string, quality int) (*protocol.ScreenshotResponse, error)
|
||||
// Shell 执行
|
||||
ExecuteClientShell(clientID, command string, timeout int) (*protocol.ShellExecuteResponse, error)
|
||||
}
|
||||
|
||||
// ConfigField 配置字段
|
||||
|
||||
@@ -177,8 +177,7 @@ func (h *JSPluginHandler) PushToClient(c *gin.Context) {
|
||||
c.ShouldBindJSON(&pushReq) // 忽略错误,允许空请求体
|
||||
|
||||
// 检查客户端是否在线
|
||||
online, _, _, _, _, _ := h.app.GetServer().GetClientStatus(clientID)
|
||||
if !online {
|
||||
if !h.app.GetServer().IsClientOnline(clientID) {
|
||||
ClientNotOnline(c)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -35,8 +35,7 @@ func (h *LogHandler) StreamLogs(c *gin.Context) {
|
||||
clientID := c.Param("id")
|
||||
|
||||
// 检查客户端是否在线
|
||||
online, _, _, _, _, _ := h.app.GetServer().GetClientStatus(clientID)
|
||||
if !online {
|
||||
if !h.app.GetServer().IsClientOnline(clientID) {
|
||||
c.JSON(400, gin.H{"code": 400, "message": "client not online"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -371,8 +371,7 @@ func (h *PluginHandler) UpdateClientConfig(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 如果客户端在线,同步配置
|
||||
online, _, _, _, _, _ := h.app.GetServer().GetClientStatus(clientID)
|
||||
if online {
|
||||
if h.app.GetServer().IsClientOnline(clientID) {
|
||||
if err := h.app.GetServer().SyncPluginConfigToClient(clientID, pluginName, req.Config); err != nil {
|
||||
PartialSuccess(c, gin.H{"status": "partial", "port_changed": portChanged}, "config saved but sync failed: "+err.Error())
|
||||
return
|
||||
|
||||
@@ -45,8 +45,7 @@ func (h *PluginAPIHandler) ProxyRequest(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 检查客户端是否在线
|
||||
online, _, _, _, _, _ := h.app.GetServer().GetClientStatus(clientID)
|
||||
if !online {
|
||||
if !h.app.GetServer().IsClientOnline(clientID) {
|
||||
ClientNotOnline(c)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -82,8 +82,7 @@ func (h *StoreHandler) Install(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 检查客户端是否在线
|
||||
online, _, _, _, _, _ := h.app.GetServer().GetClientStatus(req.ClientID)
|
||||
if !online {
|
||||
if !h.app.GetServer().IsClientOnline(req.ClientID) {
|
||||
ClientNotOnline(c)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -70,6 +70,8 @@ func (r *GinRouter) SetupRoutes(app handler.AppInterface, jwtAuth *auth.JWTAuth,
|
||||
api.POST("/client/:id/install-plugins", clientHandler.InstallPlugins)
|
||||
api.POST("/client/:id/plugin/:pluginID/:action", clientHandler.PluginAction)
|
||||
api.GET("/client/:id/system-stats", clientHandler.GetSystemStats)
|
||||
api.GET("/client/:id/screenshot", clientHandler.GetScreenshot)
|
||||
api.POST("/client/:id/shell", clientHandler.ExecuteShell)
|
||||
|
||||
// 配置管理
|
||||
configHandler := handler.NewConfigHandler(app)
|
||||
@@ -198,10 +200,10 @@ func isStaticAsset(path string) bool {
|
||||
|
||||
// Re-export types from handler package for backward compatibility
|
||||
type (
|
||||
ServerInterface = handler.ServerInterface
|
||||
AppInterface = handler.AppInterface
|
||||
ConfigField = handler.ConfigField
|
||||
RuleSchema = handler.RuleSchema
|
||||
PluginInfo = handler.PluginInfo
|
||||
ServerInterface = handler.ServerInterface
|
||||
AppInterface = handler.AppInterface
|
||||
ConfigField = handler.ConfigField
|
||||
RuleSchema = handler.RuleSchema
|
||||
PluginInfo = handler.PluginInfo
|
||||
JSPluginInstallRequest = handler.JSPluginInstallRequest
|
||||
)
|
||||
|
||||
@@ -51,6 +51,7 @@ func generateClientID() string {
|
||||
type Server struct {
|
||||
clientStore db.ClientStore
|
||||
jsPluginStore db.JSPluginStore // JS 插件存储
|
||||
trafficStore db.TrafficStore // 流量存储
|
||||
bindAddr string
|
||||
bindPort int
|
||||
token string
|
||||
@@ -83,6 +84,7 @@ type JSPluginEntry struct {
|
||||
// ClientSession 客户端会话
|
||||
type ClientSession struct {
|
||||
ID string
|
||||
Name string // 客户端名称(主机名)
|
||||
RemoteAddr string // 客户端 IP 地址
|
||||
OS string // 客户端操作系统
|
||||
Arch string // 客户端架构
|
||||
@@ -160,6 +162,11 @@ func (s *Server) SetJSPluginStore(store db.JSPluginStore) {
|
||||
s.jsPluginStore = store
|
||||
}
|
||||
|
||||
// SetTrafficStore 设置流量存储
|
||||
func (s *Server) SetTrafficStore(store db.TrafficStore) {
|
||||
s.trafficStore = store
|
||||
}
|
||||
|
||||
// LoadJSPlugins 加载 JS 插件配置
|
||||
func (s *Server) LoadJSPlugins(plugins []JSPluginEntry) {
|
||||
s.jsPlugins = plugins
|
||||
@@ -269,13 +276,22 @@ func (s *Server) handleConnection(conn net.Conn) {
|
||||
// 检查客户端是否存在,不存在则自动创建
|
||||
exists, err := s.clientStore.ClientExists(clientID)
|
||||
if err != nil || !exists {
|
||||
newClient := &db.Client{ID: clientID, Rules: []protocol.ProxyRule{}}
|
||||
newClient := &db.Client{ID: clientID, Nickname: authReq.Name, Rules: []protocol.ProxyRule{}}
|
||||
if err := s.clientStore.CreateClient(newClient); err != nil {
|
||||
log.Printf("[Server] Create client error: %v", err)
|
||||
s.sendAuthResponse(conn, false, "failed to create client", "")
|
||||
return
|
||||
}
|
||||
log.Printf("[Server] New client registered: %s", clientID)
|
||||
log.Printf("[Server] New client registered: %s (%s)", clientID, authReq.Name)
|
||||
} else if authReq.Name != "" {
|
||||
// 客户端已存在,仅当 Nickname 为空时才用客户端名称更新
|
||||
// 这样服务端手动设置的名称不会被客户端覆盖
|
||||
if client, err := s.clientStore.GetClient(clientID); err == nil {
|
||||
if client.Nickname == "" {
|
||||
client.Nickname = authReq.Name
|
||||
s.clientStore.UpdateClient(client)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rules, _ := s.clientStore.GetClientRules(clientID)
|
||||
@@ -290,11 +306,11 @@ func (s *Server) handleConnection(conn net.Conn) {
|
||||
}
|
||||
|
||||
security.LogAuthSuccess(clientIP, clientID)
|
||||
s.setupClientSession(conn, clientID, authReq.OS, authReq.Arch, authReq.Version, rules)
|
||||
s.setupClientSession(conn, clientID, authReq.Name, authReq.OS, authReq.Arch, authReq.Version, rules)
|
||||
}
|
||||
|
||||
// setupClientSession 建立客户端会话
|
||||
func (s *Server) setupClientSession(conn net.Conn, clientID, clientOS, clientArch, clientVersion string, rules []protocol.ProxyRule) {
|
||||
func (s *Server) setupClientSession(conn net.Conn, clientID, clientName, clientOS, clientArch, clientVersion string, rules []protocol.ProxyRule) {
|
||||
session, err := yamux.Server(conn, nil)
|
||||
if err != nil {
|
||||
log.Printf("[Server] Yamux error: %v", err)
|
||||
@@ -309,6 +325,7 @@ func (s *Server) setupClientSession(conn net.Conn, clientID, clientOS, clientArc
|
||||
|
||||
cs := &ClientSession{
|
||||
ID: clientID,
|
||||
Name: clientName,
|
||||
RemoteAddr: remoteAddr,
|
||||
OS: clientOS,
|
||||
Arch: clientArch,
|
||||
@@ -348,7 +365,7 @@ func (s *Server) sendAuthResponse(conn net.Conn, success bool, message, clientID
|
||||
return protocol.WriteMessage(conn, msg)
|
||||
}
|
||||
|
||||
// sendProxyConfig 发送代理配置
|
||||
// sendProxyConfig 发送代理配置并等待客户端确认
|
||||
func (s *Server) sendProxyConfig(session *yamux.Session, rules []protocol.ProxyRule) error {
|
||||
stream, err := session.Open()
|
||||
if err != nil {
|
||||
@@ -361,7 +378,20 @@ func (s *Server) sendProxyConfig(session *yamux.Session, rules []protocol.ProxyR
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return protocol.WriteMessage(stream, msg)
|
||||
if err := protocol.WriteMessage(stream, msg); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 等待客户端确认
|
||||
ack, err := protocol.ReadMessage(stream)
|
||||
if err != nil {
|
||||
return fmt.Errorf("wait config ack: %w", err)
|
||||
}
|
||||
if ack.Type != protocol.MsgTypeProxyReady {
|
||||
return fmt.Errorf("unexpected ack type: %d", ack.Type)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// registerClient 注册客户端
|
||||
@@ -484,8 +514,8 @@ func (s *Server) acceptProxyConns(cs *ClientSession, ln net.Listener, rule proto
|
||||
func (s *Server) acceptProxyServerConns(cs *ClientSession, ln net.Listener, rule protocol.ProxyRule) {
|
||||
dialer := proxy.NewTunnelDialer(cs.Session)
|
||||
|
||||
// 使用内置 proxy 实现
|
||||
proxyServer := proxy.NewServer(rule.Type, dialer)
|
||||
// 使用内置 proxy 实现 (带流量统计)
|
||||
proxyServer := proxy.NewServer(rule.Type, dialer, s.recordTraffic)
|
||||
for {
|
||||
conn, err := ln.Accept()
|
||||
if err != nil {
|
||||
@@ -512,7 +542,7 @@ func (s *Server) handleProxyConn(cs *ClientSession, conn net.Conn, rule protocol
|
||||
return
|
||||
}
|
||||
|
||||
relay.Relay(conn, stream)
|
||||
relay.RelayWithStats(conn, stream, s.recordTraffic)
|
||||
}
|
||||
|
||||
// heartbeatLoop 心跳检测循环
|
||||
@@ -573,16 +603,24 @@ func (s *Server) sendHeartbeat(cs *ClientSession) bool {
|
||||
}
|
||||
|
||||
// GetClientStatus 获取客户端状态
|
||||
func (s *Server) GetClientStatus(clientID string) (online bool, lastPing, remoteAddr, clientOS, clientArch, clientVersion string) {
|
||||
func (s *Server) GetClientStatus(clientID string) (online bool, lastPing, remoteAddr, clientName, clientOS, clientArch, clientVersion string) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
if cs, ok := s.clients[clientID]; ok {
|
||||
cs.mu.Lock()
|
||||
defer cs.mu.Unlock()
|
||||
return true, cs.LastPing.Format(time.RFC3339), cs.RemoteAddr, cs.OS, cs.Arch, cs.Version
|
||||
return true, cs.LastPing.Format(time.RFC3339), cs.RemoteAddr, cs.Name, cs.OS, cs.Arch, cs.Version
|
||||
}
|
||||
return false, "", "", "", "", ""
|
||||
return false, "", "", "", "", "", ""
|
||||
}
|
||||
|
||||
// IsClientOnline 检查客户端是否在线
|
||||
func (s *Server) IsClientOnline(clientID string) bool {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
_, ok := s.clients[clientID]
|
||||
return ok
|
||||
}
|
||||
|
||||
// GetClientPluginStatus 获取客户端插件运行状态
|
||||
@@ -633,6 +671,7 @@ func (s *Server) GetAllClientStatus() map[string]struct {
|
||||
Online bool
|
||||
LastPing string
|
||||
RemoteAddr string
|
||||
Name string
|
||||
OS string
|
||||
Arch string
|
||||
Version string
|
||||
@@ -649,6 +688,7 @@ func (s *Server) GetAllClientStatus() map[string]struct {
|
||||
Online bool
|
||||
LastPing string
|
||||
RemoteAddr string
|
||||
Name string
|
||||
OS string
|
||||
Arch string
|
||||
Version string
|
||||
@@ -660,6 +700,7 @@ func (s *Server) GetAllClientStatus() map[string]struct {
|
||||
Online bool
|
||||
LastPing string
|
||||
RemoteAddr string
|
||||
Name string
|
||||
OS string
|
||||
Arch string
|
||||
Version string
|
||||
@@ -667,6 +708,7 @@ func (s *Server) GetAllClientStatus() map[string]struct {
|
||||
Online: true,
|
||||
LastPing: cs.LastPing.Format(time.RFC3339),
|
||||
RemoteAddr: cs.RemoteAddr,
|
||||
Name: cs.Name,
|
||||
OS: cs.OS,
|
||||
Arch: cs.Arch,
|
||||
Version: cs.Version,
|
||||
@@ -921,6 +963,9 @@ func (s *Server) sendUDPPacket(cs *ClientSession, conn *net.UDPConn, clientAddr
|
||||
return
|
||||
}
|
||||
|
||||
// 记录入站流量 (从外部接收的数据)
|
||||
s.recordTraffic(int64(len(packet.Data)), 0)
|
||||
|
||||
// 等待客户端响应
|
||||
respMsg, err := protocol.ReadMessage(stream)
|
||||
if err != nil {
|
||||
@@ -933,6 +978,8 @@ func (s *Server) sendUDPPacket(cs *ClientSession, conn *net.UDPConn, clientAddr
|
||||
return
|
||||
}
|
||||
conn.WriteToUDP(respPacket.Data, clientAddr)
|
||||
// 记录出站流量 (发送回外部的数据)
|
||||
s.recordTraffic(0, int64(len(respPacket.Data)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1188,7 +1235,7 @@ func (s *Server) handleClientPluginConn(cs *ClientSession, conn net.Conn, rule p
|
||||
}
|
||||
}
|
||||
|
||||
relay.Relay(conn, stream)
|
||||
relay.RelayWithStats(conn, stream, s.recordTraffic)
|
||||
}
|
||||
|
||||
// checkHTTPBasicAuth 检查 HTTP Basic Auth
|
||||
@@ -1871,6 +1918,16 @@ func (s *Server) StopClientLogStream(sessionID string) {
|
||||
s.logSessions.RemoveSession(sessionID)
|
||||
}
|
||||
|
||||
// recordTraffic 记录流量统计
|
||||
func (s *Server) recordTraffic(inbound, outbound int64) {
|
||||
if s.trafficStore == nil {
|
||||
return
|
||||
}
|
||||
if err := s.trafficStore.AddTraffic(inbound, outbound); err != nil {
|
||||
log.Printf("[Server] Record traffic error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// boolPtr 返回 bool 值的指针
|
||||
func boolPtr(b bool) *bool {
|
||||
return &b
|
||||
@@ -1918,3 +1975,101 @@ func (s *Server) GetClientSystemStats(clientID string) (*protocol.SystemStatsRes
|
||||
|
||||
return &stats, nil
|
||||
}
|
||||
|
||||
// GetClientScreenshot 获取客户端截图
|
||||
func (s *Server) GetClientScreenshot(clientID string, quality int) (*protocol.ScreenshotResponse, error) {
|
||||
s.mu.RLock()
|
||||
cs, ok := s.clients[clientID]
|
||||
s.mu.RUnlock()
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("client %s not online", clientID)
|
||||
}
|
||||
|
||||
stream, err := cs.Session.Open()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer stream.Close()
|
||||
|
||||
// 设置超时
|
||||
stream.SetDeadline(time.Now().Add(15 * time.Second))
|
||||
|
||||
// 发送请求
|
||||
req := protocol.ScreenshotRequest{Quality: quality}
|
||||
msg, _ := protocol.NewMessage(protocol.MsgTypeScreenshotRequest, req)
|
||||
if err := protocol.WriteMessage(stream, msg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 读取响应
|
||||
resp, err := protocol.ReadMessage(stream)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.Type != protocol.MsgTypeScreenshotResponse {
|
||||
return nil, fmt.Errorf("unexpected response type: %d", resp.Type)
|
||||
}
|
||||
|
||||
var screenshot protocol.ScreenshotResponse
|
||||
if err := resp.ParsePayload(&screenshot); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if screenshot.Error != "" {
|
||||
return nil, fmt.Errorf("screenshot failed: %s", screenshot.Error)
|
||||
}
|
||||
|
||||
return &screenshot, nil
|
||||
}
|
||||
|
||||
// ExecuteClientShell 执行客户端 Shell 命令
|
||||
func (s *Server) ExecuteClientShell(clientID, command string, timeout int) (*protocol.ShellExecuteResponse, error) {
|
||||
s.mu.RLock()
|
||||
cs, ok := s.clients[clientID]
|
||||
s.mu.RUnlock()
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("client %s not online", clientID)
|
||||
}
|
||||
|
||||
stream, err := cs.Session.Open()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer stream.Close()
|
||||
|
||||
// 设置超时 (比命令超时长一点)
|
||||
if timeout <= 0 {
|
||||
timeout = 30
|
||||
}
|
||||
stream.SetDeadline(time.Now().Add(time.Duration(timeout+5) * time.Second))
|
||||
|
||||
// 发送请求
|
||||
req := protocol.ShellExecuteRequest{
|
||||
Command: command,
|
||||
Timeout: timeout,
|
||||
}
|
||||
msg, _ := protocol.NewMessage(protocol.MsgTypeShellExecuteRequest, req)
|
||||
if err := protocol.WriteMessage(stream, msg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 读取响应
|
||||
resp, err := protocol.ReadMessage(stream)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.Type != protocol.MsgTypeShellExecuteResponse {
|
||||
return nil, fmt.Errorf("unexpected response type: %d", resp.Type)
|
||||
}
|
||||
|
||||
var result protocol.ShellExecuteResponse
|
||||
if err := resp.ParsePayload(&result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
@@ -142,5 +142,5 @@ func (s *Server) handleWebsocketProxyConn(cs *ClientSession, conn net.Conn, rule
|
||||
return
|
||||
}
|
||||
|
||||
relay.Relay(conn, stream)
|
||||
relay.RelayWithStats(conn, stream, s.recordTraffic)
|
||||
}
|
||||
|
||||
@@ -75,6 +75,14 @@ const (
|
||||
// 系统状态消息
|
||||
MsgTypeSystemStatsRequest uint8 = 100 // 请求系统状态
|
||||
MsgTypeSystemStatsResponse uint8 = 101 // 系统状态响应
|
||||
|
||||
// 截图消息
|
||||
MsgTypeScreenshotRequest uint8 = 102 // 请求截图
|
||||
MsgTypeScreenshotResponse uint8 = 103 // 截图响应
|
||||
|
||||
// Shell 执行消息
|
||||
MsgTypeShellExecuteRequest uint8 = 104 // 执行 Shell 命令
|
||||
MsgTypeShellExecuteResponse uint8 = 105 // Shell 执行结果
|
||||
)
|
||||
|
||||
// Message 基础消息结构
|
||||
@@ -87,6 +95,7 @@ type Message struct {
|
||||
type AuthRequest struct {
|
||||
ClientID string `json:"client_id"`
|
||||
Token string `json:"token"`
|
||||
Name string `json:"name,omitempty"` // 客户端名称(主机名)
|
||||
OS string `json:"os,omitempty"` // 客户端操作系统
|
||||
Arch string `json:"arch,omitempty"` // 客户端架构
|
||||
Version string `json:"version,omitempty"` // 客户端版本
|
||||
@@ -460,3 +469,30 @@ type SystemStatsResponse struct {
|
||||
DiskUsed uint64 `json:"disk_used"` // 已用磁盘 (字节)
|
||||
DiskUsage float64 `json:"disk_usage"` // 磁盘使用率 (0-100)
|
||||
}
|
||||
|
||||
// ScreenshotRequest 截图请求
|
||||
type ScreenshotRequest struct {
|
||||
Quality int `json:"quality"` // JPEG 质量 1-100, 0 使用默认值
|
||||
}
|
||||
|
||||
// ScreenshotResponse 截图响应
|
||||
type ScreenshotResponse struct {
|
||||
Data string `json:"data"` // Base64 编码的 JPEG 图片
|
||||
Width int `json:"width"` // 图片宽度
|
||||
Height int `json:"height"` // 图片高度
|
||||
Timestamp int64 `json:"timestamp"` // 截图时间戳
|
||||
Error string `json:"error,omitempty"` // 错误信息
|
||||
}
|
||||
|
||||
// ShellExecuteRequest Shell 执行请求
|
||||
type ShellExecuteRequest struct {
|
||||
Command string `json:"command"` // 要执行的命令
|
||||
Timeout int `json:"timeout"` // 超时秒数, 0 使用默认值 (30秒)
|
||||
}
|
||||
|
||||
// ShellExecuteResponse Shell 执行响应
|
||||
type ShellExecuteResponse struct {
|
||||
Output string `json:"output"` // stdout + stderr 组合输出
|
||||
ExitCode int `json:"exit_code"` // 进程退出码
|
||||
Error string `json:"error,omitempty"` // 错误信息
|
||||
}
|
||||
|
||||
@@ -6,16 +6,19 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gotunnel/pkg/relay"
|
||||
)
|
||||
|
||||
// HTTPServer HTTP 代理服务
|
||||
type HTTPServer struct {
|
||||
dialer Dialer
|
||||
dialer Dialer
|
||||
onStats func(in, out int64) // 流量统计回调
|
||||
}
|
||||
|
||||
// NewHTTPServer 创建 HTTP 代理服务
|
||||
func NewHTTPServer(dialer Dialer) *HTTPServer {
|
||||
return &HTTPServer{dialer: dialer}
|
||||
func NewHTTPServer(dialer Dialer, onStats func(in, out int64)) *HTTPServer {
|
||||
return &HTTPServer{dialer: dialer, onStats: onStats}
|
||||
}
|
||||
|
||||
// HandleConn 处理 HTTP 代理连接
|
||||
@@ -50,8 +53,8 @@ func (h *HTTPServer) handleConnect(conn net.Conn, req *http.Request) error {
|
||||
|
||||
conn.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n"))
|
||||
|
||||
go io.Copy(remote, conn)
|
||||
io.Copy(conn, remote)
|
||||
// 双向转发 (带流量统计)
|
||||
relay.RelayWithStats(conn, remote, h.onStats)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -82,7 +85,10 @@ func (h *HTTPServer) handleHTTP(conn net.Conn, req *http.Request, reader *bufio.
|
||||
return err
|
||||
}
|
||||
|
||||
// 转发响应
|
||||
_, err = io.Copy(conn, remote)
|
||||
// 转发响应 (带流量统计)
|
||||
n, err := io.Copy(conn, remote)
|
||||
if h.onStats != nil && n > 0 {
|
||||
h.onStats(0, n) // 响应数据为出站流量
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -14,10 +14,10 @@ type Server struct {
|
||||
}
|
||||
|
||||
// NewServer 创建代理服务器
|
||||
func NewServer(typ string, dialer Dialer) *Server {
|
||||
func NewServer(typ string, dialer Dialer, onStats func(in, out int64)) *Server {
|
||||
return &Server{
|
||||
socks5: NewSOCKS5Server(dialer),
|
||||
http: NewHTTPServer(dialer),
|
||||
socks5: NewSOCKS5Server(dialer, onStats),
|
||||
http: NewHTTPServer(dialer, onStats),
|
||||
typ: typ,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
|
||||
"github.com/gotunnel/pkg/relay"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -19,7 +21,8 @@ const (
|
||||
|
||||
// SOCKS5Server SOCKS5 代理服务
|
||||
type SOCKS5Server struct {
|
||||
dialer Dialer
|
||||
dialer Dialer
|
||||
onStats func(in, out int64) // 流量统计回调
|
||||
}
|
||||
|
||||
// Dialer 连接拨号器接口
|
||||
@@ -28,8 +31,8 @@ type Dialer interface {
|
||||
}
|
||||
|
||||
// NewSOCKS5Server 创建 SOCKS5 服务
|
||||
func NewSOCKS5Server(dialer Dialer) *SOCKS5Server {
|
||||
return &SOCKS5Server{dialer: dialer}
|
||||
func NewSOCKS5Server(dialer Dialer, onStats func(in, out int64)) *SOCKS5Server {
|
||||
return &SOCKS5Server{dialer: dialer, onStats: onStats}
|
||||
}
|
||||
|
||||
// HandleConn 处理 SOCKS5 连接
|
||||
@@ -60,9 +63,8 @@ func (s *SOCKS5Server) HandleConn(conn net.Conn) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// 双向转发
|
||||
go io.Copy(remote, conn)
|
||||
io.Copy(conn, remote)
|
||||
// 双向转发 (带流量统计)
|
||||
relay.RelayWithStats(conn, remote, s.onStats)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
98
pkg/utils/screenshot.go
Normal file
98
pkg/utils/screenshot.go
Normal file
@@ -0,0 +1,98 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
|
||||
"github.com/kbinani/screenshot"
|
||||
)
|
||||
|
||||
// CaptureScreenshot 捕获主屏幕截图
|
||||
// quality: JPEG 质量 (1-100), 0 使用默认值 (75)
|
||||
// 返回: JPEG 图片数据, 宽度, 高度, 错误
|
||||
func CaptureScreenshot(quality int) ([]byte, int, int, error) {
|
||||
// 默认质量
|
||||
if quality <= 0 || quality > 100 {
|
||||
quality = 75
|
||||
}
|
||||
|
||||
// 获取活动显示器数量
|
||||
n := screenshot.NumActiveDisplays()
|
||||
if n == 0 {
|
||||
return nil, 0, 0, fmt.Errorf("no active display found")
|
||||
}
|
||||
|
||||
// 获取主显示器边界
|
||||
bounds := screenshot.GetDisplayBounds(0)
|
||||
if bounds.Empty() {
|
||||
return nil, 0, 0, fmt.Errorf("failed to get display bounds")
|
||||
}
|
||||
|
||||
// 捕获屏幕
|
||||
img, err := screenshot.CaptureRect(bounds)
|
||||
if err != nil {
|
||||
return nil, 0, 0, fmt.Errorf("capture screen: %w", err)
|
||||
}
|
||||
|
||||
// 编码为 JPEG
|
||||
var buf bytes.Buffer
|
||||
opts := &jpeg.Options{Quality: quality}
|
||||
if err := jpeg.Encode(&buf, img, opts); err != nil {
|
||||
return nil, 0, 0, fmt.Errorf("encode jpeg: %w", err)
|
||||
}
|
||||
|
||||
return buf.Bytes(), bounds.Dx(), bounds.Dy(), nil
|
||||
}
|
||||
|
||||
// CaptureAllScreens 捕获所有屏幕并拼接
|
||||
// quality: JPEG 质量 (1-100), 0 使用默认值 (75)
|
||||
// 返回: JPEG 图片数据, 宽度, 高度, 错误
|
||||
func CaptureAllScreens(quality int) ([]byte, int, int, error) {
|
||||
// 默认质量
|
||||
if quality <= 0 || quality > 100 {
|
||||
quality = 75
|
||||
}
|
||||
|
||||
// 获取活动显示器数量
|
||||
n := screenshot.NumActiveDisplays()
|
||||
if n == 0 {
|
||||
return nil, 0, 0, fmt.Errorf("no active display found")
|
||||
}
|
||||
|
||||
// 计算所有屏幕的总边界
|
||||
var totalBounds image.Rectangle
|
||||
for i := 0; i < n; i++ {
|
||||
bounds := screenshot.GetDisplayBounds(i)
|
||||
totalBounds = totalBounds.Union(bounds)
|
||||
}
|
||||
|
||||
// 创建总画布
|
||||
totalImg := image.NewRGBA(totalBounds)
|
||||
|
||||
// 捕获每个屏幕并绘制到总画布
|
||||
for i := 0; i < n; i++ {
|
||||
bounds := screenshot.GetDisplayBounds(i)
|
||||
img, err := screenshot.CaptureRect(bounds)
|
||||
if err != nil {
|
||||
continue // 跳过失败的屏幕
|
||||
}
|
||||
|
||||
// 绘制到总画布
|
||||
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
|
||||
for x := bounds.Min.X; x < bounds.Max.X; x++ {
|
||||
totalImg.Set(x, y, img.At(x-bounds.Min.X, y-bounds.Min.Y))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 编码为 JPEG
|
||||
var buf bytes.Buffer
|
||||
opts := &jpeg.Options{Quality: quality}
|
||||
if err := jpeg.Encode(&buf, totalImg, opts); err != nil {
|
||||
return nil, 0, 0, fmt.Errorf("encode jpeg: %w", err)
|
||||
}
|
||||
|
||||
return buf.Bytes(), totalBounds.Dx(), totalBounds.Dy(), nil
|
||||
}
|
||||
@@ -209,6 +209,28 @@ export interface SystemStats {
|
||||
|
||||
export const getClientSystemStats = (clientId: string) => get<SystemStats>(`/client/${clientId}/system-stats`)
|
||||
|
||||
// 客户端截图
|
||||
export interface ScreenshotData {
|
||||
data: string // Base64 JPEG
|
||||
width: number
|
||||
height: number
|
||||
timestamp: number
|
||||
error?: string
|
||||
}
|
||||
|
||||
export const getClientScreenshot = (clientId: string, quality?: number) =>
|
||||
get<ScreenshotData>(`/client/${clientId}/screenshot${quality ? '?quality=' + quality : ''}`)
|
||||
|
||||
// Shell 执行
|
||||
export interface ShellResult {
|
||||
output: string
|
||||
exit_code: number
|
||||
error?: string
|
||||
}
|
||||
|
||||
export const executeClientShell = (clientId: string, command: string, timeout?: number) =>
|
||||
post<ShellResult>(`/client/${clientId}/shell`, { command, timeout: timeout || 30 })
|
||||
|
||||
// 服务器配置
|
||||
export interface ServerConfigInfo {
|
||||
bind_addr: string
|
||||
|
||||
@@ -134,9 +134,9 @@ onUnmounted(() => {
|
||||
|
||||
<style scoped>
|
||||
.inline-log-panel {
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
background: var(--glass-bg);
|
||||
border-radius: 12px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border: 1px solid var(--color-border);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
@@ -145,8 +145,8 @@ onUnmounted(() => {
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 12px 16px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
background: var(--glass-bg-light);
|
||||
}
|
||||
|
||||
.toolbar-left {
|
||||
@@ -158,7 +158,7 @@ onUnmounted(() => {
|
||||
.log-title {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: white;
|
||||
color: var(--color-text-primary);
|
||||
}
|
||||
|
||||
.streaming-badge {
|
||||
@@ -166,8 +166,8 @@ onUnmounted(() => {
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 11px;
|
||||
color: #34d399;
|
||||
background: rgba(52, 211, 153, 0.15);
|
||||
color: var(--color-success);
|
||||
background: rgba(16, 185, 129, 0.15);
|
||||
padding: 2px 8px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
@@ -176,7 +176,7 @@ onUnmounted(() => {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: #34d399;
|
||||
background: var(--color-success);
|
||||
animation: pulse 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@@ -192,11 +192,11 @@ onUnmounted(() => {
|
||||
}
|
||||
|
||||
.tool-btn {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
background: var(--color-border);
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
padding: 6px;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
color: var(--color-text-secondary);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
display: flex;
|
||||
@@ -205,8 +205,8 @@ onUnmounted(() => {
|
||||
}
|
||||
|
||||
.tool-btn:hover {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
color: white;
|
||||
background: var(--color-bg-elevated);
|
||||
color: var(--color-text-primary);
|
||||
}
|
||||
|
||||
.tool-icon {
|
||||
@@ -219,14 +219,14 @@ onUnmounted(() => {
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
color: var(--color-text-secondary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.auto-scroll-toggle input {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
accent-color: #a78bfa;
|
||||
accent-color: var(--color-accent);
|
||||
}
|
||||
|
||||
.log-content {
|
||||
@@ -235,6 +235,7 @@ onUnmounted(() => {
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
background: var(--color-bg-elevated);
|
||||
}
|
||||
|
||||
.log-loading,
|
||||
@@ -243,7 +244,7 @@ onUnmounted(() => {
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
color: var(--color-text-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
@@ -259,7 +260,7 @@ onUnmounted(() => {
|
||||
}
|
||||
|
||||
.log-time {
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
color: var(--color-text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
@@ -269,12 +270,12 @@ onUnmounted(() => {
|
||||
}
|
||||
|
||||
.log-src {
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
color: var(--color-text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.log-msg {
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
color: var(--color-text-secondary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
@@ -289,11 +290,11 @@ onUnmounted(() => {
|
||||
}
|
||||
|
||||
.log-content::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
background: var(--color-border);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.log-content::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(255, 255, 255, 0.3);
|
||||
background: var(--color-text-muted);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -3,8 +3,9 @@ import { ref, onMounted, onUnmounted } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
ArrowBackOutline, CreateOutline, TrashOutline,
|
||||
PushOutline, AddOutline, StorefrontOutline, DocumentTextOutline,
|
||||
ExtensionPuzzleOutline, SettingsOutline, RefreshOutline
|
||||
PushOutline, AddOutline, StorefrontOutline,
|
||||
ExtensionPuzzleOutline, SettingsOutline, RefreshOutline,
|
||||
PlayOutline
|
||||
} from '@vicons/ionicons5'
|
||||
import GlassModal from '../components/GlassModal.vue'
|
||||
import GlassTag from '../components/GlassTag.vue'
|
||||
@@ -15,10 +16,11 @@ import {
|
||||
getClient, updateClient, deleteClient, pushConfigToClient, disconnectClient, restartClient,
|
||||
getClientPluginConfig, updateClientPluginConfig,
|
||||
getStorePlugins, installStorePlugin, getRuleSchemas, startClientPlugin, restartClientPlugin, stopClientPlugin, deleteClientPlugin,
|
||||
checkClientUpdate, applyClientUpdate, getClientSystemStats, type UpdateInfo, type SystemStats
|
||||
checkClientUpdate, applyClientUpdate, getClientSystemStats, getVersionInfo,
|
||||
getClientScreenshot, executeClientShell,
|
||||
type UpdateInfo, type SystemStats, type ScreenshotData
|
||||
} from '../api'
|
||||
import type { ProxyRule, ClientPlugin, ConfigField, StorePluginInfo, RuleSchemasMap } from '../types'
|
||||
import LogViewer from '../components/LogViewer.vue'
|
||||
import InlineLogPanel from '../components/InlineLogPanel.vue'
|
||||
|
||||
const route = useRoute()
|
||||
@@ -42,10 +44,26 @@ const clientVersion = ref('')
|
||||
// 客户端更新相关
|
||||
const clientUpdate = ref<UpdateInfo | null>(null)
|
||||
const updatingClient = ref(false)
|
||||
const serverVersion = ref('')
|
||||
|
||||
// 系统状态相关
|
||||
const systemStats = ref<SystemStats | null>(null)
|
||||
const loadingStats = ref(false)
|
||||
// 系统状态相关
|
||||
const systemStats = ref<SystemStats | null>(null)
|
||||
const loadingStats = ref(false)
|
||||
|
||||
// 截图相关
|
||||
const screenshotData = ref<ScreenshotData | null>(null)
|
||||
const loadingScreenshot = ref(false)
|
||||
const autoRefreshScreenshot = ref(false)
|
||||
const screenshotInterval = ref(5) // 默认 5s
|
||||
const screenshotTimer = ref<number | null>(null)
|
||||
|
||||
// Shell 相关
|
||||
const shellCommand = ref('')
|
||||
const shellOutput = ref('')
|
||||
const executingShell = ref(false)
|
||||
const shellHistory = ref<string[]>([])
|
||||
const historyIndex = ref(-1)
|
||||
|
||||
// Rule Schemas
|
||||
const pluginRuleSchemas = ref<RuleSchemasMap>({})
|
||||
@@ -94,6 +112,61 @@ const getExtraFields = (type: string): ConfigField[] => {
|
||||
return schema?.extra_fields || []
|
||||
}
|
||||
|
||||
// 加载服务端版本
|
||||
const loadServerVersion = async () => {
|
||||
try {
|
||||
const { data } = await getVersionInfo()
|
||||
serverVersion.value = data.version || ''
|
||||
} catch (e) {
|
||||
console.error('Failed to load server version', e)
|
||||
}
|
||||
}
|
||||
|
||||
// 版本比较函数:返回 -1 (v1 < v2), 0 (v1 == v2), 1 (v1 > v2)
|
||||
const compareVersions = (v1: string, v2: string): number => {
|
||||
const normalize = (v: string) => v.replace(/^v/, '').split('.').map(n => parseInt(n, 10) || 0)
|
||||
const parts1 = normalize(v1)
|
||||
const parts2 = normalize(v2)
|
||||
const len = Math.max(parts1.length, parts2.length)
|
||||
for (let i = 0; i < len; i++) {
|
||||
const p1 = parts1[i] || 0
|
||||
const p2 = parts2[i] || 0
|
||||
if (p1 < p2) return -1
|
||||
if (p1 > p2) return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// 判断客户端是否需要更新
|
||||
// 逻辑:如果客户端最新版>=服务端版本,则目标版本为服务端版本;否则为客户端最新版
|
||||
const needsUpdate = (): boolean => {
|
||||
if (!clientUpdate.value?.latest || !clientVersion.value) return false
|
||||
const latestClientVer = clientUpdate.value.latest
|
||||
const currentClientVer = clientVersion.value
|
||||
const serverVer = serverVersion.value
|
||||
|
||||
// 确定目标版本
|
||||
let targetVersion = latestClientVer
|
||||
if (serverVer && compareVersions(latestClientVer, serverVer) >= 0) {
|
||||
targetVersion = serverVer
|
||||
}
|
||||
|
||||
// 比较当前客户端版本和目标版本
|
||||
return compareVersions(currentClientVer, targetVersion) < 0
|
||||
}
|
||||
|
||||
// 获取目标更新版本
|
||||
const getTargetVersion = (): string => {
|
||||
if (!clientUpdate.value?.latest) return ''
|
||||
const latestClientVer = clientUpdate.value.latest
|
||||
const serverVer = serverVersion.value
|
||||
|
||||
if (serverVer && compareVersions(latestClientVer, serverVer) >= 0) {
|
||||
return serverVer
|
||||
}
|
||||
return latestClientVer
|
||||
}
|
||||
|
||||
// Actions
|
||||
const loadClient = async () => {
|
||||
loading.value = true
|
||||
@@ -146,6 +219,90 @@ const loadSystemStats = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
// 截图相关方法
|
||||
const loadScreenshot = async () => {
|
||||
if (!online.value) return
|
||||
loadingScreenshot.value = true
|
||||
try {
|
||||
const { data } = await getClientScreenshot(clientId, 70) // 默认质量 70
|
||||
screenshotData.value = data
|
||||
} catch (e: any) {
|
||||
message.error(e.response?.data?.message || '获取截图失败')
|
||||
} finally {
|
||||
loadingScreenshot.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const toggleAutoRefresh = () => {
|
||||
if (autoRefreshScreenshot.value) {
|
||||
// 开启自动刷新
|
||||
loadScreenshot()
|
||||
screenshotTimer.value = window.setInterval(loadScreenshot, screenshotInterval.value * 1000)
|
||||
} else {
|
||||
// 关闭自动刷新
|
||||
if (screenshotTimer.value) {
|
||||
clearInterval(screenshotTimer.value)
|
||||
screenshotTimer.value = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Shell 相关方法
|
||||
const executeShell = async () => {
|
||||
if (!shellCommand.value.trim()) return
|
||||
|
||||
const cmd = shellCommand.value.trim()
|
||||
shellCommand.value = ''
|
||||
executingShell.value = true
|
||||
|
||||
// 添加到历史记录
|
||||
shellHistory.value.unshift(cmd)
|
||||
if (shellHistory.value.length > 50) shellHistory.value.pop()
|
||||
historyIndex.value = -1
|
||||
|
||||
shellOutput.value += `\n> ${cmd}\n`
|
||||
|
||||
try {
|
||||
const { data } = await executeClientShell(clientId, cmd)
|
||||
if (data.error) {
|
||||
shellOutput.value += `Error: ${data.error}\n`
|
||||
} else {
|
||||
shellOutput.value += data.output + '\n'
|
||||
}
|
||||
if (data.exit_code !== 0) {
|
||||
shellOutput.value += `Exit Code: ${data.exit_code}\n`
|
||||
}
|
||||
} catch (e: any) {
|
||||
shellOutput.value += `Error: ${e.message}\n`
|
||||
} finally {
|
||||
executingShell.value = false
|
||||
// 滚动到底部 (需要 nextTick 和 ref)
|
||||
setTimeout(() => {
|
||||
const textarea = document.getElementById('shell-output')
|
||||
if (textarea) textarea.scrollTop = textarea.scrollHeight
|
||||
}, 100)
|
||||
}
|
||||
}
|
||||
|
||||
const handleShellHistory = (direction: 'up' | 'down') => {
|
||||
if (shellHistory.value.length === 0) return
|
||||
|
||||
if (direction === 'up') {
|
||||
if (historyIndex.value < shellHistory.value.length - 1) {
|
||||
historyIndex.value++
|
||||
shellCommand.value = shellHistory.value[historyIndex.value] || ''
|
||||
}
|
||||
} else {
|
||||
if (historyIndex.value > 0) {
|
||||
historyIndex.value--
|
||||
shellCommand.value = shellHistory.value[historyIndex.value] || ''
|
||||
} else if (historyIndex.value === 0) {
|
||||
historyIndex.value = -1
|
||||
shellCommand.value = ''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 格式化字节大小
|
||||
const formatBytes = (bytes: number): string => {
|
||||
if (bytes === 0) return '0 B'
|
||||
@@ -441,6 +598,7 @@ const pollTimer = ref<number | null>(null)
|
||||
|
||||
onMounted(() => {
|
||||
loadRuleSchemas()
|
||||
loadServerVersion()
|
||||
loadClient()
|
||||
// 启动自动轮询,每 5 秒刷新一次
|
||||
pollTimer.value = window.setInterval(() => {
|
||||
@@ -455,9 +613,6 @@ onUnmounted(() => {
|
||||
}
|
||||
})
|
||||
|
||||
// Log Viewer
|
||||
const showLogViewer = ref(false)
|
||||
|
||||
// Plugin Menu
|
||||
const activePluginMenu = ref('')
|
||||
const togglePluginMenu = (pluginId: string) => {
|
||||
@@ -520,10 +675,6 @@ const handleDeletePlugin = (plugin: ClientPlugin) => {
|
||||
<PushOutline class="btn-icon" />
|
||||
<span>推送配置</span>
|
||||
</button>
|
||||
<button class="glass-btn" @click="showLogViewer=true">
|
||||
<DocumentTextOutline class="btn-icon" />
|
||||
<span>日志</span>
|
||||
</button>
|
||||
<button class="glass-btn danger" @click="confirmDelete">
|
||||
<TrashOutline class="btn-icon" />
|
||||
<span>删除</span>
|
||||
@@ -557,10 +708,10 @@ const handleDeletePlugin = (plugin: ClientPlugin) => {
|
||||
<span class="stat-label">客户端版本</span>
|
||||
<span class="stat-value">
|
||||
{{ clientVersion || '-' }}
|
||||
<span v-if="clientUpdate?.available" class="update-badge" @click="handleApplyClientUpdate">
|
||||
可更新
|
||||
<span v-if="needsUpdate()" class="update-badge" @click="handleApplyClientUpdate">
|
||||
可更新 → {{ getTargetVersion() }}
|
||||
</span>
|
||||
<span v-else-if="clientUpdate && !clientUpdate.available" class="latest-badge">
|
||||
<span v-else-if="clientVersion" class="latest-badge">
|
||||
最新版本
|
||||
</span>
|
||||
</span>
|
||||
@@ -602,11 +753,12 @@ const handleDeletePlugin = (plugin: ClientPlugin) => {
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div v-if="!systemStats" class="empty-hint">
|
||||
{{ loadingStats ? '加载中...' : '点击刷新获取状态' }}
|
||||
</div>
|
||||
<template v-else>
|
||||
<div class="card-body system-stats-body">
|
||||
<Transition name="fade-slide" mode="out-in">
|
||||
<div v-if="!systemStats" class="empty-hint" key="empty">
|
||||
{{ loadingStats ? '加载中...' : '点击刷新获取状态' }}
|
||||
</div>
|
||||
<div v-else class="system-stats-content" key="stats">
|
||||
<div class="system-stat-item">
|
||||
<span class="system-stat-label">CPU</span>
|
||||
<div class="progress-bar">
|
||||
@@ -634,7 +786,64 @@ const handleDeletePlugin = (plugin: ClientPlugin) => {
|
||||
<div class="system-stat-detail">
|
||||
{{ formatBytes(systemStats.disk_used) }} / {{ formatBytes(systemStats.disk_total) }}
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</Transition>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Screenshot Card -->
|
||||
<div class="glass-card" v-if="online">
|
||||
<div class="card-header">
|
||||
<h3>屏幕截图</h3>
|
||||
<div class="header-controls">
|
||||
<GlassSwitch :model-value="autoRefreshScreenshot" @update:model-value="(v: boolean) => { autoRefreshScreenshot = v; toggleAutoRefresh() }" size="small">
|
||||
自动刷新
|
||||
</GlassSwitch>
|
||||
<button class="glass-btn tiny" :disabled="loadingScreenshot" @click="loadScreenshot">
|
||||
<RefreshOutline class="btn-icon-sm" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body screenshot-body">
|
||||
<div class="screenshot-container" v-if="screenshotData">
|
||||
<img :src="`data:image/jpeg;base64,${screenshotData.data}`" alt="Screenshot" class="screenshot-img" />
|
||||
<div class="screenshot-meta">
|
||||
{{ new Date(screenshotData.timestamp).toLocaleTimeString() }} ({{ screenshotData.width }}x{{ screenshotData.height }})
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="empty-hint" @click="loadScreenshot">
|
||||
{{ loadingScreenshot ? '截图中...' : '点击获取截图' }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Shell Terminal Card -->
|
||||
<div class="glass-card" v-if="online">
|
||||
<div class="card-header">
|
||||
<h3>远程 Shell</h3>
|
||||
</div>
|
||||
<div class="card-body shell-body">
|
||||
<textarea
|
||||
id="shell-output"
|
||||
class="shell-output"
|
||||
readonly
|
||||
v-model="shellOutput"
|
||||
></textarea>
|
||||
<div class="shell-input-group">
|
||||
<input
|
||||
type="text"
|
||||
class="glass-input shell-input"
|
||||
v-model="shellCommand"
|
||||
@keydown.enter="executeShell"
|
||||
@keydown.up.prevent="handleShellHistory('up')"
|
||||
@keydown.down.prevent="handleShellHistory('down')"
|
||||
placeholder="输入命令..."
|
||||
:disabled="executingShell"
|
||||
/>
|
||||
<button class="glass-btn primary small" :disabled="executingShell" @click="executeShell">
|
||||
<PlayOutline class="btn-icon-sm" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -845,23 +1054,66 @@ const handleDeletePlugin = (plugin: ClientPlugin) => {
|
||||
<button class="glass-btn primary" @click="confirmInstallPlugin">确认安装</button>
|
||||
</template>
|
||||
</GlassModal>
|
||||
|
||||
<LogViewer :visible="showLogViewer" @close="showLogViewer = false" :client-id="clientId" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.client-page {
|
||||
min-height: calc(100vh - 108px);
|
||||
background: var(--color-bg-primary);
|
||||
background: transparent;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
padding: 32px;
|
||||
}
|
||||
|
||||
/* Hide particles */
|
||||
/* Particles */
|
||||
.particles {
|
||||
display: none;
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
overflow: hidden;
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.particle {
|
||||
position: absolute;
|
||||
border-radius: 50%;
|
||||
opacity: 0.15;
|
||||
filter: blur(60px);
|
||||
animation: float 20s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.particle-1 {
|
||||
width: 350px;
|
||||
height: 350px;
|
||||
background: var(--color-accent);
|
||||
top: -80px;
|
||||
right: -80px;
|
||||
}
|
||||
|
||||
.particle-2 {
|
||||
width: 280px;
|
||||
height: 280px;
|
||||
background: #8b5cf6;
|
||||
bottom: -40px;
|
||||
left: -40px;
|
||||
animation-delay: -5s;
|
||||
}
|
||||
|
||||
.particle-3 {
|
||||
width: 220px;
|
||||
height: 220px;
|
||||
background: var(--color-success);
|
||||
top: 40%;
|
||||
left: 30%;
|
||||
animation-delay: -10s;
|
||||
}
|
||||
|
||||
@keyframes float {
|
||||
0%, 100% { transform: translate(0, 0) scale(1); }
|
||||
25% { transform: translate(30px, -30px) scale(1.05); }
|
||||
50% { transform: translate(-20px, 20px) scale(0.95); }
|
||||
75% { transform: translate(-30px, -20px) scale(1.02); }
|
||||
}
|
||||
|
||||
.client-content {
|
||||
@@ -984,6 +1236,7 @@ const handleDeletePlugin = (plugin: ClientPlugin) => {
|
||||
display: grid;
|
||||
grid-template-columns: 300px 1fr;
|
||||
gap: 24px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
@@ -1467,6 +1720,115 @@ const handleDeletePlugin = (plugin: ClientPlugin) => {
|
||||
height: 16px;
|
||||
}
|
||||
|
||||
/* System Stats Transition */
|
||||
.system-stats-body {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.system-stats-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
|
||||
.fade-slide-enter-active,
|
||||
.fade-slide-leave-active {
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.fade-slide-enter-from,
|
||||
.fade-slide-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(-10px);
|
||||
}
|
||||
|
||||
/* Screenshot Card */
|
||||
.screenshot-body {
|
||||
padding: 0;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-height: 200px;
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
border-radius: 0 0 16px 16px;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.screenshot-container {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.screenshot-img {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.screenshot-meta {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
right: 0;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
color: #fff;
|
||||
padding: 4px 8px;
|
||||
font-size: 12px;
|
||||
border-top-left-radius: 8px;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
/* Shell Terminal Card */
|
||||
.shell-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.shell-output {
|
||||
width: 100%;
|
||||
height: 300px;
|
||||
background: #1a1a1a;
|
||||
color: #0f0;
|
||||
font-family: 'Consolas', 'Monaco', monospace;
|
||||
font-size: 13px;
|
||||
padding: 12px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
resize: vertical;
|
||||
overflow-y: auto;
|
||||
white-space: pre-wrap;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
|
||||
.shell-input-group {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.shell-input {
|
||||
flex: 1;
|
||||
font-family: 'Consolas', 'Monaco', monospace;
|
||||
}
|
||||
|
||||
.header-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
|
||||
.fade-slide-enter-from {
|
||||
opacity: 0;
|
||||
transform: translateY(-10px);
|
||||
}
|
||||
|
||||
.fade-slide-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
|
||||
/* System Stats */
|
||||
.system-stat-item {
|
||||
display: flex;
|
||||
@@ -1484,7 +1846,7 @@ const handleDeletePlugin = (plugin: ClientPlugin) => {
|
||||
.progress-bar {
|
||||
flex: 1;
|
||||
height: 8px;
|
||||
background: var(--color-bg-elevated);
|
||||
background: var(--color-border);
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
@@ -123,91 +123,84 @@ onMounted(() => {
|
||||
<div class="dashboard-content">
|
||||
<!-- Header -->
|
||||
<div class="dashboard-header">
|
||||
<h1 class="text-3xl font-bold text-white mb-2">仪表盘</h1>
|
||||
<p class="text-white/70">监控隧道连接和流量状态</p>
|
||||
<h1 class="dashboard-title">仪表盘</h1>
|
||||
<p class="dashboard-subtitle">监控隧道连接和流量状态</p>
|
||||
</div>
|
||||
|
||||
<!-- Stats Grid -->
|
||||
<div class="stats-grid">
|
||||
<!-- Outbound Traffic -->
|
||||
<!-- 24H Traffic Combined -->
|
||||
<div class="stat-card glass-stat">
|
||||
<div class="stat-icon outbound">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 11l5-5m0 0l5 5m-5-5v12" />
|
||||
<div class="stat-icon-large traffic-24h">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="icon-lg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
|
||||
</svg>
|
||||
</div>
|
||||
<div class="stat-content">
|
||||
<span class="stat-label">24h出站</span>
|
||||
<div class="stat-value-row">
|
||||
<span class="stat-value">{{ formatted24hOutbound.value }}</span>
|
||||
<span class="stat-unit-inline">{{ formatted24hOutbound.unit }}</span>
|
||||
<div class="stat-details">
|
||||
<div class="stat-row">
|
||||
<span class="stat-title">24H 出站</span>
|
||||
<div class="stat-data">
|
||||
<span class="stat-number">{{ formatted24hOutbound.value }}</span>
|
||||
<span class="stat-unit">{{ formatted24hOutbound.unit }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="stat-row">
|
||||
<span class="stat-title">24H 入站</span>
|
||||
<div class="stat-data">
|
||||
<span class="stat-number">{{ formatted24hInbound.value }}</span>
|
||||
<span class="stat-unit">{{ formatted24hInbound.unit }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Inbound Traffic -->
|
||||
<!-- Total Traffic Combined -->
|
||||
<div class="stat-card glass-stat">
|
||||
<div class="stat-icon inbound">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 13l-5 5m0 0l-5-5m5 5V6" />
|
||||
<div class="stat-icon-large traffic-total">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="icon-lg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
|
||||
</svg>
|
||||
</div>
|
||||
<div class="stat-content">
|
||||
<span class="stat-label">24h入站</span>
|
||||
<div class="stat-value-row">
|
||||
<span class="stat-value">{{ formatted24hInbound.value }}</span>
|
||||
<span class="stat-unit-inline">{{ formatted24hInbound.unit }}</span>
|
||||
<div class="stat-details">
|
||||
<div class="stat-row">
|
||||
<span class="stat-title">总出站</span>
|
||||
<div class="stat-data">
|
||||
<span class="stat-number">{{ formattedTotalOutbound.value }}</span>
|
||||
<span class="stat-unit">{{ formattedTotalOutbound.unit }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Total Outbound Traffic -->
|
||||
<div class="stat-card glass-stat">
|
||||
<div class="stat-icon total-out">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 11l5-5m0 0l5 5m-5-5v12" />
|
||||
</svg>
|
||||
</div>
|
||||
<div class="stat-content">
|
||||
<span class="stat-label">总出站</span>
|
||||
<div class="stat-value-row">
|
||||
<span class="stat-value">{{ formattedTotalOutbound.value }}</span>
|
||||
<span class="stat-unit-inline">{{ formattedTotalOutbound.unit }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Total Inbound Traffic -->
|
||||
<div class="stat-card glass-stat">
|
||||
<div class="stat-icon total-in">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 13l-5 5m0 0l-5-5m5 5V6" />
|
||||
</svg>
|
||||
</div>
|
||||
<div class="stat-content">
|
||||
<span class="stat-label">总入站</span>
|
||||
<div class="stat-value-row">
|
||||
<span class="stat-value">{{ formattedTotalInbound.value }}</span>
|
||||
<span class="stat-unit-inline">{{ formattedTotalInbound.unit }}</span>
|
||||
<div class="stat-row">
|
||||
<span class="stat-title">总入站</span>
|
||||
<div class="stat-data">
|
||||
<span class="stat-number">{{ formattedTotalInbound.value }}</span>
|
||||
<span class="stat-unit">{{ formattedTotalInbound.unit }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Client Count -->
|
||||
<div class="stat-card glass-stat">
|
||||
<div class="stat-icon clients">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<div class="stat-icon-large clients">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="icon-lg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z" />
|
||||
</svg>
|
||||
</div>
|
||||
<div class="stat-content">
|
||||
<span class="stat-label">客户端</span>
|
||||
<div class="client-count">
|
||||
<span class="stat-value online">{{ onlineClients }}</span>
|
||||
<span class="stat-separator">/</span>
|
||||
<span class="stat-value total">{{ clients.length }}</span>
|
||||
<div class="stat-details">
|
||||
<div class="stat-row">
|
||||
<span class="stat-title">在线客户端</span>
|
||||
<div class="stat-data">
|
||||
<span class="stat-number online">{{ onlineClients }}</span>
|
||||
<span class="stat-unit">个</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="stat-row">
|
||||
<span class="stat-title">总客户端</span>
|
||||
<div class="stat-data">
|
||||
<span class="stat-number">{{ clients.length }}</span>
|
||||
<span class="stat-unit">个</span>
|
||||
</div>
|
||||
</div>
|
||||
<span class="stat-unit">在线 / 总数</span>
|
||||
</div>
|
||||
<div class="online-indicator" :class="{ active: onlineClients > 0 }">
|
||||
<span class="pulse"></span>
|
||||
@@ -216,15 +209,19 @@ onMounted(() => {
|
||||
|
||||
<!-- Rules Count -->
|
||||
<div class="stat-card glass-stat">
|
||||
<div class="stat-icon rules">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<div class="stat-icon-large rules">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="icon-lg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16" />
|
||||
</svg>
|
||||
</div>
|
||||
<div class="stat-content">
|
||||
<span class="stat-label">代理规则</span>
|
||||
<span class="stat-value">{{ totalRules }}</span>
|
||||
<span class="stat-unit">条规则</span>
|
||||
<div class="stat-details">
|
||||
<div class="stat-row single">
|
||||
<span class="stat-title">代理规则</span>
|
||||
<div class="stat-data">
|
||||
<span class="stat-number">{{ totalRules }}</span>
|
||||
<span class="stat-unit">条</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -346,10 +343,23 @@ onMounted(() => {
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
|
||||
.dashboard-title {
|
||||
font-size: 28px;
|
||||
font-weight: 700;
|
||||
color: var(--color-text-primary);
|
||||
margin: 0 0 8px 0;
|
||||
}
|
||||
|
||||
.dashboard-subtitle {
|
||||
color: var(--color-text-secondary);
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
/* Stats Grid */
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 20px;
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
@@ -375,7 +385,7 @@ onMounted(() => {
|
||||
border: 1px solid var(--color-border);
|
||||
padding: 20px;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
position: relative;
|
||||
transition: all 0.2s ease;
|
||||
@@ -402,11 +412,11 @@ onMounted(() => {
|
||||
box-shadow: var(--shadow-lg), var(--shadow-glow);
|
||||
}
|
||||
|
||||
/* Stat icon */
|
||||
.stat-icon {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 12px;
|
||||
/* Large Stat icon */
|
||||
.stat-icon-large {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
border-radius: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -414,110 +424,71 @@ onMounted(() => {
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.stat-icon.outbound {
|
||||
.stat-icon-large.traffic-24h {
|
||||
background: var(--gradient-accent);
|
||||
}
|
||||
|
||||
.stat-icon.inbound {
|
||||
.stat-icon-large.traffic-total {
|
||||
background: linear-gradient(135deg, #8b5cf6 0%, #a78bfa 100%);
|
||||
}
|
||||
|
||||
.stat-icon.clients {
|
||||
.stat-icon-large.clients {
|
||||
background: linear-gradient(135deg, #10b981 0%, #34d399 100%);
|
||||
}
|
||||
|
||||
.stat-icon.rules {
|
||||
.stat-icon-large.rules {
|
||||
background: linear-gradient(135deg, #f59e0b 0%, #fbbf24 100%);
|
||||
}
|
||||
|
||||
.stat-icon.total-out {
|
||||
background: linear-gradient(135deg, #0284c7 0%, #38bdf8 100%);
|
||||
}
|
||||
|
||||
.stat-icon.total-in {
|
||||
background: linear-gradient(135deg, #9333ea 0%, #c084fc 100%);
|
||||
}
|
||||
|
||||
.stat-icon svg {
|
||||
.icon-lg {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
color: white;
|
||||
}
|
||||
|
||||
/* Stat content */
|
||||
.stat-content {
|
||||
/* Stat details */
|
||||
.stat-details {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-height: 44px;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
.stat-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.stat-row.single {
|
||||
padding: 12px 0;
|
||||
}
|
||||
|
||||
.stat-title {
|
||||
font-size: 13px;
|
||||
color: var(--color-text-secondary);
|
||||
font-weight: 500;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 26px;
|
||||
.stat-data {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.stat-number {
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
color: var(--color-text-primary);
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.stat-number.online {
|
||||
color: var(--color-success);
|
||||
}
|
||||
|
||||
.stat-unit {
|
||||
font-size: 12px;
|
||||
color: var(--color-text-muted);
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.stat-value-row {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.stat-unit-inline {
|
||||
font-size: 14px;
|
||||
color: var(--color-text-muted);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* Client count special styling */
|
||||
.client-count {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.client-count .stat-value.online {
|
||||
color: var(--color-success);
|
||||
}
|
||||
|
||||
.client-count .stat-value.total {
|
||||
font-size: 24px;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.stat-separator {
|
||||
font-size: 20px;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
/* Stat trend indicator */
|
||||
.stat-trend {
|
||||
position: absolute;
|
||||
top: 16px;
|
||||
right: 16px;
|
||||
padding: 4px 8px;
|
||||
border-radius: 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.stat-trend.up {
|
||||
background: rgba(0, 186, 124, 0.15);
|
||||
color: var(--color-success);
|
||||
}
|
||||
|
||||
/* Online indicator with pulse */
|
||||
|
||||
@@ -235,7 +235,7 @@ onMounted(() => {
|
||||
<style scoped>
|
||||
.settings-page {
|
||||
min-height: calc(100vh - 108px);
|
||||
background: var(--color-bg-primary);
|
||||
background: transparent;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
padding: 32px;
|
||||
@@ -243,7 +243,52 @@ onMounted(() => {
|
||||
|
||||
/* Hide particles */
|
||||
.particles {
|
||||
display: none;
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
overflow: hidden;
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.particle {
|
||||
position: absolute;
|
||||
border-radius: 50%;
|
||||
opacity: 0.15;
|
||||
filter: blur(60px);
|
||||
animation: float 20s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.particle-1 {
|
||||
width: 350px;
|
||||
height: 350px;
|
||||
background: var(--color-accent);
|
||||
top: -80px;
|
||||
right: -80px;
|
||||
}
|
||||
|
||||
.particle-2 {
|
||||
width: 280px;
|
||||
height: 280px;
|
||||
background: #8b5cf6;
|
||||
bottom: -40px;
|
||||
left: -40px;
|
||||
animation-delay: -5s;
|
||||
}
|
||||
|
||||
.particle-3 {
|
||||
width: 220px;
|
||||
height: 220px;
|
||||
background: var(--color-success);
|
||||
top: 40%;
|
||||
left: 30%;
|
||||
animation-delay: -10s;
|
||||
}
|
||||
|
||||
@keyframes float {
|
||||
0%, 100% { transform: translate(0, 0) scale(1); }
|
||||
25% { transform: translate(30px, -30px) scale(1.05); }
|
||||
50% { transform: translate(-20px, 20px) scale(0.95); }
|
||||
75% { transform: translate(-30px, -20px) scale(1.02); }
|
||||
}
|
||||
|
||||
.settings-content {
|
||||
|
||||
Reference in New Issue
Block a user